Update write time marked on actual flush not on flush request.
JIRA: CONTROLLER-2108
Change-Id: I92a66ae775cbae6aeea69bddf654df741f473dbd
Signed-off-by: Ruslan Kashapov <ruslan.kashapov@pantheon.tech>
Signed-off-by: Robert Varga <robert.varga@pantheon.tech>
--- /dev/null
+# .readthedocs.yml
+# Read the Docs configuration file
+# See https://docs.readthedocs.io/en/stable/config-file/v2.html for details
+
+# Required
+version: 2
+
+build:
+ os: ubuntu-22.04
+ tools:
+ python: "3.11"
+ jobs:
+ post_checkout:
+ - git fetch --unshallow || true
+
+sphinx:
+ configuration: docs/conf.py
+
+python:
+ install:
+ - requirements: docs/requirements.txt
<parent>
<groupId>org.opendaylight.odlparent</groupId>
<artifactId>odlparent-lite</artifactId>
- <version>12.0.1</version>
+ <version>13.0.11</version>
<relativePath/>
</parent>
<groupId>org.opendaylight.controller</groupId>
<artifactId>akka-aggregator</artifactId>
- <version>7.0.2-SNAPSHOT</version>
+ <version>9.0.3-SNAPSHOT</version>
<packaging>pom</packaging>
<properties>
<parent>
<groupId>org.opendaylight.odlparent</groupId>
<artifactId>odlparent</artifactId>
- <version>12.0.1</version>
+ <version>13.0.11</version>
<relativePath/>
</parent>
<groupId>org.opendaylight.controller</groupId>
<artifactId>repackaged-akka-jar</artifactId>
<packaging>jar</packaging>
- <version>7.0.2-SNAPSHOT</version>
+ <version>9.0.3-SNAPSHOT</version>
<name>${project.artifactId}</name>
<properties>
<dependency>
<groupId>com.typesafe.akka</groupId>
<artifactId>akka-actor_2.13</artifactId>
- <version>2.6.20</version>
+ <version>2.6.21</version>
</dependency>
<dependency>
<groupId>com.typesafe.akka</groupId>
<artifactId>akka-actor-typed_2.13</artifactId>
- <version>2.6.20</version>
+ <version>2.6.21</version>
</dependency>
<dependency>
<groupId>com.typesafe.akka</groupId>
<artifactId>akka-cluster_2.13</artifactId>
- <version>2.6.20</version>
+ <version>2.6.21</version>
</dependency>
<dependency>
<groupId>com.typesafe.akka</groupId>
<artifactId>akka-cluster-typed_2.13</artifactId>
- <version>2.6.20</version>
+ <version>2.6.21</version>
</dependency>
<dependency>
<groupId>com.typesafe.akka</groupId>
<artifactId>akka-osgi_2.13</artifactId>
- <version>2.6.20</version>
+ <version>2.6.21</version>
</dependency>
<dependency>
<groupId>com.typesafe.akka</groupId>
<artifactId>akka-persistence_2.13</artifactId>
- <version>2.6.20</version>
+ <version>2.6.21</version>
</dependency>
<dependency>
<groupId>com.typesafe.akka</groupId>
<artifactId>akka-protobuf_2.13</artifactId>
- <version>2.6.20</version>
+ <version>2.6.21</version>
</dependency>
<dependency>
<groupId>com.typesafe.akka</groupId>
<artifactId>akka-remote_2.13</artifactId>
- <version>2.6.20</version>
+ <version>2.6.21</version>
</dependency>
<dependency>
<groupId>com.typesafe.akka</groupId>
<artifactId>akka-slf4j_2.13</artifactId>
- <version>2.6.20</version>
+ <version>2.6.21</version>
</dependency>
<dependency>
<groupId>com.typesafe.akka</groupId>
<artifactId>akka-stream_2.13</artifactId>
- <version>2.6.20</version>
+ <version>2.6.21</version>
</dependency>
</dependencies>
</execution>
</executions>
</plugin>
+ <plugin>
+ <artifactId>maven-source-plugin</artifactId>
+ <configuration>
+ <!-- We handle this through shade plugin -->
+ <skipSource>true</skipSource>
+ </configuration>
+ </plugin>
</plugins>
</build>
</project>
<parent>
<groupId>org.opendaylight.controller</groupId>
<artifactId>bundle-parent</artifactId>
- <version>7.0.2-SNAPSHOT</version>
+ <version>9.0.3-SNAPSHOT</version>
<relativePath>../../bundle-parent</relativePath>
</parent>
<parent>
<groupId>org.opendaylight.odlparent</groupId>
<artifactId>odlparent-lite</artifactId>
- <version>12.0.1</version>
+ <version>13.0.11</version>
<relativePath/>
</parent>
<groupId>org.opendaylight.controller</groupId>
<artifactId>controller-artifacts</artifactId>
- <version>7.0.2-SNAPSHOT</version>
+ <version>9.0.3-SNAPSHOT</version>
<packaging>pom</packaging>
<dependencyManagement>
<version>${project.version}</version>
</dependency>
+ <!-- Atomix -->
+ <dependency>
+ <groupId>${project.groupId}</groupId>
+ <artifactId>atomix-storage</artifactId>
+ <version>${project.version}</version>
+ </dependency>
+
<!-- Core API/implementation -->
<dependency>
<groupId>${project.groupId}</groupId>
<classifier>features</classifier>
<type>xml</type>
</dependency>
-
- <!-- Config remnants -->
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>netty-event-executor-config</artifactId>
- <version>0.18.2-SNAPSHOT</version>
- </dependency>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>netty-threadgroup-config</artifactId>
- <version>0.18.2-SNAPSHOT</version>
- </dependency>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>netty-timer-config</artifactId>
- <version>0.18.2-SNAPSHOT</version>
- </dependency>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>threadpool-config-api</artifactId>
- <version>0.18.2-SNAPSHOT</version>
- </dependency>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>threadpool-config-impl</artifactId>
- <version>0.18.2-SNAPSHOT</version>
- </dependency>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>odl-controller-exp-netty-config</artifactId>
- <version>${project.version}</version>
- <classifier>features</classifier>
- <type>xml</type>
- </dependency>
</dependencies>
</dependencyManagement>
</project>
--- /dev/null
+
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright [yyyy] [name of copyright owner]
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
--- /dev/null
+<!--
+ ~ Copyright 2017-2021 Open Networking Foundation
+ ~ Copyright 2023 PANTHEON.tech, s.r.o.
+ ~
+ ~ Licensed under the Apache License, Version 2.0 (the "License");
+ ~ you may not use this file except in compliance with the License.
+ ~ You may obtain a copy of the License at
+ ~
+ ~ http://www.apache.org/licenses/LICENSE-2.0
+ ~
+ ~ Unless required by applicable law or agreed to in writing, software
+ ~ distributed under the License is distributed on an "AS IS" BASIS,
+ ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ~ See the License for the specific language governing permissions and
+ ~ limitations under the License.
+ -->
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+ <modelVersion>4.0.0</modelVersion>
+
+ <parent>
+ <groupId>org.opendaylight.controller</groupId>
+ <artifactId>bundle-parent</artifactId>
+ <version>9.0.3-SNAPSHOT</version>
+ <relativePath>../bundle-parent</relativePath>
+ </parent>
+
+ <artifactId>atomix-storage</artifactId>
+ <name>Atomix Storage</name>
+ <packaging>bundle</packaging>
+
+ <properties>
+ <odlparent.checkstyle.skip>true</odlparent.checkstyle.skip>
+ <odlparent.spotbugs.enforce>false</odlparent.spotbugs.enforce>
+ </properties>
+
+ <dependencies>
+ <dependency>
+ <groupId>com.google.guava</groupId>
+ <artifactId>guava</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>io.netty</groupId>
+ <artifactId>netty-buffer</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>io.netty</groupId>
+ <artifactId>netty-common</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.eclipse.jdt</groupId>
+ <artifactId>org.eclipse.jdt.annotation</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>com.esotericsoftware</groupId>
+ <artifactId>kryo</artifactId>
+ <version>4.0.3</version>
+ <scope>provided</scope>
+ </dependency>
+ <dependency>
+ <groupId>com.esotericsoftware</groupId>
+ <artifactId>minlog</artifactId>
+ <version>1.3.1</version>
+ <scope>provided</scope>
+ </dependency>
+ <dependency>
+ <groupId>com.esotericsoftware</groupId>
+ <artifactId>reflectasm</artifactId>
+ <version>1.11.9</version>
+ <scope>provided</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.objenesis</groupId>
+ <artifactId>objenesis</artifactId>
+ <version>2.6</version>
+ <scope>provided</scope>
+ </dependency>
+
+ <dependency>
+ <groupId>com.google.guava</groupId>
+ <artifactId>guava-testlib</artifactId>
+ </dependency>
+ </dependencies>
+
+ <build>
+ <plugins>
+ <!-- This project has a different license -->
+ <plugin>
+ <artifactId>maven-dependency-plugin</artifactId>
+ <executions>
+ <execution>
+ <id>unpack-license</id>
+ <configuration>
+ <skip>true</skip>
+ </configuration>
+ </execution>
+ </executions>
+ </plugin>
+ <plugin>
+ <artifactId>maven-antrun-plugin</artifactId>
+ <executions>
+ <execution>
+ <id>copy-license</id>
+ <phase>prepare-package</phase>
+ <goals>
+ <goal>run</goal>
+ </goals>
+ <configuration>
+ <target>
+ <copy file="LICENSE" tofile="${project.build.directory}/classes/LICENSE"/>
+ </target>
+ </configuration>
+ </execution>
+ </executions>
+ </plugin>
+ <plugin>
+ <artifactId>maven-checkstyle-plugin</artifactId>
+ <executions>
+ <execution>
+ <id>check-license</id>
+ <goals>
+ <goal>check</goal>
+ </goals>
+ <configuration>
+ <skip>true</skip>
+ </configuration>
+ </execution>
+ </executions>
+ </plugin>
+
+ <plugin>
+ <groupId>org.apache.felix</groupId>
+ <artifactId>maven-bundle-plugin</artifactId>
+ <extensions>true</extensions>
+ <configuration>
+ <instructions>
+ <Export-Package>
+ io.atomix.storage.journal
+ </Export-Package>
+ <Import-Package>
+ sun.nio.ch;resolution:=optional,
+ sun.misc;resolution:=optional,
+ !COM.newmonics.*,
+ !android.os,
+ *
+ </Import-Package>
+
+ <!-- Kryo is using ancient objenesis, so let's embed it to prevent duplicates -->
+ <Embed-Dependency>
+ *;inline=true;groupId=com.esotericsoftware,
+ *;inline=true;groupId=org.objenesis,
+ </Embed-Dependency>
+ </instructions>
+ </configuration>
+ </plugin>
+ </plugins>
+ </build>
+</project>
--- /dev/null
+/*
+ * Copyright (c) 2024 PANTHEON.tech, s.r.o. and others. All rights reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package io.atomix.storage.journal;
+
+import org.eclipse.jdt.annotation.NonNullByDefault;
+
+/**
+ * A {@link JournalReader} traversing only committed entries.
+ */
+@NonNullByDefault
+final class CommitsSegmentJournalReader<E> extends SegmentedJournalReader<E> {
+ CommitsSegmentJournalReader(final SegmentedJournal<E> journal, final JournalSegment segment) {
+ super(journal, segment);
+ }
+
+ @Override
+ public <T> T tryNext(final EntryMapper<E, T> mapper) {
+ return getNextIndex() <= journal.getCommitIndex() ? super.tryNext(mapper) : null;
+ }
+}
--- /dev/null
+/*
+ * Copyright (c) 2024 PANTHEON.tech, s.r.o. and others. All rights reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package io.atomix.storage.journal;
+
+import static com.google.common.base.Verify.verify;
+import static java.util.Objects.requireNonNull;
+
+import java.io.IOException;
+import java.nio.ByteBuffer;
+import java.nio.channels.FileChannel;
+import java.nio.file.Path;
+import org.eclipse.jdt.annotation.NonNull;
+
+/**
+ * A {@link StorageLevel#DISK} implementation of {@link FileReader}. Maintains an internal buffer.
+ */
+final class DiskFileReader extends FileReader {
+ /**
+ * Just do not bother with IO smaller than this many bytes.
+ */
+ private static final int MIN_IO_SIZE = 8192;
+
+ private final FileChannel channel;
+ private final ByteBuffer buffer;
+
+ // tracks where memory's first available byte maps to in terms of FileChannel.position()
+ private int bufferPosition;
+
+ DiskFileReader(final Path path, final FileChannel channel, final int maxSegmentSize, final int maxEntrySize) {
+ this(path, channel, allocateBuffer(maxSegmentSize, maxEntrySize));
+ }
+
+ // Note: take ownership of the buffer
+ DiskFileReader(final Path path, final FileChannel channel, final ByteBuffer buffer) {
+ super(path);
+ this.channel = requireNonNull(channel);
+ this.buffer = buffer.flip();
+ bufferPosition = 0;
+ }
+
+ static ByteBuffer allocateBuffer(final int maxSegmentSize, final int maxEntrySize) {
+ return ByteBuffer.allocate(chooseBufferSize(maxSegmentSize, maxEntrySize));
+ }
+
+ private static int chooseBufferSize(final int maxSegmentSize, final int maxEntrySize) {
+ if (maxSegmentSize <= MIN_IO_SIZE) {
+ // just buffer the entire segment
+ return maxSegmentSize;
+ }
+
+ // one full entry plus its header, or MIN_IO_SIZE, which benefits the read of many small entries
+ final int minBufferSize = maxEntrySize + SegmentEntry.HEADER_BYTES;
+ return minBufferSize <= MIN_IO_SIZE ? MIN_IO_SIZE : minBufferSize;
+ }
+
+ @Override
+ void invalidateCache() {
+ buffer.clear().flip();
+ bufferPosition = 0;
+ }
+
+ @Override
+ ByteBuffer read(final int position, final int size) {
+ // calculate logical seek distance between buffer's first byte and position and split flow between
+ // forward-moving and backwards-moving code paths.
+ final int seek = bufferPosition - position;
+ return seek >= 0 ? forwardAndRead(seek, position, size) : rewindAndRead(-seek, position, size);
+ }
+
+ private @NonNull ByteBuffer forwardAndRead(final int seek, final int position, final int size) {
+ final int missing = buffer.limit() - seek - size;
+ if (missing <= 0) {
+ // fast path: we have the requested region
+ return buffer.slice(seek, size).asReadOnlyBuffer();
+ }
+
+ // We need to read more data, but let's salvage what we can:
+ // - set buffer position to seek, which means it points to the same as position
+ // - run compact, which moves everything between position and limit onto the beginning of buffer and
+ // sets it up to receive more bytes
+ // - start the read accounting for the seek
+ buffer.position(seek).compact();
+ readAtLeast(position + seek, missing);
+ return setAndSlice(position, size);
+ }
+
+ private @NonNull ByteBuffer rewindAndRead(final int rewindBy, final int position, final int size) {
+ // TODO: Lazy solution. To be super crisp, we want to find out how much of the buffer we can salvage and
+ // do all the limit/position fiddling before and after read. Right now let's just flow the buffer up and
+ // read it.
+ buffer.clear();
+ readAtLeast(position, size);
+ return setAndSlice(position, size);
+ }
+
+ private void readAtLeast(final int readPosition, final int readAtLeast) {
+ final int bytesRead;
+ try {
+ bytesRead = channel.read(buffer, readPosition);
+ } catch (IOException e) {
+ throw new StorageException(e);
+ }
+ verify(bytesRead >= readAtLeast, "Short read %s, expected %s", bytesRead, readAtLeast);
+ buffer.flip();
+ }
+
+ private @NonNull ByteBuffer setAndSlice(final int position, final int size) {
+ bufferPosition = position;
+ return buffer.slice(0, size).asReadOnlyBuffer();
+ }
+}
--- /dev/null
+/*
+ * Copyright (c) 2024 PANTHEON.tech, s.r.o. and others. All rights reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package io.atomix.storage.journal;
+
+import static io.atomix.storage.journal.SegmentEntry.HEADER_BYTES;
+
+import java.io.IOException;
+import java.nio.ByteBuffer;
+import java.nio.MappedByteBuffer;
+import java.nio.channels.FileChannel;
+import java.nio.file.Path;
+
+/**
+ * A {@link StorageLevel#DISK} {@link FileWriter}.
+ */
+final class DiskFileWriter extends FileWriter {
+ private static final ByteBuffer ZERO_ENTRY_HEADER = ByteBuffer.wrap(new byte[HEADER_BYTES]);
+
+ private final DiskFileReader reader;
+ private final ByteBuffer buffer;
+
+ DiskFileWriter(final Path path, final FileChannel channel, final int maxSegmentSize, final int maxEntrySize) {
+ super(path, channel, maxSegmentSize, maxEntrySize);
+ buffer = DiskFileReader.allocateBuffer(maxSegmentSize, maxEntrySize);
+ reader = new DiskFileReader(path, channel, buffer);
+ }
+
+ @Override
+ DiskFileReader reader() {
+ return reader;
+ }
+
+ @Override
+ MappedByteBuffer buffer() {
+ return null;
+ }
+
+ @Override
+ MappedFileWriter toMapped() {
+ flush();
+ return new MappedFileWriter(path, channel, maxSegmentSize, maxEntrySize);
+ }
+
+ @Override
+ DiskFileWriter toDisk() {
+ return null;
+ }
+
+ @Override
+ void writeEmptyHeader(final int position) {
+ try {
+ channel.write(ZERO_ENTRY_HEADER.asReadOnlyBuffer(), position);
+ } catch (IOException e) {
+ throw new StorageException(e);
+ }
+ }
+
+ @Override
+ ByteBuffer startWrite(final int position, final int size) {
+ return buffer.clear().slice(0, size);
+ }
+
+ @Override
+ void commitWrite(final int position, final ByteBuffer entry) {
+ try {
+ channel.write(entry, position);
+ } catch (IOException e) {
+ throw new StorageException(e);
+ }
+ }
+
+ @Override
+ void flush() {
+ if (channel.isOpen()) {
+ try {
+ channel.force(true);
+ } catch (IOException e) {
+ throw new StorageException(e);
+ }
+ }
+ }
+
+ @Override
+ void close() {
+ flush();
+ }
+}
--- /dev/null
+/*
+ * Copyright (c) 2024 PANTHEON.tech, s.r.o. and others. All rights reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package io.atomix.storage.journal;
+
+import static java.util.Objects.requireNonNull;
+
+import com.google.common.base.MoreObjects;
+import java.nio.ByteBuffer;
+import java.nio.file.Path;
+import org.eclipse.jdt.annotation.NonNull;
+
+/**
+ * An abstraction over how to read a {@link JournalSegmentFile}.
+ */
+abstract sealed class FileReader permits DiskFileReader, MappedFileReader {
+ private final Path path;
+
+ FileReader(final Path path) {
+ this.path = requireNonNull(path);
+ }
+
+ /**
+ * Invalidate any cache that is present, so that the next read is coherent with the backing file.
+ */
+ abstract void invalidateCache();
+
+ /**
+ * Read the some bytes as specified position. The sum of position and size is guaranteed not to exceed the maximum
+ * segment size nor maximum entry size.
+ *
+ * @param position position to the entry header
+ * @param size to read
+ * @return resulting buffer
+ */
+ abstract @NonNull ByteBuffer read(int position, int size);
+
+ @Override
+ public final String toString() {
+ return MoreObjects.toStringHelper(this).add("path", path).toString();
+ }
+}
--- /dev/null
+/*
+ * Copyright (c) 2024 PANTHEON.tech, s.r.o. and others. All rights reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package io.atomix.storage.journal;
+
+import static java.util.Objects.requireNonNull;
+
+import com.google.common.base.MoreObjects;
+import java.nio.ByteBuffer;
+import java.nio.MappedByteBuffer;
+import java.nio.channels.FileChannel;
+import java.nio.file.Path;
+import org.eclipse.jdt.annotation.Nullable;
+
+/**
+ * An abstraction over how to write a {@link JournalSegmentFile}.
+ */
+abstract sealed class FileWriter permits DiskFileWriter, MappedFileWriter {
+ final Path path;
+ final FileChannel channel;
+ final int maxSegmentSize;
+ final int maxEntrySize;
+
+ FileWriter(final Path path, final FileChannel channel, final int maxSegmentSize, final int maxEntrySize) {
+ this.path = requireNonNull(path);
+ this.channel = requireNonNull(channel);
+ this.maxSegmentSize = maxSegmentSize;
+ this.maxEntrySize = maxEntrySize;
+ }
+
+ /**
+ * Return the internal {@link FileReader}.
+ *
+ * @return the internal FileReader
+ */
+ abstract FileReader reader();
+
+ /**
+ * Write {@link SegmentEntry#HEADER_BYTES} worth of zeroes at specified position.
+ *
+ * @param position position to write to
+ */
+ abstract void writeEmptyHeader(int position);
+
+ abstract ByteBuffer startWrite(int position, int size);
+
+ abstract void commitWrite(int position, ByteBuffer entry);
+
+ /**
+ * Flushes written entries to disk.
+ */
+ abstract void flush();
+
+ /**
+ * Closes this writer.
+ */
+ abstract void close();
+
+ @Override
+ public final String toString() {
+ return MoreObjects.toStringHelper(this).add("path", path).toString();
+ }
+
+ abstract @Nullable MappedByteBuffer buffer();
+
+ abstract @Nullable MappedFileWriter toMapped();
+
+ abstract @Nullable DiskFileWriter toDisk();
+}
--- /dev/null
+/*
+ * Copyright 2017-2022 Open Networking Foundation and others. All rights reserved.
+ * Copyright (c) 2024 PANTHEON.tech, s.r.o.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package io.atomix.storage.journal;
+
+import static java.util.Objects.requireNonNull;
+
+import com.google.common.base.MoreObjects;
+import org.eclipse.jdt.annotation.NonNullByDefault;
+
+/**
+ * Indexed journal entry.
+ *
+ * @param <E> entry type
+ * @param index the entry index
+ * @param entry the indexed entry
+ * @param size the serialized entry size
+ */
+// FIXME: it seems 'index' has to be non-zero, we should enforce that if that really is the case
+// FIXME: it seems 'size' has not be non-zero, we should enforce that if that really is the case
+@NonNullByDefault
+public record Indexed<E>(long index, E entry, int size) {
+ public Indexed {
+ requireNonNull(entry);
+ }
+
+ @Override
+ public String toString() {
+ return MoreObjects.toStringHelper(this).add("index", index).add("entry", entry).toString();
+ }
+}
--- /dev/null
+/*
+ * Copyright 2017-2022 Open Networking Foundation and others. All rights reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package io.atomix.storage.journal;
+
+import java.io.Closeable;
+
+/**
+ * Journal.
+ *
+ * @author <a href="http://github.com/kuujo">Jordan Halterman</a>
+ */
+public interface Journal<E> extends Closeable {
+
+ /**
+ * Returns the journal writer.
+ *
+ * @return The journal writer.
+ */
+ JournalWriter<E> writer();
+
+ /**
+ * Opens a new journal reader.
+ *
+ * @param index The index at which to start the reader.
+ * @return A new journal reader.
+ */
+ JournalReader<E> openReader(long index);
+
+ /**
+ * Opens a new journal reader.
+ *
+ * @param index The index at which to start the reader.
+ * @param mode the reader mode
+ * @return A new journal reader.
+ */
+ JournalReader<E> openReader(long index, JournalReader.Mode mode);
+
+ /**
+ * Returns a boolean indicating whether the journal is open.
+ *
+ * @return Indicates whether the journal is open.
+ */
+ boolean isOpen();
+
+ @Override
+ void close();
+}
--- /dev/null
+/*
+ * Copyright 2017-2022 Open Networking Foundation and others. All rights reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package io.atomix.storage.journal;
+
+import org.eclipse.jdt.annotation.NonNullByDefault;
+import org.eclipse.jdt.annotation.Nullable;
+
+/**
+ * Log reader.
+ *
+ * @author <a href="http://github.com/kuujo">Jordan Halterman</a>
+ */
+@NonNullByDefault
+public interface JournalReader<E> extends AutoCloseable {
+ /**
+ * Raft log reader mode.
+ */
+ enum Mode {
+ /**
+ * Reads all entries from the log.
+ */
+ ALL,
+ /**
+ * Reads committed entries from the log.
+ */
+ COMMITS,
+ }
+
+ /**
+ * A journal entry processor. Responsible for transforming entries into their internal representation.
+ *
+ * @param <E> Entry type
+ * @param <T> Internal representation type
+ */
+ @FunctionalInterface
+ interface EntryMapper<E, T> {
+ /**
+ * Process an entry.
+ *
+ * @param index entry index
+ * @param entry entry itself
+ * @param size entry size
+ * @return resulting internal representation
+ */
+ T mapEntry(long index, E entry, int size);
+ }
+
+ /**
+ * Returns the first index in the journal.
+ *
+ * @return the first index in the journal
+ */
+ long getFirstIndex();
+
+ /**
+ * Returns the next reader index.
+ *
+ * @return The next reader index.
+ */
+ long getNextIndex();
+
+ /**
+ * Try to move to the next entry.
+ *
+ * @param mapper callback to be invoked for the entry
+ * @return processed entry, or {@code null}
+ */
+ <T> @Nullable T tryNext(EntryMapper<E, T> mapper);
+
+ /**
+ * Resets the reader to the start.
+ */
+ void reset();
+
+ /**
+ * Resets the reader to the given index.
+ *
+ * @param index The index to which to reset the reader.
+ */
+ void reset(long index);
+
+ @Override
+ void close();
+}
--- /dev/null
+/*
+ * Copyright 2017-2022 Open Networking Foundation and others. All rights reserved.
+ * Copyright (c) 2024 PANTHEON.tech, s.r.o.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package io.atomix.storage.journal;
+
+import com.google.common.base.MoreObjects;
+import io.atomix.storage.journal.index.JournalIndex;
+import io.atomix.storage.journal.index.Position;
+import io.atomix.storage.journal.index.SparseJournalIndex;
+import java.io.IOException;
+import java.nio.channels.FileChannel;
+import java.nio.file.Files;
+import java.nio.file.StandardOpenOption;
+import java.util.Set;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.atomic.AtomicInteger;
+import org.eclipse.jdt.annotation.Nullable;
+
+/**
+ * Log segment.
+ *
+ * @author <a href="http://github.com/kuujo">Jordan Halterman</a>
+ */
+final class JournalSegment implements AutoCloseable {
+ private final JournalSegmentFile file;
+ private final JournalSegmentDescriptor descriptor;
+ private final StorageLevel storageLevel;
+ private final int maxEntrySize;
+ private final JournalIndex journalIndex;
+ private final Set<JournalSegmentReader> readers = ConcurrentHashMap.newKeySet();
+ private final AtomicInteger references = new AtomicInteger();
+ private final FileChannel channel;
+
+ private JournalSegmentWriter writer;
+ private boolean open = true;
+
+ JournalSegment(
+ final JournalSegmentFile file,
+ final JournalSegmentDescriptor descriptor,
+ final StorageLevel storageLevel,
+ final int maxEntrySize,
+ final double indexDensity) {
+ this.file = file;
+ this.descriptor = descriptor;
+ this.storageLevel = storageLevel;
+ this.maxEntrySize = maxEntrySize;
+ journalIndex = new SparseJournalIndex(indexDensity);
+ try {
+ channel = FileChannel.open(file.file().toPath(),
+ StandardOpenOption.CREATE, StandardOpenOption.READ, StandardOpenOption.WRITE);
+ } catch (IOException e) {
+ throw new StorageException(e);
+ }
+
+ final var fileWriter = switch (storageLevel) {
+ case DISK -> new DiskFileWriter(file.file().toPath(), channel, descriptor.maxSegmentSize(), maxEntrySize);
+ case MAPPED -> new MappedFileWriter(file.file().toPath(), channel, descriptor.maxSegmentSize(), maxEntrySize);
+ };
+ writer = new JournalSegmentWriter(fileWriter, this, maxEntrySize, journalIndex)
+ // relinquish mapped memory
+ .toFileChannel();
+ }
+
+ /**
+ * Returns the segment's starting index.
+ *
+ * @return The segment's starting index.
+ */
+ long firstIndex() {
+ return descriptor.index();
+ }
+
+ /**
+ * Returns the last index in the segment.
+ *
+ * @return The last index in the segment.
+ */
+ long lastIndex() {
+ return writer.getLastIndex();
+ }
+
+ /**
+ * Returns the size of the segment.
+ *
+ * @return the size of the segment
+ */
+ int size() {
+ try {
+ return (int) channel.size();
+ } catch (IOException e) {
+ throw new StorageException(e);
+ }
+ }
+
+ /**
+ * Returns the segment file.
+ *
+ * @return The segment file.
+ */
+ JournalSegmentFile file() {
+ return file;
+ }
+
+ /**
+ * Returns the segment descriptor.
+ *
+ * @return The segment descriptor.
+ */
+ JournalSegmentDescriptor descriptor() {
+ return descriptor;
+ }
+
+ /**
+ * Looks up the position of the given index.
+ *
+ * @param index the index to lookup
+ * @return the position of the given index or a lesser index, or {@code null}
+ */
+ @Nullable Position lookup(final long index) {
+ return journalIndex.lookup(index);
+ }
+
+ /**
+ * Acquires a reference to the log segment.
+ */
+ private void acquire() {
+ if (references.getAndIncrement() == 0 && storageLevel == StorageLevel.MAPPED) {
+ writer = writer.toMapped();
+ }
+ }
+
+ /**
+ * Releases a reference to the log segment.
+ */
+ private void release() {
+ if (references.decrementAndGet() == 0) {
+ if (storageLevel == StorageLevel.MAPPED) {
+ writer = writer.toFileChannel();
+ }
+ if (!open) {
+ finishClose();
+ }
+ }
+ }
+
+ /**
+ * Acquires a reference to the segment writer.
+ *
+ * @return The segment writer.
+ */
+ JournalSegmentWriter acquireWriter() {
+ checkOpen();
+ acquire();
+
+ return writer;
+ }
+
+ /**
+ * Releases the reference to the segment writer.
+ */
+ void releaseWriter() {
+ release();
+ }
+
+ /**
+ * Creates a new segment reader.
+ *
+ * @return A new segment reader.
+ */
+ JournalSegmentReader createReader() {
+ checkOpen();
+ acquire();
+
+ final var buffer = writer.buffer();
+ final var path = file.file().toPath();
+ final var fileReader = buffer != null ? new MappedFileReader(path, buffer)
+ : new DiskFileReader(path, channel, descriptor.maxSegmentSize(), maxEntrySize);
+ final var reader = new JournalSegmentReader(this, fileReader, maxEntrySize);
+ reader.setPosition(JournalSegmentDescriptor.BYTES);
+ readers.add(reader);
+ return reader;
+ }
+
+ /**
+ * Closes a segment reader.
+ *
+ * @param reader the closed segment reader
+ */
+ void closeReader(JournalSegmentReader reader) {
+ if (readers.remove(reader)) {
+ release();
+ }
+ }
+
+ /**
+ * Checks whether the segment is open.
+ */
+ private void checkOpen() {
+ if (!open) {
+ throw new IllegalStateException("Segment not open");
+ }
+ }
+
+ /**
+ * Returns a boolean indicating whether the segment is open.
+ *
+ * @return indicates whether the segment is open
+ */
+ public boolean isOpen() {
+ return open;
+ }
+
+ /**
+ * Closes the segment.
+ */
+ @Override
+ public void close() {
+ if (!open) {
+ return;
+ }
+
+ open = false;
+ readers.forEach(JournalSegmentReader::close);
+ if (references.get() == 0) {
+ finishClose();
+ }
+ }
+
+ private void finishClose() {
+ writer.close();
+ try {
+ channel.close();
+ } catch (IOException e) {
+ throw new StorageException(e);
+ }
+ }
+
+ /**
+ * Deletes the segment.
+ */
+ void delete() {
+ try {
+ Files.deleteIfExists(file.file().toPath());
+ } catch (IOException e) {
+ throw new StorageException(e);
+ }
+ }
+
+ @Override
+ public String toString() {
+ return MoreObjects.toStringHelper(this)
+ .add("id", descriptor.id())
+ .add("version", descriptor.version())
+ .add("index", firstIndex())
+ .toString();
+ }
+}
--- /dev/null
+/*
+ * Copyright 2015-2022 Open Networking Foundation and others. All rights reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package io.atomix.storage.journal;
+
+import com.google.common.annotations.VisibleForTesting;
+
+import java.nio.ByteBuffer;
+
+import static com.google.common.base.MoreObjects.toStringHelper;
+import static java.util.Objects.requireNonNull;
+
+/**
+ * Stores information about a {@link JournalSegment} of the log.
+ * <p>
+ * The segment descriptor manages metadata related to a single segment of the log. Descriptors are stored within the
+ * first {@code 64} bytes of each segment in the following order:
+ * <ul>
+ * <li>{@code id} (64-bit signed integer) - A unique segment identifier. This is a monotonically increasing number within
+ * each log. Segments with in-sequence identifiers should contain in-sequence indexes.</li>
+ * <li>{@code index} (64-bit signed integer) - The effective first index of the segment. This indicates the index at which
+ * the first entry should be written to the segment. Indexes are monotonically increasing thereafter.</li>
+ * <li>{@code version} (64-bit signed integer) - The version of the segment. Versions are monotonically increasing
+ * starting at {@code 1}. Versions will only be incremented whenever the segment is rewritten to another memory/disk
+ * space, e.g. after log compaction.</li>
+ * <li>{@code maxSegmentSize} (32-bit unsigned integer) - The maximum number of bytes allowed in the segment.</li>
+ * <li>{@code maxEntries} (32-bit signed integer) - The total number of expected entries in the segment. This is the final
+ * number of entries allowed within the segment both before and after compaction. This entry count is used to determine
+ * the count of internal indexing and deduplication facilities.</li>
+ * <li>{@code updated} (64-bit signed integer) - The last update to the segment in terms of milliseconds since the epoch.
+ * When the segment is first constructed, the {@code updated} time is {@code 0}. Once all entries in the segment have
+ * been committed, the {@code updated} time should be set to the current time. Log compaction should not result in a
+ * change to {@code updated}.</li>
+ * <li>{@code locked} (8-bit boolean) - A boolean indicating whether the segment is locked. Segments will be locked once
+ * all entries have been committed to the segment. The lock state of each segment is used to determine log compaction
+ * and recovery behavior.</li>
+ * </ul>
+ * The remainder of the 64 segment header bytes are reserved for future metadata.
+ *
+ * @author <a href="http://github.com/kuujo">Jordan Halterman</a>
+ */
+public final class JournalSegmentDescriptor {
+ public static final int BYTES = 64;
+
+ // Current segment version.
+ @VisibleForTesting
+ static final int VERSION = 1;
+
+ // The lengths of each field in the header.
+ private static final int VERSION_LENGTH = Integer.BYTES; // 32-bit signed integer
+ private static final int ID_LENGTH = Long.BYTES; // 64-bit signed integer
+ private static final int INDEX_LENGTH = Long.BYTES; // 64-bit signed integer
+ private static final int MAX_SIZE_LENGTH = Integer.BYTES; // 32-bit signed integer
+ private static final int MAX_ENTRIES_LENGTH = Integer.BYTES; // 32-bit signed integer
+ private static final int UPDATED_LENGTH = Long.BYTES; // 64-bit signed integer
+
+ // The positions of each field in the header.
+ private static final int VERSION_POSITION = 0; // 0
+ private static final int ID_POSITION = VERSION_POSITION + VERSION_LENGTH; // 4
+ private static final int INDEX_POSITION = ID_POSITION + ID_LENGTH; // 12
+ private static final int MAX_SIZE_POSITION = INDEX_POSITION + INDEX_LENGTH; // 20
+ private static final int MAX_ENTRIES_POSITION = MAX_SIZE_POSITION + MAX_SIZE_LENGTH; // 24
+ private static final int UPDATED_POSITION = MAX_ENTRIES_POSITION + MAX_ENTRIES_LENGTH; // 28
+
+ /**
+ * Returns a descriptor builder.
+ * <p>
+ * The descriptor builder will write segment metadata to a {@code 48} byte in-memory buffer.
+ *
+ * @return The descriptor builder.
+ */
+ public static Builder builder() {
+ return new Builder(ByteBuffer.allocate(BYTES));
+ }
+
+ /**
+ * Returns a descriptor builder for the given descriptor buffer.
+ *
+ * @param buffer The descriptor buffer.
+ * @return The descriptor builder.
+ * @throws NullPointerException if {@code buffer} is null
+ */
+ public static Builder builder(ByteBuffer buffer) {
+ return new Builder(buffer);
+ }
+
+ private final ByteBuffer buffer;
+ private final int version;
+ private final long id;
+ private final long index;
+ private final int maxSegmentSize;
+ private final int maxEntries;
+ private volatile long updated;
+ private volatile boolean locked;
+
+ /**
+ * @throws NullPointerException if {@code buffer} is null
+ */
+ public JournalSegmentDescriptor(ByteBuffer buffer) {
+ this.buffer = buffer;
+ this.version = buffer.getInt();
+ this.id = buffer.getLong();
+ this.index = buffer.getLong();
+ this.maxSegmentSize = buffer.getInt();
+ this.maxEntries = buffer.getInt();
+ this.updated = buffer.getLong();
+ this.locked = buffer.get() == 1;
+ }
+
+ /**
+ * Returns the segment version.
+ * <p>
+ * Versions are monotonically increasing starting at {@code 1}.
+ *
+ * @return The segment version.
+ */
+ public int version() {
+ return version;
+ }
+
+ /**
+ * Returns the segment identifier.
+ * <p>
+ * The segment ID is a monotonically increasing number within each log. Segments with in-sequence identifiers should
+ * contain in-sequence indexes.
+ *
+ * @return The segment identifier.
+ */
+ public long id() {
+ return id;
+ }
+
+ /**
+ * Returns the segment index.
+ * <p>
+ * The index indicates the index at which the first entry should be written to the segment. Indexes are monotonically
+ * increasing thereafter.
+ *
+ * @return The segment index.
+ */
+ public long index() {
+ return index;
+ }
+
+ /**
+ * Returns the maximum count of the segment.
+ *
+ * @return The maximum allowed count of the segment.
+ */
+ public int maxSegmentSize() {
+ return maxSegmentSize;
+ }
+
+ /**
+ * Returns the maximum number of entries allowed in the segment.
+ *
+ * @return The maximum number of entries allowed in the segment.
+ */
+ public int maxEntries() {
+ return maxEntries;
+ }
+
+ /**
+ * Returns last time the segment was updated.
+ * <p>
+ * When the segment is first constructed, the {@code updated} time is {@code 0}. Once all entries in the segment have
+ * been committed, the {@code updated} time should be set to the current time. Log compaction should not result in a
+ * change to {@code updated}.
+ *
+ * @return The last time the segment was updated in terms of milliseconds since the epoch.
+ */
+ public long updated() {
+ return updated;
+ }
+
+ /**
+ * Writes an update to the descriptor.
+ */
+ public void update(long timestamp) {
+ if (!locked) {
+ buffer.putLong(UPDATED_POSITION, timestamp);
+ this.updated = timestamp;
+ }
+ }
+
+ /**
+ * Copies the segment to a new buffer.
+ */
+ JournalSegmentDescriptor copyTo(ByteBuffer buffer) {
+ buffer.putInt(version);
+ buffer.putLong(id);
+ buffer.putLong(index);
+ buffer.putInt(maxSegmentSize);
+ buffer.putInt(maxEntries);
+ buffer.putLong(updated);
+ buffer.put(locked ? (byte) 1 : (byte) 0);
+ return this;
+ }
+
+ @Override
+ public String toString() {
+ return toStringHelper(this)
+ .add("version", version)
+ .add("id", id)
+ .add("index", index)
+ .add("updated", updated)
+ .toString();
+ }
+
+ /**
+ * Segment descriptor builder.
+ */
+ public static class Builder {
+ private final ByteBuffer buffer;
+
+ private Builder(ByteBuffer buffer) {
+ this.buffer = requireNonNull(buffer, "buffer cannot be null");
+ buffer.putInt(VERSION_POSITION, VERSION);
+ }
+
+ /**
+ * Sets the segment identifier.
+ *
+ * @param id The segment identifier.
+ * @return The segment descriptor builder.
+ */
+ public Builder withId(long id) {
+ buffer.putLong(ID_POSITION, id);
+ return this;
+ }
+
+ /**
+ * Sets the segment index.
+ *
+ * @param index The segment starting index.
+ * @return The segment descriptor builder.
+ */
+ public Builder withIndex(long index) {
+ buffer.putLong(INDEX_POSITION, index);
+ return this;
+ }
+
+ /**
+ * Sets maximum count of the segment.
+ *
+ * @param maxSegmentSize The maximum count of the segment.
+ * @return The segment descriptor builder.
+ */
+ public Builder withMaxSegmentSize(int maxSegmentSize) {
+ buffer.putInt(MAX_SIZE_POSITION, maxSegmentSize);
+ return this;
+ }
+
+ /**
+ * Sets the maximum number of entries in the segment.
+ *
+ * @param maxEntries The maximum number of entries in the segment.
+ * @return The segment descriptor builder.
+ * @deprecated since 3.0.2
+ */
+ @Deprecated
+ public Builder withMaxEntries(int maxEntries) {
+ buffer.putInt(MAX_ENTRIES_POSITION, maxEntries);
+ return this;
+ }
+
+ /**
+ * Builds the segment descriptor.
+ *
+ * @return The built segment descriptor.
+ */
+ public JournalSegmentDescriptor build() {
+ buffer.rewind();
+ return new JournalSegmentDescriptor(buffer);
+ }
+ }
+}
--- /dev/null
+/*
+ * Copyright 2015-2022 Open Networking Foundation and others. All rights reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package io.atomix.storage.journal;
+
+import java.io.File;
+
+import static java.util.Objects.requireNonNull;
+
+/**
+ * Segment file utility.
+ *
+ * @author <a href="http://github.com/kuujo">Jordan Halterman</a>
+ */
+public final class JournalSegmentFile {
+ private static final char PART_SEPARATOR = '-';
+ private static final char EXTENSION_SEPARATOR = '.';
+ private static final String EXTENSION = "log";
+ private final File file;
+
+ /**
+ * Returns a boolean value indicating whether the given file appears to be a parsable segment file.
+ *
+ * @throws NullPointerException if {@code file} is null
+ */
+ public static boolean isSegmentFile(String name, File file) {
+ return isSegmentFile(name, file.getName());
+ }
+
+ /**
+ * Returns a boolean value indicating whether the given file appears to be a parsable segment file.
+ *
+ * @param journalName the name of the journal
+ * @param fileName the name of the file to check
+ * @throws NullPointerException if {@code file} is null
+ */
+ public static boolean isSegmentFile(String journalName, String fileName) {
+ requireNonNull(journalName, "journalName cannot be null");
+ requireNonNull(fileName, "fileName cannot be null");
+
+ int partSeparator = fileName.lastIndexOf(PART_SEPARATOR);
+ int extensionSeparator = fileName.lastIndexOf(EXTENSION_SEPARATOR);
+
+ if (extensionSeparator == -1
+ || partSeparator == -1
+ || extensionSeparator < partSeparator
+ || !fileName.endsWith(EXTENSION)) {
+ return false;
+ }
+
+ for (int i = partSeparator + 1; i < extensionSeparator; i++) {
+ if (!Character.isDigit(fileName.charAt(i))) {
+ return false;
+ }
+ }
+
+ return fileName.startsWith(journalName);
+ }
+
+ /**
+ * Creates a segment file for the given directory, log name, segment ID, and segment version.
+ */
+ static File createSegmentFile(String name, File directory, long id) {
+ return new File(directory, String.format("%s-%d.log", requireNonNull(name, "name cannot be null"), id));
+ }
+
+ /**
+ * @throws IllegalArgumentException if {@code file} is not a valid segment file
+ */
+ JournalSegmentFile(File file) {
+ this.file = file;
+ }
+
+ /**
+ * Returns the segment file.
+ *
+ * @return The segment file.
+ */
+ public File file() {
+ return file;
+ }
+}
--- /dev/null
+/*
+ * Copyright (c) 2024 PANTHEON.tech, s.r.o. and others. All rights reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package io.atomix.storage.journal;
+
+import static com.google.common.base.Verify.verify;
+import static java.util.Objects.requireNonNull;
+
+import io.netty.buffer.ByteBuf;
+import io.netty.buffer.Unpooled;
+import java.util.zip.CRC32;
+import org.eclipse.jdt.annotation.Nullable;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+final class JournalSegmentReader {
+ private static final Logger LOG = LoggerFactory.getLogger(JournalSegmentReader.class);
+
+ private final JournalSegment segment;
+ private final FileReader fileReader;
+ private final int maxSegmentSize;
+ private final int maxEntrySize;
+
+ private int position;
+
+ JournalSegmentReader(final JournalSegment segment, final FileReader fileReader, final int maxEntrySize) {
+ this.segment = requireNonNull(segment);
+ this.fileReader = requireNonNull(fileReader);
+ maxSegmentSize = segment.descriptor().maxSegmentSize();
+ this.maxEntrySize = maxEntrySize;
+ }
+
+ /**
+ * Return the current position.
+ *
+ * @return current position.
+ */
+ int position() {
+ return position;
+ }
+
+ /**
+ * Set the file position.
+ *
+ * @param position new position
+ */
+ void setPosition(final int position) {
+ verify(position >= JournalSegmentDescriptor.BYTES && position < maxSegmentSize,
+ "Invalid position %s", position);
+ this.position = position;
+ fileReader.invalidateCache();
+ }
+
+ /**
+ * Invalidate any cache that is present, so that the next read is coherent with the backing file.
+ */
+ void invalidateCache() {
+ fileReader.invalidateCache();
+ }
+
+ /**
+ * Reads the next binary data block
+ *
+ * @param index entry index
+ * @return The binary data, or {@code null}
+ */
+ @Nullable ByteBuf readBytes(final long index) {
+ // Check if there is enough in the buffer remaining
+ final int remaining = maxSegmentSize - position - SegmentEntry.HEADER_BYTES;
+ if (remaining < 0) {
+ // Not enough space in the segment, there can never be another entry
+ return null;
+ }
+
+ // Calculate maximum entry length not exceeding file size nor maxEntrySize
+ final var maxLength = Math.min(remaining, maxEntrySize);
+ final var buffer = fileReader.read(position, maxLength + SegmentEntry.HEADER_BYTES);
+
+ // Read the entry length
+ final var length = buffer.getInt(0);
+ if (length < 1 || length > maxLength) {
+ // Invalid length, make sure next read re-tries
+ invalidateCache();
+ return null;
+ }
+
+ // Read the entry checksum
+ final int checksum = buffer.getInt(Integer.BYTES);
+
+ // Slice off the entry's bytes
+ final var entryBuffer = buffer.slice(SegmentEntry.HEADER_BYTES, length);
+ // Compute the checksum for the entry bytes.
+ final var crc32 = new CRC32();
+ crc32.update(entryBuffer);
+
+ // If the stored checksum does not equal the computed checksum, do not proceed further
+ final var computed = (int) crc32.getValue();
+ if (checksum != computed) {
+ LOG.warn("Expected checksum {}, computed {}", Integer.toHexString(checksum), Integer.toHexString(computed));
+ invalidateCache();
+ return null;
+ }
+
+ // update position
+ position += SegmentEntry.HEADER_BYTES + length;
+
+ // return bytes
+ entryBuffer.rewind();
+ return Unpooled.buffer(length).writeBytes(entryBuffer);
+ }
+
+ /**
+ * Close this reader.
+ */
+ void close() {
+ segment.closeReader(this);
+ }
+}
--- /dev/null
+/*
+ * Copyright (c) 2024 PANTHEON.tech, s.r.o. and others. All rights reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package io.atomix.storage.journal;
+
+import static io.atomix.storage.journal.SegmentEntry.HEADER_BYTES;
+import static java.util.Objects.requireNonNull;
+
+import io.atomix.storage.journal.index.JournalIndex;
+import io.netty.buffer.ByteBuf;
+import java.nio.MappedByteBuffer;
+import java.util.zip.CRC32;
+import org.eclipse.jdt.annotation.NonNull;
+import org.eclipse.jdt.annotation.Nullable;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+final class JournalSegmentWriter {
+ private static final Logger LOG = LoggerFactory.getLogger(JournalSegmentWriter.class);
+
+ private final FileWriter fileWriter;
+ final @NonNull JournalSegment segment;
+ private final @NonNull JournalIndex index;
+ final int maxSegmentSize;
+ final int maxEntrySize;
+
+ private int currentPosition;
+ private Long lastIndex;
+
+ JournalSegmentWriter(final FileWriter fileWriter, final JournalSegment segment, final int maxEntrySize,
+ final JournalIndex index) {
+ this.fileWriter = requireNonNull(fileWriter);
+ this.segment = requireNonNull(segment);
+ this.index = requireNonNull(index);
+ maxSegmentSize = segment.descriptor().maxSegmentSize();
+ this.maxEntrySize = maxEntrySize;
+ // adjust lastEntry value
+ reset(0);
+ }
+
+ JournalSegmentWriter(final JournalSegmentWriter previous, final FileWriter fileWriter) {
+ segment = previous.segment;
+ index = previous.index;
+ maxSegmentSize = previous.maxSegmentSize;
+ maxEntrySize = previous.maxEntrySize;
+ lastIndex = previous.lastIndex;
+ currentPosition = previous.currentPosition;
+ this.fileWriter = requireNonNull(fileWriter);
+ }
+
+ /**
+ * Returns the last written index.
+ *
+ * @return The last written index.
+ */
+ long getLastIndex() {
+ return lastIndex != null ? lastIndex : segment.firstIndex() - 1;
+ }
+
+ /**
+ * Returns the next index to be written.
+ *
+ * @return The next index to be written.
+ */
+ long getNextIndex() {
+ return lastIndex != null ? lastIndex + 1 : segment.firstIndex();
+ }
+
+ /**
+ * Tries to append a binary data to the journal.
+ *
+ * @param buf binary data to append
+ * @return The index of appended data, or {@code null} if segment has no space
+ */
+ Long append(final ByteBuf buf) {
+ final var length = buf.readableBytes();
+ if (length > maxEntrySize) {
+ throw new StorageException.TooLarge("Serialized entry size exceeds maximum allowed bytes ("
+ + maxEntrySize + ")");
+ }
+
+ // Store the entry index.
+ final long index = getNextIndex();
+ final int position = currentPosition;
+
+ // check space available
+ final int nextPosition = position + HEADER_BYTES + length;
+ if (nextPosition >= maxSegmentSize) {
+ LOG.trace("Not enough space for {} at {}", index, position);
+ return null;
+ }
+
+ // allocate buffer and write data
+ final var writeBuffer = fileWriter.startWrite(position, length + HEADER_BYTES).position(HEADER_BYTES);
+ writeBuffer.put(buf.nioBuffer());
+
+ // Compute the checksum for the entry.
+ final var crc32 = new CRC32();
+ crc32.update(writeBuffer.flip().position(HEADER_BYTES));
+
+ // Create a single byte[] in memory for the entire entry and write it as a batch to the underlying buffer.
+ writeBuffer.putInt(0, length).putInt(Integer.BYTES, (int) crc32.getValue());
+ fileWriter.commitWrite(position, writeBuffer.rewind());
+
+ // Update the last entry with the correct index/term/length.
+ currentPosition = nextPosition;
+ lastIndex = index;
+ this.index.index(index, position);
+
+ return index;
+ }
+
+ /**
+ * Resets the head of the segment to the given index.
+ *
+ * @param index the index to which to reset the head of the segment
+ */
+ void reset(final long index) {
+ // acquire ownership of cache and make sure reader does not see anything we've done once we're done
+ final var fileReader = fileWriter.reader();
+ try {
+ resetWithBuffer(fileReader, index);
+ } finally {
+ // Make sure reader does not see anything we've done
+ fileReader.invalidateCache();
+ }
+ }
+
+ private void resetWithBuffer(final FileReader fileReader, final long index) {
+ long nextIndex = segment.firstIndex();
+
+ // Clear the buffer indexes and acquire ownership of the buffer
+ currentPosition = JournalSegmentDescriptor.BYTES;
+ final var reader = new JournalSegmentReader(segment, fileReader, maxEntrySize);
+ reader.setPosition(JournalSegmentDescriptor.BYTES);
+
+ while (index == 0 || nextIndex <= index) {
+ final var buf = reader.readBytes(nextIndex);
+ if (buf == null) {
+ break;
+ }
+
+ lastIndex = nextIndex;
+ this.index.index(nextIndex, currentPosition);
+ nextIndex++;
+
+ // Update the current position for indexing.
+ currentPosition += HEADER_BYTES + buf.readableBytes();
+ }
+ }
+
+ /**
+ * Truncates the log to the given index.
+ *
+ * @param index The index to which to truncate the log.
+ */
+ void truncate(final long index) {
+ // If the index is greater than or equal to the last index, skip the truncate.
+ if (index >= getLastIndex()) {
+ return;
+ }
+
+ // Reset the last written
+ lastIndex = null;
+
+ // Truncate the index.
+ this.index.truncate(index);
+
+ if (index < segment.firstIndex()) {
+ // Reset the writer to the first entry.
+ currentPosition = JournalSegmentDescriptor.BYTES;
+ } else {
+ // Reset the writer to the given index.
+ reset(index);
+ }
+
+ // Zero the entry header at current channel position.
+ fileWriter.writeEmptyHeader(currentPosition);
+ }
+
+ /**
+ * Flushes written entries to disk.
+ */
+ void flush() {
+ fileWriter.flush();
+ }
+
+ /**
+ * Closes this writer.
+ */
+ void close() {
+ fileWriter.close();
+ }
+
+ /**
+ * Returns the mapped buffer underlying the segment writer, or {@code null} if the writer does not have such a
+ * buffer.
+ *
+ * @return the mapped buffer underlying the segment writer, or {@code null}.
+ */
+ @Nullable MappedByteBuffer buffer() {
+ return fileWriter.buffer();
+ }
+
+ @NonNull JournalSegmentWriter toMapped() {
+ final var newWriter = fileWriter.toMapped();
+ return newWriter == null ? this : new JournalSegmentWriter(this, newWriter);
+ }
+
+ @NonNull JournalSegmentWriter toFileChannel() {
+ final var newWriter = fileWriter.toDisk();
+ return newWriter == null ? this : new JournalSegmentWriter(this, newWriter);
+ }
+}
--- /dev/null
+/*
+ * Copyright 2014-2021 Open Networking Foundation
+ * Copyright 2023 PANTHEON.tech, s.r.o.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package io.atomix.storage.journal;
+
+import com.google.common.annotations.Beta;
+import com.google.common.annotations.VisibleForTesting;
+import io.atomix.utils.serializer.KryoJournalSerdesBuilder;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.nio.ByteBuffer;
+
+/**
+ * Support for serialization of {@link Journal} entries.
+ *
+ * @deprecated due to dependency on outdated Kryo library, {@link JournalSerializer} to be used instead.
+ */
+@Deprecated(forRemoval = true, since="9.0.3")
+public interface JournalSerdes {
+ /**
+ * Serializes given object to byte array.
+ *
+ * @param obj Object to serialize
+ * @return serialized bytes
+ */
+ byte[] serialize(Object obj);
+
+ /**
+ * Serializes given object to byte array.
+ *
+ * @param obj Object to serialize
+ * @param bufferSize maximum size of serialized bytes
+ * @return serialized bytes
+ */
+ byte[] serialize(Object obj, int bufferSize);
+
+ /**
+ * Serializes given object to byte buffer.
+ *
+ * @param obj Object to serialize
+ * @param buffer to write to
+ */
+ void serialize(Object obj, ByteBuffer buffer);
+
+ /**
+ * Serializes given object to OutputStream.
+ *
+ * @param obj Object to serialize
+ * @param stream to write to
+ */
+ void serialize(Object obj, OutputStream stream);
+
+ /**
+ * Serializes given object to OutputStream.
+ *
+ * @param obj Object to serialize
+ * @param stream to write to
+ * @param bufferSize size of the buffer in front of the stream
+ */
+ void serialize(Object obj, OutputStream stream, int bufferSize);
+
+ /**
+ * Deserializes given byte array to Object.
+ *
+ * @param bytes serialized bytes
+ * @param <T> deserialized Object type
+ * @return deserialized Object
+ */
+ <T> T deserialize(byte[] bytes);
+
+ /**
+ * Deserializes given byte buffer to Object.
+ *
+ * @param buffer input with serialized bytes
+ * @param <T> deserialized Object type
+ * @return deserialized Object
+ */
+ <T> T deserialize(final ByteBuffer buffer);
+
+ /**
+ * Deserializes given InputStream to an Object.
+ *
+ * @param stream input stream
+ * @param <T> deserialized Object type
+ * @return deserialized Object
+ */
+ <T> T deserialize(InputStream stream);
+
+ /**
+ * Deserializes given InputStream to an Object.
+ *
+ * @param stream input stream
+ * @param <T> deserialized Object type
+ * @param bufferSize size of the buffer in front of the stream
+ * @return deserialized Object
+ */
+ <T> T deserialize(final InputStream stream, final int bufferSize);
+
+ /**
+ * Creates a new {@link JournalSerdes} builder.
+ *
+ * @return builder
+ */
+ static Builder builder() {
+ return new KryoJournalSerdesBuilder();
+ }
+
+ /**
+ * Builder for {@link JournalSerdes}.
+ */
+ interface Builder {
+ /**
+ * Builds a {@link JournalSerdes} instance.
+ *
+ * @return A {@link JournalSerdes} implementation.
+ */
+ JournalSerdes build();
+
+ /**
+ * Builds a {@link JournalSerdes} instance.
+ *
+ * @param friendlyName friendly name for the namespace
+ * @return A {@link JournalSerdes} implementation.
+ */
+ JournalSerdes build(String friendlyName);
+
+ /**
+ * Registers serializer for the given set of classes.
+ * <p>
+ * When multiple classes are registered with an explicitly provided serializer, the namespace guarantees
+ * all instances will be serialized with the same type ID.
+ *
+ * @param classes list of classes to register
+ * @param serdes serializer to use for the class
+ * @return this builder
+ */
+ Builder register(EntrySerdes<?> serdes, Class<?>... classes);
+
+ /**
+ * Sets the namespace class loader.
+ *
+ * @param classLoader the namespace class loader
+ * @return this builder
+ */
+ Builder setClassLoader(ClassLoader classLoader);
+ }
+
+ /**
+ * Input data stream exposed to {@link EntrySerdes#read(EntryInput)}.
+ */
+ @Beta
+ interface EntryInput {
+
+ byte[] readBytes(int length) throws IOException;
+
+ long readLong() throws IOException;
+
+ String readString() throws IOException;
+
+ Object readObject() throws IOException;
+
+ @VisibleForTesting
+ int readVarInt() throws IOException;
+ }
+
+ /**
+ * Output data stream exposed to {@link EntrySerdes#write(EntryOutput, Object)}.
+ */
+ @Beta
+ interface EntryOutput {
+
+ void writeBytes(byte[] bytes) throws IOException;
+
+ void writeLong(long value) throws IOException;
+
+ void writeObject(Object value) throws IOException;
+
+ void writeString(String value) throws IOException;
+
+ @VisibleForTesting
+ void writeVarInt(int value) throws IOException;
+ }
+
+ /**
+ * A serializer/deserializer for an entry.
+ *
+ * @param <T> Entry type
+ */
+ interface EntrySerdes<T> {
+
+ T read(EntryInput input) throws IOException;
+
+ void write(EntryOutput output, T entry) throws IOException;
+ }
+}
--- /dev/null
+/*
+ * Copyright (c) 2024 PANTHEON.tech s.r.o. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package io.atomix.storage.journal;
+
+import io.netty.buffer.ByteBuf;
+import io.netty.buffer.ByteBufUtil;
+import io.netty.buffer.Unpooled;
+
+/**
+ * Support for serialization of {@link Journal} entries.
+ */
+public interface JournalSerializer<T> {
+
+ /**
+ * Serializes given object to byte array.
+ *
+ * @param obj Object to serialize
+ * @return serialized bytes as {@link ByteBuf}
+ */
+ ByteBuf serialize(T obj) ;
+
+ /**
+ * Deserializes given byte array to Object.
+ *
+ * @param buf serialized bytes as {@link ByteBuf}
+ * @return deserialized Object
+ */
+ T deserialize(final ByteBuf buf);
+
+ static <E> JournalSerializer<E> wrap(final JournalSerdes serdes) {
+ return new JournalSerializer<>() {
+ @Override
+ public ByteBuf serialize(final E obj) {
+ return Unpooled.wrappedBuffer(serdes.serialize(obj));
+ }
+
+ @Override
+ public E deserialize(final ByteBuf buf) {
+ return serdes.deserialize(ByteBufUtil.getBytes(buf));
+ }
+ };
+ }
+}
--- /dev/null
+/*
+ * Copyright 2017-2022 Open Networking Foundation and others. All rights reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package io.atomix.storage.journal;
+
+import org.eclipse.jdt.annotation.NonNull;
+
+/**
+ * Log writer.
+ *
+ * @author <a href="http://github.com/kuujo">Jordan Halterman</a>
+ */
+public interface JournalWriter<E> {
+ /**
+ * Returns the last written index.
+ *
+ * @return The last written index.
+ */
+ long getLastIndex();
+
+ /**
+ * Returns the next index to be written.
+ *
+ * @return The next index to be written.
+ */
+ long getNextIndex();
+
+ /**
+ * Appends an entry to the journal.
+ *
+ * @param entry The entry to append.
+ * @return The appended indexed entry.
+ */
+ <T extends E> @NonNull Indexed<T> append(T entry);
+
+ /**
+ * Commits entries up to the given index.
+ *
+ * @param index The index up to which to commit entries.
+ */
+ void commit(long index);
+
+ /**
+ * Resets the head of the journal to the given index.
+ *
+ * @param index the index to which to reset the head of the journal
+ */
+ void reset(long index);
+
+ /**
+ * Truncates the log to the given index.
+ *
+ * @param index The index to which to truncate the log.
+ */
+ void truncate(long index);
+
+ /**
+ * Flushes written entries to disk.
+ */
+ void flush();
+}
--- /dev/null
+/*
+ * Copyright (c) 2024 PANTHEON.tech, s.r.o. and others. All rights reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package io.atomix.storage.journal;
+
+import java.nio.ByteBuffer;
+import java.nio.file.Path;
+
+/**
+ * A {@link StorageLevel#MAPPED} implementation of {@link FileReader}. Operates on direct mapping of the entire file.
+ */
+final class MappedFileReader extends FileReader {
+ private final ByteBuffer buffer;
+
+ MappedFileReader(final Path path, final ByteBuffer buffer) {
+ super(path);
+ this.buffer = buffer.slice().asReadOnlyBuffer();
+ }
+
+ @Override
+ void invalidateCache() {
+ // No-op: the mapping is guaranteed to be coherent
+ }
+
+ @Override
+ ByteBuffer read(final int position, final int size) {
+ return buffer.slice(position, size);
+ }
+}
--- /dev/null
+/*
+ * Copyright (c) 2024 PANTHEON.tech, s.r.o. and others. All rights reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package io.atomix.storage.journal;
+
+import io.netty.util.internal.PlatformDependent;
+import java.io.IOException;
+import java.nio.ByteBuffer;
+import java.nio.MappedByteBuffer;
+import java.nio.channels.FileChannel;
+import java.nio.file.Path;
+import org.eclipse.jdt.annotation.NonNull;
+
+/**
+ * A {@link StorageLevel#MAPPED} {@link FileWriter}.
+ */
+final class MappedFileWriter extends FileWriter {
+ private final @NonNull MappedByteBuffer mappedBuffer;
+ private final MappedFileReader reader;
+ private final ByteBuffer buffer;
+
+ MappedFileWriter(final Path path, final FileChannel channel, final int maxSegmentSize, final int maxEntrySize) {
+ super(path, channel, maxSegmentSize, maxEntrySize);
+
+ mappedBuffer = mapBuffer(channel, maxSegmentSize);
+ buffer = mappedBuffer.slice();
+ reader = new MappedFileReader(path, mappedBuffer);
+ }
+
+ private static @NonNull MappedByteBuffer mapBuffer(final FileChannel channel, final int maxSegmentSize) {
+ try {
+ return channel.map(FileChannel.MapMode.READ_WRITE, 0, maxSegmentSize);
+ } catch (IOException e) {
+ throw new StorageException(e);
+ }
+ }
+
+ @Override
+ MappedFileReader reader() {
+ return reader;
+ }
+
+ @Override
+ MappedByteBuffer buffer() {
+ return mappedBuffer;
+ }
+
+ @Override
+ MappedFileWriter toMapped() {
+ return null;
+ }
+
+ @Override
+ DiskFileWriter toDisk() {
+ close();
+ return new DiskFileWriter(path, channel, maxSegmentSize, maxEntrySize);
+ }
+
+ @Override
+ void writeEmptyHeader(final int position) {
+ // Note: we issue a single putLong() instead of two putInt()s.
+ buffer.putLong(position, 0L);
+ }
+
+ @Override
+ ByteBuffer startWrite(final int position, final int size) {
+ return buffer.slice(position, size);
+ }
+
+ @Override
+ void commitWrite(final int position, final ByteBuffer entry) {
+ // No-op, buffer is write-through
+ }
+
+ @Override
+ void flush() {
+ mappedBuffer.force();
+ }
+
+ @Override
+ void close() {
+ flush();
+ PlatformDependent.freeDirectBuffer(mappedBuffer);
+ }
+}
--- /dev/null
+/*
+ * Copyright (c) 2024 PANTHEON.tech, s.r.o. and others. All rights reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package io.atomix.storage.journal;
+
+import java.nio.ByteBuffer;
+
+/**
+ * An {@link Indexed} entry read from {@link JournalSegment}.
+ *
+ * @param checksum The CRC32 checksum of data
+ * @param bytes Entry bytes
+ */
+record SegmentEntry(int checksum, ByteBuffer bytes) {
+ /**
+ * The size of the header, comprising of:
+ * <ul>
+ * <li>32-bit signed entry length</li>
+ * <li>32-bit unsigned CRC32 checksum</li>
+ * </li>
+ */
+ static final int HEADER_BYTES = Integer.BYTES + Integer.BYTES;
+
+ SegmentEntry {
+ if (bytes.remaining() < 1) {
+ throw new IllegalArgumentException("Invalid entry bytes " + bytes);
+ }
+ }
+}
--- /dev/null
+/*
+ * Copyright 2017-2022 Open Networking Foundation and others. All rights reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package io.atomix.storage.journal;
+
+import static com.google.common.base.Preconditions.checkArgument;
+import static com.google.common.base.Preconditions.checkState;
+import static java.util.Objects.requireNonNull;
+
+import java.io.File;
+import java.io.IOException;
+import java.io.RandomAccessFile;
+import java.nio.ByteBuffer;
+import java.nio.channels.FileChannel;
+import java.nio.file.StandardOpenOption;
+import java.util.Collection;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.TreeMap;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ConcurrentNavigableMap;
+import java.util.concurrent.ConcurrentSkipListMap;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Segmented journal.
+ */
+public final class SegmentedJournal<E> implements Journal<E> {
+ /**
+ * Returns a new Raft log builder.
+ *
+ * @return A new Raft log builder.
+ */
+ public static <E> Builder<E> builder() {
+ return new Builder<>();
+ }
+
+ private static final Logger LOG = LoggerFactory.getLogger(SegmentedJournal.class);
+ private static final int SEGMENT_BUFFER_FACTOR = 3;
+
+ private final String name;
+ private final StorageLevel storageLevel;
+ private final File directory;
+ private final JournalSerializer<E> serializer;
+ private final int maxSegmentSize;
+ private final int maxEntrySize;
+ private final int maxEntriesPerSegment;
+ private final double indexDensity;
+ private final boolean flushOnCommit;
+ private final SegmentedJournalWriter<E> writer;
+ private volatile long commitIndex;
+
+ private final ConcurrentNavigableMap<Long, JournalSegment> segments = new ConcurrentSkipListMap<>();
+ private final Collection<SegmentedJournalReader> readers = ConcurrentHashMap.newKeySet();
+ private JournalSegment currentSegment;
+
+ private volatile boolean open = true;
+
+ public SegmentedJournal(
+ String name,
+ StorageLevel storageLevel,
+ File directory,
+ JournalSerdes namespace,
+ int maxSegmentSize,
+ int maxEntrySize,
+ int maxEntriesPerSegment,
+ double indexDensity,
+ boolean flushOnCommit) {
+ this.name = requireNonNull(name, "name cannot be null");
+ this.storageLevel = requireNonNull(storageLevel, "storageLevel cannot be null");
+ this.directory = requireNonNull(directory, "directory cannot be null");
+ this.serializer = JournalSerializer.wrap(requireNonNull(namespace, "namespace cannot be null"));
+ this.maxSegmentSize = maxSegmentSize;
+ this.maxEntrySize = maxEntrySize;
+ this.maxEntriesPerSegment = maxEntriesPerSegment;
+ this.indexDensity = indexDensity;
+ this.flushOnCommit = flushOnCommit;
+ open();
+ this.writer = new SegmentedJournalWriter<>(this);
+ }
+
+ /**
+ * Returns the segment file name prefix.
+ *
+ * @return The segment file name prefix.
+ */
+ public String name() {
+ return name;
+ }
+
+ /**
+ * Returns the storage directory.
+ * <p>
+ * The storage directory is the directory to which all segments write files. Segment files for multiple logs may be
+ * stored in the storage directory, and files for each log instance will be identified by the {@code prefix} provided
+ * when the log is opened.
+ *
+ * @return The storage directory.
+ */
+ public File directory() {
+ return directory;
+ }
+
+ /**
+ * Returns the storage level.
+ * <p>
+ * The storage level dictates how entries within individual journal segments should be stored.
+ *
+ * @return The storage level.
+ */
+ public StorageLevel storageLevel() {
+ return storageLevel;
+ }
+
+ /**
+ * Returns the maximum journal segment size.
+ * <p>
+ * The maximum segment size dictates the maximum size any segment in a segment may consume in bytes.
+ *
+ * @return The maximum segment size in bytes.
+ */
+ public int maxSegmentSize() {
+ return maxSegmentSize;
+ }
+
+ /**
+ * Returns the maximum journal entry size.
+ * <p>
+ * The maximum entry size dictates the maximum size any entry in the segment may consume in bytes.
+ *
+ * @return the maximum entry size in bytes
+ */
+ public int maxEntrySize() {
+ return maxEntrySize;
+ }
+
+ /**
+ * Returns the maximum number of entries per segment.
+ * <p>
+ * The maximum entries per segment dictates the maximum number of entries that are allowed to be stored in any segment
+ * in a journal.
+ *
+ * @return The maximum number of entries per segment.
+ * @deprecated since 3.0.2
+ */
+ @Deprecated
+ public int maxEntriesPerSegment() {
+ return maxEntriesPerSegment;
+ }
+
+ /**
+ * Returns the collection of journal segments.
+ *
+ * @return the collection of journal segments
+ */
+ public Collection<JournalSegment> segments() {
+ return segments.values();
+ }
+
+ /**
+ * Returns the collection of journal segments with indexes greater than the given index.
+ *
+ * @param index the starting index
+ * @return the journal segments starting with indexes greater than or equal to the given index
+ */
+ public Collection<JournalSegment> segments(long index) {
+ return segments.tailMap(index).values();
+ }
+
+ /**
+ * Returns serializer instance.
+ *
+ * @return serializer instance
+ */
+ JournalSerializer<E> serializer() {
+ return serializer;
+ }
+
+ /**
+ * Returns the total size of the journal.
+ *
+ * @return the total size of the journal
+ */
+ public long size() {
+ return segments.values().stream()
+ .mapToLong(segment -> segment.size())
+ .sum();
+ }
+
+ @Override
+ public JournalWriter<E> writer() {
+ return writer;
+ }
+
+ @Override
+ public JournalReader<E> openReader(long index) {
+ return openReader(index, JournalReader.Mode.ALL);
+ }
+
+ /**
+ * Opens a new Raft log reader with the given reader mode.
+ *
+ * @param index The index from which to begin reading entries.
+ * @param mode The mode in which to read entries.
+ * @return The Raft log reader.
+ */
+ public JournalReader<E> openReader(long index, JournalReader.Mode mode) {
+ final var segment = getSegment(index);
+ final var reader = switch (mode) {
+ case ALL -> new SegmentedJournalReader<>(this, segment);
+ case COMMITS -> new CommitsSegmentJournalReader<>(this, segment);
+ };
+
+ // Forward reader to specified index
+ long next = reader.getNextIndex();
+ while (index > next && reader.tryAdvance()) {
+ next = reader.getNextIndex();
+ }
+
+ readers.add(reader);
+ return reader;
+ }
+
+ /**
+ * Opens the segments.
+ */
+ private synchronized void open() {
+ // Load existing log segments from disk.
+ for (JournalSegment segment : loadSegments()) {
+ segments.put(segment.descriptor().index(), segment);
+ }
+
+ // If a segment doesn't already exist, create an initial segment starting at index 1.
+ if (!segments.isEmpty()) {
+ currentSegment = segments.lastEntry().getValue();
+ } else {
+ JournalSegmentDescriptor descriptor = JournalSegmentDescriptor.builder()
+ .withId(1)
+ .withIndex(1)
+ .withMaxSegmentSize(maxSegmentSize)
+ .withMaxEntries(maxEntriesPerSegment)
+ .build();
+
+ currentSegment = createSegment(descriptor);
+ currentSegment.descriptor().update(System.currentTimeMillis());
+
+ segments.put(1L, currentSegment);
+ }
+ }
+
+ /**
+ * Asserts that the manager is open.
+ *
+ * @throws IllegalStateException if the segment manager is not open
+ */
+ private void assertOpen() {
+ checkState(currentSegment != null, "journal not open");
+ }
+
+ /**
+ * Asserts that enough disk space is available to allocate a new segment.
+ */
+ private void assertDiskSpace() {
+ if (directory().getUsableSpace() < maxSegmentSize() * SEGMENT_BUFFER_FACTOR) {
+ throw new StorageException.OutOfDiskSpace("Not enough space to allocate a new journal segment");
+ }
+ }
+
+ /**
+ * Resets the current segment, creating a new segment if necessary.
+ */
+ private synchronized void resetCurrentSegment() {
+ JournalSegment lastSegment = getLastSegment();
+ if (lastSegment != null) {
+ currentSegment = lastSegment;
+ } else {
+ JournalSegmentDescriptor descriptor = JournalSegmentDescriptor.builder()
+ .withId(1)
+ .withIndex(1)
+ .withMaxSegmentSize(maxSegmentSize)
+ .withMaxEntries(maxEntriesPerSegment)
+ .build();
+
+ currentSegment = createSegment(descriptor);
+
+ segments.put(1L, currentSegment);
+ }
+ }
+
+ /**
+ * Resets and returns the first segment in the journal.
+ *
+ * @param index the starting index of the journal
+ * @return the first segment
+ */
+ JournalSegment resetSegments(long index) {
+ assertOpen();
+
+ // If the index already equals the first segment index, skip the reset.
+ JournalSegment firstSegment = getFirstSegment();
+ if (index == firstSegment.firstIndex()) {
+ return firstSegment;
+ }
+
+ for (JournalSegment segment : segments.values()) {
+ segment.close();
+ segment.delete();
+ }
+ segments.clear();
+
+ JournalSegmentDescriptor descriptor = JournalSegmentDescriptor.builder()
+ .withId(1)
+ .withIndex(index)
+ .withMaxSegmentSize(maxSegmentSize)
+ .withMaxEntries(maxEntriesPerSegment)
+ .build();
+ currentSegment = createSegment(descriptor);
+ segments.put(index, currentSegment);
+ return currentSegment;
+ }
+
+ /**
+ * Returns the first segment in the log.
+ *
+ * @throws IllegalStateException if the segment manager is not open
+ */
+ JournalSegment getFirstSegment() {
+ assertOpen();
+ Map.Entry<Long, JournalSegment> segment = segments.firstEntry();
+ return segment != null ? segment.getValue() : null;
+ }
+
+ /**
+ * Returns the last segment in the log.
+ *
+ * @throws IllegalStateException if the segment manager is not open
+ */
+ JournalSegment getLastSegment() {
+ assertOpen();
+ Map.Entry<Long, JournalSegment> segment = segments.lastEntry();
+ return segment != null ? segment.getValue() : null;
+ }
+
+ /**
+ * Creates and returns the next segment.
+ *
+ * @return The next segment.
+ * @throws IllegalStateException if the segment manager is not open
+ */
+ synchronized JournalSegment getNextSegment() {
+ assertOpen();
+ assertDiskSpace();
+
+ JournalSegment lastSegment = getLastSegment();
+ JournalSegmentDescriptor descriptor = JournalSegmentDescriptor.builder()
+ .withId(lastSegment != null ? lastSegment.descriptor().id() + 1 : 1)
+ .withIndex(currentSegment.lastIndex() + 1)
+ .withMaxSegmentSize(maxSegmentSize)
+ .withMaxEntries(maxEntriesPerSegment)
+ .build();
+
+ currentSegment = createSegment(descriptor);
+
+ segments.put(descriptor.index(), currentSegment);
+ return currentSegment;
+ }
+
+ /**
+ * Returns the segment following the segment with the given ID.
+ *
+ * @param index The segment index with which to look up the next segment.
+ * @return The next segment for the given index.
+ */
+ JournalSegment getNextSegment(long index) {
+ Map.Entry<Long, JournalSegment> nextSegment = segments.higherEntry(index);
+ return nextSegment != null ? nextSegment.getValue() : null;
+ }
+
+ /**
+ * Returns the segment for the given index.
+ *
+ * @param index The index for which to return the segment.
+ * @throws IllegalStateException if the segment manager is not open
+ */
+ synchronized JournalSegment getSegment(long index) {
+ assertOpen();
+ // Check if the current segment contains the given index first in order to prevent an unnecessary map lookup.
+ if (currentSegment != null && index > currentSegment.firstIndex()) {
+ return currentSegment;
+ }
+
+ // If the index is in another segment, get the entry with the next lowest first index.
+ Map.Entry<Long, JournalSegment> segment = segments.floorEntry(index);
+ if (segment != null) {
+ return segment.getValue();
+ }
+ return getFirstSegment();
+ }
+
+ /**
+ * Removes a segment.
+ *
+ * @param segment The segment to remove.
+ */
+ synchronized void removeSegment(JournalSegment segment) {
+ segments.remove(segment.firstIndex());
+ segment.close();
+ segment.delete();
+ resetCurrentSegment();
+ }
+
+ /**
+ * Creates a new segment.
+ */
+ JournalSegment createSegment(JournalSegmentDescriptor descriptor) {
+ File segmentFile = JournalSegmentFile.createSegmentFile(name, directory, descriptor.id());
+
+ RandomAccessFile raf;
+ FileChannel channel;
+ try {
+ raf = new RandomAccessFile(segmentFile, "rw");
+ raf.setLength(descriptor.maxSegmentSize());
+ channel = raf.getChannel();
+ } catch (IOException e) {
+ throw new StorageException(e);
+ }
+
+ ByteBuffer buffer = ByteBuffer.allocate(JournalSegmentDescriptor.BYTES);
+ descriptor.copyTo(buffer);
+ buffer.flip();
+ try {
+ channel.write(buffer);
+ } catch (IOException e) {
+ throw new StorageException(e);
+ } finally {
+ try {
+ channel.close();
+ raf.close();
+ } catch (IOException e) {
+ }
+ }
+ JournalSegment segment = newSegment(new JournalSegmentFile(segmentFile), descriptor);
+ LOG.debug("Created segment: {}", segment);
+ return segment;
+ }
+
+ /**
+ * Creates a new segment instance.
+ *
+ * @param segmentFile The segment file.
+ * @param descriptor The segment descriptor.
+ * @return The segment instance.
+ */
+ protected JournalSegment newSegment(JournalSegmentFile segmentFile, JournalSegmentDescriptor descriptor) {
+ return new JournalSegment(segmentFile, descriptor, storageLevel, maxEntrySize, indexDensity);
+ }
+
+ /**
+ * Loads a segment.
+ */
+ private JournalSegment loadSegment(long segmentId) {
+ File segmentFile = JournalSegmentFile.createSegmentFile(name, directory, segmentId);
+ ByteBuffer buffer = ByteBuffer.allocate(JournalSegmentDescriptor.BYTES);
+ try (FileChannel channel = openChannel(segmentFile)) {
+ channel.read(buffer);
+ buffer.flip();
+ JournalSegmentDescriptor descriptor = new JournalSegmentDescriptor(buffer);
+ JournalSegment segment = newSegment(new JournalSegmentFile(segmentFile), descriptor);
+ LOG.debug("Loaded disk segment: {} ({})", descriptor.id(), segmentFile.getName());
+ return segment;
+ } catch (IOException e) {
+ throw new StorageException(e);
+ }
+ }
+
+ private FileChannel openChannel(File file) {
+ try {
+ return FileChannel.open(file.toPath(), StandardOpenOption.CREATE, StandardOpenOption.READ, StandardOpenOption.WRITE);
+ } catch (IOException e) {
+ throw new StorageException(e);
+ }
+ }
+
+ /**
+ * Loads all segments from disk.
+ *
+ * @return A collection of segments for the log.
+ */
+ protected Collection<JournalSegment> loadSegments() {
+ // Ensure log directories are created.
+ directory.mkdirs();
+
+ TreeMap<Long, JournalSegment> segments = new TreeMap<>();
+
+ // Iterate through all files in the log directory.
+ for (File file : directory.listFiles(File::isFile)) {
+
+ // If the file looks like a segment file, attempt to load the segment.
+ if (JournalSegmentFile.isSegmentFile(name, file)) {
+ JournalSegmentFile segmentFile = new JournalSegmentFile(file);
+ ByteBuffer buffer = ByteBuffer.allocate(JournalSegmentDescriptor.BYTES);
+ try (FileChannel channel = openChannel(file)) {
+ channel.read(buffer);
+ buffer.flip();
+ } catch (IOException e) {
+ throw new StorageException(e);
+ }
+
+ JournalSegmentDescriptor descriptor = new JournalSegmentDescriptor(buffer);
+
+ // Load the segment.
+ JournalSegment segment = loadSegment(descriptor.id());
+
+ // Add the segment to the segments list.
+ LOG.debug("Found segment: {} ({})", segment.descriptor().id(), segmentFile.file().getName());
+ segments.put(segment.firstIndex(), segment);
+ }
+ }
+
+ // Verify that all the segments in the log align with one another.
+ JournalSegment previousSegment = null;
+ boolean corrupted = false;
+ Iterator<Map.Entry<Long, JournalSegment>> iterator = segments.entrySet().iterator();
+ while (iterator.hasNext()) {
+ JournalSegment segment = iterator.next().getValue();
+ if (previousSegment != null && previousSegment.lastIndex() != segment.firstIndex() - 1) {
+ LOG.warn("Journal is inconsistent. {} is not aligned with prior segment {}", segment.file().file(), previousSegment.file().file());
+ corrupted = true;
+ }
+ if (corrupted) {
+ segment.close();
+ segment.delete();
+ iterator.remove();
+ }
+ previousSegment = segment;
+ }
+
+ return segments.values();
+ }
+
+ /**
+ * Resets journal readers to the given head.
+ *
+ * @param index The index at which to reset readers.
+ */
+ void resetHead(long index) {
+ for (SegmentedJournalReader<E> reader : readers) {
+ if (reader.getNextIndex() < index) {
+ reader.reset(index);
+ }
+ }
+ }
+
+ /**
+ * Resets journal readers to the given tail.
+ *
+ * @param index The index at which to reset readers.
+ */
+ void resetTail(long index) {
+ for (SegmentedJournalReader<E> reader : readers) {
+ if (reader.getNextIndex() >= index) {
+ reader.reset(index);
+ }
+ }
+ }
+
+ void closeReader(SegmentedJournalReader<E> reader) {
+ readers.remove(reader);
+ }
+
+ @Override
+ public boolean isOpen() {
+ return open;
+ }
+
+ /**
+ * Returns a boolean indicating whether a segment can be removed from the journal prior to the given index.
+ *
+ * @param index the index from which to remove segments
+ * @return indicates whether a segment can be removed from the journal
+ */
+ public boolean isCompactable(long index) {
+ Map.Entry<Long, JournalSegment> segmentEntry = segments.floorEntry(index);
+ return segmentEntry != null && segments.headMap(segmentEntry.getValue().firstIndex()).size() > 0;
+ }
+
+ /**
+ * Returns the index of the last segment in the log.
+ *
+ * @param index the compaction index
+ * @return the starting index of the last segment in the log
+ */
+ public long getCompactableIndex(long index) {
+ Map.Entry<Long, JournalSegment> segmentEntry = segments.floorEntry(index);
+ return segmentEntry != null ? segmentEntry.getValue().firstIndex() : 0;
+ }
+
+ /**
+ * Compacts the journal up to the given index.
+ * <p>
+ * The semantics of compaction are not specified by this interface.
+ *
+ * @param index The index up to which to compact the journal.
+ */
+ public void compact(long index) {
+ final var segmentEntry = segments.floorEntry(index);
+ if (segmentEntry != null) {
+ final var compactSegments = segments.headMap(segmentEntry.getValue().firstIndex());
+ if (!compactSegments.isEmpty()) {
+ LOG.debug("{} - Compacting {} segment(s)", name, compactSegments.size());
+ for (JournalSegment segment : compactSegments.values()) {
+ LOG.trace("Deleting segment: {}", segment);
+ segment.close();
+ segment.delete();
+ }
+ compactSegments.clear();
+ resetHead(segmentEntry.getValue().firstIndex());
+ }
+ }
+ }
+
+ @Override
+ public void close() {
+ segments.values().forEach(segment -> {
+ LOG.debug("Closing segment: {}", segment);
+ segment.close();
+ });
+ currentSegment = null;
+ open = false;
+ }
+
+ /**
+ * Returns whether {@code flushOnCommit} is enabled for the log.
+ *
+ * @return Indicates whether {@code flushOnCommit} is enabled for the log.
+ */
+ boolean isFlushOnCommit() {
+ return flushOnCommit;
+ }
+
+ /**
+ * Commits entries up to the given index.
+ *
+ * @param index The index up to which to commit entries.
+ */
+ void setCommitIndex(long index) {
+ this.commitIndex = index;
+ }
+
+ /**
+ * Returns the Raft log commit index.
+ *
+ * @return The Raft log commit index.
+ */
+ long getCommitIndex() {
+ return commitIndex;
+ }
+
+ /**
+ * Raft log builder.
+ */
+ public static final class Builder<E> {
+ private static final boolean DEFAULT_FLUSH_ON_COMMIT = false;
+ private static final String DEFAULT_NAME = "atomix";
+ private static final String DEFAULT_DIRECTORY = System.getProperty("user.dir");
+ private static final int DEFAULT_MAX_SEGMENT_SIZE = 1024 * 1024 * 32;
+ private static final int DEFAULT_MAX_ENTRY_SIZE = 1024 * 1024;
+ private static final int DEFAULT_MAX_ENTRIES_PER_SEGMENT = 1024 * 1024;
+ private static final double DEFAULT_INDEX_DENSITY = .005;
+
+ private String name = DEFAULT_NAME;
+ private StorageLevel storageLevel = StorageLevel.DISK;
+ private File directory = new File(DEFAULT_DIRECTORY);
+ private JournalSerdes namespace;
+ private int maxSegmentSize = DEFAULT_MAX_SEGMENT_SIZE;
+ private int maxEntrySize = DEFAULT_MAX_ENTRY_SIZE;
+ private int maxEntriesPerSegment = DEFAULT_MAX_ENTRIES_PER_SEGMENT;
+ private double indexDensity = DEFAULT_INDEX_DENSITY;
+ private boolean flushOnCommit = DEFAULT_FLUSH_ON_COMMIT;
+
+ protected Builder() {
+ }
+
+ /**
+ * Sets the storage name.
+ *
+ * @param name The storage name.
+ * @return The storage builder.
+ */
+ public Builder<E> withName(String name) {
+ this.name = requireNonNull(name, "name cannot be null");
+ return this;
+ }
+
+ /**
+ * Sets the log storage level, returning the builder for method chaining.
+ * <p>
+ * The storage level indicates how individual entries should be persisted in the journal.
+ *
+ * @param storageLevel The log storage level.
+ * @return The storage builder.
+ */
+ public Builder<E> withStorageLevel(StorageLevel storageLevel) {
+ this.storageLevel = requireNonNull(storageLevel, "storageLevel cannot be null");
+ return this;
+ }
+
+ /**
+ * Sets the log directory, returning the builder for method chaining.
+ * <p>
+ * The log will write segment files into the provided directory.
+ *
+ * @param directory The log directory.
+ * @return The storage builder.
+ * @throws NullPointerException If the {@code directory} is {@code null}
+ */
+ public Builder<E> withDirectory(String directory) {
+ return withDirectory(new File(requireNonNull(directory, "directory cannot be null")));
+ }
+
+ /**
+ * Sets the log directory, returning the builder for method chaining.
+ * <p>
+ * The log will write segment files into the provided directory.
+ *
+ * @param directory The log directory.
+ * @return The storage builder.
+ * @throws NullPointerException If the {@code directory} is {@code null}
+ */
+ public Builder<E> withDirectory(File directory) {
+ this.directory = requireNonNull(directory, "directory cannot be null");
+ return this;
+ }
+
+ /**
+ * Sets the journal namespace, returning the builder for method chaining.
+ *
+ * @param namespace The journal serializer.
+ * @return The journal builder.
+ */
+ public Builder<E> withNamespace(JournalSerdes namespace) {
+ this.namespace = requireNonNull(namespace, "namespace cannot be null");
+ return this;
+ }
+
+ /**
+ * Sets the maximum segment size in bytes, returning the builder for method chaining.
+ * <p>
+ * The maximum segment size dictates when logs should roll over to new segments. As entries are written to a segment
+ * of the log, once the size of the segment surpasses the configured maximum segment size, the log will create a new
+ * segment and append new entries to that segment.
+ * <p>
+ * By default, the maximum segment size is {@code 1024 * 1024 * 32}.
+ *
+ * @param maxSegmentSize The maximum segment size in bytes.
+ * @return The storage builder.
+ * @throws IllegalArgumentException If the {@code maxSegmentSize} is not positive
+ */
+ public Builder<E> withMaxSegmentSize(int maxSegmentSize) {
+ checkArgument(maxSegmentSize > JournalSegmentDescriptor.BYTES, "maxSegmentSize must be greater than " + JournalSegmentDescriptor.BYTES);
+ this.maxSegmentSize = maxSegmentSize;
+ return this;
+ }
+
+ /**
+ * Sets the maximum entry size in bytes, returning the builder for method chaining.
+ *
+ * @param maxEntrySize the maximum entry size in bytes
+ * @return the storage builder
+ * @throws IllegalArgumentException if the {@code maxEntrySize} is not positive
+ */
+ public Builder<E> withMaxEntrySize(int maxEntrySize) {
+ checkArgument(maxEntrySize > 0, "maxEntrySize must be positive");
+ this.maxEntrySize = maxEntrySize;
+ return this;
+ }
+
+ /**
+ * Sets the maximum number of allows entries per segment, returning the builder for method chaining.
+ * <p>
+ * The maximum entry count dictates when logs should roll over to new segments. As entries are written to a segment
+ * of the log, if the entry count in that segment meets the configured maximum entry count, the log will create a
+ * new segment and append new entries to that segment.
+ * <p>
+ * By default, the maximum entries per segment is {@code 1024 * 1024}.
+ *
+ * @param maxEntriesPerSegment The maximum number of entries allowed per segment.
+ * @return The storage builder.
+ * @throws IllegalArgumentException If the {@code maxEntriesPerSegment} not greater than the default max entries
+ * per segment
+ * @deprecated since 3.0.2
+ */
+ @Deprecated
+ public Builder<E> withMaxEntriesPerSegment(int maxEntriesPerSegment) {
+ checkArgument(maxEntriesPerSegment > 0, "max entries per segment must be positive");
+ checkArgument(maxEntriesPerSegment <= DEFAULT_MAX_ENTRIES_PER_SEGMENT,
+ "max entries per segment cannot be greater than " + DEFAULT_MAX_ENTRIES_PER_SEGMENT);
+ this.maxEntriesPerSegment = maxEntriesPerSegment;
+ return this;
+ }
+
+ /**
+ * Sets the journal index density.
+ * <p>
+ * The index density is the frequency at which the position of entries written to the journal will be recorded in an
+ * in-memory index for faster seeking.
+ *
+ * @param indexDensity the index density
+ * @return the journal builder
+ * @throws IllegalArgumentException if the density is not between 0 and 1
+ */
+ public Builder<E> withIndexDensity(double indexDensity) {
+ checkArgument(indexDensity > 0 && indexDensity < 1, "index density must be between 0 and 1");
+ this.indexDensity = indexDensity;
+ return this;
+ }
+
+ /**
+ * Enables flushing buffers to disk when entries are committed to a segment, returning the builder for method
+ * chaining.
+ * <p>
+ * When flush-on-commit is enabled, log entry buffers will be automatically flushed to disk each time an entry is
+ * committed in a given segment.
+ *
+ * @return The storage builder.
+ */
+ public Builder<E> withFlushOnCommit() {
+ return withFlushOnCommit(true);
+ }
+
+ /**
+ * Sets whether to flush buffers to disk when entries are committed to a segment, returning the builder for method
+ * chaining.
+ * <p>
+ * When flush-on-commit is enabled, log entry buffers will be automatically flushed to disk each time an entry is
+ * committed in a given segment.
+ *
+ * @param flushOnCommit Whether to flush buffers to disk when entries are committed to a segment.
+ * @return The storage builder.
+ */
+ public Builder<E> withFlushOnCommit(boolean flushOnCommit) {
+ this.flushOnCommit = flushOnCommit;
+ return this;
+ }
+
+ /**
+ * Build the {@link SegmentedJournal}.
+ *
+ * @return A new {@link SegmentedJournal}.
+ */
+ public SegmentedJournal<E> build() {
+ return new SegmentedJournal<>(
+ name,
+ storageLevel,
+ directory,
+ namespace,
+ maxSegmentSize,
+ maxEntrySize,
+ maxEntriesPerSegment,
+ indexDensity,
+ flushOnCommit);
+ }
+ }
+}
--- /dev/null
+/*
+ * Copyright 2017-2022 Open Networking Foundation and others. All rights reserved.
+ * Copyright (c) 2024 PANTHEON.tech, s.r.o.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package io.atomix.storage.journal;
+
+import static java.util.Objects.requireNonNull;
+
+import org.eclipse.jdt.annotation.NonNull;
+
+/**
+ * A {@link JournalReader} traversing all entries.
+ */
+sealed class SegmentedJournalReader<E> implements JournalReader<E> permits CommitsSegmentJournalReader {
+ // Marker non-null object for tryAdvance()
+ private static final @NonNull Object ADVANCED = new Object();
+
+ final SegmentedJournal<E> journal;
+
+ private JournalSegment currentSegment;
+ private JournalSegmentReader currentReader;
+ private long nextIndex;
+
+ SegmentedJournalReader(final SegmentedJournal<E> journal, final JournalSegment segment) {
+ this.journal = requireNonNull(journal);
+ currentSegment = requireNonNull(segment);
+ currentReader = segment.createReader();
+ nextIndex = currentSegment.firstIndex();
+ }
+
+ @Override
+ public final long getFirstIndex() {
+ return journal.getFirstSegment().firstIndex();
+ }
+
+ @Override
+ public final long getNextIndex() {
+ return nextIndex;
+ }
+
+ @Override
+ public final void reset() {
+ currentReader.close();
+
+ currentSegment = journal.getFirstSegment();
+ currentReader = currentSegment.createReader();
+ nextIndex = currentSegment.firstIndex();
+ }
+
+ @Override
+ public final void reset(final long index) {
+ // If the current segment is not open, it has been replaced. Reset the segments.
+ if (!currentSegment.isOpen()) {
+ reset();
+ }
+
+ if (index < nextIndex) {
+ rewind(index);
+ } else if (index > nextIndex) {
+ while (index > nextIndex && tryAdvance()) {
+ // Nothing else
+ }
+ } else {
+ resetCurrentReader(index);
+ }
+ }
+
+ private void resetCurrentReader(final long index) {
+ final var position = currentSegment.lookup(index - 1);
+ if (position != null) {
+ nextIndex = position.index();
+ currentReader.setPosition(position.position());
+ } else {
+ nextIndex = currentSegment.firstIndex();
+ currentReader.setPosition(JournalSegmentDescriptor.BYTES);
+ }
+ while (nextIndex < index && tryAdvance()) {
+ // Nothing else
+ }
+ }
+
+ /**
+ * Rewinds the journal to the given index.
+ */
+ private void rewind(final long index) {
+ if (currentSegment.firstIndex() >= index) {
+ JournalSegment segment = journal.getSegment(index - 1);
+ if (segment != null) {
+ currentReader.close();
+
+ currentSegment = segment;
+ currentReader = currentSegment.createReader();
+ }
+ }
+
+ resetCurrentReader(index);
+ }
+
+ @Override
+ public <T> T tryNext(final EntryMapper<E, T> mapper) {
+ final var index = nextIndex;
+ var buf = currentReader.readBytes(index);
+ if (buf == null) {
+ final var nextSegment = journal.getNextSegment(currentSegment.firstIndex());
+ if (nextSegment == null || nextSegment.firstIndex() != index) {
+ return null;
+ }
+
+ currentReader.close();
+
+ currentSegment = nextSegment;
+ currentReader = currentSegment.createReader();
+ buf = currentReader.readBytes(index);
+ if (buf == null) {
+ return null;
+ }
+ }
+
+ final var entry = journal.serializer().deserialize(buf);
+ final var ret = requireNonNull(mapper.mapEntry(index, entry, buf.readableBytes()));
+ nextIndex = index + 1;
+ return ret;
+ }
+
+ /**
+ * Try to move to the next entry.
+ *
+ * @return {@code true} if there was a next entry and this reader has moved to it
+ */
+ final boolean tryAdvance() {
+ return tryNext((index, entry, size) -> ADVANCED) != null;
+ }
+
+ @Override
+ public final void close() {
+ currentReader.close();
+ journal.closeReader(this);
+ }
+}
--- /dev/null
+/*
+ * Copyright 2017-2022 Open Networking Foundation and others. All rights reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package io.atomix.storage.journal;
+
+import static com.google.common.base.Verify.verifyNotNull;
+
+/**
+ * Raft log writer.
+ */
+final class SegmentedJournalWriter<E> implements JournalWriter<E> {
+ private final SegmentedJournal<E> journal;
+ private JournalSegment currentSegment;
+ private JournalSegmentWriter currentWriter;
+
+ SegmentedJournalWriter(SegmentedJournal<E> journal) {
+ this.journal = journal;
+ this.currentSegment = journal.getLastSegment();
+ this.currentWriter = currentSegment.acquireWriter();
+ }
+
+ @Override
+ public long getLastIndex() {
+ return currentWriter.getLastIndex();
+ }
+
+ @Override
+ public long getNextIndex() {
+ return currentWriter.getNextIndex();
+ }
+
+ @Override
+ public void reset(long index) {
+ if (index > currentSegment.firstIndex()) {
+ currentSegment.releaseWriter();
+ currentSegment = journal.resetSegments(index);
+ currentWriter = currentSegment.acquireWriter();
+ } else {
+ truncate(index - 1);
+ }
+ journal.resetHead(index);
+ }
+
+ @Override
+ public void commit(long index) {
+ if (index > journal.getCommitIndex()) {
+ journal.setCommitIndex(index);
+ if (journal.isFlushOnCommit()) {
+ flush();
+ }
+ }
+ }
+
+ @Override
+ public <T extends E> Indexed<T> append(T entry) {
+ final var bytes = journal.serializer().serialize(entry);
+ var index = currentWriter.append(bytes);
+ if (index != null) {
+ return new Indexed<>(index, entry, bytes.readableBytes());
+ }
+
+ // Slow path: we do not have enough capacity
+ currentWriter.flush();
+ currentSegment.releaseWriter();
+ currentSegment = journal.getNextSegment();
+ currentWriter = currentSegment.acquireWriter();
+ final var newIndex = verifyNotNull(currentWriter.append(bytes));
+ return new Indexed<>(newIndex, entry, bytes.readableBytes());
+ }
+
+ @Override
+ public void truncate(long index) {
+ if (index < journal.getCommitIndex()) {
+ throw new IndexOutOfBoundsException("Cannot truncate committed index: " + index);
+ }
+
+ // Delete all segments with first indexes greater than the given index.
+ while (index < currentSegment.firstIndex() && currentSegment != journal.getFirstSegment()) {
+ currentSegment.releaseWriter();
+ journal.removeSegment(currentSegment);
+ currentSegment = journal.getLastSegment();
+ currentWriter = currentSegment.acquireWriter();
+ }
+
+ // Truncate the current index.
+ currentWriter.truncate(index);
+
+ // Reset segment readers.
+ journal.resetTail(index + 1);
+ }
+
+ @Override
+ public void flush() {
+ currentWriter.flush();
+ }
+}
--- /dev/null
+/*
+ * Copyright 2015-2021 Open Networking Foundation
+ * Copyright 2023 PANTHEON.tech, s.r.o.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package io.atomix.storage.journal;
+
+/**
+ * Log exception.
+ *
+ * @author <a href="http://github.com/kuujo">Jordan Halterman</a>
+ */
+public class StorageException extends RuntimeException {
+ @java.io.Serial
+ private static final long serialVersionUID = 1L;
+
+ public StorageException() {
+ }
+
+ public StorageException(final String message) {
+ super(message);
+ }
+
+ public StorageException(final String message, final Throwable cause) {
+ super(message, cause);
+ }
+
+ public StorageException(final Throwable cause) {
+ super(cause);
+ }
+
+ /**
+ * Exception thrown when an entry being stored is too large.
+ */
+ public static class TooLarge extends StorageException {
+ @java.io.Serial
+ private static final long serialVersionUID = 1L;
+
+ public TooLarge(final String message) {
+ super(message);
+ }
+
+ public TooLarge(final String message, final Throwable cause) {
+ super(message, cause);
+ }
+ }
+
+ /**
+ * Exception thrown when storage runs out of disk space.
+ */
+ public static class OutOfDiskSpace extends StorageException {
+ @java.io.Serial
+ private static final long serialVersionUID = 1L;
+
+ public OutOfDiskSpace(final String message) {
+ super(message);
+ }
+ }
+}
--- /dev/null
+/*
+ * Copyright 2015-2022 Open Networking Foundation and others. All rights reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package io.atomix.storage.journal;
+
+/**
+ * Storage level configuration values which control how logs are stored on disk or in memory.
+ */
+public enum StorageLevel {
+ /**
+ * Stores data in a memory-mapped file.
+ */
+ MAPPED,
+ /**
+ * Stores data on disk.
+ */
+ DISK
+}
--- /dev/null
+/*
+ * Copyright 2018-2022 Open Networking Foundation and others. All rights reserved.
+ * Copyright (c) 2024 PANTHEON.tech, s.r.o.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package io.atomix.storage.journal.index;
+
+import org.eclipse.jdt.annotation.Nullable;
+
+/**
+ * Index of a particular JournalSegment.
+ */
+public interface JournalIndex {
+ /**
+ * Adds an entry for the given index at the given position.
+ *
+ * @param index the index for which to add the entry
+ * @param position the position of the given index
+ */
+ void index(long index, int position);
+
+ /**
+ * Looks up the position of the given index.
+ *
+ * @param index the index to lookup
+ * @return the position of the given index or a lesser index, or {@code null}
+ */
+ @Nullable Position lookup(long index);
+
+ /**
+ * Truncates the index to the given index and returns its position, if available.
+ *
+ * @param index the index to which to truncate the index, or {@code null}
+ * @return the position of the given index or a lesser index, or {@code null}
+ */
+ @Nullable Position truncate(long index);
+}
--- /dev/null
+/*
+ * Copyright 2018-2021 Open Networking Foundation
+ * Copyright 2023 PANTHEON.tech, s.r.o.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package io.atomix.storage.journal.index;
+
+import java.util.Map.Entry;
+import org.eclipse.jdt.annotation.Nullable;
+
+/**
+ * Journal index position.
+ */
+public record Position(long index, int position) {
+ public Position(final Entry<Long, Integer> entry) {
+ this(entry.getKey(), entry.getValue());
+ }
+
+ public static @Nullable Position ofNullable(final Entry<Long, Integer> entry) {
+ return entry == null ? null : new Position(entry);
+ }
+}
--- /dev/null
+/*
+ * Copyright 2018-2022 Open Networking Foundation and others. All rights reserved.
+ * Copyright (c) 2024 PANTHEON.tech, s.r.o.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package io.atomix.storage.journal.index;
+
+import java.util.TreeMap;
+
+/**
+ * A {@link JournalIndex} maintaining target density.
+ */
+public final class SparseJournalIndex implements JournalIndex {
+ private static final int MIN_DENSITY = 1000;
+
+ private final int density;
+ private final TreeMap<Long, Integer> positions = new TreeMap<>();
+
+ public SparseJournalIndex() {
+ density = MIN_DENSITY;
+ }
+
+ public SparseJournalIndex(final double density) {
+ this.density = (int) Math.ceil(MIN_DENSITY / (density * MIN_DENSITY));
+ }
+
+ @Override
+ public void index(final long index, final int position) {
+ if (index % density == 0) {
+ positions.put(index, position);
+ }
+ }
+
+ @Override
+ public Position lookup(final long index) {
+ return Position.ofNullable(positions.floorEntry(index));
+ }
+
+ @Override
+ public Position truncate(final long index) {
+ positions.tailMap(index, false).clear();
+ return Position.ofNullable(positions.lastEntry());
+ }
+}
--- /dev/null
+/*
+ * Copyright 2018-2022 Open Networking Foundation and others. All rights reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * Provides classes and interfaces for efficiently managing journal indexes.
+ */
+package io.atomix.storage.journal.index;
--- /dev/null
+/*
+ * Copyright 2018-2022 Open Networking Foundation and others. All rights reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * Provides a low-level journal abstraction for appending to logs and managing segmented logs.
+ */
+package io.atomix.storage.journal;
--- /dev/null
+/*
+ * Copyright 2014-2022 Open Networking Foundation and others. All rights reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package io.atomix.utils.serializer;
+
+import java.io.ByteArrayOutputStream;
+
+/**
+ * Exposes protected byte array length in {@link ByteArrayOutputStream}.
+ */
+final class BufferAwareByteArrayOutputStream extends ByteArrayOutputStream {
+
+ BufferAwareByteArrayOutputStream(int size) {
+ super(size);
+ }
+
+ int getBufferSize() {
+ return buf.length;
+ }
+}
--- /dev/null
+/*
+ * Copyright 2014-2022 Open Networking Foundation and others. All rights reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package io.atomix.utils.serializer;
+
+import com.esotericsoftware.kryo.io.Output;
+
+/**
+ * Convenience class to avoid extra object allocation and casting.
+ */
+final class ByteArrayOutput extends Output {
+
+ private final BufferAwareByteArrayOutputStream stream;
+
+ ByteArrayOutput(final int bufferSize, final int maxBufferSize, final BufferAwareByteArrayOutputStream stream) {
+ super(bufferSize, maxBufferSize);
+ super.setOutputStream(stream);
+ this.stream = stream;
+ }
+
+ BufferAwareByteArrayOutputStream getByteArrayOutputStream() {
+ return stream;
+ }
+}
--- /dev/null
+/*
+ * Copyright 2023 PANTHEON.tech, s.r.o.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package io.atomix.utils.serializer;
+
+import static java.util.Objects.requireNonNull;
+
+import com.esotericsoftware.kryo.Kryo;
+import com.esotericsoftware.kryo.KryoException;
+import com.esotericsoftware.kryo.Serializer;
+import com.esotericsoftware.kryo.io.Input;
+import com.esotericsoftware.kryo.io.Output;
+import com.esotericsoftware.kryo.serializers.JavaSerializer;
+import com.google.common.base.MoreObjects;
+import io.atomix.storage.journal.JournalSerdes.EntrySerdes;
+import java.io.IOException;
+
+final class EntrySerializer<T> extends Serializer<T> {
+ // Note: uses identity to create things in Kryo, hence we want an instance for every serdes we wrap
+ private final JavaSerializer javaSerializer = new JavaSerializer();
+ private final EntrySerdes<T> serdes;
+
+ EntrySerializer(final EntrySerdes<T> serdes) {
+ this.serdes = requireNonNull(serdes);
+ }
+
+ @Override
+ public T read(final Kryo kryo, final Input input, final Class<T> type) {
+ try {
+ return serdes.read(new KryoEntryInput(kryo, input, javaSerializer));
+ } catch (IOException e) {
+ throw new KryoException(e);
+ }
+ }
+
+ @Override
+ public void write(final Kryo kryo, final Output output, final T object) {
+ try {
+ serdes.write(new KryoEntryOutput(kryo, output, javaSerializer), object);
+ } catch (IOException e) {
+ throw new KryoException(e);
+ }
+ }
+
+ @Override
+ public String toString() {
+ return MoreObjects.toStringHelper(this).addValue(serdes).toString();
+ }
+}
--- /dev/null
+/* Copyright (c) 2008, Nathan Sweet
+ * All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following
+ * conditions are met:
+ *
+ * - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
+ * - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following
+ * disclaimer in the documentation and/or other materials provided with the distribution.
+ * - Neither the name of Esoteric Software nor the names of its contributors may be used to endorse or promote products derived
+ * from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
+ * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
+ * SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+ * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+ * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+ * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
+
+package io.atomix.utils.serializer;
+
+import com.esotericsoftware.kryo.io.ByteBufferInput;
+import java.nio.ByteBuffer;
+
+/**
+ * A Kryo-4.0.3 ByteBufferInput adapted to deal with
+ * <a href="https://github.com/EsotericSoftware/kryo/issues/505">issue 505</a>.
+ *
+ * @author Roman Levenstein <romixlev@gmail.com>
+ * @author Robert Varga
+ */
+public final class Kryo505ByteBufferInput extends ByteBufferInput {
+ Kryo505ByteBufferInput (ByteBuffer buffer) {
+ super(buffer);
+ }
+
+ @Override
+ public String readString () {
+ niobuffer.position(position);
+ int available = require(1);
+ position++;
+ int b = niobuffer.get();
+ if ((b & 0x80) == 0) return readAscii(); // ASCII.
+ // Null, empty, or UTF8.
+ int charCount = available >= 5 ? readUtf8Length(b) : readUtf8Length_slow(b);
+ switch (charCount) {
+ case 0:
+ return null;
+ case 1:
+ return "";
+ }
+ charCount--;
+ if (chars.length < charCount) chars = new char[charCount];
+ readUtf8(charCount);
+ return new String(chars, 0, charCount);
+ }
+
+ private int readUtf8Length (int b) {
+ int result = b & 0x3F; // Mask all but first 6 bits.
+ if ((b & 0x40) != 0) { // Bit 7 means another byte, bit 8 means UTF8.
+ position++;
+ b = niobuffer.get();
+ result |= (b & 0x7F) << 6;
+ if ((b & 0x80) != 0) {
+ position++;
+ b = niobuffer.get();
+ result |= (b & 0x7F) << 13;
+ if ((b & 0x80) != 0) {
+ position++;
+ b = niobuffer.get();
+ result |= (b & 0x7F) << 20;
+ if ((b & 0x80) != 0) {
+ position++;
+ b = niobuffer.get();
+ result |= (b & 0x7F) << 27;
+ }
+ }
+ }
+ }
+ return result;
+ }
+
+ private int readUtf8Length_slow (int b) {
+ int result = b & 0x3F; // Mask all but first 6 bits.
+ if ((b & 0x40) != 0) { // Bit 7 means another byte, bit 8 means UTF8.
+ require(1);
+ position++;
+ b = niobuffer.get();
+ result |= (b & 0x7F) << 6;
+ if ((b & 0x80) != 0) {
+ require(1);
+ position++;
+ b = niobuffer.get();
+ result |= (b & 0x7F) << 13;
+ if ((b & 0x80) != 0) {
+ require(1);
+ position++;
+ b = niobuffer.get();
+ result |= (b & 0x7F) << 20;
+ if ((b & 0x80) != 0) {
+ require(1);
+ position++;
+ b = niobuffer.get();
+ result |= (b & 0x7F) << 27;
+ }
+ }
+ }
+ }
+ return result;
+ }
+
+ private void readUtf8 (int charCount) {
+ char[] chars = this.chars;
+ // Try to read 7 bit ASCII chars.
+ int charIndex = 0;
+ int count = Math.min(require(1), charCount);
+ int position = this.position;
+ int b;
+ while (charIndex < count) {
+ position++;
+ b = niobuffer.get();
+ if (b < 0) {
+ position--;
+ break;
+ }
+ chars[charIndex++] = (char)b;
+ }
+ this.position = position;
+ // If buffer didn't hold all chars or any were not ASCII, use slow path for remainder.
+ if (charIndex < charCount) {
+ niobuffer.position(position);
+ readUtf8_slow(charCount, charIndex);
+ }
+ }
+
+ private void readUtf8_slow (int charCount, int charIndex) {
+ char[] chars = this.chars;
+ while (charIndex < charCount) {
+ if (position == limit) require(1);
+ position++;
+ int b = niobuffer.get() & 0xFF;
+ switch (b >> 4) {
+ case 0:
+ case 1:
+ case 2:
+ case 3:
+ case 4:
+ case 5:
+ case 6:
+ case 7:
+ chars[charIndex] = (char)b;
+ break;
+ case 12:
+ case 13:
+ if (position == limit) require(1);
+ position++;
+ chars[charIndex] = (char)((b & 0x1F) << 6 | niobuffer.get() & 0x3F);
+ break;
+ case 14:
+ require(2);
+ position += 2;
+ int b2 = niobuffer.get();
+ int b3 = niobuffer.get();
+ chars[charIndex] = (char)((b & 0x0F) << 12 | (b2 & 0x3F) << 6 | b3 & 0x3F);
+ break;
+ }
+ charIndex++;
+ }
+ }
+
+ private String readAscii () {
+ int end = position;
+ int start = end - 1;
+ int limit = this.limit;
+ int b;
+ do {
+ if (end == limit) return readAscii_slow();
+ end++;
+ b = niobuffer.get();
+ } while ((b & 0x80) == 0);
+ int count = end - start;
+ byte[] tmp = new byte[count];
+ niobuffer.position(start);
+ niobuffer.get(tmp);
+ tmp[count - 1] &= 0x7F; // Mask end of ascii bit.
+ String value = new String(tmp, 0, 0, count);
+ position = end;
+ niobuffer.position(position);
+ return value;
+ }
+
+ private String readAscii_slow () {
+ position--; // Re-read the first byte.
+ // Copy chars currently in buffer.
+ int charCount = limit - position;
+ if (charCount > chars.length) chars = new char[charCount * 2];
+ char[] chars = this.chars;
+ for (int i = position, ii = 0, n = limit; i < n; i++, ii++)
+ chars[ii] = (char)niobuffer.get(i);
+ position = limit;
+ // Copy additional chars one by one.
+ while (true) {
+ require(1);
+ position++;
+ int b = niobuffer.get();
+ if (charCount == chars.length) {
+ char[] newChars = new char[charCount * 2];
+ System.arraycopy(chars, 0, newChars, 0, charCount);
+ chars = newChars;
+ this.chars = newChars;
+ }
+ if ((b & 0x80) == 0x80) {
+ chars[charCount++] = (char)(b & 0x7F);
+ break;
+ }
+ chars[charCount++] = (char)b;
+ }
+ return new String(chars, 0, charCount);
+ }
+
+ @Override
+ public StringBuilder readStringBuilder () {
+ niobuffer.position(position);
+ int available = require(1);
+ position++;
+ int b = niobuffer.get();
+ if ((b & 0x80) == 0) return new StringBuilder(readAscii()); // ASCII.
+ // Null, empty, or UTF8.
+ int charCount = available >= 5 ? readUtf8Length(b) : readUtf8Length_slow(b);
+ switch (charCount) {
+ case 0:
+ return null;
+ case 1:
+ return new StringBuilder("");
+ }
+ charCount--;
+ if (chars.length < charCount) chars = new char[charCount];
+ readUtf8(charCount);
+ StringBuilder builder = new StringBuilder(charCount);
+ builder.append(chars, 0, charCount);
+ return builder;
+ }
+}
--- /dev/null
+/*
+ * Copyright 2023 PANTHEON.tech, s.r.o.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package io.atomix.utils.serializer;
+
+import static java.util.Objects.requireNonNull;
+
+import com.esotericsoftware.kryo.Kryo;
+import com.esotericsoftware.kryo.KryoException;
+import com.esotericsoftware.kryo.io.Input;
+import com.esotericsoftware.kryo.serializers.JavaSerializer;
+import io.atomix.storage.journal.JournalSerdes.EntryInput;
+import java.io.IOException;
+
+final class KryoEntryInput implements EntryInput {
+ private final Kryo kryo;
+ private final Input input;
+ private final JavaSerializer javaSerializer;
+
+ KryoEntryInput(final Kryo kryo, final Input input, final JavaSerializer javaSerializer) {
+ this.kryo = requireNonNull(kryo);
+ this.input = requireNonNull(input);
+ this.javaSerializer = requireNonNull(javaSerializer);
+ }
+
+ @Override
+ public byte[] readBytes(final int length) throws IOException {
+ try {
+ return input.readBytes(length);
+ } catch (KryoException e) {
+ throw new IOException(e);
+ }
+ }
+
+ @Override
+ public long readLong() throws IOException {
+ try {
+ return input.readLong(false);
+ } catch (KryoException e) {
+ throw new IOException(e);
+ }
+ }
+
+ @Override
+ public Object readObject() throws IOException {
+ try {
+ return javaSerializer.read(kryo, input, null);
+ } catch (KryoException e) {
+ throw new IOException(e);
+ }
+ }
+
+ @Override
+ public String readString() throws IOException {
+ try {
+ return input.readString();
+ } catch (KryoException e) {
+ throw new IOException(e);
+ }
+ }
+
+ @Override
+ public int readVarInt() throws IOException {
+ try {
+ return input.readVarInt(true);
+ } catch (KryoException e) {
+ throw new IOException(e);
+ }
+ }
+}
--- /dev/null
+/*
+ * Copyright 2023 PANTHEON.tech, s.r.o.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package io.atomix.utils.serializer;
+
+import static java.util.Objects.requireNonNull;
+
+import com.esotericsoftware.kryo.Kryo;
+import com.esotericsoftware.kryo.KryoException;
+import com.esotericsoftware.kryo.io.Output;
+import com.esotericsoftware.kryo.serializers.JavaSerializer;
+import io.atomix.storage.journal.JournalSerdes.EntryOutput;
+import java.io.IOException;
+
+final class KryoEntryOutput implements EntryOutput {
+ private final Kryo kryo;
+ private final Output output;
+ private final JavaSerializer javaSerializer;
+
+ KryoEntryOutput(final Kryo kryo, final Output output, final JavaSerializer javaSerializer) {
+ this.kryo = requireNonNull(kryo);
+ this.output = requireNonNull(output);
+ this.javaSerializer = requireNonNull(javaSerializer);
+ }
+
+ @Override
+ public void writeBytes(final byte[] bytes) throws IOException {
+ try {
+ output.writeBytes(bytes);
+ } catch (KryoException e) {
+ throw new IOException(e);
+ }
+ }
+
+ @Override
+ public void writeLong(final long value) throws IOException {
+ try {
+ output.writeLong(value, false);
+ } catch (KryoException e) {
+ throw new IOException(e);
+ }
+ }
+
+ @Override
+ public void writeObject(final Object value) throws IOException {
+ try {
+ javaSerializer.write(kryo, output, value);
+ } catch (KryoException e) {
+ throw new IOException(e);
+ }
+ }
+
+ @Override
+ public void writeString(final String value) throws IOException {
+ try {
+ output.writeString(value);
+ } catch (KryoException e) {
+ throw new IOException(e);
+ }
+ }
+
+ @Override
+ public void writeVarInt(final int value) throws IOException {
+ try {
+ output.writeVarInt(value, true);
+ } catch (KryoException e) {
+ throw new IOException(e);
+ }
+ }
+}
--- /dev/null
+/*
+ * Copyright 2014-2022 Open Networking Foundation and others. All rights reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package io.atomix.utils.serializer;
+
+import java.lang.ref.SoftReference;
+import java.util.concurrent.ConcurrentLinkedQueue;
+import java.util.function.Function;
+
+abstract class KryoIOPool<T> {
+
+ private final ConcurrentLinkedQueue<SoftReference<T>> queue = new ConcurrentLinkedQueue<>();
+
+ private T borrow(final int bufferSize) {
+ T element;
+ SoftReference<T> reference;
+ while ((reference = queue.poll()) != null) {
+ if ((element = reference.get()) != null) {
+ return element;
+ }
+ }
+ return create(bufferSize);
+ }
+
+ protected abstract T create(final int bufferSize);
+
+ protected abstract boolean recycle(final T element);
+
+ <R> R run(final Function<T, R> function, final int bufferSize) {
+ final T element = borrow(bufferSize);
+ try {
+ return function.apply(element);
+ } finally {
+ if (recycle(element)) {
+ queue.offer(new SoftReference<>(element));
+ }
+ }
+ }
+}
--- /dev/null
+/*
+ * Copyright 2014-2022 Open Networking Foundation and others. All rights reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package io.atomix.utils.serializer;
+
+import com.esotericsoftware.kryo.io.Input;
+
+class KryoInputPool extends KryoIOPool<Input> {
+
+ static final int MAX_POOLED_BUFFER_SIZE = 512 * 1024;
+
+ @Override
+ protected Input create(int bufferSize) {
+ return new Input(bufferSize);
+ }
+
+ @Override
+ protected boolean recycle(Input input) {
+ if (input.getBuffer().length < MAX_POOLED_BUFFER_SIZE) {
+ input.setInputStream(null);
+ return true;
+ }
+ return false; // discard
+ }
+}
--- /dev/null
+/*
+ * Copyright 2014-2021 Open Networking Foundation
+ * Copyright 2023 PANTHEON.tech, s.r.o.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package io.atomix.utils.serializer;
+
+import static java.util.Objects.requireNonNull;
+
+import com.esotericsoftware.kryo.Kryo;
+import com.esotericsoftware.kryo.Registration;
+import com.esotericsoftware.kryo.Serializer;
+import com.esotericsoftware.kryo.io.ByteBufferInput;
+import com.esotericsoftware.kryo.io.ByteBufferOutput;
+import com.esotericsoftware.kryo.pool.KryoCallback;
+import com.esotericsoftware.kryo.pool.KryoFactory;
+import com.esotericsoftware.kryo.pool.KryoPool;
+import com.google.common.base.MoreObjects;
+import io.atomix.storage.journal.JournalSerdes;
+import java.io.ByteArrayInputStream;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.nio.ByteBuffer;
+import java.util.Arrays;
+import java.util.List;
+import org.objenesis.strategy.StdInstantiatorStrategy;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Pool of Kryo instances, with classes pre-registered.
+ */
+final class KryoJournalSerdes implements JournalSerdes, KryoFactory, KryoPool {
+ /**
+ * Default buffer size used for serialization.
+ *
+ * @see #serialize(Object)
+ */
+ private static final int DEFAULT_BUFFER_SIZE = 4096;
+
+ /**
+ * Smallest ID free to use for user defined registrations.
+ */
+ private static final int INITIAL_ID = 16;
+
+ static final String NO_NAME = "(no name)";
+
+ private static final Logger LOGGER = LoggerFactory.getLogger(KryoJournalSerdes.class);
+
+ private final KryoPool kryoPool = new KryoPool.Builder(this).softReferences().build();
+
+ private final KryoOutputPool kryoOutputPool = new KryoOutputPool();
+ private final KryoInputPool kryoInputPool = new KryoInputPool();
+
+ private final List<RegisteredType> registeredTypes;
+ private final ClassLoader classLoader;
+ private final String friendlyName;
+
+ /**
+ * Creates a Kryo instance pool.
+ *
+ * @param registeredTypes types to register
+ * @param registrationRequired whether registration is required
+ * @param friendlyName friendly name for the namespace
+ */
+ KryoJournalSerdes(
+ final List<RegisteredType> registeredTypes,
+ final ClassLoader classLoader,
+ final String friendlyName) {
+ this.registeredTypes = List.copyOf(registeredTypes);
+ this.classLoader = requireNonNull(classLoader);
+ this.friendlyName = requireNonNull(friendlyName);
+
+ // Pre-populate with a single instance
+ release(create());
+ }
+
+ @Override
+ public byte[] serialize(final Object obj) {
+ return serialize(obj, DEFAULT_BUFFER_SIZE);
+ }
+
+ @Override
+ public byte[] serialize(final Object obj, final int bufferSize) {
+ return kryoOutputPool.run(output -> kryoPool.run(kryo -> {
+ kryo.writeClassAndObject(output, obj);
+ output.flush();
+ return output.getByteArrayOutputStream().toByteArray();
+ }), bufferSize);
+ }
+
+ @Override
+ public void serialize(final Object obj, final ByteBuffer buffer) {
+ ByteBufferOutput out = new ByteBufferOutput(buffer);
+ Kryo kryo = borrow();
+ try {
+ kryo.writeClassAndObject(out, obj);
+ out.flush();
+ } finally {
+ release(kryo);
+ }
+ }
+
+ @Override
+ public void serialize(final Object obj, final OutputStream stream) {
+ serialize(obj, stream, DEFAULT_BUFFER_SIZE);
+ }
+
+ @Override
+ public void serialize(final Object obj, final OutputStream stream, final int bufferSize) {
+ ByteBufferOutput out = new ByteBufferOutput(stream, bufferSize);
+ Kryo kryo = borrow();
+ try {
+ kryo.writeClassAndObject(out, obj);
+ out.flush();
+ } finally {
+ release(kryo);
+ }
+ }
+
+ @Override
+ public <T> T deserialize(final byte[] bytes) {
+ return kryoInputPool.run(input -> {
+ input.setInputStream(new ByteArrayInputStream(bytes));
+ return kryoPool.run(kryo -> {
+ @SuppressWarnings("unchecked")
+ T obj = (T) kryo.readClassAndObject(input);
+ return obj;
+ });
+ }, DEFAULT_BUFFER_SIZE);
+ }
+
+ @Override
+ public <T> T deserialize(final ByteBuffer buffer) {
+ Kryo kryo = borrow();
+ try {
+ @SuppressWarnings("unchecked")
+ T obj = (T) kryo.readClassAndObject(new Kryo505ByteBufferInput(buffer));
+ return obj;
+ } finally {
+ release(kryo);
+ }
+ }
+
+ @Override
+ public <T> T deserialize(final InputStream stream) {
+ return deserialize(stream, DEFAULT_BUFFER_SIZE);
+ }
+
+ @Override
+ public <T> T deserialize(final InputStream stream, final int bufferSize) {
+ Kryo kryo = borrow();
+ try {
+ @SuppressWarnings("unchecked")
+ T obj = (T) kryo.readClassAndObject(new ByteBufferInput(stream, bufferSize));
+ return obj;
+ } finally {
+ release(kryo);
+ }
+ }
+
+ /**
+ * Creates a Kryo instance.
+ *
+ * @return Kryo instance
+ */
+ @Override
+ public Kryo create() {
+ LOGGER.trace("Creating Kryo instance for {}", this);
+ Kryo kryo = new Kryo();
+ kryo.setClassLoader(classLoader);
+ kryo.setRegistrationRequired(true);
+
+ // TODO rethink whether we want to use StdInstantiatorStrategy
+ kryo.setInstantiatorStrategy(
+ new Kryo.DefaultInstantiatorStrategy(new StdInstantiatorStrategy()));
+
+ int id = INITIAL_ID;
+ for (RegisteredType registeredType : registeredTypes) {
+ register(kryo, registeredType.types(), registeredType.serializer(), id++);
+ }
+ return kryo;
+ }
+
+ /**
+ * Register {@code type} and {@code serializer} to {@code kryo} instance.
+ *
+ * @param kryo Kryo instance
+ * @param types types to register
+ * @param serializer Specific serializer to register or null to use default.
+ * @param id type registration id to use
+ */
+ private void register(final Kryo kryo, final Class<?>[] types, final Serializer<?> serializer, final int id) {
+ Registration existing = kryo.getRegistration(id);
+ if (existing != null) {
+ boolean matches = false;
+ for (Class<?> type : types) {
+ if (existing.getType() == type) {
+ matches = true;
+ break;
+ }
+ }
+
+ if (!matches) {
+ LOGGER.error("{}: Failed to register {} as {}, {} was already registered.",
+ friendlyName, types, id, existing.getType());
+
+ throw new IllegalStateException(String.format(
+ "Failed to register %s as %s, %s was already registered.",
+ Arrays.toString(types), id, existing.getType()));
+ }
+ // falling through to register call for now.
+ // Consider skipping, if there's reasonable
+ // way to compare serializer equivalence.
+ }
+
+ for (Class<?> type : types) {
+ Registration r = null;
+ if (serializer == null) {
+ r = kryo.register(type, id);
+ } else if (type.isInterface()) {
+ kryo.addDefaultSerializer(type, serializer);
+ } else {
+ r = kryo.register(type, serializer, id);
+ }
+ if (r != null) {
+ if (r.getId() != id) {
+ LOGGER.debug("{}: {} already registered as {}. Skipping {}.",
+ friendlyName, r.getType(), r.getId(), id);
+ }
+ LOGGER.trace("{} registered as {}", r.getType(), r.getId());
+ }
+ }
+ }
+
+ @Override
+ public Kryo borrow() {
+ return kryoPool.borrow();
+ }
+
+ @Override
+ public void release(final Kryo kryo) {
+ kryoPool.release(kryo);
+ }
+
+ @Override
+ public <T> T run(final KryoCallback<T> callback) {
+ return kryoPool.run(callback);
+ }
+
+ @Override
+ public String toString() {
+ if (!NO_NAME.equals(friendlyName)) {
+ return MoreObjects.toStringHelper(getClass())
+ .omitNullValues()
+ .add("friendlyName", friendlyName)
+ // omit lengthy detail, when there's a name
+ .toString();
+ }
+ return MoreObjects.toStringHelper(getClass()).add("registeredTypes", registeredTypes).toString();
+ }
+}
--- /dev/null
+/*
+ * Copyright 2014-2021 Open Networking Foundation
+ * Copyright 2023 PANTHEON.tech, s.r.o.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package io.atomix.utils.serializer;
+
+import static com.google.common.base.Preconditions.checkState;
+import static java.util.Objects.requireNonNull;
+
+import io.atomix.storage.journal.JournalSerdes;
+import io.atomix.storage.journal.JournalSerdes.Builder;
+import io.atomix.storage.journal.JournalSerdes.EntrySerdes;
+import java.util.ArrayList;
+import java.util.List;
+
+public final class KryoJournalSerdesBuilder implements Builder {
+ private final List<RegisteredType> types = new ArrayList<>();
+ private ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
+
+ @Override
+ public KryoJournalSerdesBuilder register(final EntrySerdes<?> serdes, final Class<?>... classes) {
+ types.add(new RegisteredType(new EntrySerializer<>(serdes), classes));
+ return this;
+ }
+
+ @Override
+ public KryoJournalSerdesBuilder setClassLoader(final ClassLoader classLoader) {
+ this.classLoader = requireNonNull(classLoader);
+ return this;
+ }
+
+ @Override
+ public JournalSerdes build() {
+ return build(KryoJournalSerdes.NO_NAME);
+ }
+
+ @Override
+ public JournalSerdes build(final String friendlyName) {
+ checkState(!types.isEmpty(), "No serializers registered");
+ return new KryoJournalSerdes(types, classLoader, friendlyName);
+ }
+}
\ No newline at end of file
--- /dev/null
+/*
+ * Copyright 2014-2022 Open Networking Foundation and others. All rights reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package io.atomix.utils.serializer;
+
+class KryoOutputPool extends KryoIOPool<ByteArrayOutput> {
+
+ private static final int MAX_BUFFER_SIZE = 768 * 1024;
+ static final int MAX_POOLED_BUFFER_SIZE = 512 * 1024;
+
+ @Override
+ protected ByteArrayOutput create(int bufferSize) {
+ return new ByteArrayOutput(bufferSize, MAX_BUFFER_SIZE, new BufferAwareByteArrayOutputStream(bufferSize));
+ }
+
+ @Override
+ protected boolean recycle(ByteArrayOutput output) {
+ if (output.getByteArrayOutputStream().getBufferSize() < MAX_POOLED_BUFFER_SIZE) {
+ output.getByteArrayOutputStream().reset();
+ output.clear();
+ return true;
+ }
+ return false; // discard
+ }
+}
--- /dev/null
+/*
+ * Copyright 2023 PANTHEON.tech, s.r.o.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package io.atomix.utils.serializer;
+
+import static java.util.Objects.requireNonNull;
+
+record RegisteredType(EntrySerializer<?> serializer, Class<?>[] types) {
+ RegisteredType {
+ requireNonNull(serializer);
+ requireNonNull(types);
+ }
+}
--- /dev/null
+/*
+ * Copyright 2018-2022 Open Networking Foundation and others. All rights reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * Provides classes and interfaces for binary serialization.
+ */
+package io.atomix.utils.serializer;
--- /dev/null
+/*
+ * Copyright 2017-2021 Open Networking Foundation
+ * Copyright 2023 PANTHEON.tech, s.r.o.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package io.atomix.storage.journal;
+
+import static org.junit.Assert.assertArrayEquals;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
+
+import java.io.IOException;
+import java.nio.file.FileVisitResult;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.nio.file.SimpleFileVisitor;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.util.ArrayList;
+import java.util.List;
+import org.eclipse.jdt.annotation.NonNull;
+import org.eclipse.jdt.annotation.Nullable;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.Parameterized;
+
+/**
+ * Base journal test.
+ *
+ * @author <a href="http://github.com/kuujo">Jordan Halterman</a>
+ */
+@RunWith(Parameterized.class)
+public abstract class AbstractJournalTest {
+ private static final JournalSerdes NAMESPACE = JournalSerdes.builder()
+ .register(new TestEntrySerdes(), TestEntry.class)
+ .register(new ByteArraySerdes(), byte[].class)
+ .build();
+
+ protected static final TestEntry ENTRY = new TestEntry(32);
+ private static final Path PATH = Paths.get("target/test-logs/");
+
+ private final StorageLevel storageLevel;
+ private final int maxSegmentSize;
+ protected final int entriesPerSegment;
+
+ protected AbstractJournalTest(final StorageLevel storageLevel, final int maxSegmentSize) {
+ this.storageLevel = storageLevel;
+ this.maxSegmentSize = maxSegmentSize;
+ int entryLength = NAMESPACE.serialize(ENTRY).length + 8;
+ entriesPerSegment = (maxSegmentSize - 64) / entryLength;
+ }
+
+ @Parameterized.Parameters
+ public static List<Object[]> primeNumbers() {
+ var runs = new ArrayList<Object[]>();
+ for (int i = 1; i <= 10; i++) {
+ for (int j = 1; j <= 10; j++) {
+ runs.add(new Object[] { 64 + i * (NAMESPACE.serialize(ENTRY).length + 8) + j });
+ }
+ }
+ return runs;
+ }
+
+ protected SegmentedJournal<TestEntry> createJournal() {
+ return SegmentedJournal.<TestEntry>builder()
+ .withName("test")
+ .withDirectory(PATH.toFile())
+ .withNamespace(NAMESPACE)
+ .withStorageLevel(storageLevel)
+ .withMaxSegmentSize(maxSegmentSize)
+ .withIndexDensity(.2)
+ .build();
+ }
+
+ @Test
+ public void testCloseMultipleTimes() {
+ // given
+ final Journal<TestEntry> journal = createJournal();
+
+ // when
+ journal.close();
+
+ // then
+ journal.close();
+ }
+
+ @Test
+ public void testWriteRead() throws Exception {
+ try (Journal<TestEntry> journal = createJournal()) {
+ JournalWriter<TestEntry> writer = journal.writer();
+ JournalReader<TestEntry> reader = journal.openReader(1);
+
+ // Append a couple entries.
+ assertEquals(1, writer.getNextIndex());
+ var indexed = writer.append(ENTRY);
+ assertEquals(1, indexed.index());
+
+ assertEquals(2, writer.getNextIndex());
+ writer.append(ENTRY);
+ reader.reset(2);
+ indexed = assertNext(reader);
+ assertEquals(2, indexed.index());
+ assertNoNext(reader);
+
+ // Test reading an entry
+ reader.reset();
+ var entry1 = assertNext(reader);
+ assertEquals(1, entry1.index());
+
+ // Test reading a second entry
+ assertEquals(2, reader.getNextIndex());
+ var entry2 = assertNext(reader);
+ assertEquals(2, entry2.index());
+ assertEquals(3, reader.getNextIndex());
+ assertNoNext(reader);
+
+ // Test opening a new reader and reading from the journal.
+ reader = journal.openReader(1);
+ entry1 = assertNext(reader);
+ assertEquals(1, entry1.index());
+
+ assertEquals(2, reader.getNextIndex());
+ entry2 = assertNext(reader);
+ assertEquals(2, entry2.index());
+ assertNoNext(reader);
+
+ // Reset the reader.
+ reader.reset();
+
+ // Test opening a new reader and reading from the journal.
+ reader = journal.openReader(1);
+ entry1 = assertNext(reader);
+ assertEquals(1, entry1.index());
+
+ assertEquals(2, reader.getNextIndex());
+ entry2 = assertNext(reader);
+ assertEquals(2, entry2.index());
+ assertNoNext(reader);
+
+ // Truncate the journal and write a different entry.
+ writer.truncate(1);
+ assertEquals(2, writer.getNextIndex());
+ writer.append(ENTRY);
+ reader.reset(2);
+ indexed = assertNext(reader);
+ assertEquals(2, indexed.index());
+
+ // Reset the reader to a specific index and read the last entry again.
+ reader.reset(2);
+
+ assertEquals(2, reader.getNextIndex());
+ entry2 = assertNext(reader);
+ assertEquals(2, entry2.index());
+ assertNoNext(reader);
+ }
+ }
+
+ @Test
+ public void testResetTruncateZero() throws Exception {
+ try (SegmentedJournal<TestEntry> journal = createJournal()) {
+ JournalWriter<TestEntry> writer = journal.writer();
+ JournalReader<TestEntry> reader = journal.openReader(1);
+
+ assertEquals(0, writer.getLastIndex());
+ writer.append(ENTRY);
+ writer.append(ENTRY);
+ writer.reset(1);
+ assertEquals(0, writer.getLastIndex());
+ writer.append(ENTRY);
+
+ var indexed = assertNext(reader);
+ assertEquals(1, indexed.index());
+ writer.reset(1);
+ assertEquals(0, writer.getLastIndex());
+ indexed = writer.append(ENTRY);
+ assertEquals(1, writer.getLastIndex());
+ assertEquals(1, indexed.index());
+
+ indexed = assertNext(reader);
+ assertEquals(1, indexed.index());
+
+ writer.truncate(0);
+ assertEquals(0, writer.getLastIndex());
+ indexed = writer.append(ENTRY);
+ assertEquals(1, writer.getLastIndex());
+ assertEquals(1, indexed.index());
+
+ indexed = assertNext(reader);
+ assertEquals(1, indexed.index());
+ }
+ }
+
+ @Test
+ public void testTruncateRead() throws Exception {
+ int i = 10;
+ try (Journal<TestEntry> journal = createJournal()) {
+ JournalWriter<TestEntry> writer = journal.writer();
+ JournalReader<TestEntry> reader = journal.openReader(1);
+
+ for (int j = 1; j <= i; j++) {
+ assertEquals(j, writer.append(new TestEntry(32)).index());
+ }
+
+ for (int j = 1; j <= i - 2; j++) {
+ assertEquals(j, assertNext(reader).index());
+ }
+
+ writer.truncate(i - 2);
+
+ assertNoNext(reader);
+ assertEquals(i - 1, writer.append(new TestEntry(32)).index());
+ assertEquals(i, writer.append(new TestEntry(32)).index());
+
+ var entry = assertNext(reader);
+ assertEquals(i - 1, entry.index());
+ entry = assertNext(reader);
+ assertNotNull(entry);
+ assertEquals(i, entry.index());
+ }
+ }
+
+ @Test
+ public void testWriteReadEntries() throws Exception {
+ try (Journal<TestEntry> journal = createJournal()) {
+ JournalWriter<TestEntry> writer = journal.writer();
+ JournalReader<TestEntry> reader = journal.openReader(1);
+
+ for (int i = 1; i <= entriesPerSegment * 5; i++) {
+ writer.append(ENTRY);
+ var entry = assertNext(reader);
+ assertEquals(i, entry.index());
+ assertArrayEquals(ENTRY.bytes(), entry.entry().bytes());
+ reader.reset(i);
+ entry = assertNext(reader);
+ assertEquals(i, entry.index());
+ assertArrayEquals(ENTRY.bytes(), entry.entry().bytes());
+
+ if (i > 6) {
+ reader.reset(i - 5);
+ assertEquals(i - 5, reader.getNextIndex());
+ assertNext(reader);
+ reader.reset(i + 1);
+ }
+
+ writer.truncate(i - 1);
+ writer.append(ENTRY);
+
+ assertNext(reader);
+ reader.reset(i);
+ entry = assertNext(reader);
+ assertEquals(i, entry.index());
+ assertArrayEquals(ENTRY.bytes(), entry.entry().bytes());
+ }
+ }
+ }
+
+ @Test
+ public void testWriteReadCommittedEntries() throws Exception {
+ try (Journal<TestEntry> journal = createJournal()) {
+ JournalWriter<TestEntry> writer = journal.writer();
+ JournalReader<TestEntry> reader = journal.openReader(1, JournalReader.Mode.COMMITS);
+
+ for (int i = 1; i <= entriesPerSegment * 5; i++) {
+ writer.append(ENTRY);
+ assertNoNext(reader);
+ writer.commit(i);
+ var entry = assertNext(reader);
+ assertEquals(i, entry.index());
+ assertArrayEquals(ENTRY.bytes(), entry.entry().bytes());
+ reader.reset(i);
+ entry = assertNext(reader);
+ assertEquals(i, entry.index());
+ assertArrayEquals(ENTRY.bytes(), entry.entry().bytes());
+ }
+ }
+ }
+
+ @Test
+ public void testReadAfterCompact() throws Exception {
+ try (SegmentedJournal<TestEntry> journal = createJournal()) {
+ JournalWriter<TestEntry> writer = journal.writer();
+ JournalReader<TestEntry> uncommittedReader = journal.openReader(1, JournalReader.Mode.ALL);
+ JournalReader<TestEntry> committedReader = journal.openReader(1, JournalReader.Mode.COMMITS);
+
+ for (int i = 1; i <= entriesPerSegment * 10; i++) {
+ assertEquals(i, writer.append(ENTRY).index());
+ }
+
+ assertEquals(1, uncommittedReader.getNextIndex());
+ assertEquals(1, committedReader.getNextIndex());
+
+ // This creates asymmetry, as uncommitted reader will move one step ahead...
+ assertNext(uncommittedReader);
+ assertEquals(2, uncommittedReader.getNextIndex());
+ assertNoNext(committedReader);
+ assertEquals(1, committedReader.getNextIndex());
+
+ writer.commit(entriesPerSegment * 9);
+
+ // ... so here we catch up ...
+ assertNext(committedReader);
+ assertEquals(2, committedReader.getNextIndex());
+
+ // ... and continue from the second entry
+ for (int i = 2; i <= entriesPerSegment * 2.5; i++) {
+ var entry = assertNext(uncommittedReader);
+ assertEquals(i, entry.index());
+
+ entry = assertNext(committedReader);
+ assertEquals(i, entry.index());
+ }
+
+ journal.compact(entriesPerSegment * 5 + 1);
+
+ assertEquals(entriesPerSegment * 5 + 1, uncommittedReader.getNextIndex());
+ var entry = assertNext(uncommittedReader);
+ assertEquals(entriesPerSegment * 5 + 1, entry.index());
+
+ assertEquals(entriesPerSegment * 5 + 1, committedReader.getNextIndex());
+ entry = assertNext(committedReader);
+ assertEquals(entriesPerSegment * 5 + 1, entry.index());
+ }
+ }
+
+ /**
+ * Tests reading from a compacted journal.
+ */
+ @Test
+ public void testCompactAndRecover() throws Exception {
+ try (var journal = createJournal()) {
+ // Write three segments to the journal.
+ final var writer = journal.writer();
+ for (int i = 0; i < entriesPerSegment * 3; i++) {
+ writer.append(ENTRY);
+ }
+
+ // Commit the entries and compact the first segment.
+ writer.commit(entriesPerSegment * 3);
+ journal.compact(entriesPerSegment + 1);
+ }
+
+ // Reopen the journal and create a reader.
+ try (var journal = createJournal()) {
+ final var writer = journal.writer();
+ final var reader = journal.openReader(1, JournalReader.Mode.COMMITS);
+ writer.append(ENTRY);
+ writer.append(ENTRY);
+ writer.commit(entriesPerSegment * 3);
+
+ // Ensure the reader starts at the first physical index in the journal.
+ assertEquals(entriesPerSegment + 1, reader.getNextIndex());
+ assertEquals(reader.getFirstIndex(), reader.getNextIndex());
+ assertEquals(entriesPerSegment + 1, assertNext(reader).index());
+ assertEquals(entriesPerSegment + 2, reader.getNextIndex());
+ }
+ }
+
+ @Before
+ @After
+ public void cleanupStorage() throws IOException {
+ if (Files.exists(PATH)) {
+ Files.walkFileTree(PATH, new SimpleFileVisitor<Path>() {
+ @Override
+ public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs) throws IOException {
+ Files.delete(file);
+ return FileVisitResult.CONTINUE;
+ }
+
+ @Override
+ public FileVisitResult postVisitDirectory(final Path dir, final IOException exc) throws IOException {
+ Files.delete(dir);
+ return FileVisitResult.CONTINUE;
+ }
+ });
+ }
+ }
+
+ private static @NonNull Indexed<TestEntry> assertNext(final JournalReader<TestEntry> reader) {
+ final var ret = tryNext(reader);
+ assertNotNull(ret);
+ return ret;
+ }
+
+ private static void assertNoNext(final JournalReader<TestEntry> reader) {
+ assertNull(tryNext(reader));
+ }
+
+ private static @Nullable Indexed<TestEntry> tryNext(final JournalReader<TestEntry> reader) {
+ return reader.tryNext(Indexed::new);
+ }
+}
--- /dev/null
+/*
+ * Copyright 2023 PANTHEON.tech, s.r.o.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package io.atomix.storage.journal;
+
+import io.atomix.storage.journal.JournalSerdes.EntryInput;
+import io.atomix.storage.journal.JournalSerdes.EntryOutput;
+import io.atomix.storage.journal.JournalSerdes.EntrySerdes;
+import java.io.IOException;
+
+final class ByteArraySerdes implements EntrySerdes<byte[]> {
+ @Override
+ public byte[] read(final EntryInput input) throws IOException {
+ int length = input.readVarInt();
+ return length == 0 ? null : input.readBytes(length - 1);
+ }
+
+ @Override
+ public void write(final EntryOutput output, final byte[] entry) throws IOException {
+ if (entry != null) {
+ output.writeVarInt(entry.length + 1);
+ output.writeBytes(entry);
+ } else {
+ output.writeVarInt(0);
+ }
+ }
+}
--- /dev/null
+/*
+ * Copyright 2017-2022 Open Networking Foundation and others. All rights reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package io.atomix.storage.journal;
+
+/**
+ * Disk journal test.
+ */
+public class DiskJournalTest extends AbstractJournalTest {
+ public DiskJournalTest(final int maxSegmentSize) {
+ super(StorageLevel.DISK, maxSegmentSize);
+ }
+}
--- /dev/null
+/*
+ * Copyright 2017-2022 Open Networking Foundation and others. All rights reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package io.atomix.storage.journal;
+
+import org.junit.Test;
+
+import java.nio.ByteBuffer;
+
+import static org.junit.Assert.assertEquals;
+
+/**
+ * Segment descriptor test.
+ *
+ * @author <a href="http://github.com/kuujo">Jordan Halterman</a>
+ */
+public class JournalSegmentDescriptorTest {
+
+ /**
+ * Tests the segment descriptor builder.
+ */
+ @Test
+ public void testDescriptorBuilder() {
+ JournalSegmentDescriptor descriptor = JournalSegmentDescriptor.builder(ByteBuffer.allocate(JournalSegmentDescriptor.BYTES))
+ .withId(2)
+ .withIndex(1025)
+ .withMaxSegmentSize(1024 * 1024)
+ .withMaxEntries(2048)
+ .build();
+
+ assertEquals(2, descriptor.id());
+ assertEquals(JournalSegmentDescriptor.VERSION, descriptor.version());
+ assertEquals(1025, descriptor.index());
+ assertEquals(1024 * 1024, descriptor.maxSegmentSize());
+ assertEquals(2048, descriptor.maxEntries());
+
+ assertEquals(0, descriptor.updated());
+ long time = System.currentTimeMillis();
+ descriptor.update(time);
+ assertEquals(time, descriptor.updated());
+ }
+
+ /**
+ * Tests copying the segment descriptor.
+ */
+ @Test
+ public void testDescriptorCopy() {
+ JournalSegmentDescriptor descriptor = JournalSegmentDescriptor.builder()
+ .withId(2)
+ .withIndex(1025)
+ .withMaxSegmentSize(1024 * 1024)
+ .withMaxEntries(2048)
+ .build();
+
+ long time = System.currentTimeMillis();
+ descriptor.update(time);
+
+ descriptor = descriptor.copyTo(ByteBuffer.allocate(JournalSegmentDescriptor.BYTES));
+
+ assertEquals(2, descriptor.id());
+ assertEquals(JournalSegmentDescriptor.VERSION, descriptor.version());
+ assertEquals(1025, descriptor.index());
+ assertEquals(1024 * 1024, descriptor.maxSegmentSize());
+ assertEquals(2048, descriptor.maxEntries());
+ assertEquals(time, descriptor.updated());
+ }
+}
--- /dev/null
+/*
+ * Copyright 2017-2022 Open Networking Foundation and others. All rights reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package io.atomix.storage.journal;
+
+import java.io.File;
+
+import org.junit.Test;
+
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+
+/**
+ * Journal segment file test.
+ */
+public class JournalSegmentFileTest {
+
+ @Test
+ public void testIsSegmentFile() throws Exception {
+ assertTrue(JournalSegmentFile.isSegmentFile("foo", "foo-1.log"));
+ assertFalse(JournalSegmentFile.isSegmentFile("foo", "bar-1.log"));
+ assertTrue(JournalSegmentFile.isSegmentFile("foo", "foo-1-1.log"));
+ }
+
+ @Test
+ public void testCreateSegmentFile() throws Exception {
+ File file = JournalSegmentFile.createSegmentFile("foo", new File(System.getProperty("user.dir")), 1);
+ assertTrue(JournalSegmentFile.isSegmentFile("foo", file));
+ }
+
+}
--- /dev/null
+/*
+ * Copyright 2017-2022 Open Networking Foundation and others. All rights reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package io.atomix.storage.journal;
+
+/**
+ * Memory mapped journal test.
+ */
+public class MappedJournalTest extends AbstractJournalTest {
+ public MappedJournalTest(final int maxSegmentSize) {
+ super(StorageLevel.MAPPED, maxSegmentSize);
+ }
+}
--- /dev/null
+/*
+ * Copyright 2017-2022 Open Networking Foundation and others. All rights reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package io.atomix.storage.journal;
+
+import java.util.Arrays;
+
+import static com.google.common.base.MoreObjects.toStringHelper;
+
+/**
+ * Test entry.
+ *
+ * @author <a href="http://github.com/kuujo">Jordan Halterman</a>
+ */
+public class TestEntry {
+ private final byte[] bytes;
+
+ public TestEntry(int size) {
+ this(new byte[size]);
+ }
+
+ public TestEntry(byte[] bytes) {
+ this.bytes = bytes;
+ }
+
+ public byte[] bytes() {
+ return bytes;
+ }
+
+ @Override
+ public String toString() {
+ return toStringHelper(this)
+ .add("length", bytes.length)
+ .add("hash", Arrays.hashCode(bytes))
+ .toString();
+ }
+}
--- /dev/null
+/*
+ * Copyright (c) 2023 PANTHEON.tech, s.r.o. and others. All rights reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package io.atomix.storage.journal;
+
+import io.atomix.storage.journal.JournalSerdes.EntryInput;
+import io.atomix.storage.journal.JournalSerdes.EntryOutput;
+import io.atomix.storage.journal.JournalSerdes.EntrySerdes;
+import java.io.IOException;
+
+final class TestEntrySerdes implements EntrySerdes<TestEntry> {
+ private static final ByteArraySerdes BA_SERIALIZER = new ByteArraySerdes();
+
+ @Override
+ public TestEntry read(final EntryInput input) throws IOException {
+ return new TestEntry(BA_SERIALIZER.read(input));
+ }
+
+ @Override
+ public void write(final EntryOutput output, final TestEntry entry) throws IOException {
+ BA_SERIALIZER.write(output, entry.bytes());
+ }
+}
--- /dev/null
+/*
+ * Copyright 2018-2022 Open Networking Foundation and others. All rights reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package io.atomix.storage.journal.index;
+
+import org.junit.Test;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNull;
+
+/**
+ * Sparse journal index test.
+ */
+public class SparseJournalIndexTest {
+ @Test
+ public void testSparseJournalIndex() throws Exception {
+ JournalIndex index = new SparseJournalIndex(.2);
+ assertNull(index.lookup(1));
+ index.index(1, 2);
+ assertNull(index.lookup(1));
+ index.index(2, 4);
+ index.index(3, 6);
+ index.index(4, 8);
+ index.index(5, 10);
+ assertEquals(new Position(5, 10), index.lookup(5));
+ index.index(6, 12);
+ index.index(7, 14);
+ index.index(8, 16);
+ assertEquals(new Position(5, 10), index.lookup(8));
+ index.index(9, 18);
+ index.index(10, 20);
+ assertEquals(new Position(10, 20), index.lookup(10));
+ index.truncate(8);
+ assertEquals(new Position(5, 10), index.lookup(8));
+ assertEquals(new Position(5, 10), index.lookup(10));
+ index.truncate(4);
+ assertNull(index.lookup(4));
+ assertNull(index.lookup(8));
+
+ index = new SparseJournalIndex(.2);
+ assertNull(index.lookup(100));
+ index.index(101, 2);
+ assertNull(index.lookup(1));
+ index.index(102, 4);
+ index.index(103, 6);
+ index.index(104, 8);
+ index.index(105, 10);
+ assertEquals(new Position(105, 10), index.lookup(105));
+ index.index(106, 12);
+ index.index(107, 14);
+ index.index(108, 16);
+ assertEquals(new Position(105, 10), index.lookup(108));
+ index.index(109, 18);
+ index.index(110, 20);
+ assertEquals(new Position(110, 20), index.lookup(110));
+ index.truncate(108);
+ assertEquals(new Position(105, 10), index.lookup(108));
+ assertEquals(new Position(105, 10), index.lookup(110));
+ index.truncate(104);
+ assertNull(index.lookup(104));
+ assertNull(index.lookup(108));
+ }
+}
--- /dev/null
+/*
+ * Copyright 2017-2022 Open Networking Foundation and others. All rights reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package io.atomix.utils.serializer;
+
+import org.junit.Test;
+
+import static org.junit.Assert.assertEquals;
+
+public class BufferAwareByteArrayOutputStreamTest {
+
+ @Test
+ public void testBufferSize() throws Exception {
+ BufferAwareByteArrayOutputStream outputStream = new BufferAwareByteArrayOutputStream(8);
+ assertEquals(8, outputStream.getBufferSize());
+ outputStream.write(new byte[]{1, 2, 3, 4, 5, 6, 7, 8});
+ assertEquals(8, outputStream.getBufferSize());
+ outputStream.write(new byte[]{1, 2, 3, 4, 5, 6, 7, 8});
+ assertEquals(16, outputStream.getBufferSize());
+ outputStream.reset();
+ assertEquals(16, outputStream.getBufferSize());
+ }
+}
--- /dev/null
+/*
+ * Copyright 2017-2022 Open Networking Foundation and others. All rights reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package io.atomix.utils.serializer;
+
+import com.esotericsoftware.kryo.io.Input;
+import org.junit.Before;
+import org.junit.Test;
+
+import static org.junit.Assert.assertArrayEquals;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
+
+public class KryoInputPoolTest {
+
+ private KryoInputPool kryoInputPool;
+
+ @Before
+ public void setUp() throws Exception {
+ kryoInputPool = new KryoInputPool();
+ }
+
+ @Test
+ public void discardOutput() {
+ final Input[] result = new Input[2];
+ kryoInputPool.run(input -> {
+ result[0] = input;
+ return null;
+ }, KryoInputPool.MAX_POOLED_BUFFER_SIZE + 1);
+ kryoInputPool.run(input -> {
+ result[1] = input;
+ return null;
+ }, 0);
+ assertTrue(result[0] != result[1]);
+ }
+
+ @Test
+ public void recycleOutput() {
+ final Input[] result = new Input[2];
+ kryoInputPool.run(input -> {
+ assertEquals(0, input.position());
+ byte[] payload = new byte[]{1, 2, 3, 4};
+ input.setBuffer(payload);
+ assertArrayEquals(payload, input.readBytes(4));
+ result[0] = input;
+ return null;
+ }, 0);
+ assertNull(result[0].getInputStream());
+ assertEquals(0, result[0].position());
+ kryoInputPool.run(input -> {
+ result[1] = input;
+ return null;
+ }, 0);
+ assertTrue(result[0] == result[1]);
+ }
+}
--- /dev/null
+/*
+ * Copyright 2017-2022 Open Networking Foundation and others. All rights reserved.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package io.atomix.utils.serializer;
+
+import com.esotericsoftware.kryo.io.Output;
+import org.junit.Before;
+import org.junit.Test;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+
+public class KryoOutputPoolTest {
+
+ private KryoOutputPool kryoOutputPool;
+
+ @Before
+ public void setUp() throws Exception {
+ kryoOutputPool = new KryoOutputPool();
+ }
+
+ @Test
+ public void discardOutput() {
+ final Output[] result = new Output[2];
+ kryoOutputPool.run(output -> {
+ result[0] = output;
+ return null;
+ }, KryoOutputPool.MAX_POOLED_BUFFER_SIZE + 1);
+ kryoOutputPool.run(output -> {
+ result[1] = output;
+ return null;
+ }, 0);
+ assertTrue(result[0] != result[1]);
+ }
+
+ @Test
+ public void recycleOutput() {
+ final ByteArrayOutput[] result = new ByteArrayOutput[2];
+ kryoOutputPool.run(output -> {
+ output.writeInt(1);
+ assertEquals(Integer.BYTES, output.position());
+ result[0] = output;
+ return null;
+ }, 0);
+ assertEquals(0, result[0].position());
+ assertEquals(0, result[0].getByteArrayOutputStream().size());
+ kryoOutputPool.run(output -> {
+ assertEquals(0, output.position());
+ result[1] = output;
+ return null;
+ }, 0);
+ assertTrue(result[0] == result[1]);
+ }
+}
--- /dev/null
+<!--
+ ~ Copyright 2017-present Open Networking Laboratory
+ ~
+ ~ Licensed under the Apache License, Version 2.0 (the "License");
+ ~ you may not use this file except in compliance with the License.
+ ~ You may obtain a copy of the License at
+ ~
+ ~ http://www.apache.org/licenses/LICENSE-2.0
+ ~
+ ~ Unless required by applicable law or agreed to in writing, software
+ ~ distributed under the License is distributed on an "AS IS" BASIS,
+ ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ ~ See the License for the specific language governing permissions and
+ ~ limitations under the License.
+ -->
+<configuration>
+ <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
+ <encoder>
+ <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
+ </pattern>
+ </encoder>
+ </appender>
+
+ <logger name="io.atomix.storage" level="INFO" />
+
+ <root level="${root.logging.level:-INFO}">
+ <appender-ref ref="STDOUT" />
+ </root>
+</configuration>
\ No newline at end of file
<parent>
<groupId>org.opendaylight.controller</groupId>
<artifactId>mdsal-parent</artifactId>
- <version>7.0.2-SNAPSHOT</version>
+ <version>9.0.3-SNAPSHOT</version>
<relativePath>../../opendaylight/md-sal/parent</relativePath>
</parent>
<parent>
<groupId>org.opendaylight.controller</groupId>
<artifactId>mdsal-parent</artifactId>
- <version>7.0.2-SNAPSHOT</version>
+ <version>9.0.3-SNAPSHOT</version>
<relativePath>../../opendaylight/md-sal/parent</relativePath>
</parent>
<packaging>bundle</packaging>
<dependencies>
+ <dependency>
+ <groupId>com.github.spotbugs</groupId>
+ <artifactId>spotbugs-annotations</artifactId>
+ <optional>true</optional>
+ </dependency>
<dependency>
<groupId>org.opendaylight.controller</groupId>
<artifactId>benchmark-api</artifactId>
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.dsbenchmark.rev150105.test.exec.OuterList;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.dsbenchmark.rev150105.test.exec.outer.list.InnerList;
import org.opendaylight.yangtools.yang.common.QName;
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
-import org.opendaylight.yangtools.yang.data.api.schema.SystemMapNode;
-import org.opendaylight.yangtools.yang.data.api.schema.builder.CollectionNodeBuilder;
-import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
+import org.opendaylight.yangtools.yang.data.spi.node.ImmutableNodes;
public final class DomListBuilder {
// Inner List Qname identifiers for yang model's 'name' and 'value'
}
public static List<MapEntryNode> buildOuterList(final int outerElements, final int innerElements) {
- List<MapEntryNode> outerList = new ArrayList<>(outerElements);
+ final var outerList = new ArrayList<MapEntryNode>(outerElements);
for (int j = 0; j < outerElements; j++) {
- outerList.add(ImmutableNodes.mapEntryBuilder()
+ outerList.add(ImmutableNodes.newMapEntryBuilder()
.withNodeIdentifier(NodeIdentifierWithPredicates.of(OuterList.QNAME, OL_ID, j))
.withChild(ImmutableNodes.leafNode(OL_ID, j))
.withChild(buildInnerList(j, innerElements))
}
private static MapNode buildInnerList(final int index, final int elements) {
- CollectionNodeBuilder<MapEntryNode, SystemMapNode> innerList = ImmutableNodes.mapNodeBuilder(InnerList.QNAME);
+ final var innerList = ImmutableNodes.newSystemMapBuilder()
+ .withNodeIdentifier(new NodeIdentifier(InnerList.QNAME));
final String itemStr = "Item-" + index + "-";
for (int i = 0; i < elements; i++) {
- innerList.addChild(ImmutableNodes.mapEntryBuilder()
+ innerList.addChild(ImmutableNodes.newMapEntryBuilder()
.withNodeIdentifier(NodeIdentifierWithPredicates.of(InnerList.QNAME, IL_NAME, i))
.withChild(ImmutableNodes.leafNode(IL_NAME, i))
.withChild(ImmutableNodes.leafNode(IL_VALUE, itemStr + String.valueOf(i)))
import org.opendaylight.mdsal.binding.api.WriteTransaction;
import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
import org.opendaylight.mdsal.dom.api.DOMDataBroker;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.dsbenchmark.rev150105.CleanupStore;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.dsbenchmark.rev150105.CleanupStoreInput;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.dsbenchmark.rev150105.CleanupStoreOutput;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.dsbenchmark.rev150105.CleanupStoreOutputBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.dsbenchmark.rev150105.DsbenchmarkService;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.dsbenchmark.rev150105.StartTest;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.dsbenchmark.rev150105.StartTestInput;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.dsbenchmark.rev150105.StartTestOutput;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.dsbenchmark.rev150105.StartTestOutputBuilder;
@Singleton
@Component(service = { })
@RequireServiceComponentRuntime
-public final class DsbenchmarkProvider implements DsbenchmarkService, AutoCloseable {
+public final class DsbenchmarkProvider implements AutoCloseable {
private static final Logger LOG = LoggerFactory.getLogger(DsbenchmarkProvider.class);
private static final InstanceIdentifier<TestExec> TEST_EXEC_IID = InstanceIdentifier.create(TestExec.class);
private static final InstanceIdentifier<TestStatus> TEST_STATUS_IID = InstanceIdentifier.create(TestStatus.class);
LOG.warn("Working around Bugs 8829 and 6793 by ignoring exception from setTestOperData", e);
}
- rpcReg = rpcService.registerRpcImplementation(DsbenchmarkService.class, this);
+ rpcReg = rpcService.registerRpcImplementations((StartTest) this::startTest, (CleanupStore) this::cleanupStore);
LOG.info("DsbenchmarkProvider initiated");
}
LOG.info("DsbenchmarkProvider closed");
}
- @Override
- public ListenableFuture<RpcResult<CleanupStoreOutput>> cleanupStore(final CleanupStoreInput input) {
+ private ListenableFuture<RpcResult<CleanupStoreOutput>> cleanupStore(final CleanupStoreInput input) {
cleanupTestStore();
LOG.debug("Data Store cleaned up");
return Futures.immediateFuture(RpcResultBuilder.success(new CleanupStoreOutputBuilder().build()).build());
}
- @Override
@SuppressWarnings("checkstyle:illegalCatch")
- public ListenableFuture<RpcResult<StartTestOutput>> startTest(final StartTestInput input) {
+ private ListenableFuture<RpcResult<StartTestOutput>> startTest(final StartTestInput input) {
LOG.info("Starting the data store benchmark test, input: {}", input);
// Check if there is a test in progress
*/
package org.opendaylight.dsbenchmark.listener;
-import java.util.Collection;
+import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
-import org.opendaylight.mdsal.binding.api.DataObjectModification;
-import org.opendaylight.mdsal.binding.api.DataObjectModification.ModificationType;
import org.opendaylight.mdsal.binding.api.DataTreeChangeListener;
import org.opendaylight.mdsal.binding.api.DataTreeModification;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.dsbenchmark.rev150105.TestExec;
-import org.opendaylight.yangtools.yang.binding.DataObject;
-import org.opendaylight.yangtools.yang.binding.InstanceIdentifier.PathArgument;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
private final AtomicInteger numDataChanges = new AtomicInteger(0);
@Override
- public void onDataTreeChanged(
- final Collection<DataTreeModification<TestExec>> changes) {
+ public void onDataTreeChanged(final List<DataTreeModification<TestExec>> changes) {
// Since we're registering the same DsbenchmarkListener object for both
// OPERATIONAL and CONFIG, the onDataTreeChanged() method can be called
// from different threads, and we need to use atomic counters.
}
private static synchronized void logDataTreeChangeEvent(final int eventNum,
- final Collection<DataTreeModification<TestExec>> changes) {
+ final List<DataTreeModification<TestExec>> changes) {
LOG.debug("DsbenchmarkListener-onDataTreeChanged: Event {}", eventNum);
- for (DataTreeModification<TestExec> change : changes) {
- final DataObjectModification<TestExec> rootNode = change.getRootNode();
- final ModificationType modType = rootNode.getModificationType();
- final PathArgument changeId = rootNode.getIdentifier();
- final Collection<? extends DataObjectModification<? extends DataObject>> modifications =
- rootNode.getModifiedChildren();
+ for (var change : changes) {
+ final var rootNode = change.getRootNode();
+ final var modType = rootNode.modificationType();
+ final var changeId = rootNode.step();
+ final var modifications = rootNode.modifiedChildren();
LOG.debug(" changeId {}, modType {}, mods: {}", changeId, modType, modifications.size());
- for (DataObjectModification<? extends DataObject> mod : modifications) {
- LOG.debug(" mod-getDataAfter: {}", mod.getDataAfter());
+ for (var mod : modifications) {
+ LOG.debug(" mod-getDataAfter: {}", mod.dataAfter());
}
}
}
import org.opendaylight.mdsal.binding.api.DataTreeIdentifier;
import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.dsbenchmark.rev150105.TestExec;
-import org.opendaylight.yangtools.concepts.ListenerRegistration;
+import org.opendaylight.yangtools.concepts.Registration;
import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
private static final Logger LOG = LoggerFactory.getLogger(DsbenchmarkListenerProvider.class);
private static final InstanceIdentifier<TestExec> TEST_EXEC_IID =
InstanceIdentifier.builder(TestExec.class).build();
- private final List<ListenerRegistration<DsbenchmarkListener>> listeners = new ArrayList<>();
+ private final List<DsbenchmarkListener> listeners = new ArrayList<>();
+ private final List<Registration> registrations = new ArrayList<>();
private final DataBroker dataBroker;
public DsbenchmarkListenerProvider(final DataBroker dataBroker) {
public void createAndRegisterListeners(final int numListeners) {
for (int i = 0; i < numListeners; i++) {
- DsbenchmarkListener listener = new DsbenchmarkListener();
- listeners.add(dataBroker.registerDataTreeChangeListener(
- DataTreeIdentifier.create(LogicalDatastoreType.CONFIGURATION, TEST_EXEC_IID), listener));
- listeners.add(dataBroker.registerDataTreeChangeListener(
- DataTreeIdentifier.create(LogicalDatastoreType.OPERATIONAL, TEST_EXEC_IID), listener));
+ var listener = new DsbenchmarkListener();
+ listeners.add(listener);
+ registrations.add(dataBroker.registerTreeChangeListener(
+ DataTreeIdentifier.of(LogicalDatastoreType.CONFIGURATION, TEST_EXEC_IID), listener));
+ registrations.add(dataBroker.registerTreeChangeListener(
+ DataTreeIdentifier.of(LogicalDatastoreType.OPERATIONAL, TEST_EXEC_IID), listener));
}
LOG.debug("DsbenchmarkListenerProvider created {} listeneres", numListeners);
public long getDataChangeCount() {
long dataChanges = 0;
- for (ListenerRegistration<DsbenchmarkListener> listenerRegistration : listeners) {
- dataChanges += listenerRegistration.getInstance().getNumDataChanges();
+ for (var listener : listeners) {
+ dataChanges += listener.getNumDataChanges();
}
LOG.debug("DsbenchmarkListenerProvider , total data changes {}", dataChanges);
return dataChanges;
public long getEventCountAndDestroyListeners() {
long totalEvents = 0;
- for (ListenerRegistration<DsbenchmarkListener> listenerRegistration : listeners) {
- totalEvents += listenerRegistration.getInstance().getNumEvents();
- listenerRegistration.close();
+ registrations.forEach(Registration::close);
+ registrations.clear();
+
+ for (var listener : listeners) {
+ totalEvents += listener.getNumEvents();
}
listeners.clear();
+
LOG.debug("DsbenchmarkListenerProvider destroyed listeneres, total events {}", totalEvents);
return totalEvents;
}
try {
optionalDataObject = submitFuture.get();
if (optionalDataObject != null && optionalDataObject.isPresent()) {
- OuterList outerList = optionalDataObject.get();
+ OuterList outerList = optionalDataObject.orElseThrow();
String[] objectsArray = new String[outerList.getInnerList().size()];
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
-
package org.opendaylight.dsbenchmark.simpletx;
+import static java.util.Objects.requireNonNull;
+
import java.util.List;
import java.util.concurrent.ExecutionException;
import org.opendaylight.dsbenchmark.BaListBuilder;
import org.opendaylight.dsbenchmark.DatastoreAbstractWriter;
import org.opendaylight.mdsal.binding.api.DataBroker;
-import org.opendaylight.mdsal.binding.api.WriteTransaction;
-import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.dsbenchmark.rev150105.StartTestInput;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.dsbenchmark.rev150105.StartTestInput.DataStore;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.dsbenchmark.rev150105.TestExec;
public class SimpletxBaWrite extends DatastoreAbstractWriter {
private static final Logger LOG = LoggerFactory.getLogger(SimpletxBaWrite.class);
+
private final DataBroker dataBroker;
- private List<OuterList> list;
+ private List<OuterList> list = null;
public SimpletxBaWrite(final DataBroker dataBroker, final StartTestInput.Operation oper,
final int outerListElem, final int innerListElem, final long writesPerTx, final DataStore dataStore) {
super(oper, outerListElem, innerListElem, writesPerTx, dataStore);
- this.dataBroker = dataBroker;
+ this.dataBroker = requireNonNull(dataBroker);
LOG.debug("Created SimpletxBaWrite");
}
@Override
public void createList() {
- list = BaListBuilder.buildOuterList(this.outerListElem, this.innerListElem);
+ list = BaListBuilder.buildOuterList(outerListElem, innerListElem);
}
@Override
public void executeList() {
- final LogicalDatastoreType dsType = getDataStoreType();
+ final var dsType = getDataStoreType();
- WriteTransaction tx = dataBroker.newWriteOnlyTransaction();
+ var tx = dataBroker.newWriteOnlyTransaction();
long writeCnt = 0;
- for (OuterList element : this.list) {
- InstanceIdentifier<OuterList> iid = InstanceIdentifier.create(TestExec.class)
- .child(OuterList.class, element.key());
+ for (var element : list) {
+ final var iid = InstanceIdentifier.create(TestExec.class).child(OuterList.class, element.key());
if (oper == StartTestInput.Operation.PUT) {
tx.put(dsType, iid, element);
} else {
}
}
}
-
}
try {
Optional<NormalizedNode> optionalDataObject = submitFuture.get();
if (optionalDataObject != null && optionalDataObject.isPresent()) {
- NormalizedNode ret = optionalDataObject.get();
+ NormalizedNode ret = optionalDataObject.orElseThrow();
LOG.trace("optionalDataObject is {}", ret);
txOk++;
} else {
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
-
package org.opendaylight.dsbenchmark.simpletx;
+import static java.util.Objects.requireNonNull;
+
import java.util.List;
import java.util.concurrent.ExecutionException;
import org.opendaylight.dsbenchmark.DatastoreAbstractWriter;
import org.opendaylight.dsbenchmark.DomListBuilder;
-import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
import org.opendaylight.mdsal.dom.api.DOMDataBroker;
-import org.opendaylight.mdsal.dom.api.DOMDataTreeWriteTransaction;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.dsbenchmark.rev150105.StartTestInput;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.dsbenchmark.rev150105.StartTestInput.DataStore;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.dsbenchmark.rev150105.TestExec;
public class SimpletxDomWrite extends DatastoreAbstractWriter {
private static final Logger LOG = LoggerFactory.getLogger(SimpletxDomWrite.class);
- private final DOMDataBroker domDataBroker;
- private List<MapEntryNode> list;
- public SimpletxDomWrite(final DOMDataBroker domDataBroker, final StartTestInput.Operation oper,
+ private final DOMDataBroker dataBroker;
+ private List<MapEntryNode> list = null;
+
+ public SimpletxDomWrite(final DOMDataBroker dataBroker, final StartTestInput.Operation oper,
final int outerListElem, final int innerListElem, final long putsPerTx, final DataStore dataStore) {
super(oper, outerListElem, innerListElem, putsPerTx, dataStore);
- this.domDataBroker = domDataBroker;
+ this.dataBroker = requireNonNull(dataBroker);
LOG.debug("Created SimpletxDomWrite");
}
@Override
public void createList() {
- list = DomListBuilder.buildOuterList(this.outerListElem, this.innerListElem);
+ list = DomListBuilder.buildOuterList(outerListElem, innerListElem);
}
@Override
public void executeList() {
- final LogicalDatastoreType dsType = getDataStoreType();
- final YangInstanceIdentifier pid =
- YangInstanceIdentifier.builder().node(TestExec.QNAME).node(OuterList.QNAME).build();
+ final var dsType = getDataStoreType();
+ final var pid = YangInstanceIdentifier.of(TestExec.QNAME, OuterList.QNAME);
- DOMDataTreeWriteTransaction tx = domDataBroker.newWriteOnlyTransaction();
+ var tx = dataBroker.newWriteOnlyTransaction();
long writeCnt = 0;
- for (MapEntryNode element : this.list) {
- YangInstanceIdentifier yid =
- pid.node(NodeIdentifierWithPredicates.of(OuterList.QNAME, element.getIdentifier().asMap()));
+ for (var element : list) {
+ final var yid = pid.node(NodeIdentifierWithPredicates.of(OuterList.QNAME, element.name().asMap()));
if (oper == StartTestInput.Operation.PUT) {
tx.put(dsType, yid, element);
LOG.error("Transaction failed", e);
txError++;
}
- tx = domDataBroker.newWriteOnlyTransaction();
+ tx = dataBroker.newWriteOnlyTransaction();
writeCnt = 0;
}
}
import java.util.concurrent.ExecutionException;
import org.opendaylight.dsbenchmark.DatastoreAbstractWriter;
import org.opendaylight.mdsal.binding.api.DataBroker;
-import org.opendaylight.mdsal.binding.api.Transaction;
import org.opendaylight.mdsal.binding.api.TransactionChain;
-import org.opendaylight.mdsal.binding.api.TransactionChainListener;
import org.opendaylight.mdsal.binding.api.WriteTransaction;
import org.opendaylight.mdsal.common.api.CommitInfo;
import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.dsbenchmark.rev150105.test.exec.OuterList;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.dsbenchmark.rev150105.test.exec.OuterListKey;
import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
+import org.opendaylight.yangtools.yang.common.Empty;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-public class TxchainBaDelete extends DatastoreAbstractWriter implements TransactionChainListener {
+public class TxchainBaDelete extends DatastoreAbstractWriter implements FutureCallback<Empty> {
private static final Logger LOG = LoggerFactory.getLogger(TxchainBaDelete.class);
private final DataBroker bindingDataBroker;
@Override
public void executeList() {
final LogicalDatastoreType dsType = getDataStoreType();
- final TransactionChain chain = bindingDataBroker.createMergingTransactionChain(this);
+ final TransactionChain chain = bindingDataBroker.createMergingTransactionChain();
+ chain.addCallback(this);
WriteTransaction tx = chain.newWriteOnlyTransaction();
int txSubmitted = 0;
}
@Override
- public void onTransactionChainFailed(final TransactionChain chain, final Transaction transaction,
- final Throwable cause) {
- LOG.error("Broken chain {} in TxchainBaDelete, transaction {}", chain, transaction.getIdentifier(), cause);
+ public void onFailure(final Throwable cause) {
+ LOG.error("Broken chain in TxchainBaDelete", cause);
}
@Override
- public void onTransactionChainSuccessful(final TransactionChain chain) {
- LOG.debug("TxchainBaDelete closed successfully, chain {}", chain);
+ public void onSuccess(final Empty chain) {
+ LOG.debug("TxchainBaDelete closed successfully");
}
}
import org.opendaylight.dsbenchmark.DatastoreAbstractWriter;
import org.opendaylight.mdsal.binding.api.DataBroker;
import org.opendaylight.mdsal.binding.api.ReadTransaction;
-import org.opendaylight.mdsal.binding.api.Transaction;
-import org.opendaylight.mdsal.binding.api.TransactionChain;
-import org.opendaylight.mdsal.binding.api.TransactionChainListener;
import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.dsbenchmark.rev150105.StartTestInput;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.dsbenchmark.rev150105.StartTestInput.DataStore;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-public class TxchainBaRead extends DatastoreAbstractWriter implements TransactionChainListener {
+public class TxchainBaRead extends DatastoreAbstractWriter {
private static final Logger LOG = LoggerFactory.getLogger(TxchainBaRead.class);
private final DataBroker bindingDataBroker;
try {
Optional<OuterList> optionalDataObject = submitFuture.get();
if (optionalDataObject != null && optionalDataObject.isPresent()) {
- OuterList outerList = optionalDataObject.get();
+ OuterList outerList = optionalDataObject.orElseThrow();
String[] objectsArray = new String[outerList.nonnullInnerList().size()];
for (InnerList innerList : outerList.nonnullInnerList().values()) {
}
}
}
-
- @Override
- public void onTransactionChainFailed(final TransactionChain chain, final Transaction transaction,
- final Throwable cause) {
- LOG.error("Broken chain {} in TxchainBaDelete, transaction {}", chain, transaction.getIdentifier(), cause);
- }
-
- @Override
- public void onTransactionChainSuccessful(final TransactionChain chain) {
- LOG.debug("TxchainBaDelete closed successfully, chain {}", chain);
- }
}
*/
package org.opendaylight.dsbenchmark.txchain;
+import static java.util.Objects.requireNonNull;
+
import com.google.common.util.concurrent.FutureCallback;
import com.google.common.util.concurrent.MoreExecutors;
import java.util.List;
import org.opendaylight.dsbenchmark.BaListBuilder;
import org.opendaylight.dsbenchmark.DatastoreAbstractWriter;
import org.opendaylight.mdsal.binding.api.DataBroker;
-import org.opendaylight.mdsal.binding.api.Transaction;
-import org.opendaylight.mdsal.binding.api.TransactionChain;
-import org.opendaylight.mdsal.binding.api.TransactionChainListener;
-import org.opendaylight.mdsal.binding.api.WriteTransaction;
import org.opendaylight.mdsal.common.api.CommitInfo;
-import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.dsbenchmark.rev150105.StartTestInput;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.dsbenchmark.rev150105.StartTestInput.DataStore;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.dsbenchmark.rev150105.StartTestInput.Operation;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.dsbenchmark.rev150105.TestExec;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.dsbenchmark.rev150105.test.exec.OuterList;
import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
+import org.opendaylight.yangtools.yang.common.Empty;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-public class TxchainBaWrite extends DatastoreAbstractWriter implements TransactionChainListener {
+public class TxchainBaWrite extends DatastoreAbstractWriter implements FutureCallback<Empty> {
private static final Logger LOG = LoggerFactory.getLogger(TxchainBaWrite.class);
- private final DataBroker bindingDataBroker;
- private List<OuterList> list;
- public TxchainBaWrite(final DataBroker bindingDataBroker, final Operation oper,
- final int outerListElem, final int innerListElem, final long writesPerTx, final DataStore dataStore) {
+ private final DataBroker dataBroker;
+ private List<OuterList> list = null;
+
+ public TxchainBaWrite(final DataBroker dataBroker, final Operation oper, final int outerListElem,
+ final int innerListElem, final long writesPerTx, final DataStore dataStore) {
super(oper, outerListElem, innerListElem, writesPerTx, dataStore);
- this.bindingDataBroker = bindingDataBroker;
+ this.dataBroker = requireNonNull(dataBroker);
LOG.debug("Created TxchainBaWrite");
}
@Override
public void createList() {
- list = BaListBuilder.buildOuterList(this.outerListElem, this.innerListElem);
+ list = BaListBuilder.buildOuterList(outerListElem, innerListElem);
}
@Override
public void executeList() {
- final TransactionChain chain = bindingDataBroker.createMergingTransactionChain(this);
- final LogicalDatastoreType dsType = getDataStoreType();
+ final var chain = dataBroker.createMergingTransactionChain();
+ chain.addCallback(this);
+ final var dsType = getDataStoreType();
- WriteTransaction tx = chain.newWriteOnlyTransaction();
+ var tx = chain.newWriteOnlyTransaction();
int txSubmitted = 0;
int writeCnt = 0;
- for (OuterList element : this.list) {
- InstanceIdentifier<OuterList> iid = InstanceIdentifier.create(TestExec.class)
- .child(OuterList.class, element.key());
+ for (var element : list) {
+ final var iid = InstanceIdentifier.create(TestExec.class).child(OuterList.class, element.key());
if (oper == StartTestInput.Operation.PUT) {
tx.put(dsType, iid, element);
}
@Override
- public void onTransactionChainFailed(final TransactionChain chain, final Transaction transaction,
- final Throwable cause) {
- LOG.error("Broken chain {} in DatastoreBaAbstractWrite, transaction {}", chain, transaction.getIdentifier(),
- cause);
+ public void onFailure(final Throwable cause) {
+ LOG.error("Broken chain in DatastoreBaAbstractWrite", cause);
}
@Override
- public void onTransactionChainSuccessful(final TransactionChain chain) {
- LOG.debug("DatastoreBaAbstractWrite closed successfully, chain {}", chain);
+ public void onSuccess(final Empty result) {
+ LOG.debug("DatastoreBaAbstractWrite closed successfully");
}
}
import org.opendaylight.mdsal.common.api.CommitInfo;
import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
import org.opendaylight.mdsal.dom.api.DOMDataBroker;
-import org.opendaylight.mdsal.dom.api.DOMDataTreeTransaction;
import org.opendaylight.mdsal.dom.api.DOMDataTreeWriteTransaction;
import org.opendaylight.mdsal.dom.api.DOMTransactionChain;
-import org.opendaylight.mdsal.dom.api.DOMTransactionChainListener;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.dsbenchmark.rev150105.StartTestInput;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.dsbenchmark.rev150105.StartTestInput.DataStore;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.dsbenchmark.rev150105.TestExec;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.dsbenchmark.rev150105.test.exec.OuterList;
+import org.opendaylight.yangtools.yang.common.Empty;
import org.opendaylight.yangtools.yang.common.QName;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-public class TxchainDomDelete extends DatastoreAbstractWriter implements DOMTransactionChainListener {
+public class TxchainDomDelete extends DatastoreAbstractWriter implements FutureCallback<Empty> {
private static final Logger LOG = LoggerFactory.getLogger(TxchainDomDelete.class);
private final DOMDataBroker domDataBroker;
final org.opendaylight.yangtools.yang.common.QName olId = QName.create(OuterList.QNAME, "id");
final YangInstanceIdentifier pid =
YangInstanceIdentifier.builder().node(TestExec.QNAME).node(OuterList.QNAME).build();
- final DOMTransactionChain chain = domDataBroker.createMergingTransactionChain(this);
+ final DOMTransactionChain chain = domDataBroker.createMergingTransactionChain();
+ chain.addCallback(this);
DOMDataTreeWriteTransaction tx = chain.newWriteOnlyTransaction();
int txSubmitted = 0;
}
@Override
- public void onTransactionChainFailed(final DOMTransactionChain chain, final DOMDataTreeTransaction transaction,
- final Throwable cause) {
- LOG.error("Broken chain {} in TxchainDomDelete, transaction {}", chain, transaction.getIdentifier(), cause);
+ public void onFailure(final Throwable cause) {
+ LOG.error("Broken chain in TxchainDomDelete", cause);
}
@Override
- public void onTransactionChainSuccessful(final DOMTransactionChain chain) {
- LOG.debug("TxchainDomDelete closed successfully, chain {}", chain);
+ public void onSuccess(final Empty result) {
+ LOG.debug("TxchainDomDelete closed successfully");
}
}
import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
import org.opendaylight.mdsal.dom.api.DOMDataBroker;
import org.opendaylight.mdsal.dom.api.DOMDataTreeReadTransaction;
-import org.opendaylight.mdsal.dom.api.DOMDataTreeTransaction;
-import org.opendaylight.mdsal.dom.api.DOMTransactionChain;
-import org.opendaylight.mdsal.dom.api.DOMTransactionChainListener;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.dsbenchmark.rev150105.StartTestInput;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.dsbenchmark.rev150105.StartTestInput.DataStore;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.dsbenchmark.rev150105.TestExec;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-public class TxchainDomRead extends DatastoreAbstractWriter implements DOMTransactionChainListener {
+public class TxchainDomRead extends DatastoreAbstractWriter {
private static final Logger LOG = LoggerFactory.getLogger(TxchainDomRead.class);
private final DOMDataBroker domDataBroker;
@Override
public void executeList() {
final LogicalDatastoreType dsType = getDataStoreType();
- final org.opendaylight.yangtools.yang.common.QName olId = QName.create(OuterList.QNAME, "id");
+ final QName olId = QName.create(OuterList.QNAME, "id");
final YangInstanceIdentifier pid =
YangInstanceIdentifier.builder().node(TestExec.QNAME).node(OuterList.QNAME).build();
}
}
}
-
- @Override
- public void onTransactionChainFailed(final DOMTransactionChain chain, final DOMDataTreeTransaction transaction,
- final Throwable cause) {
- LOG.error("Broken chain {} in TxchainDomDelete, transaction {}", chain, transaction.getIdentifier(), cause);
- }
-
- @Override
- public void onTransactionChainSuccessful(final DOMTransactionChain chain) {
- LOG.debug("TxchainDomDelete closed successfully, chain {}", chain);
- }
}
import org.opendaylight.dsbenchmark.DatastoreAbstractWriter;
import org.opendaylight.dsbenchmark.DomListBuilder;
import org.opendaylight.mdsal.common.api.CommitInfo;
-import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
import org.opendaylight.mdsal.dom.api.DOMDataBroker;
-import org.opendaylight.mdsal.dom.api.DOMDataTreeTransaction;
-import org.opendaylight.mdsal.dom.api.DOMDataTreeWriteTransaction;
-import org.opendaylight.mdsal.dom.api.DOMTransactionChain;
-import org.opendaylight.mdsal.dom.api.DOMTransactionChainListener;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.dsbenchmark.rev150105.StartTestInput;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.dsbenchmark.rev150105.StartTestInput.DataStore;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.dsbenchmark.rev150105.TestExec;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.dsbenchmark.rev150105.test.exec.OuterList;
+import org.opendaylight.yangtools.yang.common.Empty;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-public class TxchainDomWrite extends DatastoreAbstractWriter implements DOMTransactionChainListener {
+public class TxchainDomWrite extends DatastoreAbstractWriter implements FutureCallback<Empty> {
private static final Logger LOG = LoggerFactory.getLogger(TxchainDomWrite.class);
- private final DOMDataBroker domDataBroker;
- private List<MapEntryNode> list;
- public TxchainDomWrite(final DOMDataBroker domDataBroker, final StartTestInput.Operation oper,
+ private final DOMDataBroker dataBroker;
+ private List<MapEntryNode> list = null;
+
+ public TxchainDomWrite(final DOMDataBroker dataBroker, final StartTestInput.Operation oper,
final int outerListElem, final int innerListElem, final long writesPerTx, final DataStore dataStore) {
super(oper, outerListElem, innerListElem, writesPerTx, dataStore);
- this.domDataBroker = domDataBroker;
+ this.dataBroker = dataBroker;
LOG.debug("Created TxchainDomWrite");
}
@Override
public void createList() {
- list = DomListBuilder.buildOuterList(this.outerListElem, this.innerListElem);
+ list = DomListBuilder.buildOuterList(outerListElem, innerListElem);
}
@Override
public void executeList() {
- final LogicalDatastoreType dsType = getDataStoreType();
- final YangInstanceIdentifier pid =
- YangInstanceIdentifier.builder().node(TestExec.QNAME).node(OuterList.QNAME).build();
- final DOMTransactionChain chain = domDataBroker.createMergingTransactionChain(this);
+ final var dsType = getDataStoreType();
+ final var pid = YangInstanceIdentifier.of(TestExec.QNAME, OuterList.QNAME);
+ final var chain = dataBroker.createMergingTransactionChain();
+ chain.addCallback(this);
- DOMDataTreeWriteTransaction tx = chain.newWriteOnlyTransaction();
+ var tx = chain.newWriteOnlyTransaction();
int txSubmitted = 0;
int writeCnt = 0;
- for (MapEntryNode element : this.list) {
- YangInstanceIdentifier yid =
- pid.node(NodeIdentifierWithPredicates.of(OuterList.QNAME, element.getIdentifier().asMap()));
+ for (var element : list) {
+ var yid = pid.node(NodeIdentifierWithPredicates.of(OuterList.QNAME, element.name().asMap()));
if (oper == StartTestInput.Operation.PUT) {
tx.put(dsType, yid, element);
}
@Override
- public void onTransactionChainFailed(final DOMTransactionChain chain, final DOMDataTreeTransaction transaction,
- final Throwable cause) {
- LOG.error("Broken chain {} in TxchainDomWrite, transaction {}", chain, transaction.getIdentifier(), cause);
+ public void onFailure(final Throwable cause) {
+ LOG.error("Broken chain in TxchainDomWrite", cause);
}
@Override
- public void onTransactionChainSuccessful(final DOMTransactionChain chain) {
- LOG.debug("Chain {} closed successfully", chain);
+ public void onSuccess(final Empty result) {
+ LOG.debug("Chain closed successfully");
}
}
<parent>
<groupId>org.opendaylight.controller</groupId>
<artifactId>mdsal-parent</artifactId>
- <version>7.0.2-SNAPSHOT</version>
+ <version>9.0.3-SNAPSHOT</version>
<relativePath>../../opendaylight/md-sal/parent</relativePath>
</parent>
import com.google.common.util.concurrent.Futures;
import java.util.concurrent.Future;
+import org.opendaylight.mdsal.binding.api.NotificationService.Listener;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ntfbench.payload.rev150709.Ntfbench;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ntfbench.payload.rev150709.NtfbenchPayloadListener;
-
-public class NtfbenchTestListener implements NtfbenchPayloadListener {
+public class NtfbenchTestListener implements Listener<Ntfbench> {
private final int expectedSize;
private int received = 0;
}
@Override
- public void onNtfbench(final Ntfbench notification) {
+ public void onNotification(final Ntfbench notification) {
if (expectedSize == notification.getPayload().size()) {
received++;
}
}
@Override
- public void onNtfbench(final Ntfbench notification) {
- // TODO Auto-generated method stub
- super.onNtfbench(notification);
+ public void onNotification(final Ntfbench notification) {
+ super.onNotification(notification);
if (expectedCount == getReceived()) {
allDone.set(null);
}
import com.google.common.util.concurrent.ListenableFuture;
import java.util.ArrayList;
-import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import org.opendaylight.mdsal.binding.api.NotificationPublishService;
import org.opendaylight.mdsal.binding.api.NotificationService;
import org.opendaylight.mdsal.binding.api.RpcProviderService;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ntfbenchmark.rev150105.NtfbenchmarkService;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ntfbench.payload.rev150709.Ntfbench;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ntfbenchmark.rev150105.StartTest;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ntfbenchmark.rev150105.StartTestInput;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ntfbenchmark.rev150105.StartTestInput.ProducerType;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ntfbenchmark.rev150105.StartTestOutput;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ntfbenchmark.rev150105.StartTestOutputBuilder;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ntfbenchmark.rev150105.TestStatus;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ntfbenchmark.rev150105.TestStatusInput;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.ntfbenchmark.rev150105.TestStatusOutput;
-import org.opendaylight.yangtools.concepts.ListenerRegistration;
import org.opendaylight.yangtools.concepts.Registration;
import org.opendaylight.yangtools.yang.common.RpcResult;
import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
@Singleton
@Component(service = {})
@RequireServiceComponentRuntime
-public final class NtfbenchmarkProvider implements AutoCloseable, NtfbenchmarkService {
+public final class NtfbenchmarkProvider implements AutoCloseable {
private static final Logger LOG = LoggerFactory.getLogger(NtfbenchmarkProvider.class);
private static final int TEST_TIMEOUT = 5;
@Reference final RpcProviderService rpcService) {
this.listenService = requireNonNull(listenService);
this.publishService = requireNonNull(publishService);
- reg = rpcService.registerRpcImplementation(NtfbenchmarkService.class, this);
+ reg = rpcService.registerRpcImplementations((TestStatus) this::testStatus, (StartTest) this::startTest);
LOG.debug("NtfbenchmarkProvider initiated");
}
LOG.info("NtfbenchmarkProvider closed");
}
- @Override
- public ListenableFuture<RpcResult<StartTestOutput>> startTest(final StartTestInput input) {
+ private ListenableFuture<RpcResult<StartTestOutput>> startTest(final StartTestInput input) {
final int producerCount = input.getProducers().intValue();
final int listenerCount = input.getListeners().intValue();
final int iterations = input.getIterations().intValue();
final int payloadSize = input.getIterations().intValue();
- final List<AbstractNtfbenchProducer> producers = new ArrayList<>(producerCount);
- final List<ListenerRegistration<NtfbenchTestListener>> listeners = new ArrayList<>(listenerCount);
+ final var producers = new ArrayList<AbstractNtfbenchProducer>(producerCount);
for (int i = 0; i < producerCount; i++) {
producers.add(new NtfbenchBlockingProducer(publishService, iterations, payloadSize));
}
int expectedCntPerListener = producerCount * iterations;
+ final var listeners = new ArrayList<NtfbenchTestListener>(listenerCount);
+ final var registrations = new ArrayList<Registration>(listenerCount);
for (int i = 0; i < listenerCount; i++) {
final NtfbenchTestListener listener;
if (input.getProducerType() == ProducerType.BLOCKING) {
} else {
listener = new NtfbenchTestListener(payloadSize);
}
- listeners.add(listenService.registerNotificationListener(listener));
+ listeners.add(listener);
+ registrations.add(listenService.registerListener(Ntfbench.class, listener));
}
try {
executor.shutdown();
try {
executor.awaitTermination(TEST_TIMEOUT, TimeUnit.MINUTES);
- for (ListenerRegistration<NtfbenchTestListener> listenerRegistration : listeners) {
- listenerRegistration.getInstance().getAllDone().get();
+ for (var listener : listeners) {
+ listener.getAllDone().get();
}
} catch (final InterruptedException | ExecutionException e) {
LOG.error("Out of time: test did not finish within the {} min deadline ", TEST_TIMEOUT, e);
long allProducersOk = 0;
long allProducersError = 0;
- for (final ListenerRegistration<NtfbenchTestListener> listenerRegistration : listeners) {
- allListeners += listenerRegistration.getInstance().getReceived();
+ for (var listener : listeners) {
+ allListeners += listener.getReceived();
}
final long listenerElapsedTime = producerEndTime - startTime;
.build();
return RpcResultBuilder.success(output).buildFuture();
} finally {
- for (final ListenerRegistration<NtfbenchTestListener> listenerRegistration : listeners) {
- listenerRegistration.close();
- }
+ registrations.forEach(Registration::close);
}
}
- @Override
- public ListenableFuture<RpcResult<TestStatusOutput>> testStatus(final TestStatusInput input) {
+ private ListenableFuture<RpcResult<TestStatusOutput>> testStatus(final TestStatusInput input) {
throw new UnsupportedOperationException("Not implemented");
}
}
<parent>
<groupId>org.opendaylight.odlparent</groupId>
<artifactId>odlparent-lite</artifactId>
- <version>12.0.1</version>
+ <version>13.0.11</version>
<relativePath/>
</parent>
<groupId>org.opendaylight.controller</groupId>
<artifactId>benchmark-aggregator</artifactId>
- <version>7.0.2-SNAPSHOT</version>
+ <version>9.0.3-SNAPSHOT</version>
<packaging>pom</packaging>
<properties>
<module>dsbenchmark</module>
<module>ntfbenchmark</module>
<module>rpcbenchmark</module>
+ <module>segjournal-benchmark</module>
</modules>
</project>
and is available at http://www.eclipse.org/legal/epl-v10.html
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
- <modelVersion>4.0.0</modelVersion>
- <parent>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>mdsal-parent</artifactId>
- <version>7.0.2-SNAPSHOT</version>
- <relativePath>../../opendaylight/md-sal/parent</relativePath>
- </parent>
+ <modelVersion>4.0.0</modelVersion>
+ <parent>
+ <groupId>org.opendaylight.controller</groupId>
+ <artifactId>mdsal-parent</artifactId>
+ <version>9.0.3-SNAPSHOT</version>
+ <relativePath>../../opendaylight/md-sal/parent</relativePath>
+ </parent>
- <artifactId>rpcbenchmark</artifactId>
- <packaging>bundle</packaging>
+ <artifactId>rpcbenchmark</artifactId>
+ <packaging>bundle</packaging>
- <dependencies>
- <dependency>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>benchmark-api</artifactId>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.mdsal</groupId>
- <artifactId>mdsal-binding-api</artifactId>
- </dependency>
- <dependency>
- <groupId>org.osgi</groupId>
- <artifactId>org.osgi.service.component.annotations</artifactId>
- </dependency>
- <dependency>
- <groupId>com.guicedee.services</groupId>
- <artifactId>javax.inject</artifactId>
- <optional>true</optional>
- </dependency>
- <dependency>
- <groupId>jakarta.annotation</groupId>
- <artifactId>jakarta.annotation-api</artifactId>
- <optional>true</optional>
- </dependency>
- </dependencies>
+ <dependencies>
+ <dependency>
+ <groupId>com.guicedee.services</groupId>
+ <artifactId>javax.inject</artifactId>
+ <optional>true</optional>
+ </dependency>
+ <dependency>
+ <groupId>com.google.guava</groupId>
+ <artifactId>guava</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>jakarta.annotation</groupId>
+ <artifactId>jakarta.annotation-api</artifactId>
+ <optional>true</optional>
+ </dependency>
+ <dependency>
+ <groupId>org.opendaylight.controller</groupId>
+ <artifactId>benchmark-api</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.opendaylight.mdsal</groupId>
+ <artifactId>yang-binding</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.opendaylight.mdsal</groupId>
+ <artifactId>mdsal-binding-api</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.opendaylight.yangtools</groupId>
+ <artifactId>concepts</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.opendaylight.yangtools</groupId>
+ <artifactId>yang-common</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.osgi</groupId>
+ <artifactId>org.osgi.service.component.annotations</artifactId>
+ </dependency>
+ </dependencies>
</project>
import org.opendaylight.yang.gen.v1.rpcbench.payload.rev150702.RoutedRpcBenchInput;
import org.opendaylight.yang.gen.v1.rpcbench.payload.rev150702.RoutedRpcBenchOutput;
import org.opendaylight.yang.gen.v1.rpcbench.payload.rev150702.RoutedRpcBenchOutputBuilder;
-import org.opendaylight.yang.gen.v1.rpcbench.payload.rev150702.RpcbenchPayloadService;
import org.opendaylight.yangtools.yang.common.RpcResult;
import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
-abstract class AbstractRpcbenchPayloadService implements RpcbenchPayloadService {
+abstract class AbstractRpcbenchPayloadService {
private int numRpcs = 0;
- @Override
- public final ListenableFuture<RpcResult<GlobalRpcBenchOutput>> globalRpcBench(final GlobalRpcBenchInput input) {
+ final ListenableFuture<RpcResult<GlobalRpcBenchOutput>> globalRpcBench(final GlobalRpcBenchInput input) {
numRpcs++;
return RpcResultBuilder.success(new GlobalRpcBenchOutputBuilder(input).build()).buildFuture();
}
- @Override
- public final ListenableFuture<RpcResult<RoutedRpcBenchOutput>> routedRpcBench(final RoutedRpcBenchInput input) {
+ final ListenableFuture<RpcResult<RoutedRpcBenchOutput>> routedRpcBench(final RoutedRpcBenchInput input) {
numRpcs++;
return RpcResultBuilder.success(new RoutedRpcBenchOutputBuilder(input).build()).buildFuture();
}
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableMap.Builder;
-import java.util.Map;
import java.util.concurrent.ExecutionException;
-import java.util.concurrent.Future;
import java.util.concurrent.atomic.AtomicLong;
-import org.opendaylight.mdsal.binding.api.RpcConsumerRegistry;
+import org.opendaylight.mdsal.binding.api.RpcService;
+import org.opendaylight.yang.gen.v1.rpcbench.payload.rev150702.GlobalRpcBench;
import org.opendaylight.yang.gen.v1.rpcbench.payload.rev150702.GlobalRpcBenchInput;
import org.opendaylight.yang.gen.v1.rpcbench.payload.rev150702.GlobalRpcBenchInputBuilder;
-import org.opendaylight.yang.gen.v1.rpcbench.payload.rev150702.GlobalRpcBenchOutput;
-import org.opendaylight.yang.gen.v1.rpcbench.payload.rev150702.RpcbenchPayloadService;
import org.opendaylight.yang.gen.v1.rpcbench.payload.rev150702.payload.Payload;
import org.opendaylight.yang.gen.v1.rpcbench.payload.rev150702.payload.PayloadBuilder;
import org.opendaylight.yang.gen.v1.rpcbench.payload.rev150702.payload.PayloadKey;
-import org.opendaylight.yangtools.yang.common.RpcResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class GlobalBindingRTCClient implements RTCClient {
private static final Logger LOG = LoggerFactory.getLogger(GlobalBindingRTCClient.class);
- private final RpcbenchPayloadService service;
+ private final GlobalRpcBench globalRpcBench;
private final AtomicLong rpcOk = new AtomicLong(0);
private final AtomicLong rpcError = new AtomicLong(0);
private final GlobalRpcBenchInput inVal;
return rpcError.get();
}
- public GlobalBindingRTCClient(final RpcConsumerRegistry registry, final int inSize) {
- if (registry != null) {
- this.service = registry.getRpcService(RpcbenchPayloadService.class);
- } else {
- this.service = null;
- }
+ public GlobalBindingRTCClient(final RpcService rpcService, final int inSize) {
+ globalRpcBench = rpcService.getRpc(GlobalRpcBench.class);
this.inSize = inSize;
Builder<PayloadKey, Payload> listVals = ImmutableMap.builderWithExpectedSize(inSize);
int error = 0;
for (int i = 0; i < iterations; i++) {
- Future<RpcResult<GlobalRpcBenchOutput>> output = service.globalRpcBench(inVal);
+ final var output = globalRpcBench.invoke(inVal);
try {
- RpcResult<GlobalRpcBenchOutput> rpcResult = output.get();
+ final var rpcResult = output.get();
if (rpcResult.isSuccessful()) {
- Map<PayloadKey, Payload> retVal = rpcResult.getResult().getPayload();
+ final var retVal = rpcResult.getResult().getPayload();
if (retVal.size() == inSize) {
ok++;
}
// TODO Auto-generated method stub
}
-
}
package rpcbenchmark.impl;
import org.opendaylight.mdsal.binding.api.RpcProviderService;
-import org.opendaylight.yang.gen.v1.rpcbench.payload.rev150702.RpcbenchPayloadService;
+import org.opendaylight.yang.gen.v1.rpcbench.payload.rev150702.GlobalRpcBench;
+import org.opendaylight.yang.gen.v1.rpcbench.payload.rev150702.RoutedRpcBench;
import org.opendaylight.yangtools.concepts.Registration;
import org.osgi.service.component.annotations.Reference;
import org.slf4j.Logger;
private final Registration reg;
GlobalBindingRTCServer(@Reference final RpcProviderService rpcProvider) {
- reg = rpcProvider.registerRpcImplementation(RpcbenchPayloadService.class, this);
+ reg = rpcProvider.registerRpcImplementations(
+ (GlobalRpcBench) this::globalRpcBench,
+ (RoutedRpcBench) this::routedRpcBench);
LOG.debug("GlobalBindingRTCServer started");
}
*/
package rpcbenchmark.impl;
+import java.util.List;
import java.util.Set;
import org.opendaylight.mdsal.binding.api.RpcProviderService;
-import org.opendaylight.yang.gen.v1.rpcbench.payload.rev150702.RpcbenchPayloadService;
+import org.opendaylight.yang.gen.v1.rpcbench.payload.rev150702.GlobalRpcBench;
+import org.opendaylight.yang.gen.v1.rpcbench.payload.rev150702.RoutedRpcBench;
import org.opendaylight.yangtools.concepts.Registration;
import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
private final Registration reg;
RoutedBindingRTCServer(final RpcProviderService rpcProvider, final Set<InstanceIdentifier<?>> paths) {
- reg = rpcProvider.registerRpcImplementation(RpcbenchPayloadService.class, this, paths);
+ reg = rpcProvider.registerRpcImplementations(List.of(
+ (GlobalRpcBench) this::globalRpcBench,
+ (RoutedRpcBench) this::routedRpcBench), paths);
}
@Override
import java.util.concurrent.Future;
import java.util.concurrent.ThreadLocalRandom;
import java.util.concurrent.atomic.AtomicLong;
-import org.opendaylight.mdsal.binding.api.RpcConsumerRegistry;
+import org.opendaylight.mdsal.binding.api.RpcService;
+import org.opendaylight.yang.gen.v1.rpcbench.payload.rev150702.RoutedRpcBench;
import org.opendaylight.yang.gen.v1.rpcbench.payload.rev150702.RoutedRpcBenchInput;
import org.opendaylight.yang.gen.v1.rpcbench.payload.rev150702.RoutedRpcBenchInputBuilder;
import org.opendaylight.yang.gen.v1.rpcbench.payload.rev150702.RoutedRpcBenchOutput;
-import org.opendaylight.yang.gen.v1.rpcbench.payload.rev150702.RpcbenchPayloadService;
import org.opendaylight.yang.gen.v1.rpcbench.payload.rev150702.payload.Payload;
import org.opendaylight.yang.gen.v1.rpcbench.payload.rev150702.payload.PayloadBuilder;
import org.opendaylight.yang.gen.v1.rpcbench.payload.rev150702.payload.PayloadKey;
public class RoutedBindingRTClient implements RTCClient {
private static final Logger LOG = LoggerFactory.getLogger(RoutedBindingRTClient.class);
- private final RpcbenchPayloadService service;
+ private final RoutedRpcBench routedRpcBench;
private final AtomicLong rpcOk = new AtomicLong(0);
private final AtomicLong rpcError = new AtomicLong(0);
private final List<RoutedRpcBenchInput> inVal = new ArrayList<>();
private final int inSize;
- public RoutedBindingRTClient(final RpcConsumerRegistry registry, final int inSize,
+ public RoutedBindingRTClient(final RpcService rpcService, final int inSize,
final List<InstanceIdentifier<?>> routeIid) {
- service = registry.getRpcService(RpcbenchPayloadService.class);
+ routedRpcBench = rpcService.getRpc(RoutedRpcBench.class);
this.inSize = inSize;
Builder<PayloadKey, Payload> listVals = ImmutableMap.builderWithExpectedSize(inSize);
int rpcServerCnt = inVal.size();
for (int i = 0; i < iterations; i++) {
RoutedRpcBenchInput input = inVal.get(ThreadLocalRandom.current().nextInt(rpcServerCnt));
- Future<RpcResult<RoutedRpcBenchOutput>> output = service.routedRpcBench(input);
+ Future<RpcResult<RoutedRpcBenchOutput>> output = routedRpcBench.invoke(input);
try {
RpcResult<RoutedRpcBenchOutput> rpcResult = output.get();
import javax.annotation.PreDestroy;
import javax.inject.Inject;
import javax.inject.Singleton;
-import org.opendaylight.mdsal.binding.api.RpcConsumerRegistry;
import org.opendaylight.mdsal.binding.api.RpcProviderService;
+import org.opendaylight.mdsal.binding.api.RpcService;
import org.opendaylight.yang.gen.v1.rpcbench.payload.rev150702.RpcbenchRpcRoutes;
import org.opendaylight.yang.gen.v1.rpcbench.payload.rev150702.rpcbench.rpc.routes.RpcRoute;
import org.opendaylight.yang.gen.v1.rpcbench.payload.rev150702.rpcbench.rpc.routes.RpcRouteKey;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.rpcbenchmark.rev150702.RpcbenchmarkService;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.rpcbenchmark.rev150702.StartTest;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.rpcbenchmark.rev150702.StartTestInput;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.rpcbenchmark.rev150702.StartTestOutput;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.rpcbenchmark.rev150702.StartTestOutputBuilder;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.rpcbenchmark.rev150702.TestStatus;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.rpcbenchmark.rev150702.TestStatusInput;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.rpcbenchmark.rev150702.TestStatusOutput;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.rpcbenchmark.rev150702.TestStatusOutput.ExecStatus;
@Singleton
@Component(service = {})
@RequireServiceComponentRuntime
-public final class RpcbenchmarkProvider implements AutoCloseable, RpcbenchmarkService {
+public final class RpcbenchmarkProvider implements AutoCloseable {
private static final Logger LOG = LoggerFactory.getLogger(RpcbenchmarkProvider.class);
private static final int TEST_TIMEOUT = 5;
private final AtomicReference<ExecStatus> execStatus = new AtomicReference<>(ExecStatus.Idle);
private final RpcProviderService providerRegistry;
- private final RpcConsumerRegistry consumerRegistry;
+ private final RpcService consumerRegistry;
private final GlobalBindingRTCServer globalServer;
private final Registration reg;
@Inject
@Activate
public RpcbenchmarkProvider(@Reference final RpcProviderService providerRegistry,
- @Reference final RpcConsumerRegistry consumerRegistry) {
+ @Reference final RpcService consumerRegistry) {
this.providerRegistry = requireNonNull(providerRegistry);
this.consumerRegistry = requireNonNull(consumerRegistry);
globalServer = new GlobalBindingRTCServer(providerRegistry);
- reg = providerRegistry.registerRpcImplementation(RpcbenchmarkService.class, this);
+ reg = providerRegistry.registerRpcImplementations((TestStatus) this::testStatus, (StartTest) this::startTest);
LOG.info("RpcbenchmarkProvider initiated");
}
LOG.info("RpcbenchmarkProvider closed");
}
- @Override
- public ListenableFuture<RpcResult<StartTestOutput>> startTest(final StartTestInput input) {
+ private ListenableFuture<RpcResult<StartTestOutput>> startTest(final StartTestInput input) {
LOG.debug("startTest {}", input);
final RTCClient client;
}
}
- @Override
- public ListenableFuture<RpcResult<TestStatusOutput>> testStatus(final TestStatusInput input) {
+ private ListenableFuture<RpcResult<TestStatusOutput>> testStatus(final TestStatusInput input) {
LOG.info("testStatus");
TestStatusOutput output = new TestStatusOutputBuilder()
.setGlobalServerCnt(Uint32.valueOf(globalServer.getNumRpcs()))
--- /dev/null
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+ Copyright (c) 2024 PANTHEON.tech s.r.o. and others. All rights reserved.
+
+ This program and the accompanying materials are made available under the
+ terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ and is available at http://www.eclipse.org/legal/epl-v10.html
+ -->
+<project xmlns="http://maven.apache.org/POM/4.0.0"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+ <modelVersion>4.0.0</modelVersion>
+ <parent>
+ <groupId>org.opendaylight.controller</groupId>
+ <artifactId>mdsal-parent</artifactId>
+ <version>9.0.3-SNAPSHOT</version>
+ <relativePath>../../opendaylight/md-sal/parent</relativePath>
+ </parent>
+
+ <artifactId>segjournal-benchmark</artifactId>
+ <packaging>jar</packaging>
+
+ <properties>
+ <maven.javadoc.skip>true</maven.javadoc.skip>
+ <maven.deploy.skip>true</maven.deploy.skip>
+ <maven.install.skip>true</maven.install.skip>
+ </properties>
+
+ <dependencies>
+ <dependency>
+ <groupId>com.github.spotbugs</groupId>
+ <artifactId>spotbugs-annotations</artifactId>
+ <optional>true</optional>
+ </dependency>
+ <dependency>
+ <groupId>org.eclipse.jdt</groupId>
+ <artifactId>org.eclipse.jdt.annotation</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>net.sourceforge.argparse4j</groupId>
+ <artifactId>argparse4j</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.slf4j</groupId>
+ <artifactId>slf4j-api</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>ch.qos.logback</groupId>
+ <artifactId>logback-classic</artifactId>
+ <scope>compile</scope>
+ </dependency>
+ <dependency>
+ <groupId>commons-io</groupId>
+ <artifactId>commons-io</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>io.dropwizard.metrics</groupId>
+ <artifactId>metrics-core</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.opendaylight.controller</groupId>
+ <artifactId>repackaged-akka</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.opendaylight.controller</groupId>
+ <artifactId>sal-clustering-commons</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.opendaylight.controller</groupId>
+ <artifactId>atomix-storage</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.opendaylight.controller</groupId>
+ <artifactId>sal-akka-segmented-journal</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.opendaylight.controller</groupId>
+ <artifactId>sal-clustering-config</artifactId>
+ </dependency>
+ </dependencies>
+
+ <build>
+ <plugins>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-shade-plugin</artifactId>
+ <configuration>
+ <createDependencyReducedPom>false</createDependencyReducedPom>
+ </configuration>
+ <executions>
+ <execution>
+ <phase>package</phase>
+ <goals>
+ <goal>shade</goal>
+ </goals>
+ <configuration>
+ <shadedArtifactAttached>true</shadedArtifactAttached>
+ <shadedClassifierName>executable</shadedClassifierName>
+ <filters>
+ <filter>
+ <artifact>*:*</artifact>
+ <!-- causing SecurityException -->
+ <excludes>
+ <exclude>META-INF/*.SF</exclude>
+ <exclude>META-INF/*.DSA</exclude>
+ <exclude>META-INF/*.RSA</exclude>
+ </excludes>
+ </filter>
+ </filters>
+ <transformers>
+ <transformer implementation= "org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
+ <mainClass>org.opendaylight.controller.akka.segjournal.BenchmarkMain</mainClass>
+ </transformer>
+ </transformers>
+ </configuration>
+ </execution>
+ </executions>
+ </plugin>
+ </plugins>
+ </build>
+
+ <profiles>
+ <profile>
+ <id>benchmarks</id>
+ <build>
+ <plugins>
+ <plugin>
+ <groupId>org.codehaus.mojo</groupId>
+ <artifactId>exec-maven-plugin</artifactId>
+ <version>3.1.1</version>
+ <executions>
+ <execution>
+ <id>execute-segmented-journal-benchmark</id>
+ <phase>integration-test</phase>
+ <goals>
+ <goal>exec</goal>
+ </goals>
+ </execution>
+ </executions>
+ <configuration>
+ <executable>java</executable>
+ <useMavenLogger>true</useMavenLogger>
+ <arguments>
+ <argument>-classpath</argument>
+ <!-- includes all dependencies to class path -->
+ <classpath/>
+ <argument>org.opendaylight.controller.akka.segjournal.BenchmarkMain</argument>
+ <!-- configuration taken from factory-akka.conf of sal-clustering-config -->
+ <argument>--current</argument>
+ <!-- 100_000 messages to write -->
+ <argument>-n100000</argument>
+ <!-- message payload is 100K -->
+ <argument>-p100K</argument>
+ </arguments>
+ </configuration>
+ </plugin>
+ </plugins>
+ </build>
+ </profile>
+ </profiles>
+</project>
\ No newline at end of file
--- /dev/null
+/*
+ * Copyright (c) 2024 PANTHEON.tech s.r.o. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.controller.akka.segjournal;
+
+import static org.opendaylight.controller.akka.segjournal.BenchmarkUtils.buildConfig;
+import static org.opendaylight.controller.akka.segjournal.BenchmarkUtils.formatBytes;
+import static org.opendaylight.controller.akka.segjournal.BenchmarkUtils.formatNanos;
+import static org.opendaylight.controller.akka.segjournal.BenchmarkUtils.toMetricId;
+
+import akka.actor.ActorRef;
+import akka.actor.ActorSystem;
+import akka.persistence.AtomicWrite;
+import akka.persistence.PersistentRepr;
+import com.google.common.base.Stopwatch;
+import com.google.common.util.concurrent.ThreadFactoryBuilder;
+import java.io.Serializable;
+import java.util.Optional;
+import java.util.Queue;
+import java.util.concurrent.ConcurrentLinkedQueue;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.Executors;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.ThreadLocalRandom;
+import java.util.concurrent.TimeUnit;
+import org.apache.commons.io.FileUtils;
+import org.opendaylight.controller.akka.segjournal.BenchmarkUtils.BenchmarkConfig;
+import org.opendaylight.controller.akka.segjournal.SegmentedJournalActor.WriteMessages;
+import org.opendaylight.controller.cluster.common.actor.MeteringBehavior;
+import org.opendaylight.controller.cluster.reporting.MetricsReporter;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import scala.concurrent.Future;
+
+public final class BenchmarkMain {
+ private static final String BENCHMARK = "benchmark";
+ private static final Logger LOG = LoggerFactory.getLogger("benchmark");
+
+ public static void main(String[] args) {
+ final var config = buildConfig(args);
+ final var benchmark = new BenchmarkMain(config);
+ Runtime.getRuntime().addShutdownHook(new Thread(benchmark::shutdown));
+ benchmark.execute();
+ System.exit(0);
+ }
+
+ private final BenchmarkConfig config;
+ private final ActorSystem system;
+ private final ScheduledExecutorService executor;
+ private ActorRef actor;
+
+ private BenchmarkMain(BenchmarkConfig config) {
+ this.config = config;
+ system = ActorSystem.create(BENCHMARK);
+ executor = Executors.newSingleThreadScheduledExecutor(
+ new ThreadFactoryBuilder().setNameFormat("progress-check-%d").build());
+ }
+
+ void execute() {
+ LOG.info("Starting with settings");
+ LOG.info("\tstorage : {}", config.storage());
+ LOG.info("\tworking dir : {}", config.workingDir().getAbsolutePath());
+ LOG.info("\tmaxEntrySize : {}", formatBytes(config.maxEntrySize()));
+ LOG.info("\tmaxSegmentSize : {}", formatBytes(config.maxSegmentSize()));
+ LOG.info("\tmaxUnflushedBytes : {}", formatBytes(config.maxUnflushedBytes()));
+
+ final var minLoadSize = Math.round(config.payloadSize() * 0.8f);
+ final var maxLoadSize = Math.min(Math.round(config.payloadSize() * 1.2f), config.maxEntrySize());
+ LOG.info("Preparing load");
+ LOG.info("\tnumber of messages : {}", config.messagesNum());
+ LOG.info("\tpayload size : {} .. {}", formatBytes(minLoadSize), formatBytes(maxLoadSize));
+
+ // reset metrics
+ final var metricsRegistry = MetricsReporter.getInstance(MeteringBehavior.DOMAIN).getMetricsRegistry();
+ final var keys = metricsRegistry.getMetrics().keySet();
+ keys.forEach(metricsRegistry::remove);
+
+ // get actor
+ actor = system.actorOf(
+ SegmentedJournalActor.props("perf", config.workingDir(), config.storage(),
+ config.maxEntrySize(), config.maxSegmentSize(), config.maxUnflushedBytes()));
+
+ // randomize payloads
+ final var random = ThreadLocalRandom.current();
+ final var payloads = new Payload[1_000];
+ for (int i = 0; i < payloads.length; ++i) {
+ final var bytes = new byte[random.nextInt(minLoadSize, maxLoadSize)];
+ random.nextBytes(bytes);
+ payloads[i] = new Payload(bytes);
+ }
+
+ // enable periodic check for completed writes
+ final var results = new ConcurrentLinkedQueue<Future<Optional<Exception>>>();
+ final var progressReporter =
+ new ProgressReporter(executor, results, config.messagesNum(), 10, TimeUnit.SECONDS);
+
+ // start async message writing
+ final var sw = Stopwatch.createStarted();
+ for (int i = 0; i < config.messagesNum(); ++i) {
+ results.add(writeMessage(i, payloads[random.nextInt(payloads.length)]));
+ }
+ LOG.info("{} Messages sent to akka in {}", config.messagesNum(), sw);
+
+ // await completion
+ try {
+ progressReporter.awaitCompletion();
+ } catch (InterruptedException e) {
+ LOG.error("Interrupted", e);
+ }
+ LOG.info("Messages written in {}", sw.stop());
+
+ // report
+ LOG.info("Following metrics collected");
+ // meters
+ metricsRegistry.getMeters().forEach((key, meter) -> {
+ LOG.info("Meter '{}'", toMetricId(key));
+ LOG.info("\tCount = {}", meter.getCount());
+ LOG.info("\tMean Rate = {}", meter.getMeanRate());
+ LOG.info("\t1 Min Rate = {}", meter.getOneMinuteRate());
+ LOG.info("\t5 Min Rate = {}", meter.getFiveMinuteRate());
+ LOG.info("\t15 Min Rate = {}", meter.getFifteenMinuteRate());
+ });
+ // timers
+ metricsRegistry.getTimers().forEach((key, timer) -> {
+ LOG.info("Timer '{}'", toMetricId(key));
+ final var snap = timer.getSnapshot();
+ LOG.info("\tMin = {}", formatNanos(snap.getMin()));
+ LOG.info("\tMax = {}", formatNanos(snap.getMax()));
+ LOG.info("\tMean = {}", formatNanos(snap.getMean()));
+ LOG.info("\tStdDev = {}", formatNanos(snap.getStdDev()));
+ LOG.info("\tMedian = {}", formatNanos(snap.getMedian()));
+ LOG.info("\t75th = {}", formatNanos(snap.get75thPercentile()));
+ LOG.info("\t95th = {}", formatNanos(snap.get95thPercentile()));
+ LOG.info("\t98th = {}", formatNanos(snap.get98thPercentile()));
+ LOG.info("\t99th = {}", formatNanos(snap.get99thPercentile()));
+ LOG.info("\t99.9th = {}", formatNanos(snap.get999thPercentile()));
+ });
+ // histograms
+ metricsRegistry.getHistograms().forEach((key, histogram) -> {
+ LOG.info("Histogram '{}'", toMetricId(key));
+ final var snap = histogram.getSnapshot();
+ LOG.info("\tMin = {}", snap.getMin());
+ LOG.info("\tMax = {}", snap.getMax());
+ LOG.info("\tMean = {}", snap.getMean());
+ LOG.info("\tStdDev = {}", snap.getStdDev());
+ LOG.info("\tMedian = {}", snap.getMedian());
+ LOG.info("\t75th = {}", snap.get75thPercentile());
+ LOG.info("\t95th = {}", snap.get95thPercentile());
+ LOG.info("\t98th = {}", snap.get98thPercentile());
+ LOG.info("\t99th = {}", snap.get99thPercentile());
+ LOG.info("\t99.9th = {}", snap.get999thPercentile());
+ });
+ }
+
+ Future<Optional<Exception>> writeMessage(final long seqNum, final Payload payload) {
+ final var writeMessage = new WriteMessages();
+ final var result = writeMessage.add(AtomicWrite.apply(
+ PersistentRepr.apply(payload, seqNum, BENCHMARK, null, false, ActorRef.noSender(), "uuid")));
+ actor.tell(writeMessage, ActorRef.noSender());
+ return result;
+ }
+
+ void shutdown() {
+ LOG.info("shutting down ...");
+ executor.shutdown();
+ if (actor != null) {
+ system.stop(actor);
+ }
+ if (config.workingDir().exists()) {
+ FileUtils.deleteQuietly(config.workingDir());
+ }
+ system.terminate();
+ LOG.info("Done.");
+ }
+
+ private static final class Payload implements Serializable {
+ @java.io.Serial
+ private static final long serialVersionUID = 1L;
+ final byte[] bytes;
+
+ Payload(final byte[] bytes) {
+ this.bytes = bytes;
+ }
+ }
+
+ private static final class ProgressReporter implements Runnable {
+ final ScheduledExecutorService executor;
+ final CountDownLatch latch = new CountDownLatch(1);
+ final Queue<Future<Optional<Exception>>> queue;
+ final long total;
+ final int checkInterval;
+ final TimeUnit timeUnit;
+ long completed;
+ long errors;
+
+ ProgressReporter(final ScheduledExecutorService executor, final Queue<Future<Optional<Exception>>> queue,
+ final long total, final int checkInterval, final TimeUnit timeUnit) {
+ this.executor = executor;
+ this.queue = queue;
+ this.total = total;
+ this.checkInterval = checkInterval;
+ this.timeUnit = timeUnit;
+ scheduleNextCheck();
+ }
+
+ @Override
+ public void run() {
+ // release completed from the beginning of the queue
+ while (!queue.isEmpty() && queue.peek().isCompleted()) {
+ final var future = queue.poll();
+ completed++;
+ if (!future.value().get().get().isEmpty()) {
+ errors++;
+ }
+ }
+ LOG.info("{} of {} = {}% messages written, {} in queue",
+ completed, total, completed * 100 / total, queue.size());
+ if (total == completed) {
+ LOG.info("Check completed, errors found : {}", errors);
+ latch.countDown();
+ return;
+ }
+ scheduleNextCheck();
+ }
+
+ void scheduleNextCheck() {
+ executor.schedule(this, checkInterval, timeUnit);
+ }
+
+ void awaitCompletion() throws InterruptedException {
+ latch.await();
+ }
+ }
+}
--- /dev/null
+/*
+ * Copyright (c) 2024 PANTHEON.tech s.r.o. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.controller.akka.segjournal;
+
+import static org.opendaylight.controller.akka.segjournal.SegmentedFileJournal.STORAGE_MAX_ENTRY_SIZE;
+import static org.opendaylight.controller.akka.segjournal.SegmentedFileJournal.STORAGE_MAX_ENTRY_SIZE_DEFAULT;
+import static org.opendaylight.controller.akka.segjournal.SegmentedFileJournal.STORAGE_MAX_SEGMENT_SIZE;
+import static org.opendaylight.controller.akka.segjournal.SegmentedFileJournal.STORAGE_MAX_SEGMENT_SIZE_DEFAULT;
+import static org.opendaylight.controller.akka.segjournal.SegmentedFileJournal.STORAGE_MAX_UNFLUSHED_BYTES;
+import static org.opendaylight.controller.akka.segjournal.SegmentedFileJournal.STORAGE_MEMORY_MAPPED;
+
+import com.google.common.base.Stopwatch;
+import com.google.common.base.Ticker;
+import com.typesafe.config.Config;
+import com.typesafe.config.ConfigFactory;
+import io.atomix.storage.journal.StorageLevel;
+import java.io.File;
+import java.io.IOException;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.util.HashMap;
+import java.util.Map;
+import net.sourceforge.argparse4j.ArgumentParsers;
+import net.sourceforge.argparse4j.impl.Arguments;
+import net.sourceforge.argparse4j.inf.ArgumentParser;
+import net.sourceforge.argparse4j.inf.ArgumentParserException;
+
+@SuppressWarnings("RegexpSinglelineJava")
+final class BenchmarkUtils {
+
+ static final String PROG_NAME = "segjourlan-benchmark";
+
+ static final String BENCHMARK_USE_CURRENT = "current";
+ static final String BENCHMARK_NUMBER_OF_MESSAGES = "messages-num";
+ static final String BENCHMARK_PAYLOAD_SIZE = "payload-size";
+ static final String BENCHMARK_PAYLOAD_SIZE_DEFAULT = "10K";
+
+ static final String CURRENT_CONFIG_RESOURCE = "/initial/factory-akka.conf";
+ static final String CURRENT_CONFIG_PATH = "odl-cluster-data.akka.persistence.journal.segmented-file";
+
+ private static final String[] BYTE_SFX = {"G", "M", "K"};
+ private static final int[] BYTE_THRESH = {1024 * 1024 * 1024, 1024 * 1024, 1024};
+
+ record BenchmarkConfig(StorageLevel storage, File workingDir, int maxEntrySize, int maxSegmentSize,
+ int maxUnflushedBytes, int payloadSize, int messagesNum) {
+ }
+
+ private BenchmarkUtils() {
+ // utility class
+ }
+
+ static BenchmarkConfig buildConfig(final String[] args) {
+ final var parser = getArgumentParser();
+ final var paramsMap = new HashMap<String, Object>();
+ try {
+ parser.parseArgs(args, paramsMap);
+ } catch (ArgumentParserException e) {
+ parser.handleError(e);
+ System.exit(1);
+ return null;
+ }
+ return toConfig(paramsMap);
+ }
+
+ private static ArgumentParser getArgumentParser() {
+ final var parser = ArgumentParsers.newArgumentParser(PROG_NAME).defaultHelp(true);
+
+ parser.description("Performs asynchronous write to segmented journal, collects and prints variety of metrics");
+
+ parser.addArgument("--current")
+ .type(Boolean.class).setDefault(Boolean.FALSE)
+ .action(Arguments.storeConst()).setConst(Boolean.TRUE)
+ .dest(BENCHMARK_USE_CURRENT)
+ .help("indicates base configuration to be taken from current cluster configuration, "
+ + "all other arguments excepting 'requests' and 'payload size' will be ignored");
+
+ parser.addArgument("--memory-mapped")
+ .type(Boolean.class).setDefault(Boolean.FALSE)
+ .action(Arguments.storeConst()).setConst(Boolean.TRUE)
+ .dest(STORAGE_MEMORY_MAPPED)
+ .help("indicates mapping journal segments to memory, otherwise file system is used");
+
+ parser.addArgument("-e", "--max-entry-size")
+ .type(String.class).setDefault(formatBytes(STORAGE_MAX_ENTRY_SIZE_DEFAULT))
+ .dest(STORAGE_MAX_ENTRY_SIZE)
+ .help("max entry size, bytes format");
+
+ parser.addArgument("-s", "--max-segment-size")
+ .type(String.class).setDefault(formatBytes(STORAGE_MAX_SEGMENT_SIZE_DEFAULT))
+ .dest(STORAGE_MAX_SEGMENT_SIZE)
+ .help("max segment size, bytes ");
+
+ parser.addArgument("-u", "--max-unflushed-bytes")
+ .type(String.class)
+ .dest(STORAGE_MAX_UNFLUSHED_BYTES)
+ .help("max unflushed bytes, bytes format, "
+ + "if not defined the value is taken from 'max-entry-size'");
+
+ parser.addArgument("-n", "--messages-num")
+ .type(Integer.class).required(true)
+ .dest(BENCHMARK_NUMBER_OF_MESSAGES)
+ .setDefault(10_000)
+ .help("number of messages to write");
+
+ parser.addArgument("-p", "--payload-size")
+ .type(String.class).setDefault(BENCHMARK_PAYLOAD_SIZE_DEFAULT)
+ .dest(BENCHMARK_PAYLOAD_SIZE)
+ .help("median for request payload size, bytes format supported, "
+ + "actual size is variable 80% to 120% from defined median value");
+
+ return parser;
+ }
+
+ static BenchmarkConfig toConfig(final Map<String, Object> paramsMap) {
+ final var inputConfig = ConfigFactory.parseMap(paramsMap);
+ final var finalConfig = (Boolean) paramsMap.get(BENCHMARK_USE_CURRENT)
+ ? currentConfig().withFallback(inputConfig) : inputConfig;
+
+ final var benchmarkConfig = new BenchmarkConfig(
+ finalConfig.getBoolean(STORAGE_MEMORY_MAPPED) ? StorageLevel.MAPPED : StorageLevel.DISK,
+ createTempDirectory(),
+ bytes(finalConfig, STORAGE_MAX_ENTRY_SIZE),
+ bytes(finalConfig, STORAGE_MAX_SEGMENT_SIZE),
+ finalConfig.hasPath(STORAGE_MAX_UNFLUSHED_BYTES)
+ ? bytes(finalConfig, STORAGE_MAX_UNFLUSHED_BYTES) : bytes(finalConfig, STORAGE_MAX_ENTRY_SIZE),
+ bytes(finalConfig, BENCHMARK_PAYLOAD_SIZE),
+ finalConfig.getInt(BENCHMARK_NUMBER_OF_MESSAGES)
+ );
+ // validate
+ if (benchmarkConfig.payloadSize > benchmarkConfig.maxEntrySize) {
+ printAndExit("payloadSize should be less than maxEntrySize");
+ }
+ return benchmarkConfig;
+ }
+
+ private static int bytes(final Config config, final String key) {
+ final var bytesLong = config.getBytes(key);
+ if (bytesLong <= 0 || bytesLong > Integer.MAX_VALUE) {
+ printAndExit(
+ key + " value (" + bytesLong + ") is invalid, expected in range 1 .. " + Integer.MAX_VALUE);
+ }
+ return bytesLong.intValue();
+ }
+
+ static Config currentConfig() {
+ try (var in = BenchmarkUtils.class.getResourceAsStream(CURRENT_CONFIG_RESOURCE)) {
+ final var content = new String(in.readAllBytes(), StandardCharsets.UTF_8);
+ final var globalConfig = ConfigFactory.parseString(content);
+ final var currentConfig = globalConfig.getConfig(CURRENT_CONFIG_PATH);
+ System.out.println("Current configuration loaded from " + CURRENT_CONFIG_RESOURCE);
+ return currentConfig;
+
+ } catch (IOException e) {
+ printAndExit("Error loading current configuration from resource " + CURRENT_CONFIG_RESOURCE, e);
+ return null;
+ }
+ }
+
+ private static File createTempDirectory() {
+ try {
+ return Files.createTempDirectory(PROG_NAME).toFile();
+ } catch (IOException e) {
+ printAndExit("Cannot create temp directory", e);
+ }
+ return null;
+ }
+
+ private static void printAndExit(final String message) {
+ printAndExit(message, null);
+ }
+
+ private static void printAndExit(final String message, final Exception exception) {
+ System.err.println(message);
+ if (exception != null) {
+ exception.printStackTrace(System.err);
+ }
+ System.exit(1);
+ }
+
+ static String formatBytes(int bytes) {
+ for (int i = 0; i < 3; i++) {
+ if (bytes > BYTE_THRESH[i]) {
+ return bytes / BYTE_THRESH[i] + BYTE_SFX[i];
+ }
+ }
+ return String.valueOf(bytes);
+ }
+
+ static String formatNanos(final double nanos) {
+ return formatNanos(Math.round(nanos));
+ }
+
+ static String formatNanos(final long nanos) {
+ return Stopwatch.createStarted(new Ticker() {
+ boolean started;
+
+ @Override
+ public long read() {
+ if (started) {
+ return nanos;
+ }
+ started = true;
+ return 0;
+ }
+ }).toString();
+ }
+
+ static String toMetricId(final String metricKey) {
+ return metricKey.substring(metricKey.lastIndexOf('.') + 1);
+ }
+}
--- /dev/null
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+ Copyright (c) 2024 PANTHEON.tech s.r.o. and others. All rights reserved.
+
+ This program and the accompanying materials are made available under the
+ terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ and is available at http://www.eclipse.org/legal/epl-v10.html
+ -->
+<configuration>
+ <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
+ <encoder>
+ <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
+ </pattern>
+ </encoder>
+ </appender>
+
+ <root level="INFO">
+ <appender-ref ref="STDOUT" />
+ </root>
+</configuration>
\ No newline at end of file
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.opendaylight.mdsal</groupId>
- <artifactId>dom-parent</artifactId>
- <version>11.0.4</version>
+ <artifactId>bundle-parent</artifactId>
+ <version>13.0.1</version>
<relativePath/>
</parent>
<groupId>org.opendaylight.controller</groupId>
<artifactId>bundle-parent</artifactId>
- <version>7.0.2-SNAPSHOT</version>
+ <version>9.0.3-SNAPSHOT</version>
<packaging>pom</packaging>
<dependencyManagement>
<dependency>
<groupId>org.opendaylight.controller</groupId>
<artifactId>controller-artifacts</artifactId>
- <version>7.0.2-SNAPSHOT</version>
+ <version>9.0.3-SNAPSHOT</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>org.scala-lang</groupId>
<artifactId>scala-library</artifactId>
- <version>2.13.10</version>
+ <version>2.13.13</version>
</dependency>
<dependency>
<groupId>org.scala-lang</groupId>
<artifactId>scala-reflect</artifactId>
- <version>2.13.10</version>
+ <version>2.13.13</version>
</dependency>
<dependency>
<groupId>org.scala-lang.modules</groupId>
<dependency>
<groupId>com.typesafe.akka</groupId>
<artifactId>akka-testkit_2.13</artifactId>
- <version>2.6.20</version>
+ <version>2.6.21</version>
<scope>test</scope>
<exclusions>
<exclusion>
<dependency>
<groupId>com.typesafe.akka</groupId>
<artifactId>akka-actor-testkit-typed_2.13</artifactId>
- <version>2.6.20</version>
+ <version>2.6.21</version>
<scope>test</scope>
<exclusions>
<exclusion>
<dependency>
<groupId>com.typesafe.akka</groupId>
<artifactId>akka-persistence-tck_2.13</artifactId>
- <version>2.6.20</version>
+ <version>2.6.21</version>
<scope>test</scope>
<exclusions>
<exclusion>
The OpenDaylight Controller provides following model-driven subsystems
as a foundation for Java applications:
-- :ref:`config_subsystem` - an activation,
- dependency-injection and configuration framework, which allows
- two-phase commits of configuration and dependency-injection, and
- allows for run-time rewiring.
-
- :ref:`MD-SAL <mdsal_dev_guide>` - messaging and data storage
functionality for data, notifications and RPCs modeled by application
developers. MD-SAL uses YANG as the modeling for both interface and
.. note::
- | Each request must start with the URI /restconf.
+ | Each request must start with the URI /rests.
| RESTCONF listens on port 8080 for HTTP requests.
RESTCONF supports **OPTIONS**, **GET**, **PUT**, **POST**, and
**DELETE** operations. Request and response data can either be in the
XML or JSON format. XML structures according to yang are defined at:
-`XML-YANG <http://tools.ietf.org/html/rfc6020>`__. JSON structures are
+`XML-YANG <https://www.rfc-editor.org/rfc/rfc6020>`__. JSON structures are
defined at:
-`JSON-YANG <http://tools.ietf.org/html/draft-lhotka-netmod-yang-json-02>`__.
+`JSON-YANG <https://datatracker.ietf.org/doc/html/draft-lhotka-netmod-yang-json-02>`__.
Data in the request must have a correctly set **Content-Type** field in
the http header with the allowed value of the media type. The media type
of the requested data has to be set in the **Accept** field. Get the
media types for each resource by calling the OPTIONS operation. Most of
the paths of the pathsRestconf endpoints use `Instance
-Identifier <https://wiki.opendaylight.org/view/OpenDaylight_Controller:MD-SAL:Concepts#Instance_Identifier>`__.
+Identifier <https://wiki-archive.opendaylight.org/view/OpenDaylight_Controller:MD-SAL:Concepts#Instance_Identifier>`__.
``<identifier>`` is used in the explanation of the operations.
| **<identifier>**
- <nodeName> can represent a data node which is a list or container
yang built-in type. If the data node is a list, there must be defined
keys of the list behind the data node name for example,
- <nodeName>/<valueOfKey1>/<valueOfKey2>.
+ <nodeName>=<valueOfKey1>,<valueOfKey2>.
- | The format <moduleName>:<nodeName> has to be used in this case as
well:
| Module A has node A1. Module B augments node A1 by adding node X.
Module C augments node A1 by adding node X. For clarity, it has to
be known which node is X (for example: C:X). For more details about
- encoding, see: `RESTCONF 02 - Encoding YANG Instance Identifiers in
+ encoding, see: `RESTCONF RFC 8040 - Encoding YANG Instance Identifiers in
the Request
- URI. <http://tools.ietf.org/html/draft-bierman-netconf-restconf-02#section-5.3.1>`__
+ URI. <https://datatracker.ietf.org/doc/html/rfc8040#section-3.5.3>`__
Mount point
~~~~~~~~~~~
point itself by using <identifier>/**yang-ext:mount**.
| More information on how to actually use mountpoints is available at:
`OpenDaylight
- Controller:Config:Examples:Netconf <https://wiki.opendaylight.org/view/OpenDaylight_Controller:Config:Examples:Netconf>`__.
+ Controller:Config:Examples:Netconf <https://wiki-archive.opendaylight.org/view/OpenDaylight_Controller:Config:Examples:Netconf>`__.
HTTP methods
~~~~~~~~~~~~
-OPTIONS /restconf
-^^^^^^^^^^^^^^^^^
+OPTIONS /rests
+^^^^^^^^^^^^^^
- Returns the XML description of the resources with the required
request and response media types in Web Application Description
Language (WADL)
-GET /restconf/config/<identifier>
-^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+GET /rests/data/<identifier>?content=config
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
- Returns a data node from the Config datastore.
- <identifier> points to a data node which must be retrieved.
-GET /restconf/operational/<identifier>
-^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+GET /rests/data/<identifier>?content=nonconfig
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
-- Returns the value of the data node from the Operational datastore.
+- Returns the value of the data node from the non-configuration datastore.
- <identifier> points to a data node which must be retrieved.
-PUT /restconf/config/<identifier>
-^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+PUT /rests/data/<identifier>
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^
- Updates or creates data in the Config datastore and returns the state
about success.
::
- PUT http://<controllerIP>:8080/restconf/config/module1:foo/bar
+ PUT http://<controllerIP>:8080/rests/data/module1:foo/bar
Content-Type: applicaton/xml
<bar>
…
::
- PUT http://<controllerIP>:8080/restconf/config/module1:foo1/foo2/yang-ext:mount/module2:foo/bar
+ PUT http://<controllerIP>:8080/rests/data/module1:foo1/foo2/yang-ext:mount/module2:foo/bar
Content-Type: applicaton/xml
<bar>
…
</bar>
-POST /restconf/config
-^^^^^^^^^^^^^^^^^^^^^
+POST /rests/data
+^^^^^^^^^^^^^^^^
- Creates the data if it does not exist
::
- POST URL: http://localhost:8080/restconf/config/
+ POST URL: http://localhost:8080/rests/data/
content-type: application/yang.data+json
JSON payload:
}
}
-POST /restconf/config/<identifier>
-^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+POST /rests/data/<identifier>
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
- Creates the data if it does not exist in the Config datastore, and
returns the state about success.
::
- POST http://<controllerIP>:8080/restconf/config/module1:foo
+ POST http://<controllerIP>:8080/rests/data/module1:foo
Content-Type: applicaton/xml/
<bar xmlns=“module1namespace”>
…
::
- http://<controllerIP>:8080/restconf/config/module1:foo1/foo2/yang-ext:mount/module2:foo
+ http://<controllerIP>:8080/rests/data/module1:foo1/foo2/yang-ext:mount/module2:foo
Content-Type: applicaton/xml
<bar xmlns=“module2namespace”>
…
</bar>
-POST /restconf/operations/<moduleName>:<rpcName>
-^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+POST /rests/operations/<moduleName>:<rpcName>
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
- Invokes RPC.
::
- POST http://<controllerIP>:8080/restconf/operations/module1:fooRpc
+ POST http://<controllerIP>:8080/rests/operations/module1:fooRpc
Content-Type: applicaton/xml
Accept: applicaton/xml
<input>
::
- POST http://localhost:8080/restconf/operations/toaster:make-toast
+ POST http://localhost:8080/rests/operations/toaster:make-toast
Content-Type: application/yang.data+json
{
"input" :
Even though this is a default for the toasterToastType value in the
yang, you still need to define it.
-DELETE /restconf/config/<identifier>
-^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+DELETE /rests/data/<identifier>
+^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
- Removes the data node in the Config datastore and returns the state
about success.
- <identifier> points to a data node which must be removed.
More information is available in the `RESTCONF
-RFC <http://tools.ietf.org/html/draft-bierman-netconf-restconf-02>`__.
+RFC <https://datatracker.ietf.org/doc/html/rfc8040>`__.
How RESTCONF works
~~~~~~~~~~~~~~~~~~
GET in action
~~~~~~~~~~~~~
-Figure 1 shows the GET operation with URI restconf/config/M:N where M is
-the module name, and N is the node name.
+Figure 1 shows the GET operation with URI rests/data/M:N?content=config
+where M is the module name, and N is the node name.
.. figure:: ./images/Get.png
:alt: Get
PUT in action
~~~~~~~~~~~~~
-Figure 2 shows the PUT operation with the URI restconf/config/M:N where
+Figure 2 shows the PUT operation with the URI rests/data/M:N where
M is the module name, and N is the node name. Data is sent in the
request either in the XML or JSON format.
::
Operation: POST
- URI: http://192.168.11.1:8080/restconf/config/opendaylight-inventory:nodes/node/openflow:1/table/2
+ URI: http://192.168.11.1:8080/rests/data/opendaylight-inventory:nodes/node=openflow:1/table=2
Content-Type: application/xml
::
::
Operation: PUT
- URI: http://192.168.11.1:8080/restconf/config/opendaylight-inventory:nodes/node/openflow:1/table/2/flow/111
+ URI: http://192.168.11.1:8080/rests/data/opendaylight-inventory:nodes/node=openflow:1/table=2/flow=111
Content-Type: application/xml
::
::
Operation: GET
- URI: http://192.168.11.1:8080/restconf/config/opendaylight-inventory:nodes/node/openflow:1/table/2/flow/111
+ URI: http://192.168.11.1:8080/rests/data/opendaylight-inventory:nodes/node=openflow:1/table=2/flow=111?content=config
Accept: application/xml
| **HTTP response**
::
Operation: DELETE
- URI: http://192.168.11.1:8080/restconf/config/opendaylight-inventory:nodes/node/openflow:1/table/2/flow/111
+ URI: http://192.168.11.1:8080/rests/data/opendaylight-inventory:nodes/node=openflow:1/table=2/flow=111
| **HTTP response**
Status: 200 OK
-Websocket change event notification subscription tutorial
----------------------------------------------------------
-
-Subscribing to data change notifications makes it possible to obtain
-notifications about data manipulation (insert, change, delete) which are
-done on any specified **path** of any specified **datastore** with
-specific **scope**. In following examples *{odlAddress}* is address of
-server where ODL is running and *{odlPort}* is port on which
-OpenDaylight is running.
-
-Websocket notifications subscription process
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-
-In this section we will learn what steps need to be taken in order to
-successfully subscribe to data change event notifications.
-
-Create stream
-^^^^^^^^^^^^^
-
-In order to use event notifications you first need to call RPC that
-creates notification stream that you can later listen to. You need to
-provide three parameters to this RPC:
-
-- **path**: data store path that you plan to listen to. You can
- register listener on containers, lists and leaves.
-
-- **datastore**: data store type. *OPERATIONAL* or *CONFIGURATION*.
-
-- **scope**: Represents scope of data change. Possible options are:
-
- - BASE: only changes directly to the data tree node specified in the
- path will be reported
-
- - ONE: changes to the node and to direct child nodes will be
- reported
-
- - SUBTREE: changes anywhere in the subtree starting at the node will
- be reported
-
-The RPC to create the stream can be invoked via RESTCONF like this:
-
-- URI:
- http://{odlAddress}:{odlPort}/restconf/operations/sal-remote:create-data-change-event-subscription
-
-- HEADER: Content-Type=application/json
-
-- OPERATION: POST
-
-- DATA:
-
- .. code:: json
-
- {
- "input": {
- "path": "/toaster:toaster/toaster:toasterStatus",
- "sal-remote-augment:datastore": "OPERATIONAL",
- "sal-remote-augment:scope": "ONE"
- }
- }
-
-The response should look something like this:
-
-.. code:: json
-
- {
- "output": {
- "stream-name": "data-change-event-subscription/toaster:toaster/toaster:toasterStatus/datastore=CONFIGURATION/scope=SUBTREE"
- }
- }
-
-**stream-name** is important because you will need to use it when you
-subscribe to the stream in the next step.
-
-.. note::
-
- Internally, this will create a new listener for *stream-name* if it
- did not already exist.
-
-Subscribe to stream
-^^^^^^^^^^^^^^^^^^^
-
-In order to subscribe to stream and obtain WebSocket location you need
-to call *GET* on your stream path. The URI should generally be
-http://{odlAddress}:{odlPort}/restconf/streams/stream/{streamName},
-where *{streamName}* is the *stream-name* parameter contained in
-response from *create-data-change-event-subscription* RPC from the
-previous step.
-
-- URI:
- http://{odlAddress}:{odlPort}/restconf/streams/stream/data-change-event-subscription/toaster:toaster/datastore=CONFIGURATION/scope=SUBTREE
-
-- OPERATION: GET
-
-The subscription call may be modified with the following query parameters defined in the RESTCONF RFC:
-
-- `filter <https://tools.ietf.org/html/draft-ietf-netconf-restconf-05#section-4.8.6>`__
-
-- `start-time <https://tools.ietf.org/html/draft-ietf-netconf-restconf-05#section-4.8.7>`__
-
-- `end-time <https://tools.ietf.org/html/draft-ietf-netconf-restconf-05#section-4.8.8>`__
-
-In addition, the following ODL extension query parameter is supported:
-
-:odl-leaf-nodes-only:
- If this parameter is set to "true", create and update notifications will only
- contain the leaf nodes modified instead of the entire subscription subtree.
- This can help in reducing the size of the notifications.
-
-:odl-skip-notification-data:
- If this parameter is set to "true", create and update notifications will only
- contain modified leaf nodes without data.
- This can help in reducing the size of the notifications.
-
-The expected response status is 200 OK and response body should be
-empty. You will get your WebSocket location from **Location** header of
-response. For example in our particular toaster example location header
-would have this value:
-*ws://{odlAddress}:8185/toaster:toaster/datastore=CONFIGURATION/scope=SUBTREE*
-
-.. note::
-
- During this phase there is an internal check for to see if a
- listener for the *stream-name* from the URI exists. If not, new a
- new listener is registered with the DOM data broker.
-
-Receive notifications
-^^^^^^^^^^^^^^^^^^^^^
-
-You should now have a data change notification stream created and have
-location of a WebSocket. You can use this WebSocket to listen to data
-change notifications. To listen to notifications you can use a
-JavaScript client or if you are using chrome browser you can use the
-`Simple WebSocket
-Client <https://chrome.google.com/webstore/detail/simple-websocket-client/pfdhoblngboilpfeibdedpjgfnlcodoo>`__.
-
-Also, for testing purposes, there is simple Java application named
-WebSocketClient. The application is placed in the
-*-sal-rest-connector-classes.class* project. It accepts a WebSocket URI
-as and input parameter. After starting the utility (WebSocketClient
-class directly in Eclipse/InteliJ Idea) received notifications should be
-displayed in console.
-
-Notifications are always in XML format and look like this:
-
-.. code:: xml
-
- <notification xmlns="urn:ietf:params:xml:ns:netconf:notification:1.0">
- <eventTime>2014-09-11T09:58:23+02:00</eventTime>
- <data-changed-notification xmlns="urn:opendaylight:params:xml:ns:yang:controller:md:sal:remote">
- <data-change-event>
- <path xmlns:meae="http://netconfcentral.org/ns/toaster">/meae:toaster</path>
- <operation>updated</operation>
- <data>
- <!-- updated data -->
- </data>
- </data-change-event>
- </data-changed-notification>
- </notification>
-
-Example use case
-~~~~~~~~~~~~~~~~
-
-The typical use case is listening to data change events to update web
-page data in real-time. In this tutorial we will be using toaster as the
-base.
-
-When you call *make-toast* RPC, it sets *toasterStatus* to "down" to
-reflect that the toaster is busy making toast. When it finishes,
-*toasterStatus* is set to "up" again. We will listen to this toaster
-status changes in data store and will reflect it on our web page in
-real-time thanks to WebSocket data change notification.
-
-Simple javascript client implementation
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-
-We will create simple JavaScript web application that will listen
-updates on *toasterStatus* leaf and update some element of our web page
-according to new toaster status state.
-
-Create stream
-^^^^^^^^^^^^^
-
-First you need to create stream that you are planing to subscribe to.
-This can be achieved by invoking "create-data-change-event-subscription"
-RPC on RESTCONF via AJAX request. You need to provide data store
-**path** that you plan to listen on, **data store type** and **scope**.
-If the request is successful you can extract the **stream-name** from
-the response and use that to subscribe to the newly created stream. The
-*{username}* and *{password}* fields represent your credentials that you
-use to connect to OpenDaylight via RESTCONF:
-
-.. note::
-
- The default user name and password are "admin".
-
-.. code:: javascript
-
- function createStream() {
- $.ajax(
- {
- url: 'http://{odlAddress}:{odlPort}/restconf/operations/sal-remote:create-data-change-event-subscription',
- type: 'POST',
- headers: {
- 'Authorization': 'Basic ' + btoa('{username}:{password}'),
- 'Content-Type': 'application/json'
- },
- data: JSON.stringify(
- {
- 'input': {
- 'path': '/toaster:toaster/toaster:toasterStatus',
- 'sal-remote-augment:datastore': 'OPERATIONAL',
- 'sal-remote-augment:scope': 'ONE'
- }
- }
- )
- }).done(function (data) {
- // this function will be called when ajax call is executed successfully
- subscribeToStream(data.output['stream-name']);
- }).fail(function (data) {
- // this function will be called when ajax call fails
- console.log("Create stream call unsuccessful");
- })
- }
-
-Subscribe to stream
-^^^^^^^^^^^^^^^^^^^
-
-The Next step is to subscribe to the stream. To subscribe to the stream
-you need to call *GET* on
-*http://{odlAddress}:{odlPort}/restconf/streams/stream/{stream-name}*.
-If the call is successful, you get WebSocket address for this stream in
-**Location** parameter inside response header. You can get response
-header by calling *getResponseHeader(\ *Location*)* on HttpRequest
-object inside *done()* function call:
-
-.. code:: javascript
-
- function subscribeToStream(streamName) {
- $.ajax(
- {
- url: 'http://{odlAddress}:{odlPort}/restconf/streams/stream/' + streamName;
- type: 'GET',
- headers: {
- 'Authorization': 'Basic ' + btoa('{username}:{password}'),
- }
- }
- ).done(function (data, textStatus, httpReq) {
- // we need function that has http request object parameter in order to access response headers.
- listenToNotifications(httpReq.getResponseHeader('Location'));
- }).fail(function (data) {
- console.log("Subscribe to stream call unsuccessful");
- });
- }
-
-Receive notifications
-^^^^^^^^^^^^^^^^^^^^^
-
-Once you got WebSocket server location you can now connect to it and
-start receiving data change events. You need to define functions that
-will handle events on WebSocket. In order to process incoming events
-from OpenDaylight you need to provide a function that will handle
-*onmessage* events. The function must have one parameter that represents
-the received event object. The event data will be stored in
-*event.data*. The data will be in an XML format that you can then easily
-parse using jQuery.
-
-.. code:: javascript
-
- function listenToNotifications(socketLocation) {
- try {
- var notificatinSocket = new WebSocket(socketLocation);
-
- notificatinSocket.onmessage = function (event) {
- // we process our received event here
- console.log('Received toaster data change event.');
- $($.parseXML(event.data)).find('data-change-event').each(
- function (index) {
- var operation = $(this).find('operation').text();
- if (operation == 'updated') {
- // toaster status was updated so we call function that gets the value of toasterStatus leaf
- updateToasterStatus();
- return false;
- }
- }
- );
- }
- notificatinSocket.onerror = function (error) {
- console.log("Socket error: " + error);
- }
- notificatinSocket.onopen = function (event) {
- console.log("Socket connection opened.");
- }
- notificatinSocket.onclose = function (event) {
- console.log("Socket connection closed.");
- }
- // if there is a problem on socket creation we get exception (i.e. when socket address is incorrect)
- } catch(e) {
- alert("Error when creating WebSocket" + e );
- }
- }
-
-The *updateToasterStatus()* function represents function that calls
-*GET* on the path that was modified and sets toaster status in some web
-page element according to received data. After the WebSocket connection
-has been established you can test events by calling make-toast RPC via
-RESTCONF.
-
-.. note::
-
- for more information about WebSockets in JavaScript visit `Writing
- WebSocket client
- applications <https://developer.mozilla.org/en-US/docs/WebSockets/Writing_WebSocket_client_applications>`__
-
-.. _config_subsystem:
-
-Config Subsystem
-----------------
-
-Overview
-~~~~~~~~
-
-The Controller configuration operation has three stages:
-
-- First, a Proposed configuration is created. Its target is to replace
- the old configuration.
-
-- Second, the Proposed configuration is validated, and then committed.
- If it passes validation successfully, the Proposed configuration
- state will be changed to Validated.
-
-- Finally, a Validated configuration can be Committed, and the affected
- modules can be reconfigured.
-
-In fact, each configuration operation is wrapped in a transaction. Once
-a transaction is created, it can be configured, that is to say, a user
-can abort the transaction during this stage. After the transaction
-configuration is done, it is committed to the validation stage. In this
-stage, the validation procedures are invoked. If one or more validations
-fail, the transaction can be reconfigured. Upon success, the second
-phase commit is invoked. If this commit is successful, the transaction
-enters the last stage, committed. After that, the desired modules are
-reconfigured. If the second phase commit fails, it means that the
-transaction is unhealthy - basically, a new configuration instance
-creation failed, and the application can be in an inconsistent state.
-
-.. figure:: ./images/configuration.jpg
- :alt: Configuration states
-
- Configuration states
-
-.. figure:: ./images/Transaction.jpg
- :alt: Transaction states
-
- Transaction states
-
-Validation
-~~~~~~~~~~
-
-To secure the consistency and safety of the new configuration and to
-avoid conflicts, the configuration validation process is necessary.
-Usually, validation checks the input parameters of a new configuration,
-and mostly verifies module-specific relationships. The validation
-procedure results in a decision on whether the proposed configuration is
-healthy.
-
-Dependency resolver
-~~~~~~~~~~~~~~~~~~~
-
-Since there can be dependencies between modules, a change in a module
-configuration can affect the state of other modules. Therefore, we need
-to verify whether dependencies on other modules can be resolved. The
-Dependency Resolver acts in a manner similar to dependency injectors.
-Basically, a dependency tree is built.
-
-APIs and SPIs
-~~~~~~~~~~~~~
-
-This section describes configuration system APIs and SPIs.
-
-SPIs
-^^^^
-
-**Module** org.opendaylight.controller.config.spi. Module is the common
-interface for all modules: every module must implement it. The module is
-designated to hold configuration attributes, validate them, and create
-instances of service based on the attributes. This instance must
-implement the AutoCloseable interface, owing to resources clean up. If
-the module was created from an already running instance, it contains an
-old instance of the module. A module can implement multiple services. If
-the module depends on other modules, setters need to be annotated with
-@RequireInterface.
-
-**Module creation**
-
-1. The module needs to be configured, set with all required attributes.
-
-2. The module is then moved to the commit stage for validation. If the
- validation fails, the module attributes can be reconfigured.
- Otherwise, a new instance is either created, or an old instance is
- reconfigured. A module instance is identified by ModuleIdentifier,
- consisting of the factory name and instance name.
-
-| **ModuleFactory** org.opendaylight.controller.config.spi. The
- ModuleFactory interface must be implemented by each module factory.
-| A module factory can create a new module instance in two ways:
-
-- From an existing module instance
-
-- | An entirely new instance
- | ModuleFactory can also return default modules, useful for
- populating registry with already existing configurations. A module
- factory implementation must have a globally unique name.
-
-APIs
-^^^^
-
-+--------------------------------------+--------------------------------------+
-| ConfigRegistry | Represents functionality provided by |
-| | a configuration transaction (create, |
-| | destroy module, validate, or abort |
-| | transaction). |
-+--------------------------------------+--------------------------------------+
-| ConfigTransactionController | Represents functionality for |
-| | manipulating with configuration |
-| | transactions (begin, commit config). |
-+--------------------------------------+--------------------------------------+
-| RuntimeBeanRegistratorAwareConfiBean | The module implementing this |
-| | interface will receive |
-| | RuntimeBeanRegistrator before |
-| | getInstance is invoked. |
-+--------------------------------------+--------------------------------------+
-
-Runtime APIs
-^^^^^^^^^^^^
-
-+--------------------------------------+--------------------------------------+
-| RuntimeBean | Common interface for all runtime |
-| | beans |
-+--------------------------------------+--------------------------------------+
-| RootRuntimeBeanRegistrator | Represents functionality for root |
-| | runtime bean registration, which |
-| | subsequently allows hierarchical |
-| | registrations |
-+--------------------------------------+--------------------------------------+
-| HierarchicalRuntimeBeanRegistration | Represents functionality for runtime |
-| | bean registration and |
-| | unreregistration from hierarchy |
-+--------------------------------------+--------------------------------------+
-
-JMX APIs
-^^^^^^^^
-
-| JMX API is purposed as a transition between the Client API and the JMX
- platform.
-
-+--------------------------------------+--------------------------------------+
-| ConfigTransactionControllerMXBean | Extends ConfigTransactionController, |
-| | executed by Jolokia clients on |
-| | configuration transaction. |
-+--------------------------------------+--------------------------------------+
-| ConfigRegistryMXBean | Represents entry point of |
-| | configuration management for |
-| | MXBeans. |
-+--------------------------------------+--------------------------------------+
-| Object names | Object Name is the pattern used in |
-| | JMX to locate JMX beans. It consists |
-| | of domain and key properties (at |
-| | least one key-value pair). Domain is |
-| | defined as |
-| | "org.opendaylight.controller". The |
-| | only mandatory property is "type". |
-+--------------------------------------+--------------------------------------+
-
-Use case scenarios
-^^^^^^^^^^^^^^^^^^
-
-| A few samples of successful and unsuccessful transaction scenarios
- follow:
-
-**Successful commit scenario**
-
-1. The user creates a transaction calling creteTransaction() method on
- ConfigRegistry.
-
-2. ConfigRegisty creates a transaction controller, and registers the
- transaction as a new bean.
-
-3. Runtime configurations are copied to the transaction. The user can
- create modules and set their attributes.
-
-4. The configuration transaction is to be committed.
-
-5. The validation process is performed.
-
-6. After successful validation, the second phase commit begins.
-
-7. Modules proposed to be destroyed are destroyed, and their service
- instances are closed.
-
-8. Runtime beans are set to registrator.
-
-9. The transaction controller invokes the method getInstance on each
- module.
-
-10. The transaction is committed, and resources are either closed or
- released.
-
-| **Validation failure scenario**
-| The transaction is the same as the previous case until the validation
- process.
-
-1. If validation fails, (that is to day, illegal input attributes values
- or dependency resolver failure), the validationException is thrown
- and exposed to the user.
-
-2. The user can decide to reconfigure the transaction and commit again,
- or abort the current transaction.
-
-3. On aborted transactions, TransactionController and JMXRegistrator are
- properly closed.
-
-4. Unregistration event is sent to ConfigRegistry.
-
-Default module instances
-^^^^^^^^^^^^^^^^^^^^^^^^
-
-The configuration subsystem provides a way for modules to create default
-instances. A default instance is an instance of a module, that is
-created at the module bundle start-up (module becomes visible for
-configuration subsystem, for example, its bundle is activated in the
-OSGi environment). By default, no default instances are produced.
-
-The default instance does not differ from instances created later in the
-module life-cycle. The only difference is that the configuration for the
-default instance cannot be provided by the configuration subsystem. The
-module has to acquire the configuration for these instances on its own.
-It can be acquired from, for example, environment variables. After the
-creation of a default instance, it acts as a regular instance and fully
-participates in the configuration subsystem (It can be reconfigured or
-deleted in following transactions.).
<parent>
<groupId>org.opendaylight.odlparent</groupId>
<artifactId>odlparent</artifactId>
- <version>12.0.1</version>
+ <version>13.0.11</version>
<relativePath/>
</parent>
<groupId>org.opendaylight.controller</groupId>
<artifactId>controller-docs</artifactId>
<packaging>jar</packaging>
- <version>7.0.2-SNAPSHOT</version>
+ <version>9.0.3-SNAPSHOT</version>
<name>${project.artifactId}</name>
<description>Controller documentation</description>
</dependencyManagement>
<dependencies>
- <!-- Config Subsystem remnants -->
- <dependency>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>netty-event-executor-config</artifactId>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>netty-threadgroup-config</artifactId>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>netty-timer-config</artifactId>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>threadpool-config-api</artifactId>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>threadpool-config-impl</artifactId>
- </dependency>
-
<!-- Clustered implementation -->
<dependency>
<groupId>org.opendaylight.controller</groupId>
</dependency>
<!-- Third-party dependencies -->
+ <dependency>
+ <groupId>com.github.spotbugs</groupId>
+ <artifactId>spotbugs-annotations</artifactId>
+ </dependency>
<dependency>
<groupId>com.guicedee.services</groupId>
<artifactId>javax.inject</artifactId>
<configuration combine.children="append">
<links>
<link>https://junit.org/junit4/javadoc/4.13/</link>
- <link>http://hamcrest.org/JavaHamcrest/javadoc/2.2/</link>
- <link>http://www.slf4j.org/apidocs/</link>
- <link>https://google.github.io/guava/releases/31.1-jre/api/docs/</link>
- <link>http://doc.akka.io/japi/akka/2.6.20/</link>
- <link>http://netty.io/4.1/api/</link>
+ <link>https://hamcrest.org/JavaHamcrest/javadoc/2.2/</link>
+ <link>https://www.slf4j.org/apidocs/</link>
+ <link>https://guava.dev/releases/32.0.1-jre/api/docs/</link>
+ <link>https://doc.akka.io/japi/akka/2.6/</link>
+ <link>https://netty.io/4.1/api/</link>
<link>https://commons.apache.org/proper/commons-lang/javadocs/api-release/</link>
- <link>https://www.javadoc.io/doc/org.opendaylight.odlparent/odlparent-docs/12.0.1/</link>
- <link>https://www.javadoc.io/doc/org.opendaylight.yangtools/yangtools-docs/10.0.2/</link>
- <link>https://www.javadoc.io/doc/org.opendaylight.mdsal/mdsal-docs/11.0.4/</link>
+ <link>https://www.javadoc.io/doc/org.opendaylight.odlparent/odlparent-docs/13.0.11/</link>
+ <link>https://www.javadoc.io/doc/org.opendaylight.yangtools/yangtools-docs/13.0.2/</link>
+ <link>https://www.javadoc.io/doc/org.opendaylight.mdsal/mdsal-docs/13.0.1/</link>
</links>
<groups>
<group>
<parent>
<groupId>org.opendaylight.odlparent</groupId>
<artifactId>feature-repo-parent</artifactId>
- <version>12.0.1</version>
+ <version>13.0.11</version>
<relativePath/>
</parent>
<groupId>org.opendaylight.controller</groupId>
<artifactId>features-controller-experimental</artifactId>
- <version>7.0.2-SNAPSHOT</version>
+ <version>9.0.3-SNAPSHOT</version>
<packaging>feature</packaging>
<name>OpenDaylight :: Controller :: Experimental Features</name>
<description>Controller Experimental Features</description>
</dependencyManagement>
<dependencies>
- <dependency>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>odl-controller-exp-netty-config</artifactId>
- <type>xml</type>
- <classifier>features</classifier>
- </dependency>
<dependency>
<groupId>org.opendaylight.controller</groupId>
<artifactId>odl-toaster</artifactId>
<parent>
<groupId>org.opendaylight.odlparent</groupId>
<artifactId>feature-repo-parent</artifactId>
- <version>12.0.1</version>
+ <version>13.0.11</version>
<relativePath/>
</parent>
<groupId>org.opendaylight.controller</groupId>
<artifactId>features-controller-testing</artifactId>
- <version>7.0.2-SNAPSHOT</version>
+ <version>9.0.3-SNAPSHOT</version>
<packaging>feature</packaging>
<name>OpenDaylight :: Controller :: Features to support CSIT testing</name>
<description>Controller CSIT Features</description>
<parent>
<groupId>org.opendaylight.odlparent</groupId>
<artifactId>feature-repo-parent</artifactId>
- <version>12.0.1</version>
+ <version>13.0.11</version>
<relativePath/>
</parent>
<groupId>org.opendaylight.controller</groupId>
<artifactId>features-controller</artifactId>
- <version>7.0.2-SNAPSHOT</version>
+ <version>9.0.3-SNAPSHOT</version>
<packaging>feature</packaging>
<name>OpenDaylight :: Controller :: Features</name>
<description>Controller Production Features</description>
<parent>
<groupId>org.opendaylight.controller</groupId>
<artifactId>single-feature-parent</artifactId>
- <version>7.0.2-SNAPSHOT</version>
+ <version>9.0.3-SNAPSHOT</version>
<relativePath>../single-feature-parent</relativePath>
</parent>
-->
<features xmlns="http://karaf.apache.org/xmlns/features/v1.2.0" name="odl-clustering-test-app-${project.version}">
<feature name="odl-clustering-test-app" version="${project.version}">
- <feature version="[11,12)">odl-mdsal-model-rfc6991</feature>
+ <feature version="[13,14)">odl-mdsal-model-rfc6991</feature>
</feature>
</features>
<parent>
<groupId>org.opendaylight.controller</groupId>
<artifactId>single-feature-parent</artifactId>
- <version>7.0.2-SNAPSHOT</version>
+ <version>9.0.3-SNAPSHOT</version>
<relativePath>../single-feature-parent</relativePath>
</parent>
<parent>
<groupId>org.opendaylight.controller</groupId>
<artifactId>single-feature-parent</artifactId>
- <version>7.0.2-SNAPSHOT</version>
+ <version>9.0.3-SNAPSHOT</version>
<relativePath>../single-feature-parent</relativePath>
</parent>
-->
<features xmlns="http://karaf.apache.org/xmlns/features/v1.2.0" name="odl-controller-blueprint-${project.version}">
<feature name="odl-controller-blueprint" version="${project.version}">
- <feature version="[10,11)">odl-yangtools-codec</feature>
- <feature version="[11,12)">odl-mdsal-binding-api</feature>
- <feature version="[11,12)">odl-mdsal-binding-runtime</feature>
- <feature version="[11,12)">odl-mdsal-dom-api</feature>
+ <feature version="[13,14)">odl-yangtools-codec</feature>
+ <feature version="[13,14)">odl-mdsal-binding-api</feature>
+ <feature version="[13,14)">odl-mdsal-binding-runtime</feature>
+ <feature version="[13,14)">odl-mdsal-dom-api</feature>
<bundle start-level="40">mvn:org.opendaylight.controller/blueprint/${project.version}</bundle>
</feature>
</features>
<parent>
<groupId>org.opendaylight.controller</groupId>
<artifactId>single-feature-parent</artifactId>
- <version>7.0.2-SNAPSHOT</version>
+ <version>9.0.3-SNAPSHOT</version>
<relativePath>../single-feature-parent</relativePath>
</parent>
-->
<features xmlns="http://karaf.apache.org/xmlns/features/v1.2.0" name="odl-mdsal-${project.version}">
<feature name="odl-controller-broker-local" version="${project.version}">
- <feature version="[11,12)">odl-mdsal-dom</feature>
- <feature version="[11,12)">odl-mdsal-eos-binding</feature>
- <feature version="[11,12)">odl-mdsal-eos-dom</feature>
- <feature version="[11,12)">odl-mdsal-singleton-dom</feature>
+ <feature version="[13,14)">odl-mdsal-dom</feature>
+ <feature version="[13,14)">odl-mdsal-eos-binding</feature>
+ <feature version="[13,14)">odl-mdsal-eos-dom</feature>
+ <feature version="[13,14)">odl-mdsal-singleton-dom</feature>
</feature>
</features>
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<!--
- Copyright © 2016, 2017 Red Hat, Inc. and others.
-
- This program and the accompanying materials are made available under the
- terms of the Eclipse Public License v1.0 which accompanies this distribution,
- and is available at http://www.eclipse.org/legal/epl-v10.html
- -->
-<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
- <modelVersion>4.0.0</modelVersion>
- <parent>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>single-feature-parent</artifactId>
- <version>7.0.2-SNAPSHOT</version>
- <relativePath>../single-feature-parent</relativePath>
- </parent>
-
- <artifactId>odl-controller-exp-netty-config</artifactId>
- <packaging>feature</packaging>
- <name>OpenDaylight :: Controller :: Experimental :: Netty Configuration</name>
- <description>Common configuration for Netty resources</description>
-
- <dependencies>
- <dependency>
- <groupId>org.opendaylight.odlparent</groupId>
- <artifactId>odl-netty-4</artifactId>
- <type>xml</type>
- <classifier>features</classifier>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>netty-event-executor-config</artifactId>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>netty-threadgroup-config</artifactId>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>netty-timer-config</artifactId>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>threadpool-config-api</artifactId>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>threadpool-config-impl</artifactId>
- </dependency>
- </dependencies>
-</project>
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
-<!--
- Copyright © 2018 Red Hat, Inc. and others.
-
- This program and the accompanying materials are made available under the
- terms of the Eclipse Public License v1.0 which accompanies this distribution,
- and is available at http://www.eclipse.org/legal/epl-v10.html
- -->
-<features xmlns="http://karaf.apache.org/xmlns/features/v1.4.0" name="odl-controller-exp-netty-config">
- <feature name="odl-controller-exp-netty-config">
- <feature version="[12,13)">odl-netty-4</feature>
- </feature>
-</features>
<parent>
<groupId>org.opendaylight.controller</groupId>
<artifactId>single-feature-parent</artifactId>
- <version>7.0.2-SNAPSHOT</version>
+ <version>9.0.3-SNAPSHOT</version>
<relativePath>../single-feature-parent</relativePath>
</parent>
-->
<features xmlns="http://karaf.apache.org/xmlns/features/v1.2.0" name="odl-controller-mdsal-common-${project.version}">
<feature name="odl-controller-mdsal-common" version="${project.version}">
- <feature version="[11,12)">odl-mdsal-common</feature>
- <feature version="[11,12)">odl-mdsal-binding-runtime</feature>
+ <feature version="[13,14)">odl-mdsal-common</feature>
+ <feature version="[13,14)">odl-mdsal-binding-runtime</feature>
</feature>
</features>
<parent>
<groupId>org.opendaylight.controller</groupId>
<artifactId>single-feature-parent</artifactId>
- <version>7.0.2-SNAPSHOT</version>
+ <version>9.0.3-SNAPSHOT</version>
<relativePath>../single-feature-parent</relativePath>
</parent>
<feature version="0.0.0">
<bundle>mvn:org.scala-lang.modules/scala-java8-compat_2.13/1.0.2</bundle>
<bundle>mvn:org.scala-lang.modules/scala-parser-combinators_2.13/1.1.2</bundle>
- <bundle>mvn:org.scala-lang/scala-library/2.13.10</bundle>
- <bundle>mvn:org.scala-lang/scala-reflect/2.13.10</bundle>
+ <bundle>mvn:org.scala-lang/scala-library/2.13.13</bundle>
+ <bundle>mvn:org.scala-lang/scala-reflect/2.13.13</bundle>
</feature>
</features>
<parent>
<groupId>org.opendaylight.controller</groupId>
<artifactId>single-feature-parent</artifactId>
- <version>7.0.2-SNAPSHOT</version>
+ <version>9.0.3-SNAPSHOT</version>
<relativePath>../single-feature-parent</relativePath>
</parent>
<parent>
<groupId>org.opendaylight.controller</groupId>
<artifactId>single-feature-parent</artifactId>
- <version>7.0.2-SNAPSHOT</version>
+ <version>9.0.3-SNAPSHOT</version>
<relativePath>../single-feature-parent</relativePath>
</parent>
<parent>
<groupId>org.opendaylight.controller</groupId>
<artifactId>single-feature-parent</artifactId>
- <version>7.0.2-SNAPSHOT</version>
+ <version>9.0.3-SNAPSHOT</version>
<relativePath>../single-feature-parent</relativePath>
</parent>
-->
<features xmlns="http://karaf.apache.org/xmlns/features/v1.2.0" name="odl-mdsal-${project.version}">
<feature name="odl-mdsal-broker" version="${project.version}">
- <feature version="[11,12)">odl-mdsal-singleton-dom</feature>
- <feature version="[11,12)">odl-mdsal-eos-binding</feature>
+ <feature version="[13,14)">odl-mdsal-singleton-dom</feature>
+ <feature version="[13,14)">odl-mdsal-eos-binding</feature>
</feature>
</features>
<parent>
<groupId>org.opendaylight.controller</groupId>
<artifactId>single-feature-parent</artifactId>
- <version>7.0.2-SNAPSHOT</version>
+ <version>9.0.3-SNAPSHOT</version>
<relativePath>../single-feature-parent</relativePath>
</parent>
<type>xml</type>
<classifier>features</classifier>
</dependency>
+ <dependency>
+ <groupId>org.opendaylight.odlparent</groupId>
+ <artifactId>odl-netty-4</artifactId>
+ <type>xml</type>
+ <classifier>features</classifier>
+ </dependency>
<dependency>
<groupId>org.opendaylight.odlparent</groupId>
<artifactId>odl-servlet-api</artifactId>
-->
<features xmlns="http://karaf.apache.org/xmlns/features/v1.4.0" name="odl-controller-${project.version}">
<feature name="odl-mdsal-clustering-commons" version="${project.version}">
- <feature version="[12,13)">odl-apache-commons-lang3</feature>
- <feature version="[12,13)">odl-dropwizard-metrics</feature>
- <feature version="[12,13)">odl-servlet-api</feature>
- <feature version="[10,11)">odl-yangtools-data</feature>
- <feature version="[10,11)">odl-yangtools-codec</feature>
+ <feature version="[13,14)">odl-apache-commons-lang3</feature>
+ <feature version="[13,14)">odl-dropwizard-metrics</feature>
+ <feature version="[13,14)">odl-netty-4</feature>
+ <feature version="[13,14)">odl-servlet-api</feature>
+ <feature version="[13,14)">odl-yangtools-data</feature>
+ <feature version="[13,14)">odl-yangtools-codec</feature>
</feature>
</features>
<parent>
<groupId>org.opendaylight.controller</groupId>
<artifactId>single-feature-parent</artifactId>
- <version>7.0.2-SNAPSHOT</version>
+ <version>9.0.3-SNAPSHOT</version>
<relativePath>../single-feature-parent</relativePath>
</parent>
-->
<features xmlns="http://karaf.apache.org/xmlns/features/v1.4.0" name="odl-controller-${project.version}">
<feature name="odl-mdsal-distributed-datastore" version="${project.version}">
- <feature version="[12,13)">odl-apache-commons-text</feature>
- <feature version="[10,11)">odl-yangtools-codec</feature>
- <feature version="[11,12)">odl-mdsal-eos-dom</feature>
- <feature version="[11,12)">odl-mdsal-dom-broker</feature>
- <feature version="[11,12)">odl-mdsal-binding-dom-adapter</feature>
+ <feature version="[13,14)">odl-apache-commons-text</feature>
+ <feature version="[13,14)">odl-yangtools-codec</feature>
+ <feature version="[13,14)">odl-mdsal-eos-dom</feature>
+ <feature version="[13,14)">odl-mdsal-dom-broker</feature>
+ <feature version="[13,14)">odl-mdsal-binding-dom-adapter</feature>
<configfile finalname="configuration/initial/akka.conf">
mvn:org.opendaylight.controller/sal-clustering-config/${project.version}/xml/akkaconf
</configfile>
<parent>
<groupId>org.opendaylight.controller</groupId>
<artifactId>single-feature-parent</artifactId>
- <version>7.0.2-SNAPSHOT</version>
+ <version>9.0.3-SNAPSHOT</version>
<relativePath>../single-feature-parent</relativePath>
</parent>
<parent>
<groupId>org.opendaylight.controller</groupId>
<artifactId>single-feature-parent</artifactId>
- <version>7.0.2-SNAPSHOT</version>
+ <version>9.0.3-SNAPSHOT</version>
<relativePath>../single-feature-parent</relativePath>
</parent>
<type>xml</type>
<classifier>features</classifier>
</dependency>
- <dependency>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>odl-controller-blueprint</artifactId>
- <type>xml</type>
- <classifier>features</classifier>
- </dependency>
<dependency>
<groupId>org.opendaylight.controller.samples</groupId>
<artifactId>sample-toaster</artifactId>
-->
<features xmlns="http://karaf.apache.org/xmlns/features/v1.2.0" name="odl-toaster-${project.version}">
<feature name="odl-toaster" version="${project.version}">
- <feature version="[11,12)">odl-mdsal-binding-runtime</feature>
+ <feature version="[13,14)">odl-mdsal-binding-runtime</feature>
</feature>
</features>
<parent>
<groupId>org.opendaylight.odlparent</groupId>
<artifactId>odlparent-lite</artifactId>
- <version>12.0.1</version>
+ <version>13.0.11</version>
<relativePath/>
</parent>
<groupId>org.opendaylight.controller</groupId>
<artifactId>features-aggregator</artifactId>
- <version>7.0.2-SNAPSHOT</version>
+ <version>9.0.3-SNAPSHOT</version>
<packaging>pom</packaging>
<properties>
<!-- Experimental features -->
<module>features-controller-experimental</module>
- <module>odl-controller-exp-netty-config</module>
+ <module>odl-toaster</module>
<!-- CSIT features -->
<module>features-controller-testing</module>
<!-- Single features, to be cleaned up -->
<module>odl-controller-blueprint</module>
+ <module>odl-controller-broker-local</module>
<module>odl-controller-mdsal-common</module>
<module>odl-jolokia</module>
- <module>odl-controller-broker-local</module>
<module>odl-mdsal-broker</module>
<module>odl-mdsal-clustering-commons</module>
<module>odl-mdsal-distributed-datastore</module>
<module>odl-mdsal-remoterpc-connector</module>
- <module>odl-toaster</module>
</modules>
</project>
<parent>
<groupId>org.opendaylight.odlparent</groupId>
<artifactId>single-feature-parent</artifactId>
- <version>12.0.1</version>
+ <version>13.0.11</version>
<relativePath/>
</parent>
<groupId>org.opendaylight.controller</groupId>
<artifactId>single-feature-parent</artifactId>
- <version>7.0.2-SNAPSHOT</version>
+ <version>9.0.3-SNAPSHOT</version>
<packaging>pom</packaging>
<dependencyManagement>
<dependency>
<groupId>org.opendaylight.controller</groupId>
<artifactId>bundle-parent</artifactId>
- <version>7.0.2-SNAPSHOT</version>
+ <version>9.0.3-SNAPSHOT</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<parent>
<groupId>org.opendaylight.odlparent</groupId>
<artifactId>odlparent</artifactId>
- <version>12.0.1</version>
+ <version>13.0.11</version>
<relativePath/>
</parent>
<groupId>org.opendaylight.controller</groupId>
<artifactId>odl-jolokia-osgi</artifactId>
- <version>7.0.2-SNAPSHOT</version>
+ <version>9.0.3-SNAPSHOT</version>
<packaging>jar</packaging>
<build>
<parent>
<groupId>org.opendaylight.odlparent</groupId>
<artifactId>karaf4-parent</artifactId>
- <version>12.0.1</version>
+ <version>13.0.11</version>
<relativePath/>
</parent>
<groupId>org.opendaylight.controller</groupId>
<artifactId>controller-test-karaf</artifactId>
- <version>7.0.2-SNAPSHOT</version>
+ <version>9.0.3-SNAPSHOT</version>
<packaging>pom</packaging>
<dependencyManagement>
<parent>
<groupId>org.opendaylight.odlparent</groupId>
<artifactId>bundle-parent</artifactId>
- <version>12.0.1</version>
+ <version>13.0.11</version>
<relativePath/>
</parent>
<artifactId>blueprint</artifactId>
<packaging>bundle</packaging>
<name>${project.artifactId}</name>
- <version>7.0.2-SNAPSHOT</version>
+ <version>9.0.3-SNAPSHOT</version>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.opendaylight.yangtools</groupId>
<artifactId>yangtools-artifacts</artifactId>
- <version>10.0.2</version>
+ <version>13.0.2</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>org.opendaylight.mdsal</groupId>
<artifactId>mdsal-artifacts</artifactId>
- <version>11.0.4</version>
+ <version>13.0.1</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
</dependency>
+ <dependency>
+ <groupId>com.github.spotbugs</groupId>
+ <artifactId>spotbugs-annotations</artifactId>
+ <optional>true</optional>
+ </dependency>
<dependency>
<groupId>org.apache.aries.blueprint</groupId>
<artifactId>org.apache.aries.blueprint.core</artifactId>
<groupId>org.apache.aries</groupId>
<artifactId>org.apache.aries.util</artifactId>
</dependency>
+ <dependency>
+ <groupId>org.opendaylight.yangtools</groupId>
+ <artifactId>concepts</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.opendaylight.yangtools</groupId>
+ <artifactId>util</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.opendaylight.yangtools</groupId>
+ <artifactId>yang-common</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.opendaylight.yangtools</groupId>
+ <artifactId>yang-data-api</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.opendaylight.yangtools</groupId>
+ <artifactId>yang-data-impl</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.opendaylight.yangtools</groupId>
+ <artifactId>yang-data-codec-xml</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.opendaylight.yangtools</groupId>
+ <artifactId>yang-model-api</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.opendaylight.yangtools</groupId>
+ <artifactId>yang-model-util</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.opendaylight.mdsal</groupId>
+ <artifactId>mdsal-common-api</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.opendaylight.mdsal</groupId>
+ <artifactId>mdsal-dom-api</artifactId>
+ </dependency>
<dependency>
<groupId>org.opendaylight.mdsal</groupId>
<artifactId>mdsal-dom-spi</artifactId>
<artifactId>mdsal-binding-dom-codec-api</artifactId>
</dependency>
<dependency>
- <groupId>org.opendaylight.yangtools</groupId>
- <artifactId>yang-data-codec-xml</artifactId>
+ <groupId>org.opendaylight.mdsal</groupId>
+ <artifactId>mdsal-binding-spec-util</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.opendaylight.mdsal</groupId>
+ <artifactId>yang-binding</artifactId>
</dependency>
<dependency>
<groupId>org.osgi</groupId>
<groupId>org.opendaylight.mdsal</groupId>
<artifactId>mdsal-binding-test-model</artifactId>
</dependency>
+ <dependency>
+ <groupId>org.opendaylight.mdsal</groupId>
+ <artifactId>mdsal-binding-dom-adapter</artifactId>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.opendaylight.mdsal</groupId>
+ <artifactId>mdsal-binding-dom-adapter</artifactId>
+ <type>test-jar</type>
+ <scope>test</scope>
+ </dependency>
<dependency>
<groupId>org.opendaylight.mdsal</groupId>
<artifactId>mdsal-binding-test-utils</artifactId>
+++ /dev/null
-/*
- * Copyright (c) 2016 Brocade Communications Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.blueprint.ext;
-
-import static java.util.Objects.requireNonNull;
-
-import com.google.common.base.MoreObjects;
-import com.google.common.collect.ImmutableSet;
-import java.util.Collection;
-import java.util.Set;
-import java.util.function.Predicate;
-import org.apache.aries.blueprint.services.ExtendedBlueprintContainer;
-import org.opendaylight.mdsal.binding.api.RpcConsumerRegistry;
-import org.opendaylight.mdsal.dom.api.DOMRpcAvailabilityListener;
-import org.opendaylight.mdsal.dom.api.DOMRpcIdentifier;
-import org.opendaylight.mdsal.dom.api.DOMRpcService;
-import org.opendaylight.mdsal.dom.api.DOMSchemaService;
-import org.opendaylight.mdsal.dom.spi.ContentRoutedRpcContext;
-import org.opendaylight.yangtools.concepts.ListenerRegistration;
-import org.opendaylight.yangtools.yang.binding.RpcService;
-import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
-import org.osgi.service.blueprint.container.ComponentDefinitionException;
-
-abstract class AbstractInvokableServiceMetadata extends AbstractDependentComponentFactoryMetadata {
- private final String interfaceName;
-
- private ListenerRegistration<DOMRpcAvailabilityListener> rpcListenerReg;
- private RpcConsumerRegistry rpcRegistry;
- private Class<RpcService> rpcInterface;
- private Set<QName> rpcSchemaPaths;
-
- AbstractInvokableServiceMetadata(final String id, final String interfaceName) {
- super(id);
- this.interfaceName = requireNonNull(interfaceName);
- }
-
- Class<RpcService> rpcInterface() {
- return rpcInterface;
- }
-
- @SuppressWarnings({ "checkstyle:IllegalCatch", "unchecked" })
- @Override
- public final void init(final ExtendedBlueprintContainer container) {
- super.init(container);
-
- final Class<?> interfaceClass;
- try {
- interfaceClass = container().getBundleContext().getBundle().loadClass(interfaceName);
- } catch (final Exception e) {
- throw new ComponentDefinitionException(String.format("%s: Error obtaining interface class %s",
- logName(), interfaceName), e);
- }
-
- if (!RpcService.class.isAssignableFrom(interfaceClass)) {
- throw new ComponentDefinitionException(String.format(
- "%s: The specified interface %s is not an RpcService", logName(), interfaceName));
- }
-
- rpcInterface = (Class<RpcService>)interfaceClass;
- }
-
- @Override
- protected final void startTracking() {
- // Request RpcProviderRegistry first ...
- retrieveService("RpcConsumerRegistry", RpcConsumerRegistry.class, this::onRpcRegistry);
- }
-
- private void onRpcRegistry(final Object service) {
- log.debug("{}: Retrieved RpcProviderRegistry {}", logName(), service);
- rpcRegistry = (RpcConsumerRegistry)service;
-
- // Now acquire SchemaService...
- retrieveService("SchemaService", DOMSchemaService.class, this::onSchemaService);
- }
-
- private void onSchemaService(final Object service) {
- log.debug("{}: Retrieved SchemaService {}", logName(), service);
-
- // Now get the SchemaContext and trigger RPC resolution
- retrievedSchemaContext(((DOMSchemaService)service).getGlobalContext());
- }
-
- private void retrievedSchemaContext(final EffectiveModelContext schemaContext) {
- log.debug("{}: retrievedSchemaContext", logName());
-
- final Collection<QName> schemaPaths = RpcUtil.decomposeRpcService(rpcInterface, schemaContext,
- rpcFilter());
- if (schemaPaths.isEmpty()) {
- log.debug("{}: interface {} has no acceptable entries, assuming it is satisfied", logName(), rpcInterface);
- setSatisfied();
- return;
- }
-
- rpcSchemaPaths = ImmutableSet.copyOf(schemaPaths);
- log.debug("{}: Got SchemaPaths: {}", logName(), rpcSchemaPaths);
-
- // First get the DOMRpcService OSGi service. This will be used to register a listener to be notified
- // when the underlying DOM RPC service is available.
- retrieveService("DOMRpcService", DOMRpcService.class, this::retrievedDOMRpcService);
- }
-
- private void retrievedDOMRpcService(final Object service) {
- log.debug("{}: retrievedDOMRpcService {}", logName(), service);
- final DOMRpcService domRpcService = (DOMRpcService)service;
-
- setDependencyDesc("Available DOM RPC for binding RPC: " + rpcInterface);
- rpcListenerReg = domRpcService.registerRpcListener(new DOMRpcAvailabilityListener() {
- @Override
- public void onRpcAvailable(final Collection<DOMRpcIdentifier> rpcs) {
- onRpcsAvailable(rpcs);
- }
-
- @Override
- public void onRpcUnavailable(final Collection<DOMRpcIdentifier> rpcs) {
- }
- });
- }
-
- abstract Predicate<ContentRoutedRpcContext> rpcFilter();
-
- @SuppressWarnings("checkstyle:IllegalCatch")
- @Override
- public final Object create() throws ComponentDefinitionException {
- log.debug("{}: In create: interfaceName: {}", logName(), interfaceName);
-
- super.onCreate();
-
- try {
- RpcService rpcService = rpcRegistry.getRpcService(rpcInterface);
-
- log.debug("{}: create returning service {}", logName(), rpcService);
-
- return rpcService;
- } catch (final RuntimeException e) {
- throw new ComponentDefinitionException("Error getting RPC service for " + interfaceName, e);
- }
- }
-
- protected final void onRpcsAvailable(final Collection<DOMRpcIdentifier> rpcs) {
- for (DOMRpcIdentifier identifier : rpcs) {
- if (rpcSchemaPaths.contains(identifier.getType())) {
- log.debug("{}: onRpcsAvailable - found SchemaPath {}", logName(), identifier.getType());
- setSatisfied();
- break;
- }
- }
- }
-
- @Override
- public final void stopTracking() {
- super.stopTracking();
- closeRpcListenerReg();
- }
-
- private void closeRpcListenerReg() {
- if (rpcListenerReg != null) {
- rpcListenerReg.close();
- rpcListenerReg = null;
- }
- }
-
- @Override
- public final void destroy(final Object instance) {
- super.destroy(instance);
- closeRpcListenerReg();
- }
-
- @Override
- public final String toString() {
- return MoreObjects.toStringHelper(this).add("id", getId()).add("interfaceName", interfaceName).toString();
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2017 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.blueprint.ext;
-
-import com.google.common.collect.Collections2;
-import com.google.common.collect.ImmutableSet;
-import java.util.Collection;
-import java.util.Objects;
-import java.util.Set;
-import org.opendaylight.mdsal.binding.api.RpcProviderService;
-import org.opendaylight.mdsal.dom.api.DOMRpcIdentifier;
-import org.opendaylight.mdsal.dom.api.DOMRpcImplementationNotAvailableException;
-import org.opendaylight.mdsal.dom.api.DOMRpcProviderService;
-import org.opendaylight.mdsal.dom.api.DOMSchemaService;
-import org.opendaylight.yangtools.concepts.Registration;
-import org.opendaylight.yangtools.util.concurrent.FluentFutures;
-import org.opendaylight.yangtools.yang.binding.RpcService;
-import org.opendaylight.yangtools.yang.common.QName;
-import org.osgi.framework.Bundle;
-import org.osgi.service.blueprint.container.ComponentDefinitionException;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * Blueprint bean corresponding to the "action-provider" element that registers the promise to instantiate action
- * instances with RpcProviderRegistry.
- *
- * <p>
- * This bean has two distinct facets:
- * - if a reference bean is provided, it registers it with {@link RpcProviderService}
- * - if a reference bean is not provided, it registers the corresponding no-op implementation with
- * {@link DOMRpcProviderService} for all action (Routed RPC) elements in the provided interface
- */
-public class ActionProviderBean {
- static final String ACTION_PROVIDER = "action-provider";
-
- private static final Logger LOG = LoggerFactory.getLogger(ActionProviderBean.class);
-
- private DOMRpcProviderService domRpcProvider;
- private RpcProviderService bindingRpcProvider;
- private DOMSchemaService schemaService;
- private RpcService implementation;
- private String interfaceName;
- private Registration reg;
- private Bundle bundle;
-
- public void setBundle(final Bundle bundle) {
- this.bundle = bundle;
- }
-
- public void setInterfaceName(final String interfaceName) {
- this.interfaceName = interfaceName;
- }
-
- public void setImplementation(final RpcService implementation) {
- this.implementation = implementation;
- }
-
- public void setDomRpcProvider(final DOMRpcProviderService rpcProviderService) {
- domRpcProvider = rpcProviderService;
- }
-
- public void setBindingRpcProvider(final RpcProviderService rpcProvider) {
- bindingRpcProvider = rpcProvider;
- }
-
- public void setSchemaService(final DOMSchemaService schemaService) {
- this.schemaService = schemaService;
- }
-
- public void init() {
- // First resolve the interface class
- final Class<RpcService> interfaceClass = getRpcClass();
-
- LOG.debug("{}: resolved interface {} to {}", ACTION_PROVIDER, interfaceName, interfaceClass);
-
- if (implementation != null) {
- registerImplementation(interfaceClass);
- } else {
- registerFallback(interfaceClass);
- }
- }
-
- @SuppressWarnings("checkstyle:IllegalCatch")
- public void destroy() {
- if (reg != null) {
- try {
- reg.close();
- } catch (final Exception e) {
- LOG.warn("{}: error while unregistering", ACTION_PROVIDER, e);
- } finally {
- reg = null;
- }
- }
- }
-
- @SuppressWarnings("unchecked")
- private Class<RpcService> getRpcClass() {
- final Class<?> iface;
-
- try {
- iface = bundle.loadClass(interfaceName);
- } catch (final ClassNotFoundException e) {
- throw new ComponentDefinitionException(String.format(
- "The specified \"interface\" for %s \"%s\" does not refer to an available class", interfaceName,
- ACTION_PROVIDER), e);
- }
- if (!RpcService.class.isAssignableFrom(iface)) {
- throw new ComponentDefinitionException(String.format(
- "The specified \"interface\" %s for \"%s\" is not an RpcService", interfaceName, ACTION_PROVIDER));
- }
-
- return (Class<RpcService>) iface;
- }
-
- private void registerFallback(final Class<RpcService> interfaceClass) {
- final Collection<QName> paths = RpcUtil.decomposeRpcService(interfaceClass,
- schemaService.getGlobalContext(), Objects::nonNull);
- if (paths.isEmpty()) {
- LOG.warn("{}: interface {} has no actions defined", ACTION_PROVIDER, interfaceClass);
- return;
- }
-
- final Set<DOMRpcIdentifier> rpcs = ImmutableSet.copyOf(Collections2.transform(paths, DOMRpcIdentifier::create));
- reg = domRpcProvider.registerRpcImplementation(
- (rpc, input) -> FluentFutures.immediateFailedFluentFuture(new DOMRpcImplementationNotAvailableException(
- "Action %s has no instance matching %s", rpc, input)), rpcs);
- LOG.debug("Registered provider for {}", interfaceName);
- }
-
- private void registerImplementation(final Class<RpcService> interfaceClass) {
- if (!interfaceClass.isInstance(implementation)) {
- throw new ComponentDefinitionException(String.format(
- "The specified \"interface\" %s for \"%s\" is not implemented by RpcService \"ref\" %s",
- interfaceName, ACTION_PROVIDER, implementation.getClass()));
- }
-
- reg = bindingRpcProvider.registerRpcImplementation(interfaceClass, implementation);
- LOG.debug("Registered implementation {} for {}", implementation, interfaceName);
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2017 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.blueprint.ext;
-
-import java.util.Objects;
-import java.util.function.Predicate;
-import org.opendaylight.mdsal.dom.api.DOMRpcService;
-import org.opendaylight.mdsal.dom.spi.ContentRoutedRpcContext;
-
-/**
- * Factory metadata corresponding to the "action-service" element. It waits for a DOM promise of registration
- * to appear in the {@link DOMRpcService} and then acquires a dynamic proxy via RpcProviderRegistry.
- */
-final class ActionServiceMetadata extends AbstractInvokableServiceMetadata {
- /*
- * Implementation note:
- *
- * This implementation assumes Binding V1 semantics for actions, which means actions are packaged along with RPCs
- * into a single interface. This has interesting implications on working with RpcServiceMetadata, which only
- * handles the RPC side of the contract.
- *
- * Further interesting interactions stem from the fact that in DOM world each action is a separate entity, so the
- * interface contract can let some actions to be invoked, while failing for others. This is a shortcoming of the
- * Binding Specification and will be addressed in Binding V2 -- where each action is its own interface.
- */
- ActionServiceMetadata(final String id, final String interfaceName) {
- super(id, interfaceName);
- }
-
- @Override
- Predicate<ContentRoutedRpcContext> rpcFilter() {
- return Objects::nonNull;
- }
-}
import java.util.Set;
import javax.xml.stream.XMLStreamException;
import javax.xml.transform.dom.DOMSource;
-import org.opendaylight.mdsal.binding.spec.naming.BindingMapping;
import org.opendaylight.mdsal.binding.spec.reflect.BindingReflections;
import org.opendaylight.yangtools.yang.binding.DataObject;
-import org.opendaylight.yangtools.yang.binding.Identifiable;
-import org.opendaylight.yangtools.yang.binding.Identifier;
import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
+import org.opendaylight.yangtools.yang.binding.Key;
+import org.opendaylight.yangtools.yang.binding.KeyAware;
+import org.opendaylight.yangtools.yang.binding.contract.Naming;
import org.opendaylight.yangtools.yang.common.QName;
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
+import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
import org.opendaylight.yangtools.yang.data.codec.xml.XmlParserStream;
-import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNormalizedNodeStreamWriter;
-import org.opendaylight.yangtools.yang.data.impl.schema.NormalizedNodeResult;
+import org.opendaylight.yangtools.yang.data.impl.schema.NormalizationResultHolder;
+import org.opendaylight.yangtools.yang.data.spi.node.ImmutableNodes;
import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
public abstract class BindingContext {
public static BindingContext create(final String logName, final Class<? extends DataObject> klass,
final String appConfigListKeyValue) {
- if (Identifiable.class.isAssignableFrom(klass)) {
+ if (KeyAware.class.isAssignableFrom(klass)) {
// The binding class corresponds to a yang list.
if (Strings.isNullOrEmpty(appConfigListKeyValue)) {
throw new ComponentDefinitionException(String.format(
public NormalizedNode parseDataElement(final Element element, final SchemaTreeInference dataSchema)
throws XMLStreamException, IOException, SAXException, URISyntaxException {
- final NormalizedNodeResult resultHolder = new NormalizedNodeResult();
+ final NormalizationResultHolder resultHolder = new NormalizationResultHolder();
final NormalizedNodeStreamWriter writer = ImmutableNormalizedNodeStreamWriter.from(resultHolder);
final XmlParserStream xmlParser = XmlParserStream.create(writer, dataSchema);
xmlParser.traverse(new DOMSource(element));
- final NormalizedNode result = resultHolder.getResult();
+ final NormalizedNode result = resultHolder.getResult().data();
return result instanceof MapNode mapNode ? mapNode.body().iterator().next() : result;
}
}
@Override
- public NormalizedNode newDefaultNode(final SchemaTreeInference dataSchema) {
- return ImmutableNodes.containerNode(bindingQName);
+ public ContainerNode newDefaultNode(final SchemaTreeInference dataSchema) {
+ return ImmutableNodes.newContainerBuilder().withNodeIdentifier(new NodeIdentifier(bindingQName)).build();
}
}
final String listKeyValue) throws InstantiationException, IllegalAccessException,
IllegalArgumentException, InvocationTargetException, NoSuchMethodException, SecurityException {
// We assume the yang list key type is string.
- Identifier keyInstance = (Identifier) bindingClass.getMethod(BindingMapping.IDENTIFIABLE_KEY_NAME)
+ Key keyInstance = (Key) bindingClass.getMethod(Naming.KEY_AWARE_KEY_NAME)
.getReturnType().getConstructor(String.class).newInstance(listKeyValue);
InstanceIdentifier appConfigPath = InstanceIdentifier.builder((Class)bindingClass, keyInstance).build();
return new ListBindingContext(bindingClass, appConfigPath, listKeyValue);
checkArgument(keys.size() == 1, "Expected only 1 key for list %s", appConfigBindingClass);
QName listKeyQName = keys.iterator().next();
- return ImmutableNodes.mapEntryBuilder(bindingQName, listKeyQName, appConfigListKeyValue).build();
+ return ImmutableNodes.newMapEntryBuilder()
+ .withNodeIdentifier(NodeIdentifierWithPredicates.of(bindingQName, listKeyQName, appConfigListKeyValue))
+ .withChild(ImmutableNodes.leafNode(listKeyQName, appConfigListKeyValue))
+ .build();
}
}
}
import org.apache.aries.blueprint.mutable.MutableBeanMetadata;
import org.apache.aries.blueprint.mutable.MutableServiceReferenceMetadata;
import org.apache.aries.util.AriesFrameworkUtil;
-import org.gaul.modernizer_maven_annotations.SuppressModernizer;
import org.opendaylight.controller.blueprint.BlueprintContainerRestartService;
import org.osgi.framework.Bundle;
import org.osgi.framework.Constants;
import org.osgi.framework.FrameworkUtil;
import org.osgi.framework.ServiceRegistration;
-import org.osgi.service.blueprint.reflect.BeanProperty;
-import org.osgi.service.blueprint.reflect.ComponentMetadata;
import org.osgi.service.blueprint.reflect.ValueMetadata;
import org.osgi.service.cm.ManagedService;
import org.slf4j.Logger;
private static final String CM_PERSISTENT_ID_PROPERTY = "persistentId";
private final List<ServiceRegistration<?>> managedServiceRegs = new ArrayList<>();
- private Bundle bundle;
- private BlueprintContainerRestartService blueprintContainerRestartService;
+ private Bundle bundle = null;
+ private BlueprintContainerRestartService blueprintContainerRestartService = null;
private boolean restartDependentsOnUpdates;
private boolean useDefaultForReferenceTypes;
}
public void destroy() {
- for (ServiceRegistration<?> reg: managedServiceRegs) {
- AriesFrameworkUtil.safeUnregisterService(reg);
- }
+ managedServiceRegs.forEach(AriesFrameworkUtil::safeUnregisterService);
}
@Override
public void process(final ComponentDefinitionRegistry registry) {
LOG.debug("{}: In process", logName());
- for (String name : registry.getComponentDefinitionNames()) {
- ComponentMetadata component = registry.getComponentDefinition(name);
- if (component instanceof MutableBeanMetadata) {
- processMutableBeanMetadata((MutableBeanMetadata) component);
- } else if (component instanceof MutableServiceReferenceMetadata) {
- processServiceReferenceMetadata((MutableServiceReferenceMetadata)component);
+ for (var name : registry.getComponentDefinitionNames()) {
+ final var component = registry.getComponentDefinition(name);
+ if (component instanceof MutableBeanMetadata bean) {
+ processMutableBeanMetadata(bean);
+ } else if (component instanceof MutableServiceReferenceMetadata serviceRef) {
+ processServiceReferenceMetadata(serviceRef);
}
}
}
LOG.debug("{}: Found PropertyPlaceholder bean: {}, runtime {}", logName(), bean.getId(),
bean.getRuntimeClass());
- for (BeanProperty prop : bean.getProperties()) {
+ for (var prop : bean.getProperties()) {
if (CM_PERSISTENT_ID_PROPERTY.equals(prop.getName())) {
- if (prop.getValue() instanceof ValueMetadata) {
- ValueMetadata persistentId = (ValueMetadata)prop.getValue();
-
- LOG.debug("{}: Found {} property, value : {}", logName(),
- CM_PERSISTENT_ID_PROPERTY, persistentId.getStringValue());
-
+ if (prop.getValue() instanceof ValueMetadata persistentId) {
+ LOG.debug("{}: Found {} property, value : {}", logName(), CM_PERSISTENT_ID_PROPERTY,
+ persistentId.getStringValue());
registerManagedService(persistentId.getStringValue());
} else {
- LOG.debug("{}: {} property metadata {} is not instanceof ValueMetadata",
- logName(), CM_PERSISTENT_ID_PROPERTY, prop.getValue());
+ LOG.debug("{}: {} property metadata {} is not instanceof ValueMetadata", logName(),
+ CM_PERSISTENT_ID_PROPERTY, prop.getValue());
}
break;
}
}
- @SuppressModernizer
private void registerManagedService(final String persistentId) {
// Register a ManagedService so we get updates from the ConfigAdmin when the cfg file corresponding
// to the persistentId changes.
- final ManagedService managedService = new ManagedService() {
+ final var managedService = new ManagedService() {
private final AtomicBoolean initialUpdate = new AtomicBoolean(true);
private volatile Dictionary<String, ?> previousProperties;
if (!optionalURL.isPresent()) {
return null;
}
- URL url = optionalURL.get();
+ URL url = optionalURL.orElseThrow();
try (InputStream is = url.openStream()) {
Document root = UntrustedXML.newDocumentBuilder().parse(is);
NormalizedNode dataNode = bindingContext.parseDataElement(root.getDocumentElement(),
import org.eclipse.jdt.annotation.NonNull;
import org.eclipse.jdt.annotation.Nullable;
import org.opendaylight.controller.blueprint.ext.DataStoreAppConfigDefaultXMLReader.ConfigURLProvider;
-import org.opendaylight.mdsal.binding.api.ClusteredDataTreeChangeListener;
import org.opendaylight.mdsal.binding.api.DataBroker;
import org.opendaylight.mdsal.binding.api.DataObjectModification;
import org.opendaylight.mdsal.binding.api.DataObjectModification.ModificationType;
import org.opendaylight.mdsal.binding.dom.codec.api.BindingNormalizedNodeSerializer;
import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
import org.opendaylight.mdsal.dom.api.DOMSchemaService;
-import org.opendaylight.yangtools.concepts.ListenerRegistration;
+import org.opendaylight.yangtools.concepts.Registration;
import org.opendaylight.yangtools.yang.binding.ChildOf;
import org.opendaylight.yangtools.yang.binding.DataObject;
import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
private final AtomicBoolean readingInitialAppConfig = new AtomicBoolean(true);
private volatile BindingContext bindingContext;
- private volatile ListenerRegistration<?> appConfigChangeListenerReg;
+ private volatile Registration appConfigChangeListenerReg;
private volatile DataObject currentAppConfig;
// Note: the BindingNormalizedNodeSerializer interface is annotated as deprecated because there's an
setDependencyDesc("Initial app config " + bindingContext.appConfigBindingClass.getSimpleName());
- // We register a DTCL to get updates and also read the app config data from the data store. If
- // the app config data is present then both the read and initial DTCN update will return it. If the
- // the data isn't present, we won't get an initial DTCN update so the read will indicate the data
- // isn't present.
-
- DataTreeIdentifier<DataObject> dataTreeId = DataTreeIdentifier.create(LogicalDatastoreType.CONFIGURATION,
- bindingContext.appConfigPath);
- appConfigChangeListenerReg = dataBroker.registerDataTreeChangeListener(dataTreeId,
- (ClusteredDataTreeChangeListener<DataObject>) this::onAppConfigChanged);
+ // We register a DTCL to get updates and also read the app config data from the data store. If the app config
+ // data is present then both the read and initial DTCN update will return it. If the the data isn't present, we
+ // will not get an initial DTCN update so the read will indicate the data is not present.
+ appConfigChangeListenerReg = dataBroker.registerTreeChangeListener(
+ DataTreeIdentifier.of(LogicalDatastoreType.CONFIGURATION, bindingContext.appConfigPath),
+ this::onAppConfigChanged);
readInitialAppConfig(dataBroker);
}
private void onAppConfigChanged(final Collection<DataTreeModification<DataObject>> changes) {
for (DataTreeModification<DataObject> change: changes) {
DataObjectModification<DataObject> changeRoot = change.getRootNode();
- ModificationType type = changeRoot.getModificationType();
+ ModificationType type = changeRoot.modificationType();
LOG.debug("{}: onAppConfigChanged: {}, {}", logName(), type, change.getRootPath());
if (type == ModificationType.SUBTREE_MODIFIED || type == ModificationType.WRITE) {
- DataObject newAppConfig = changeRoot.getDataAfter();
+ DataObject newAppConfig = changeRoot.dataAfter();
LOG.debug("New app config instance: {}, previous: {}", newAppConfig, currentAppConfig);
if (result) {
DataObject localAppConfig;
if (possibleAppConfig.isPresent()) {
- localAppConfig = possibleAppConfig.get();
+ localAppConfig = possibleAppConfig.orElseThrow();
} else {
// No app config data is present so create an empty instance via the bindingSerializer service.
// This will also return default values for leafs that haven't been explicitly set.
+++ /dev/null
-/*
- * Copyright (c) 2016 Brocade Communications Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.blueprint.ext;
-
-import org.opendaylight.mdsal.binding.api.NotificationService;
-import org.opendaylight.yangtools.concepts.ListenerRegistration;
-import org.opendaylight.yangtools.yang.binding.NotificationListener;
-import org.osgi.framework.Bundle;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * Blueprint bean corresponding to the "notification-listener" element that registers a NotificationListener
- * with the NotificationService.
- *
- * @author Thomas Pantelis
- */
-public class NotificationListenerBean {
- private static final Logger LOG = LoggerFactory.getLogger(NotificationListenerBean.class);
- static final String NOTIFICATION_LISTENER = "notification-listener";
-
- private Bundle bundle;
- private NotificationService notificationService;
- private NotificationListener notificationListener;
- private ListenerRegistration<?> registration;
-
- public void setNotificationService(final NotificationService notificationService) {
- this.notificationService = notificationService;
- }
-
- public void setNotificationListener(final NotificationListener notificationListener) {
- this.notificationListener = notificationListener;
- }
-
- public void setBundle(final Bundle bundle) {
- this.bundle = bundle;
- }
-
- public void init() {
- LOG.debug("{}: init - registering NotificationListener {}", bundle.getSymbolicName(), notificationListener);
-
- registration = notificationService.registerNotificationListener(notificationListener);
- }
-
- public void destroy() {
- if (registration != null) {
- LOG.debug("{}: destroy - closing ListenerRegistration {}", bundle.getSymbolicName(), notificationListener);
- registration.close();
- } else {
- LOG.debug("{}: destroy - listener was not registered", bundle.getSymbolicName());
- }
- }
-}
import java.io.IOException;
import java.io.StringReader;
import java.net.URL;
-import java.util.Collections;
import java.util.Set;
import org.apache.aries.blueprint.ComponentDefinitionRegistry;
import org.apache.aries.blueprint.NamespaceHandler;
import org.apache.aries.blueprint.ParserContext;
-import org.apache.aries.blueprint.ext.ComponentFactoryMetadata;
import org.apache.aries.blueprint.mutable.MutableBeanMetadata;
import org.apache.aries.blueprint.mutable.MutableRefMetadata;
import org.apache.aries.blueprint.mutable.MutableReferenceMetadata;
import org.apache.aries.blueprint.mutable.MutableServiceReferenceMetadata;
import org.apache.aries.blueprint.mutable.MutableValueMetadata;
import org.opendaylight.controller.blueprint.BlueprintContainerRestartService;
-import org.opendaylight.mdsal.binding.api.NotificationService;
-import org.opendaylight.mdsal.binding.api.RpcProviderService;
-import org.opendaylight.mdsal.dom.api.DOMRpcProviderService;
-import org.opendaylight.mdsal.dom.api.DOMSchemaService;
import org.opendaylight.yangtools.util.xml.UntrustedXML;
import org.osgi.service.blueprint.container.ComponentDefinitionException;
import org.osgi.service.blueprint.reflect.BeanMetadata;
*/
public final class OpendaylightNamespaceHandler implements NamespaceHandler {
public static final String NAMESPACE_1_0_0 = "http://opendaylight.org/xmlns/blueprint/v1.0.0";
- static final String ROUTED_RPC_REG_CONVERTER_NAME = "org.opendaylight.blueprint.RoutedRpcRegConverter";
- static final String DOM_RPC_PROVIDER_SERVICE_NAME = "org.opendaylight.blueprint.DOMRpcProviderService";
- static final String RPC_REGISTRY_NAME = "org.opendaylight.blueprint.RpcRegistry";
- static final String BINDING_RPC_PROVIDER_SERVICE_NAME = "org.opendaylight.blueprint.RpcProviderService";
- static final String SCHEMA_SERVICE_NAME = "org.opendaylight.blueprint.SchemaService";
- static final String NOTIFICATION_SERVICE_NAME = "org.opendaylight.blueprint.NotificationService";
- static final String TYPE_ATTR = "type";
- static final String UPDATE_STRATEGY_ATTR = "update-strategy";
private static final Logger LOG = LoggerFactory.getLogger(OpendaylightNamespaceHandler.class);
+ private static final String TYPE_ATTR = "type";
+ private static final String UPDATE_STRATEGY_ATTR = "update-strategy";
private static final String COMPONENT_PROCESSOR_NAME = ComponentProcessor.class.getName();
private static final String RESTART_DEPENDENTS_ON_UPDATES = "restart-dependents-on-updates";
private static final String USE_DEFAULT_FOR_REFERENCE_TYPES = "use-default-for-reference-types";
private static final String CLUSTERED_APP_CONFIG = "clustered-app-config";
- private static final String INTERFACE = "interface";
- private static final String REF_ATTR = "ref";
private static final String ID_ATTR = "id";
- private static final String RPC_SERVICE = "rpc-service";
- private static final String ACTION_SERVICE = "action-service";
- private static final String SPECIFIC_SERVICE_REF_LIST = "specific-reference-list";
- private static final String STATIC_REFERENCE = "static-reference";
@SuppressWarnings("rawtypes")
@Override
public Set<Class> getManagedClasses() {
- return Collections.emptySet();
+ return Set.of();
}
@Override
public Metadata parse(final Element element, final ParserContext context) {
LOG.debug("In parse for {}", element);
- if (nodeNameEquals(element, RpcImplementationBean.RPC_IMPLEMENTATION)) {
- return parseRpcImplementation(element, context);
- } else if (nodeNameEquals(element, RPC_SERVICE)) {
- return parseRpcService(element, context);
- } else if (nodeNameEquals(element, NotificationListenerBean.NOTIFICATION_LISTENER)) {
- return parseNotificationListener(element, context);
- } else if (nodeNameEquals(element, CLUSTERED_APP_CONFIG)) {
+ if (nodeNameEquals(element, CLUSTERED_APP_CONFIG)) {
return parseClusteredAppConfig(element, context);
- } else if (nodeNameEquals(element, SPECIFIC_SERVICE_REF_LIST)) {
- return parseSpecificReferenceList(element, context);
- } else if (nodeNameEquals(element, STATIC_REFERENCE)) {
- return parseStaticReference(element, context);
- } else if (nodeNameEquals(element, ACTION_SERVICE)) {
- return parseActionService(element, context);
- } else if (nodeNameEquals(element, ActionProviderBean.ACTION_PROVIDER)) {
- return parseActionProvider(element, context);
}
throw new ComponentDefinitionException("Unsupported standalone element: " + element.getNodeName());
private static ComponentMetadata decorateServiceType(final Attr attr, final ComponentMetadata component,
final ParserContext context) {
- if (!(component instanceof MutableServiceMetadata)) {
+ if (!(component instanceof MutableServiceMetadata service)) {
throw new ComponentDefinitionException("Expected an instanceof MutableServiceMetadata");
}
- MutableServiceMetadata service = (MutableServiceMetadata)component;
-
LOG.debug("decorateServiceType for {} - adding type property {}", service.getId(), attr.getValue());
service.addServiceProperty(createValue(context, TYPE_ATTR), createValue(context, attr.getValue()));
return metadata;
}
- private static Metadata parseActionProvider(final Element element, final ParserContext context) {
- registerDomRpcProviderServiceRefBean(context);
- registerBindingRpcProviderServiceRefBean(context);
- registerSchemaServiceRefBean(context);
-
- MutableBeanMetadata metadata = createBeanMetadata(context, context.generateId(), ActionProviderBean.class,
- true, true);
- addBlueprintBundleRefProperty(context, metadata);
- metadata.addProperty("domRpcProvider", createRef(context, DOM_RPC_PROVIDER_SERVICE_NAME));
- metadata.addProperty("bindingRpcProvider", createRef(context, BINDING_RPC_PROVIDER_SERVICE_NAME));
- metadata.addProperty("schemaService", createRef(context, SCHEMA_SERVICE_NAME));
- metadata.addProperty("interfaceName", createValue(context, element.getAttribute(INTERFACE)));
-
- if (element.hasAttribute(REF_ATTR)) {
- metadata.addProperty("implementation", createRef(context, element.getAttribute(REF_ATTR)));
- }
-
- LOG.debug("parseActionProvider returning {}", metadata);
- return metadata;
- }
-
-
- private static Metadata parseRpcImplementation(final Element element, final ParserContext context) {
- registerBindingRpcProviderServiceRefBean(context);
-
- MutableBeanMetadata metadata = createBeanMetadata(context, context.generateId(), RpcImplementationBean.class,
- true, true);
- addBlueprintBundleRefProperty(context, metadata);
- metadata.addProperty("rpcProvider", createRef(context, BINDING_RPC_PROVIDER_SERVICE_NAME));
- metadata.addProperty("implementation", createRef(context, element.getAttribute(REF_ATTR)));
-
- if (element.hasAttribute(INTERFACE)) {
- metadata.addProperty("interfaceName", createValue(context, element.getAttribute(INTERFACE)));
- }
-
- LOG.debug("parseRpcImplementation returning {}", metadata);
- return metadata;
- }
-
- private static Metadata parseActionService(final Element element, final ParserContext context) {
- ComponentFactoryMetadata metadata = new ActionServiceMetadata(getId(context, element),
- element.getAttribute(INTERFACE));
-
- LOG.debug("parseActionService returning {}", metadata);
-
- return metadata;
- }
-
- private static Metadata parseRpcService(final Element element, final ParserContext context) {
- ComponentFactoryMetadata metadata = new RpcServiceMetadata(getId(context, element),
- element.getAttribute(INTERFACE));
-
- LOG.debug("parseRpcService returning {}", metadata);
-
- return metadata;
- }
-
- private static void registerDomRpcProviderServiceRefBean(final ParserContext context) {
- registerRefBean(context, DOM_RPC_PROVIDER_SERVICE_NAME, DOMRpcProviderService.class);
- }
-
- private static void registerBindingRpcProviderServiceRefBean(final ParserContext context) {
- registerRefBean(context, BINDING_RPC_PROVIDER_SERVICE_NAME, RpcProviderService.class);
- }
-
- private static void registerSchemaServiceRefBean(final ParserContext context) {
- registerRefBean(context, SCHEMA_SERVICE_NAME, DOMSchemaService.class);
- }
-
- private static void registerRefBean(final ParserContext context, final String name, final Class<?> clazz) {
- ComponentDefinitionRegistry registry = context.getComponentDefinitionRegistry();
- if (registry.getComponentDefinition(name) == null) {
- MutableReferenceMetadata metadata = createServiceRef(context, clazz, null);
- metadata.setId(name);
- registry.registerComponentDefinition(metadata);
- }
- }
-
- private static Metadata parseNotificationListener(final Element element, final ParserContext context) {
- registerNotificationServiceRefBean(context);
-
- MutableBeanMetadata metadata = createBeanMetadata(context, context.generateId(), NotificationListenerBean.class,
- true, true);
- addBlueprintBundleRefProperty(context, metadata);
- metadata.addProperty("notificationService", createRef(context, NOTIFICATION_SERVICE_NAME));
- metadata.addProperty("notificationListener", createRef(context, element.getAttribute(REF_ATTR)));
-
- LOG.debug("parseNotificationListener returning {}", metadata);
-
- return metadata;
- }
-
- private static void registerNotificationServiceRefBean(final ParserContext context) {
- ComponentDefinitionRegistry registry = context.getComponentDefinitionRegistry();
- if (registry.getComponentDefinition(NOTIFICATION_SERVICE_NAME) == null) {
- MutableReferenceMetadata metadata = createServiceRef(context, NotificationService.class, null);
- metadata.setId(NOTIFICATION_SERVICE_NAME);
- registry.registerComponentDefinition(metadata);
- }
- }
-
private static Metadata parseClusteredAppConfig(final Element element, final ParserContext context) {
LOG.debug("parseClusteredAppConfig");
}
}
- private static Metadata parseSpecificReferenceList(final Element element, final ParserContext context) {
- ComponentFactoryMetadata metadata = new SpecificReferenceListMetadata(getId(context, element),
- element.getAttribute(INTERFACE));
-
- LOG.debug("parseSpecificReferenceList returning {}", metadata);
-
- return metadata;
- }
-
- private static Metadata parseStaticReference(final Element element, final ParserContext context) {
- ComponentFactoryMetadata metadata = new StaticReferenceMetadata(getId(context, element),
- element.getAttribute(INTERFACE));
-
- LOG.debug("parseStaticReference returning {}", metadata);
-
- return metadata;
- }
-
private static Element parseXML(final String name, final String xml) {
try {
return UntrustedXML.newDocumentBuilder().parse(new InputSource(new StringReader(xml))).getDocumentElement();
+++ /dev/null
-/*
- * Copyright (c) 2016 Brocade Communications Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.blueprint.ext;
-
-import com.google.common.base.Strings;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.List;
-import org.opendaylight.mdsal.binding.api.RpcProviderService;
-import org.opendaylight.yangtools.concepts.ObjectRegistration;
-import org.opendaylight.yangtools.yang.binding.RpcService;
-import org.osgi.framework.Bundle;
-import org.osgi.service.blueprint.container.ComponentDefinitionException;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * Blueprint bean corresponding to the "rpc-implementation" element that registers an RPC implementation with
- * the RpcProviderRegistry.
- *
- * @author Thomas Pantelis
- */
-public class RpcImplementationBean {
- private static final Logger LOG = LoggerFactory.getLogger(RpcImplementationBean.class);
- static final String RPC_IMPLEMENTATION = "rpc-implementation";
-
- private RpcProviderService rpcProvider;
- private Bundle bundle;
- private String interfaceName;
- private RpcService implementation;
- private final List<ObjectRegistration<RpcService>> rpcRegistrations = new ArrayList<>();
-
- public void setRpcProvider(final RpcProviderService rpcProvider) {
- this.rpcProvider = rpcProvider;
- }
-
- public void setBundle(final Bundle bundle) {
- this.bundle = bundle;
- }
-
- public void setInterfaceName(final String interfaceName) {
- this.interfaceName = interfaceName;
- }
-
- public void setImplementation(final RpcService implementation) {
- this.implementation = implementation;
- }
-
- @SuppressWarnings("checkstyle:IllegalCatch")
- public void init() {
- try {
- List<Class<RpcService>> rpcInterfaces = getImplementedRpcServiceInterfaces(interfaceName,
- implementation.getClass(), bundle, RPC_IMPLEMENTATION);
-
- LOG.debug("{}: init - adding implementation {} for RpcService interface(s) {}", bundle.getSymbolicName(),
- implementation, rpcInterfaces);
-
- for (Class<RpcService> rpcInterface : rpcInterfaces) {
- rpcRegistrations.add(rpcProvider.registerRpcImplementation(rpcInterface, implementation));
- }
- } catch (final ComponentDefinitionException e) {
- throw e;
- } catch (final Exception e) {
- throw new ComponentDefinitionException(String.format(
- "Error processing \"%s\" for %s", RPC_IMPLEMENTATION, implementation.getClass()), e);
- }
- }
-
- public void destroy() {
- for (ObjectRegistration<RpcService> reg: rpcRegistrations) {
- reg.close();
- }
- }
-
- @SuppressWarnings("unchecked")
- static List<Class<RpcService>> getImplementedRpcServiceInterfaces(final String interfaceName,
- final Class<?> implementationClass, final Bundle bundle, final String logName)
- throws ClassNotFoundException {
- if (!Strings.isNullOrEmpty(interfaceName)) {
- Class<?> rpcInterface = bundle.loadClass(interfaceName);
-
- if (!rpcInterface.isAssignableFrom(implementationClass)) {
- throw new ComponentDefinitionException(String.format(
- "The specified \"interface\" %s for \"%s\" is not implemented by RpcService \"ref\" %s",
- interfaceName, logName, implementationClass));
- }
-
- return Collections.singletonList((Class<RpcService>)rpcInterface);
- }
-
- List<Class<RpcService>> rpcInterfaces = new ArrayList<>();
- for (Class<?> intface : implementationClass.getInterfaces()) {
- if (RpcService.class.isAssignableFrom(intface)) {
- rpcInterfaces.add((Class<RpcService>) intface);
- }
- }
-
- if (rpcInterfaces.isEmpty()) {
- throw new ComponentDefinitionException(String.format(
- "The \"ref\" instance %s for \"%s\" does not implemented any RpcService interfaces",
- implementationClass, logName));
- }
-
- return rpcInterfaces;
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2016 Brocade Communications Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.blueprint.ext;
-
-import java.util.Objects;
-import java.util.function.Predicate;
-import org.opendaylight.mdsal.dom.spi.ContentRoutedRpcContext;
-
-/**
- * Factory metadata corresponding to the "rpc-service" element that gets an RPC service implementation from
- * the RpcProviderRegistry and provides it to the Blueprint container.
- *
- * @author Thomas Pantelis
- */
-final class RpcServiceMetadata extends AbstractInvokableServiceMetadata {
- RpcServiceMetadata(final String id, final String interfaceName) {
- super(id, interfaceName);
- }
-
- @Override
- Predicate<ContentRoutedRpcContext> rpcFilter() {
- return Objects::isNull;
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2017 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.blueprint.ext;
-
-import java.util.List;
-import java.util.function.Predicate;
-import java.util.stream.Collectors;
-import org.opendaylight.mdsal.binding.spec.reflect.BindingReflections;
-import org.opendaylight.mdsal.dom.spi.ContentRoutedRpcContext;
-import org.opendaylight.yangtools.yang.binding.RpcService;
-import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
-import org.opendaylight.yangtools.yang.model.api.stmt.RpcEffectiveStatement;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * Utility methods for dealing with various aspects of RPCs and actions.
- */
-final class RpcUtil {
- private static final Logger LOG = LoggerFactory.getLogger(RpcUtil.class);
-
- private RpcUtil() {
- // Hidden on purpose
- }
-
- static List<QName> decomposeRpcService(final Class<RpcService> service,
- final EffectiveModelContext schemaContext, final Predicate<ContentRoutedRpcContext> filter) {
- final var moduleName = BindingReflections.getQNameModule(service);
- final var module = schemaContext.findModuleStatement(moduleName)
- .orElseThrow(() -> new IllegalArgumentException("Module not found in SchemaContext: " + moduleName
- + "; service: " + service));
- LOG.debug("Resolved service {} to module {}", service, module);
-
- return module.streamEffectiveSubstatements(RpcEffectiveStatement.class)
- .filter(rpc -> filter.test(ContentRoutedRpcContext.forRpc(rpc)))
- .map(RpcEffectiveStatement::argument)
- .collect(Collectors.toList());
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2016 Brocade Communications Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.blueprint.ext;
-
-import com.google.common.io.Resources;
-import java.io.IOException;
-import java.net.URL;
-import java.nio.charset.StandardCharsets;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Set;
-import java.util.concurrent.ConcurrentSkipListSet;
-import org.osgi.framework.Bundle;
-import org.osgi.framework.BundleEvent;
-import org.osgi.framework.ServiceReference;
-import org.osgi.service.blueprint.container.ComponentDefinitionException;
-import org.osgi.util.tracker.BundleTracker;
-import org.osgi.util.tracker.BundleTrackerCustomizer;
-import org.osgi.util.tracker.ServiceTracker;
-import org.osgi.util.tracker.ServiceTrackerCustomizer;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * Factory metadata corresponding to the "specific-reference-list" element that obtains a specific list
- * of service instances from the OSGi registry for a given interface. The specific list is learned by first
- * extracting the list of expected service types by inspecting RESOLVED bundles for a resource file under
- * META-INF/services with the same name as the given interface. The type(s) listed in the resource file
- * must match the "type" property of the advertised service(s). In this manner, an app bundle announces the
- * service type(s) that it will advertise so that this class knows which services to expect up front. Once
- * all the expected services are obtained, the container is notified that all dependencies of this component
- * factory are satisfied.
- *
- * @author Thomas Pantelis
- */
-class SpecificReferenceListMetadata extends AbstractDependentComponentFactoryMetadata {
- private static final Logger LOG = LoggerFactory.getLogger(SpecificReferenceListMetadata.class);
-
- private final String interfaceName;
- private final String serviceResourcePath;
- private final Collection<String> expectedServiceTypes = new ConcurrentSkipListSet<>();
- private final Collection<String> retrievedServiceTypes = new ConcurrentSkipListSet<>();
- private final Collection<Object> retrievedServices = Collections.synchronizedList(new ArrayList<>());
- private volatile BundleTracker<Bundle> bundleTracker;
- private volatile ServiceTracker<Object, Object> serviceTracker;
-
- SpecificReferenceListMetadata(final String id, final String interfaceName) {
- super(id);
- this.interfaceName = interfaceName;
- serviceResourcePath = "META-INF/services/" + interfaceName;
- }
-
- @Override
- protected void startTracking() {
- BundleTrackerCustomizer<Bundle> bundleListener = new BundleTrackerCustomizer<>() {
- @Override
- public Bundle addingBundle(final Bundle bundle, final BundleEvent event) {
- bundleAdded(bundle);
- return bundle;
- }
-
- @Override
- public void modifiedBundle(final Bundle bundle, final BundleEvent event, final Bundle object) {
- }
-
- @Override
- public void removedBundle(final Bundle bundle, final BundleEvent event, final Bundle object) {
- }
- };
-
- bundleTracker = new BundleTracker<>(container().getBundleContext(), Bundle.RESOLVED | Bundle.STARTING
- | Bundle.STOPPING | Bundle.ACTIVE, bundleListener);
-
- // This will get the list of all current RESOLVED+ bundles.
- bundleTracker.open();
-
- if (expectedServiceTypes.isEmpty()) {
- setSatisfied();
- return;
- }
-
- ServiceTrackerCustomizer<Object, Object> serviceListener = new ServiceTrackerCustomizer<>() {
- @Override
- public Object addingService(final ServiceReference<Object> reference) {
- return serviceAdded(reference);
- }
-
- @Override
- public void modifiedService(final ServiceReference<Object> reference, final Object service) {
- }
-
- @Override
- public void removedService(final ServiceReference<Object> reference, final Object service) {
- container().getBundleContext().ungetService(reference);
- }
- };
-
- setDependencyDesc(interfaceName + " services with types " + expectedServiceTypes);
-
- serviceTracker = new ServiceTracker<>(container().getBundleContext(), interfaceName, serviceListener);
- serviceTracker.open();
- }
-
- private void bundleAdded(final Bundle bundle) {
- URL resource = bundle.getEntry(serviceResourcePath);
- if (resource == null) {
- return;
- }
-
- LOG.debug("{}: Found {} resource in bundle {}", logName(), resource, bundle.getSymbolicName());
-
- try {
- for (String line : Resources.readLines(resource, StandardCharsets.UTF_8)) {
- int ci = line.indexOf('#');
- if (ci >= 0) {
- line = line.substring(0, ci);
- }
-
- line = line.trim();
- if (line.isEmpty()) {
- continue;
- }
-
- String serviceType = line;
- LOG.debug("{}: Retrieved service type {}", logName(), serviceType);
- expectedServiceTypes.add(serviceType);
- }
- } catch (final IOException e) {
- setFailure(String.format("%s: Error reading resource %s from bundle %s", logName(), resource,
- bundle.getSymbolicName()), e);
- }
- }
-
- private Object serviceAdded(final ServiceReference<Object> reference) {
- Object service = container().getBundleContext().getService(reference);
- String serviceType = (String) reference.getProperty(OpendaylightNamespaceHandler.TYPE_ATTR);
-
- LOG.debug("{}: Service type {} added from bundle {}", logName(), serviceType,
- reference.getBundle().getSymbolicName());
-
- if (serviceType == null) {
- LOG.error("{}: Missing OSGi service property '{}' for service interface {} in bundle {}", logName(),
- OpendaylightNamespaceHandler.TYPE_ATTR, interfaceName, reference.getBundle().getSymbolicName());
- return service;
- }
-
- if (!expectedServiceTypes.contains(serviceType)) {
- LOG.error("{}: OSGi service property '{}' for service interface {} in bundle {} was not found in the "
- + "expected service types {} obtained via {} bundle resources. Is the bundle resource missing or "
- + "the service type misspelled?", logName(), OpendaylightNamespaceHandler.TYPE_ATTR, interfaceName,
- reference.getBundle().getSymbolicName(), expectedServiceTypes, serviceResourcePath);
- return service;
- }
-
- // If already satisfied, meaning we got all initial services, then a new bundle must've been
- // dynamically installed or a prior service's blueprint container was restarted, in which case we
- // restart our container.
- if (isSatisfied()) {
- restartContainer();
- } else {
- retrievedServiceTypes.add(serviceType);
- retrievedServices.add(service);
-
- if (retrievedServiceTypes.equals(expectedServiceTypes)) {
- LOG.debug("{}: Got all expected service types", logName());
- setSatisfied();
- } else {
- Set<String> remaining = new HashSet<>(expectedServiceTypes);
- remaining.removeAll(retrievedServiceTypes);
- setDependencyDesc(interfaceName + " services with types " + remaining);
- }
- }
-
- return service;
- }
-
- @Override
- public Object create() throws ComponentDefinitionException {
- LOG.debug("{}: In create: interfaceName: {}", logName(), interfaceName);
-
- super.onCreate();
-
- LOG.debug("{}: create returning service list {}", logName(), retrievedServices);
-
- synchronized (retrievedServices) {
- return List.copyOf(retrievedServices);
- }
- }
-
- @Override
- public void destroy(final Object instance) {
- super.destroy(instance);
-
- if (bundleTracker != null) {
- bundleTracker.close();
- bundleTracker = null;
- }
-
- if (serviceTracker != null) {
- serviceTracker.close();
- serviceTracker = null;
- }
- }
-
- @Override
- public String toString() {
- return new StringBuilder()
- .append("SpecificReferenceListMetadata [interfaceName=").append(interfaceName)
- .append(", serviceResourcePath=").append(serviceResourcePath).append("]")
- .toString();
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2016 Brocade Communications Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.blueprint.ext;
-
-import org.osgi.service.blueprint.container.ComponentDefinitionException;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * Factory metadata corresponding to the "static-reference" element that obtains an OSGi service and
- * returns the actual instance. This differs from the standard "reference" element that returns a dynamic
- * proxy whose underlying service instance can come and go.
- *
- * @author Thomas Pantelis
- */
-class StaticReferenceMetadata extends AbstractDependentComponentFactoryMetadata {
- private static final Logger LOG = LoggerFactory.getLogger(StaticReferenceMetadata.class);
-
- private final String interfaceName;
- private volatile Object retrievedService;
-
- StaticReferenceMetadata(final String id, final String interfaceName) {
- super(id);
- this.interfaceName = interfaceName;
- }
-
- @Override
- protected void startTracking() {
- retrieveService(interfaceName, interfaceName, service -> {
- retrievedService = service;
- setSatisfied();
- });
- }
-
- @Override
- public Object create() throws ComponentDefinitionException {
- super.onCreate();
-
- LOG.debug("{}: create returning service {}", logName(), retrievedService);
-
- return retrievedService;
- }
-
- @Override
- public String toString() {
- StringBuilder builder = new StringBuilder();
- builder.append("StaticReferenceMetadata [interfaceName=").append(interfaceName).append("]");
- return builder.toString();
- }
-}
class StaticServiceReferenceRecipe extends AbstractServiceReferenceRecipe {
private static final Logger LOG = LoggerFactory.getLogger(StaticServiceReferenceRecipe.class);
- private static final SatisfactionListener NOOP_LISTENER = satisfiable -> {
- // Intentional NOOP
- };
-
private volatile ServiceReference<?> trackedServiceReference;
private volatile Object trackedService;
private Consumer<Object> serviceSatisfiedCallback;
}
void startTracking(final Consumer<Object> newServiceSatisfiedCallback) {
- this.serviceSatisfiedCallback = newServiceSatisfiedCallback;
- super.start(NOOP_LISTENER);
+ serviceSatisfiedCallback = newServiceSatisfiedCallback;
+ super.start(satisfiable -> {
+ // Intentional NOOP
+ });
}
@SuppressWarnings("rawtypes")
getDataBrokerTestCustomizer().getAdapterContext().currentSerializer(), Lists.class)
.createDefaultInstance();
- UnorderedList element = lists.getUnorderedContainer().getUnorderedList().values().iterator().next();
+ UnorderedList element = lists.nonnullUnorderedContainer().nonnullUnorderedList().values().iterator().next();
assertEquals("someName", element.getName());
assertEquals("someValue", element.getValue());
}
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<!-- vi: set et smarttab sw=4 tabstop=4: -->
-<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
- <modelVersion>4.0.0</modelVersion>
- <parent>
- <groupId>org.opendaylight.odlparent</groupId>
- <artifactId>bundle-parent</artifactId>
- <version>12.0.1</version>
- <relativePath/>
- </parent>
-
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>netty-event-executor-config</artifactId>
- <version>0.18.2-SNAPSHOT</version>
- <packaging>bundle</packaging>
- <name>${project.artifactId}</name>
- <description>Configuration Wrapper around netty's event executor</description>
-
- <dependencies>
- <dependency>
- <groupId>com.google.guava</groupId>
- <artifactId>guava</artifactId>
- </dependency>
- <dependency>
- <groupId>io.netty</groupId>
- <artifactId>netty-common</artifactId>
- </dependency>
- <dependency>
- <groupId>org.osgi</groupId>
- <artifactId>org.osgi.service.component.annotations</artifactId>
- </dependency>
- </dependencies>
-</project>
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.yang.netty.eventexecutor;
-
-import com.google.common.reflect.AbstractInvocationHandler;
-import com.google.common.reflect.Reflection;
-import io.netty.util.concurrent.EventExecutor;
-import io.netty.util.concurrent.GlobalEventExecutor;
-import io.netty.util.concurrent.ImmediateEventExecutor;
-import java.lang.reflect.Method;
-import java.util.concurrent.TimeUnit;
-
-public interface AutoCloseableEventExecutor extends EventExecutor, AutoCloseable {
- static AutoCloseableEventExecutor globalEventExecutor() {
- return createCloseableProxy(GlobalEventExecutor.INSTANCE);
- }
-
- static AutoCloseableEventExecutor immediateEventExecutor() {
- return createCloseableProxy(ImmediateEventExecutor.INSTANCE);
- }
-
- private static AutoCloseableEventExecutor createCloseableProxy(final EventExecutor eventExecutor) {
- return Reflection.newProxy(AutoCloseableEventExecutor.class, new AbstractInvocationHandler() {
- @Override
- protected Object handleInvocation(final Object proxy, final Method method, final Object[] args)
- throws Throwable {
- if (method.getName().equals("close")) {
- eventExecutor.shutdownGracefully(0, 1, TimeUnit.SECONDS);
- return null;
- } else {
- return method.invoke(eventExecutor, args);
- }
- }
- });
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2020 PANTHEON.tech, s.r.o. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.yang.netty.eventexecutor;
-
-import static io.netty.util.concurrent.GlobalEventExecutor.INSTANCE;
-
-import io.netty.util.concurrent.EventExecutor;
-import io.netty.util.concurrent.EventExecutorGroup;
-import io.netty.util.concurrent.Future;
-import io.netty.util.concurrent.ProgressivePromise;
-import io.netty.util.concurrent.Promise;
-import io.netty.util.concurrent.ScheduledFuture;
-import java.util.Collection;
-import java.util.Iterator;
-import java.util.List;
-import java.util.concurrent.Callable;
-import java.util.concurrent.ExecutionException;
-import java.util.concurrent.TimeUnit;
-import java.util.concurrent.TimeoutException;
-import org.osgi.service.component.annotations.Activate;
-import org.osgi.service.component.annotations.Component;
-import org.osgi.service.component.annotations.Deactivate;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-@Component(immediate = true, property = "type=global-event-executor")
-public final class OSGiGlobalEventExecutor implements EventExecutor {
- private static final Logger LOG = LoggerFactory.getLogger(OSGiGlobalEventExecutor.class);
-
- @Override
- public boolean isShuttingDown() {
- return INSTANCE.isShuttingDown();
- }
-
- @Override
- public Future<?> shutdownGracefully() {
- return INSTANCE.shutdownGracefully();
- }
-
- @Override
- public Future<?> shutdownGracefully(final long quietPeriod, final long timeout, final TimeUnit unit) {
- return INSTANCE.shutdownGracefully(quietPeriod, timeout, unit);
- }
-
- @Override
- public Future<?> terminationFuture() {
- return INSTANCE.terminationFuture();
- }
-
- @Override
- @Deprecated
- public void shutdown() {
- INSTANCE.shutdown();
- }
-
- @Override
- public List<Runnable> shutdownNow() {
- return INSTANCE.shutdownNow();
- }
-
- @Override
- public Iterator<EventExecutor> iterator() {
- return INSTANCE.iterator();
- }
-
- @Override
- public Future<?> submit(final Runnable task) {
- return INSTANCE.submit(task);
- }
-
- @Override
- public <T> Future<T> submit(final Runnable task, final T result) {
- return INSTANCE.submit(task, result);
- }
-
- @Override
- public <T> Future<T> submit(final Callable<T> task) {
- return INSTANCE.submit(task);
- }
-
- @Override
- public ScheduledFuture<?> schedule(final Runnable command, final long delay, final TimeUnit unit) {
- return INSTANCE.schedule(command, delay, unit);
- }
-
- @Override
- public <V> ScheduledFuture<V> schedule(final Callable<V> callable, final long delay, final TimeUnit unit) {
- return INSTANCE.schedule(callable, delay, unit);
- }
-
- @Override
- public ScheduledFuture<?> scheduleAtFixedRate(final Runnable command, final long initialDelay, final long period,
- final TimeUnit unit) {
- return INSTANCE.scheduleAtFixedRate(command, initialDelay, period, unit);
- }
-
- @Override
- public ScheduledFuture<?> scheduleWithFixedDelay(final Runnable command, final long initialDelay, final long delay,
- final TimeUnit unit) {
- return INSTANCE.scheduleWithFixedDelay(command, initialDelay, delay, unit);
- }
-
- @Override
- public boolean isShutdown() {
- return INSTANCE.isShutdown();
- }
-
- @Override
- public boolean isTerminated() {
- return INSTANCE.isTerminated();
- }
-
- @Override
- public boolean awaitTermination(final long timeout, final TimeUnit unit) throws InterruptedException {
- return INSTANCE.awaitTermination(timeout, unit);
- }
-
- @Override
- public <T> List<java.util.concurrent.Future<T>> invokeAll(final Collection<? extends Callable<T>> tasks)
- throws InterruptedException {
- return INSTANCE.invokeAll(tasks);
- }
-
- @Override
- public <T> List<java.util.concurrent.Future<T>> invokeAll(final Collection<? extends Callable<T>> tasks,
- final long timeout, final TimeUnit unit) throws InterruptedException {
- return INSTANCE.invokeAll(tasks, timeout, unit);
- }
-
- @Override
- public <T> T invokeAny(final Collection<? extends Callable<T>> tasks)
- throws InterruptedException, ExecutionException {
- return INSTANCE.invokeAny(tasks);
- }
-
- @Override
- public <T> T invokeAny(final Collection<? extends Callable<T>> tasks, final long timeout, final TimeUnit unit)
- throws InterruptedException, ExecutionException, TimeoutException {
- return INSTANCE.invokeAny(tasks, timeout, unit);
- }
-
- @Override
- public void execute(final Runnable command) {
- INSTANCE.execute(command);
- }
-
- @Override
- public EventExecutor next() {
- return INSTANCE.next();
- }
-
- @Override
- public EventExecutorGroup parent() {
- return INSTANCE.parent();
- }
-
- @Override
- public boolean inEventLoop() {
- return INSTANCE.inEventLoop();
- }
-
- @Override
- public boolean inEventLoop(final Thread thread) {
- return INSTANCE.inEventLoop(thread);
- }
-
- @Override
- public <V> Promise<V> newPromise() {
- return INSTANCE.newPromise();
- }
-
- @Override
- public <V> ProgressivePromise<V> newProgressivePromise() {
- return INSTANCE.newProgressivePromise();
- }
-
- @Override
- public <V> Future<V> newSucceededFuture(final V result) {
- return INSTANCE.newSucceededFuture(result);
- }
-
- @Override
- public <V> Future<V> newFailedFuture(final Throwable cause) {
- return INSTANCE.newFailedFuture(cause);
- }
-
- @Activate
- void activate() {
- LOG.info("Global Event executor enabled");
- }
-
- @Deactivate
- void deactivate() {
- LOG.info("Global Event executor disabled");
- }
-
-}
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<!-- vi: set et smarttab sw=4 tabstop=4: -->
-<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
- <modelVersion>4.0.0</modelVersion>
- <parent>
- <groupId>org.opendaylight.odlparent</groupId>
- <artifactId>bundle-parent</artifactId>
- <version>12.0.1</version>
- <relativePath/>
- </parent>
-
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>netty-threadgroup-config</artifactId>
- <version>0.18.2-SNAPSHOT</version>
- <packaging>bundle</packaging>
- <name>${project.artifactId}</name>
- <description>Configuration Wrapper around netty's event group</description>
-
- <dependencies>
- <dependency>
- <groupId>io.netty</groupId>
- <artifactId>netty-transport</artifactId>
- </dependency>
- <dependency>
- <groupId>org.osgi</groupId>
- <artifactId>org.osgi.service.component.annotations</artifactId>
- </dependency>
- <dependency>
- <groupId>org.osgi</groupId>
- <artifactId>org.osgi.service.metatype.annotations</artifactId>
- </dependency>
- </dependencies>
-</project>
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.yang.netty.threadgroup;
-
-import io.netty.channel.nio.NioEventLoopGroup;
-import java.util.concurrent.TimeUnit;
-
-abstract class AbstractGlobalGroup extends NioEventLoopGroup implements AutoCloseable {
- AbstractGlobalGroup(final int threadCount) {
- super(threadCount < 0 ? 0 : threadCount);
- }
-
- @Override
- public final void close() {
- shutdownGracefully(0, 1, TimeUnit.SECONDS);
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2021 PANTHEON.tech, s.r.o. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.yang.netty.threadgroup;
-
-import org.osgi.service.metatype.annotations.AttributeDefinition;
-import org.osgi.service.metatype.annotations.ObjectClassDefinition;
-
-@ObjectClassDefinition(pid = "org.opendaylight.netty.threadgroup")
-public @interface Configuration {
- @AttributeDefinition(name = "global-boss-group-thread-count")
- int bossThreadCount() default 0;
-
- @AttributeDefinition(name = "global-worker-group-thread-count")
- int workerThreadCount() default 0;
-}
+++ /dev/null
-/*
- * Copyright (c) 2021 PANTHEON.tech, s.r.o. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.yang.netty.threadgroup;
-
-import io.netty.channel.EventLoopGroup;
-import org.osgi.service.component.annotations.Activate;
-import org.osgi.service.component.annotations.Component;
-import org.osgi.service.component.annotations.Deactivate;
-import org.osgi.service.metatype.annotations.Designate;
-
-@Component(immediate = true, service = EventLoopGroup.class, property = "type=global-boss-group")
-@Designate(ocd = Configuration.class)
-public final class GlobalBossGroup extends AbstractGlobalGroup {
- @Activate
- public GlobalBossGroup(final Configuration configuration) {
- super(configuration.bossThreadCount());
- }
-
- @Deactivate
- void deactivate() {
- close();
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2021 PANTHEON.tech, s.r.o. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.yang.netty.threadgroup;
-
-import io.netty.channel.EventLoopGroup;
-import org.osgi.service.component.annotations.Activate;
-import org.osgi.service.component.annotations.Component;
-import org.osgi.service.component.annotations.Deactivate;
-import org.osgi.service.metatype.annotations.Designate;
-
-@Component(immediate = true, service = EventLoopGroup.class, property = "type=global-worker-group")
-@Designate(ocd = Configuration.class)
-public final class GlobalWorkerGroup extends AbstractGlobalGroup {
- @Activate
- public GlobalWorkerGroup(final Configuration configuration) {
- super(configuration.workerThreadCount());
- }
-
- @Deactivate
- void deactivate() {
- close();
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2021 PANTHEON.tech, s.r.o. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-@org.osgi.service.component.annotations.RequireServiceComponentRuntime
-package org.opendaylight.controller.config.yang.netty.threadgroup;
\ No newline at end of file
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<!-- vi: set et smarttab sw=4 tabstop=4: -->
-<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
- <modelVersion>4.0.0</modelVersion>
- <parent>
- <groupId>org.opendaylight.odlparent</groupId>
- <artifactId>bundle-parent</artifactId>
- <version>12.0.1</version>
- <relativePath/>
- </parent>
-
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>netty-timer-config</artifactId>
- <version>0.18.2-SNAPSHOT</version>
- <packaging>bundle</packaging>
- <name>${project.artifactId}</name>
- <description>Configuration Wrapper around netty's timer</description>
-
- <dependencies>
- <dependency>
- <groupId>io.netty</groupId>
- <artifactId>netty-common</artifactId>
- </dependency>
- <dependency>
- <groupId>org.osgi</groupId>
- <artifactId>org.osgi.service.component.annotations</artifactId>
- </dependency>
- <dependency>
- <groupId>org.osgi</groupId>
- <artifactId>org.osgi.service.metatype.annotations</artifactId>
- </dependency>
- </dependencies>
-</project>
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.yang.netty.timer;
-
-import io.netty.util.HashedWheelTimer;
-import io.netty.util.Timeout;
-import io.netty.util.Timer;
-import io.netty.util.TimerTask;
-import java.util.Set;
-import java.util.concurrent.ThreadFactory;
-import java.util.concurrent.TimeUnit;
-import org.eclipse.jdt.annotation.Nullable;
-
-public final class HashedWheelTimerCloseable implements AutoCloseable, Timer {
-
- private final Timer timer;
-
- private HashedWheelTimerCloseable(final Timer timer) {
- this.timer = timer;
- }
-
- @Override
- public void close() {
- stop();
- }
-
- @Override
- public Timeout newTimeout(final TimerTask task, final long delay, final TimeUnit unit) {
- return this.timer.newTimeout(task, delay, unit);
- }
-
- @Override
- public Set<Timeout> stop() {
- return this.timer.stop();
- }
-
- public static HashedWheelTimerCloseable newInstance(final @Nullable Long duration,
- final @Nullable Integer ticksPerWheel) {
- return newInstance(null, duration, ticksPerWheel);
- }
-
- public static HashedWheelTimerCloseable newInstance(final @Nullable ThreadFactory threadFactory,
- final @Nullable Long duration, final @Nullable Integer ticksPerWheel) {
- TimeUnit unit = TimeUnit.MILLISECONDS;
- if (!nullOrNonPositive(duration) && threadFactory == null && nullOrNonPositive(ticksPerWheel)) {
- return new HashedWheelTimerCloseable(new HashedWheelTimer(duration, unit));
- }
-
- if (!nullOrNonPositive(duration) && threadFactory == null && !nullOrNonPositive(ticksPerWheel)) {
- return new HashedWheelTimerCloseable(new HashedWheelTimer(duration, unit, ticksPerWheel));
- }
-
- if (nullOrNonPositive(duration) && threadFactory != null && nullOrNonPositive(ticksPerWheel)) {
- return new HashedWheelTimerCloseable(new HashedWheelTimer(threadFactory));
- }
-
- if (!nullOrNonPositive(duration) && threadFactory != null && nullOrNonPositive(ticksPerWheel)) {
- return new HashedWheelTimerCloseable(
- new HashedWheelTimer(threadFactory, duration, unit));
- }
-
- if (!nullOrNonPositive(duration) && threadFactory != null && !nullOrNonPositive(ticksPerWheel)) {
- return new HashedWheelTimerCloseable(
- new HashedWheelTimer(threadFactory, duration, unit, ticksPerWheel));
- }
-
- return new HashedWheelTimerCloseable(new HashedWheelTimer());
- }
-
- private static boolean nullOrNonPositive(final Number num) {
- return num == null || num.longValue() <= 0;
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2020 PANTHEON.tech, s.r.o. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.yang.netty.timer;
-
-import io.netty.util.Timeout;
-import io.netty.util.Timer;
-import io.netty.util.TimerTask;
-import java.util.Set;
-import java.util.concurrent.TimeUnit;
-import org.osgi.service.component.annotations.Activate;
-import org.osgi.service.component.annotations.Component;
-import org.osgi.service.component.annotations.Deactivate;
-import org.osgi.service.metatype.annotations.AttributeDefinition;
-import org.osgi.service.metatype.annotations.Designate;
-import org.osgi.service.metatype.annotations.ObjectClassDefinition;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-@Component(immediate = true, configurationPid = "org.opendaylight.netty.timer", property = "type=global-timer")
-@Designate(ocd = OSGiGlobalTimer.Config.class)
-public final class OSGiGlobalTimer implements Timer {
- @ObjectClassDefinition
- public @interface Config {
- @AttributeDefinition(name = "tick-duration")
- long tickDuration() default 0;
- @AttributeDefinition(name = "ticks-per-wheel")
- int ticksPerWheel() default 0;
- }
-
- private static final Logger LOG = LoggerFactory.getLogger(OSGiGlobalTimer.class);
-
- private Timer delegate;
-
- @Override
- public Timeout newTimeout(final TimerTask task, final long delay, final TimeUnit unit) {
- return delegate.newTimeout(task, delay, unit);
- }
-
- @Override
- public Set<Timeout> stop() {
- return delegate.stop();
- }
-
- @Activate
- void activate(final Config config) {
- delegate = HashedWheelTimerCloseable.newInstance(config.tickDuration(), config.ticksPerWheel());
- LOG.info("Global Netty timer started");
- }
-
- @Deactivate
- void deactivate() {
- delegate.stop();
- LOG.info("Global Netty timer stopped");
- }
-}
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
- <modelVersion>4.0.0</modelVersion>
- <parent>
- <groupId>org.opendaylight.odlparent</groupId>
- <artifactId>odlparent-lite</artifactId>
- <version>12.0.1</version>
- <relativePath/>
- </parent>
-
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>config-aggregator</artifactId>
- <version>0.18.2-SNAPSHOT</version>
- <packaging>pom</packaging>
-
- <properties>
- <maven.deploy.skip>true</maven.deploy.skip>
- <maven.install.skip>true</maven.install.skip>
- </properties>
-
- <modules>
- <module>threadpool-config-api</module>
- <module>threadpool-config-impl</module>
- <module>netty-threadgroup-config</module>
- <module>netty-event-executor-config</module>
- <module>netty-timer-config</module>
- </modules>
-</project>
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<!-- vi: set et smarttab sw=4 tabstop=4: -->
-<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
- <modelVersion>4.0.0</modelVersion>
- <parent>
- <groupId>org.opendaylight.odlparent</groupId>
- <artifactId>bundle-parent</artifactId>
- <version>12.0.1</version>
- <relativePath/>
- </parent>
-
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>threadpool-config-api</artifactId>
- <version>0.18.2-SNAPSHOT</version>
- <packaging>bundle</packaging>
- <name>${project.artifactId}</name>
-</project>
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.config.threadpool;
-
-import java.util.concurrent.ScheduledExecutorService;
-
-/**
- * Interface representing scheduled {@link ThreadPool}.
- */
-public interface ScheduledThreadPool extends ThreadPool {
-
- @Override
- ScheduledExecutorService getExecutor();
-}
\ No newline at end of file
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.config.threadpool;
-
-import java.util.concurrent.ExecutorService;
-
-/**
- * Interface representing thread pool.
- */
-public interface ThreadPool {
-
- ExecutorService getExecutor();
-
- int getMaxThreadCount();
-}
\ No newline at end of file
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<!-- vi: set et smarttab sw=4 tabstop=4: -->
-<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
- <modelVersion>4.0.0</modelVersion>
- <parent>
- <groupId>org.opendaylight.odlparent</groupId>
- <artifactId>bundle-parent</artifactId>
- <version>12.0.1</version>
- <relativePath/>
- </parent>
-
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>threadpool-config-impl</artifactId>
- <version>0.18.2-SNAPSHOT</version>
- <packaging>bundle</packaging>
- <name>${project.artifactId}</name>
-
- <dependencyManagement>
- <dependencies>
- <dependency>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>controller-artifacts</artifactId>
- <version>7.0.2-SNAPSHOT</version>
- <type>pom</type>
- <scope>import</scope>
- </dependency>
- </dependencies>
- </dependencyManagement>
-
- <dependencies>
- <dependency>
- <groupId>${project.groupId}</groupId>
- <artifactId>threadpool-config-api</artifactId>
- </dependency>
- <dependency>
- <groupId>com.google.guava</groupId>
- <artifactId>guava</artifactId>
- </dependency>
- </dependencies>
-</project>
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.config.threadpool.util;
-
-import java.io.Closeable;
-import java.util.concurrent.ExecutorService;
-import java.util.concurrent.Executors;
-import java.util.concurrent.ThreadFactory;
-import java.util.concurrent.ThreadPoolExecutor;
-import org.opendaylight.controller.config.threadpool.ThreadPool;
-
-/**
- * Implementation of {@link ThreadPool} using fixed number of threads wraps
- * {@link ExecutorService}.
- */
-public class FixedThreadPoolWrapper implements ThreadPool, Closeable {
-
- private final ThreadPoolExecutor executor;
-
- public FixedThreadPoolWrapper(int threadCount, ThreadFactory factory) {
- this.executor = (ThreadPoolExecutor) Executors.newFixedThreadPool(threadCount, factory);
- executor.prestartAllCoreThreads();
- }
-
- @Override
- public ExecutorService getExecutor() {
- return Executors.unconfigurableExecutorService(executor);
- }
-
- @Override
- public void close() {
- executor.shutdown();
- }
-
- @Override
- public int getMaxThreadCount() {
- return executor.getMaximumPoolSize();
- }
-
- public void setMaxThreadCount(int maxThreadCount) {
- executor.setCorePoolSize(maxThreadCount);
- executor.setMaximumPoolSize(maxThreadCount);
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.threadpool.util;
-
-import java.io.Closeable;
-import java.util.OptionalInt;
-import java.util.concurrent.BlockingQueue;
-import java.util.concurrent.ExecutorService;
-import java.util.concurrent.Executors;
-import java.util.concurrent.LinkedBlockingQueue;
-import java.util.concurrent.RejectedExecutionException;
-import java.util.concurrent.RejectedExecutionHandler;
-import java.util.concurrent.ThreadFactory;
-import java.util.concurrent.ThreadPoolExecutor;
-import java.util.concurrent.TimeUnit;
-import org.opendaylight.controller.config.threadpool.ThreadPool;
-
-/**
- * Implementation of {@link ThreadPool} using flexible number of threads wraps
- * {@link ExecutorService}.
- */
-public class FlexibleThreadPoolWrapper implements ThreadPool, Closeable {
- private final ThreadPoolExecutor executor;
-
- public FlexibleThreadPoolWrapper(final int minThreadCount, final int maxThreadCount, final long keepAlive,
- final TimeUnit timeUnit, final ThreadFactory threadFactory) {
- this(minThreadCount, maxThreadCount, keepAlive, timeUnit, threadFactory, getQueue(OptionalInt.empty()));
- }
-
- public FlexibleThreadPoolWrapper(final int minThreadCount, final int maxThreadCount, final long keepAlive,
- final TimeUnit timeUnit, final ThreadFactory threadFactory, final OptionalInt queueCapacity) {
- this(minThreadCount, maxThreadCount, keepAlive, timeUnit, threadFactory, getQueue(queueCapacity));
- }
-
- private FlexibleThreadPoolWrapper(final int minThreadCount, final int maxThreadCount, final long keepAlive,
- final TimeUnit timeUnit, final ThreadFactory threadFactory, final BlockingQueue<Runnable> queue) {
-
- executor = new ThreadPoolExecutor(minThreadCount, maxThreadCount, keepAlive, timeUnit,
- queue, threadFactory, new FlexibleRejectionHandler());
- executor.prestartAllCoreThreads();
- }
-
- /**
- * Overriding the queue:
- * ThreadPoolExecutor would not create new threads if the queue is not full, thus adding
- * occurs in RejectedExecutionHandler.
- * This impl saturates threadpool first, then queue. When both are full caller will get blocked.
- */
- private static ForwardingBlockingQueue getQueue(final OptionalInt capacity) {
- final BlockingQueue<Runnable> delegate = capacity.isPresent() ? new LinkedBlockingQueue<>(capacity.getAsInt())
- : new LinkedBlockingQueue<>();
- return new ForwardingBlockingQueue(delegate);
- }
-
- @Override
- public ExecutorService getExecutor() {
- return Executors.unconfigurableExecutorService(executor);
- }
-
- public int getMinThreadCount() {
- return executor.getCorePoolSize();
- }
-
- public void setMinThreadCount(final int minThreadCount) {
- executor.setCorePoolSize(minThreadCount);
- }
-
- @Override
- public int getMaxThreadCount() {
- return executor.getMaximumPoolSize();
- }
-
- public void setMaxThreadCount(final int maxThreadCount) {
- executor.setMaximumPoolSize(maxThreadCount);
- }
-
- public long getKeepAliveMillis() {
- return executor.getKeepAliveTime(TimeUnit.MILLISECONDS);
- }
-
- public void setKeepAliveMillis(final long keepAliveMillis) {
- executor.setKeepAliveTime(keepAliveMillis, TimeUnit.MILLISECONDS);
- }
-
- public void setThreadFactory(final ThreadFactory threadFactory) {
- executor.setThreadFactory(threadFactory);
- }
-
- public void prestartAllCoreThreads() {
- executor.prestartAllCoreThreads();
- }
-
- @Override
- public void close() {
- executor.shutdown();
- }
-
- /**
- * if the max threads are met, then it will raise a rejectedExecution. We then push to the queue.
- */
- private static class FlexibleRejectionHandler implements RejectedExecutionHandler {
- @Override
- @SuppressWarnings("checkstyle:parameterName")
- public void rejectedExecution(final Runnable r, final ThreadPoolExecutor executor) {
- try {
- executor.getQueue().put(r);
- } catch (InterruptedException e) {
- throw new RejectedExecutionException("Interrupted while waiting on the queue", e);
- }
- }
- }
-
- private static class ForwardingBlockingQueue
- extends com.google.common.util.concurrent.ForwardingBlockingQueue<Runnable> {
- private final BlockingQueue<Runnable> delegate;
-
- ForwardingBlockingQueue(final BlockingQueue<Runnable> delegate) {
- this.delegate = delegate;
- }
-
- @Override
- protected BlockingQueue<Runnable> delegate() {
- return delegate;
- }
-
- @Override
- @SuppressWarnings("checkstyle:parameterName")
- public boolean offer(final Runnable o) {
- // ThreadPoolExecutor will spawn a new thread after core size is reached only
- // if the queue.offer returns false.
- return false;
- }
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.config.threadpool.util;
-
-import static java.util.Objects.requireNonNull;
-
-import java.io.Closeable;
-import java.util.concurrent.ThreadFactory;
-import java.util.concurrent.atomic.AtomicLong;
-
-/**
- * Implementation of {@link ThreadFactory}. This class is thread-safe.
- */
-public class NamingThreadPoolFactory implements ThreadFactory, Closeable {
-
- private final ThreadGroup group;
- private final String namePrefix;
- private final AtomicLong threadName = new AtomicLong();
-
- public NamingThreadPoolFactory(final String namePrefix) {
- this.namePrefix = requireNonNull(namePrefix);
- this.group = new ThreadGroup(namePrefix);
- }
-
- @Override
- @SuppressWarnings("checkstyle:parameterName")
- public Thread newThread(final Runnable r) {
- return new Thread(group, r, String.format("%s-%d", group.getName(), threadName.incrementAndGet()));
- }
-
- @Override
- public void close() {
- }
-
- public String getNamePrefix() {
- return namePrefix;
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.config.threadpool.util;
-
-import java.io.Closeable;
-import java.util.concurrent.Executors;
-import java.util.concurrent.ScheduledExecutorService;
-import java.util.concurrent.ScheduledThreadPoolExecutor;
-import java.util.concurrent.ThreadFactory;
-import org.opendaylight.controller.config.threadpool.ScheduledThreadPool;
-
-/**
- * Implementation of {@link ScheduledThreadPool} wraps
- * {@link ScheduledExecutorService}.
- */
-public class ScheduledThreadPoolWrapper implements ScheduledThreadPool, Closeable {
-
- private final ScheduledThreadPoolExecutor executor;
- private final int threadCount;
-
- public ScheduledThreadPoolWrapper(int threadCount, ThreadFactory factory) {
- this.threadCount = threadCount;
- this.executor = new ScheduledThreadPoolExecutor(threadCount, factory);
- executor.prestartAllCoreThreads();
- }
-
- @Override
- public ScheduledExecutorService getExecutor() {
- return Executors.unconfigurableScheduledExecutorService(executor);
- }
-
- @Override
- public void close() {
- executor.shutdown();
- }
-
- @Override
- public int getMaxThreadCount() {
- return threadCount;
- }
-
-}
<parent>
<groupId>org.opendaylight.controller</groupId>
<artifactId>mdsal-parent</artifactId>
- <version>7.0.2-SNAPSHOT</version>
+ <version>9.0.3-SNAPSHOT</version>
<relativePath>../parent</relativePath>
</parent>
<dependencies>
<dependency>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>repackaged-akka</artifactId>
+ <groupId>com.github.spotbugs</groupId>
+ <artifactId>spotbugs-annotations</artifactId>
+ <optional>true</optional>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
</dependency>
-
+ <dependency>
+ <groupId>org.eclipse.jdt</groupId>
+ <artifactId>org.eclipse.jdt.annotation</artifactId>
+ </dependency>
<dependency>
<groupId>org.opendaylight.yangtools</groupId>
<artifactId>concepts</artifactId>
<groupId>org.opendaylight.yangtools</groupId>
<artifactId>yang-data-impl</artifactId>
</dependency>
+ <dependency>
+ <groupId>org.opendaylight.yangtools</groupId>
+ <artifactId>yang-data-spi</artifactId>
+ </dependency>
<dependency>
<groupId>org.opendaylight.yangtools</groupId>
<artifactId>yang-data-codec-binfmt</artifactId>
<groupId>org.opendaylight.yangtools</groupId>
<artifactId>yang-data-tree-api</artifactId>
</dependency>
+ <dependency>
+ <groupId>org.opendaylight.controller</groupId>
+ <artifactId>repackaged-akka</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.scala-lang</groupId>
+ <artifactId>scala-library</artifactId>
+ </dependency>
<!-- Testing dependencies -->
+ <dependency>
+ <groupId>org.apache.commons</groupId>
+ <artifactId>commons-lang3</artifactId>
+ <scope>test</scope>
+ </dependency>
<dependency>
<groupId>org.opendaylight.yangtools</groupId>
<artifactId>mockito-configuration</artifactId>
<groupId>com.typesafe.akka</groupId>
<artifactId>akka-testkit_2.13</artifactId>
</dependency>
- <dependency>
- <groupId>commons-lang</groupId>
- <artifactId>commons-lang</artifactId>
- <scope>test</scope>
- </dependency>
</dependencies>
<build>
// BORON was 5
// NEON_SR2 was 6
// SODIUM_SR1 was 7
+ // MAGNESIUM was 8
+ // CHLORINE_SR2 was 9
+
/**
- * Oldest ABI version we support. The messages remain the same as {@code BORON}, but messages bearing QNames in any
- * shape are using {@link NormalizedNodeStreamVersion#MAGNESIUM}, which improves encoding.
- *
- * @deprecated Support for this version is going to be removed in the next major version.
- */
- @Deprecated(since = "7.0.0", forRemoval = true)
- MAGNESIUM(8) {
- @Override
- public NormalizedNodeStreamVersion getStreamVersion() {
- return NormalizedNodeStreamVersion.MAGNESIUM;
- }
- },
- /**
- * Revised ABI version. The messages remain the same as {@link #MAGNESIUM}, the serialization proxies in use are
- * flat objects without any superclasses.
+ * Oldest ABI version we support. The messages remain the same as {@code CHLORINE_SR2}, the serialization proxies in
+ * use are flat objects without any superclasses. Data encoding does not include augmentations as separate objects.
*/
- CHLORINE_SR2(9) {
+ POTASSIUM(10) {
@Override
public NormalizedNodeStreamVersion getStreamVersion() {
- return NormalizedNodeStreamVersion.MAGNESIUM;
+ return NormalizedNodeStreamVersion.POTASSIUM;
}
},
* @return Current {@link ABIVersion}
*/
public static @NonNull ABIVersion current() {
- return CHLORINE_SR2;
+ return POTASSIUM;
}
/**
*/
public static @NonNull ABIVersion valueOf(final short value) throws FutureVersionException, PastVersionException {
return switch (Short.toUnsignedInt(value)) {
- case 0, 1, 2, 3, 4, 6, 7 -> throw new PastVersionException(value, MAGNESIUM);
- case 8 -> MAGNESIUM;
- case 9 -> CHLORINE_SR2;
- default -> throw new FutureVersionException(value, CHLORINE_SR2);
+ case 0, 1, 2, 3, 4, 6, 7, 8, 9 -> throw new PastVersionException(value, POTASSIUM);
+ case 10 -> POTASSIUM;
+ default -> throw new FutureVersionException(value, POTASSIUM);
};
}
+++ /dev/null
-/*
- * Copyright (c) 2016 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.cluster.access.commands;
-
-import org.opendaylight.controller.cluster.access.concepts.AbstractRequestProxy;
-import org.opendaylight.controller.cluster.access.concepts.LocalHistoryIdentifier;
-
-/**
- * Abstract base class for serialization proxies associated with {@link LocalHistoryRequest}s.
- *
- * @param <T> Message type
- */
-@Deprecated(since = "7.0.0", forRemoval = true)
-abstract class AbstractLocalHistoryRequestProxy<T extends LocalHistoryRequest<T>>
- extends AbstractRequestProxy<LocalHistoryIdentifier, T> implements LocalHistoryRequest.SerialForm<T> {
- @java.io.Serial
- private static final long serialVersionUID = 1L;
-
- protected AbstractLocalHistoryRequestProxy() {
- // For Externalizable
- }
-
- AbstractLocalHistoryRequestProxy(final T request) {
- super(request);
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2017 Pantheon Technologies, s.r.o. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.cluster.access.commands;
-
-/**
- * Abstract base class for serialization proxies associated with {@link AbstractReadTransactionRequest}s. It implements
- * the initial (Boron) serialization format.
- *
- * @param <T> Message type
- */
-@Deprecated(since = "7.0.0", forRemoval = true)
-abstract class AbstractReadPathTransactionRequestProxyV1<T extends AbstractReadPathTransactionRequest<T>>
- extends AbstractReadTransactionRequestProxyV1<T> implements AbstractReadPathTransactionRequest.SerialForm<T> {
- @java.io.Serial
- private static final long serialVersionUID = 1L;
-
- protected AbstractReadPathTransactionRequestProxyV1() {
- // For Externalizable
- }
-
- AbstractReadPathTransactionRequestProxyV1(final T request) {
- super(request);
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2016 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.cluster.access.commands;
-
-/**
- * Abstract base class for serialization proxies associated with {@link AbstractReadTransactionRequest}s. It implements
- * the initial (Boron) serialization format.
- *
- * @param <T> Message type
- */
-@Deprecated(since = "7.0.0", forRemoval = true)
-abstract class AbstractReadTransactionRequestProxyV1<T extends AbstractReadTransactionRequest<T>>
- extends AbstractTransactionRequestProxy<T> implements AbstractReadTransactionRequest.SerialForm<T> {
- @java.io.Serial
- private static final long serialVersionUID = 1L;
-
- protected AbstractReadTransactionRequestProxyV1() {
- // For Externalizable
- }
-
- AbstractReadTransactionRequestProxyV1(final T request) {
- super(request);
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2016 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.cluster.access.commands;
-
-import org.opendaylight.controller.cluster.access.concepts.AbstractRequestProxy;
-import org.opendaylight.controller.cluster.access.concepts.TransactionIdentifier;
-
-/**
- * Abstract base class for serialization proxies associated with {@link TransactionRequest}s.
- *
- * @param <T> Message type
- */
-@Deprecated(since = "7.0.0", forRemoval = true)
-abstract class AbstractTransactionRequestProxy<T extends TransactionRequest<T>>
- extends AbstractRequestProxy<TransactionIdentifier, T> implements TransactionRequest.SerialForm<T> {
- @java.io.Serial
- private static final long serialVersionUID = 1L;
-
- AbstractTransactionRequestProxy() {
- // For Externalizable
- }
-
- AbstractTransactionRequestProxy(final T request) {
- super(request);
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2016 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.cluster.access.commands;
-
-import org.opendaylight.controller.cluster.access.concepts.AbstractSuccessProxy;
-import org.opendaylight.controller.cluster.access.concepts.TransactionIdentifier;
-
-/**
- * Abstract base class for serialization proxies associated with {@link TransactionSuccess}es.
- *
- * @param <T> Message type
- */
-@Deprecated(since = "7.0.0", forRemoval = true)
-abstract class AbstractTransactionSuccessProxy<T extends TransactionSuccess<T>>
- extends AbstractSuccessProxy<TransactionIdentifier, T> implements TransactionSuccess.SerialForm<T> {
- @java.io.Serial
- private static final long serialVersionUID = 1L;
-
- AbstractTransactionSuccessProxy() {
- // For Externalizable
- }
-
- AbstractTransactionSuccessProxy(final T request) {
- super(request);
- }
-}
import akka.actor.ActorRef;
import com.google.common.base.MoreObjects.ToStringHelper;
-import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
+import java.io.IOException;
+import java.io.ObjectInputStream;
+import java.io.ObjectOutputStream;
+import java.io.ObjectStreamException;
import java.util.Optional;
import org.eclipse.jdt.annotation.NonNull;
import org.eclipse.jdt.annotation.Nullable;
@java.io.Serial
private static final long serialVersionUID = 1L;
- @SuppressFBWarnings(value = "SE_BAD_FIELD", justification = "This field is not Serializable but this class "
- + "implements writeReplace to delegate serialization to a Proxy class and thus instances of this class "
- + "aren't serialized. FindBugs does not recognize this.")
private final DataTreeModification mod;
private final Exception delayedFailure;
private final boolean coordinated;
return super.addToStringAttributes(toStringHelper).add("coordinated", coordinated)
.add("delayedError", delayedFailure);
}
+
+ @java.io.Serial
+ private void readObject(final ObjectInputStream stream) throws IOException, ClassNotFoundException {
+ throwNSE();
+ }
+
+ @java.io.Serial
+ private void readObjectNoData() throws ObjectStreamException {
+ throwNSE();
+ }
+
+ @java.io.Serial
+ private void writeObject(final ObjectOutputStream stream) throws IOException {
+ throwNSE();
+ }
}
@Override
protected SerialForm externalizableProxy(final ABIVersion version) {
- return ABIVersion.MAGNESIUM.lt(version) ? new CCF(this) : new ConnectClientFailureProxyV1(this);
+ return new CCF(this);
}
@Override
+++ /dev/null
-/*
- * Copyright (c) 2016 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.cluster.access.commands;
-
-import org.opendaylight.controller.cluster.access.concepts.AbstractRequestFailureProxy;
-import org.opendaylight.controller.cluster.access.concepts.ClientIdentifier;
-
-/**
- * Serialization proxy for use with {@link ConnectClientFailure}. This class implements initial (Boron) serialization
- * format.
- */
-@Deprecated(since = "7.0.0", forRemoval = true)
-final class ConnectClientFailureProxyV1 extends AbstractRequestFailureProxy<ClientIdentifier, ConnectClientFailure>
- implements ConnectClientFailure.SerialForm {
- @java.io.Serial
- private static final long serialVersionUID = 2688639416324657256L;
-
- // checkstyle flags the public modifier as redundant however it is explicitly needed for Java serialization to
- // be able to create instances via reflection.
- @SuppressWarnings("checkstyle:RedundantModifier")
- public ConnectClientFailureProxyV1() {
- // For Externalizable
- }
-
- ConnectClientFailureProxyV1(final ConnectClientFailure failure) {
- super(failure);
- }
-}
@Override
protected SerialForm externalizableProxy(final ABIVersion version) {
- return ABIVersion.MAGNESIUM.lt(version) ? new CCR(this) : new ConnectClientRequestProxyV1(this);
+ return new CCR(this);
}
@Override
+++ /dev/null
-/*
- * Copyright (c) 2016 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.cluster.access.commands;
-
-import org.opendaylight.controller.cluster.access.concepts.AbstractRequestProxy;
-import org.opendaylight.controller.cluster.access.concepts.ClientIdentifier;
-
-/**
- * Externalizable proxy for use with {@link ConnectClientRequest}. It implements the initial (Boron) serialization
- * format.
- */
-@Deprecated(since = "7.0.0", forRemoval = true)
-final class ConnectClientRequestProxyV1 extends AbstractRequestProxy<ClientIdentifier, ConnectClientRequest>
- implements ConnectClientRequest.SerialForm {
- @java.io.Serial
- private static final long serialVersionUID = 8439729661327852159L;
-
- // checkstyle flags the public modifier as redundant however it is explicitly needed for Java serialization to
- // be able to create instances via reflection.
- @SuppressWarnings("checkstyle:RedundantModifier")
- public ConnectClientRequestProxyV1() {
- // for Externalizable
- }
-
- ConnectClientRequestProxyV1(final ConnectClientRequest request) {
- super(request);
- }
-}
import akka.serialization.Serialization;
import com.google.common.base.MoreObjects.ToStringHelper;
import com.google.common.collect.ImmutableList;
-import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import java.io.DataInput;
import java.io.IOException;
import java.io.ObjectInput;
+import java.io.ObjectInputStream;
import java.io.ObjectOutput;
+import java.io.ObjectOutputStream;
+import java.io.ObjectStreamException;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
private static final long serialVersionUID = 1L;
private final @NonNull ImmutableList<ActorSelection> alternates;
-
- @SuppressFBWarnings(value = "SE_BAD_FIELD", justification = "See justification above.")
private final ReadOnlyDataTree dataTree;
private final @NonNull ActorRef backend;
private final int maxMessages;
@Override
protected SerialForm externalizableProxy(final ABIVersion version) {
- return ABIVersion.MAGNESIUM.lt(version) ? new CCS(this) : new ConnectClientSuccessProxyV1(this);
+ return new CCS(this);
}
@Override
return super.addToStringAttributes(toStringHelper).add("alternates", alternates)
.add("dataTree present", getDataTree().isPresent()).add("maxMessages", maxMessages);
}
+
+ @java.io.Serial
+ private void readObject(final ObjectInputStream stream) throws IOException, ClassNotFoundException {
+ throwNSE();
+ }
+
+ @java.io.Serial
+ private void readObjectNoData() throws ObjectStreamException {
+ throwNSE();
+ }
+
+ @java.io.Serial
+ private void writeObject(final ObjectOutputStream stream) throws IOException {
+ throwNSE();
+ }
}
+++ /dev/null
-/*
- * Copyright (c) 2016 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.cluster.access.commands;
-
-import org.opendaylight.controller.cluster.access.concepts.AbstractSuccessProxy;
-import org.opendaylight.controller.cluster.access.concepts.ClientIdentifier;
-
-/**
- * Externalizable proxy for use with {@link ConnectClientSuccess}. It implements the initial (Boron) serialization
- * format.
- */
-@Deprecated(since = "7.0.0", forRemoval = true)
-final class ConnectClientSuccessProxyV1 extends AbstractSuccessProxy<ClientIdentifier, ConnectClientSuccess>
- implements ConnectClientSuccess.SerialForm {
- @java.io.Serial
- private static final long serialVersionUID = 1L;
-
- // checkstyle flags the public modifier as redundant however it is explicitly needed for Java serialization to
- // be able to create instances via reflection.
- @SuppressWarnings("checkstyle:RedundantModifier")
- public ConnectClientSuccessProxyV1() {
- // For Externalizable
- }
-
- ConnectClientSuccessProxyV1(final ConnectClientSuccess success) {
- super(success);
- }
-}
@Override
protected SerialForm externalizableProxy(final ABIVersion version) {
- return ABIVersion.MAGNESIUM.lt(version) ? new CHR(this) : new CreateLocalHistoryRequestProxyV1(this);
+ return new CHR(this);
}
@Override
+++ /dev/null
-/*
- * Copyright (c) 2016 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.cluster.access.commands;
-
-/**
- * Externalizable proxy for use with {@link CreateLocalHistoryRequest}. It implements the initial (Boron) serialization
- * format.
- */
-@Deprecated(since = "7.0.0", forRemoval = true)
-final class CreateLocalHistoryRequestProxyV1 extends AbstractLocalHistoryRequestProxy<CreateLocalHistoryRequest>
- implements CreateLocalHistoryRequest.SerialForm {
- @java.io.Serial
- private static final long serialVersionUID = 1L;
-
- // checkstyle flags the public modifier as redundant however it is explicitly needed for Java serialization to
- // be able to create instances via reflection.
- @SuppressWarnings("checkstyle:RedundantModifier")
- public CreateLocalHistoryRequestProxyV1() {
- // For Externalizable
- }
-
- CreateLocalHistoryRequestProxyV1(final CreateLocalHistoryRequest request) {
- super(request);
- }
-}
@Override
protected SerialForm externalizableProxy(final ABIVersion version) {
- return ABIVersion.MAGNESIUM.lt(version) ? new DHR(this) : new DestroyLocalHistoryRequestProxyV1(this);
+ return new DHR(this);
}
@Override
+++ /dev/null
-/*
- * Copyright (c) 2016 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.cluster.access.commands;
-
-/**
- * Externalizable proxy for use with {@link DestroyLocalHistoryRequest}. It implements the initial (Boron) serialization
- * format.
- */
-@Deprecated(since = "7.0.0", forRemoval = true)
-final class DestroyLocalHistoryRequestProxyV1 extends AbstractLocalHistoryRequestProxy<DestroyLocalHistoryRequest>
- implements DestroyLocalHistoryRequest.SerialForm {
- @java.io.Serial
- private static final long serialVersionUID = 1L;
-
- // checkstyle flags the public modifier as redundant however it is explicitly needed for Java serialization to
- // be able to create instances via reflection.
- @SuppressWarnings("checkstyle:RedundantModifier")
- public DestroyLocalHistoryRequestProxyV1() {
- // For Externalizable
- }
-
- DestroyLocalHistoryRequestProxyV1(final DestroyLocalHistoryRequest request) {
- super(request);
- }
-}
import static com.google.common.base.Verify.verifyNotNull;
import static java.util.Objects.requireNonNull;
+import java.io.IOException;
+import java.io.ObjectInput;
+import java.io.ObjectOutput;
+import org.opendaylight.controller.cluster.access.concepts.TransactionIdentifier;
+
/**
* Externalizable proxy for use with {@link ExistsTransactionSuccess}. It implements the Chlorine SR2 serialization
* format.
*/
-final class ETS implements ExistsTransactionSuccess.SerialForm {
+final class ETS implements TransactionSuccess.SerialForm<ExistsTransactionSuccess> {
@java.io.Serial
private static final long serialVersionUID = 1L;
this.message = requireNonNull(message);
}
+ @Override
+ public void writeExternal(final ObjectOutput out, final ExistsTransactionSuccess msg) throws IOException {
+ out.writeBoolean(msg.getExists());
+ }
+
+ @Override
+ public ExistsTransactionSuccess readExternal(final ObjectInput in, final TransactionIdentifier target,
+ final long sequence) throws IOException {
+ return new ExistsTransactionSuccess(target, sequence, in.readBoolean());
+ }
+
@Override
public Object readResolve() {
return message();
@Override
protected SerialForm externalizableProxy(final ABIVersion version) {
- return ABIVersion.MAGNESIUM.lt(version) ? new ETR(this) : new ExistsTransactionRequestProxyV1(this);
+ return new ETR(this);
}
}
+++ /dev/null
-/*
- * Copyright (c) 2016 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.cluster.access.commands;
-
-/**
- * Externalizable proxy for use with {@link ExistsTransactionRequest}. It implements the initial (Boron) serialization
- * format.
- */
-@Deprecated(since = "7.0.0", forRemoval = true)
-final class ExistsTransactionRequestProxyV1 extends AbstractReadPathTransactionRequestProxyV1<ExistsTransactionRequest>
- implements ExistsTransactionRequest.SerialForm {
- @java.io.Serial
- private static final long serialVersionUID = 1L;
-
- // checkstyle flags the public modifier as redundant however it is explicitly needed for Java serialization to
- // be able to create instances via reflection.
- @SuppressWarnings("checkstyle:RedundantModifier")
- public ExistsTransactionRequestProxyV1() {
- // For Externalizable
- }
-
- ExistsTransactionRequestProxyV1(final ExistsTransactionRequest request) {
- super(request);
- }
-}
package org.opendaylight.controller.cluster.access.commands;
import com.google.common.base.MoreObjects.ToStringHelper;
-import java.io.IOException;
-import java.io.ObjectInput;
-import java.io.ObjectOutput;
import org.opendaylight.controller.cluster.access.ABIVersion;
import org.opendaylight.controller.cluster.access.concepts.TransactionIdentifier;
* {@link #getExists()}.
*/
public final class ExistsTransactionSuccess extends TransactionSuccess<ExistsTransactionSuccess> {
- interface SerialForm extends TransactionSuccess.SerialForm<ExistsTransactionSuccess> {
- @Override
- default ExistsTransactionSuccess readExternal(final ObjectInput in, final TransactionIdentifier target,
- final long sequence) throws IOException {
- return new ExistsTransactionSuccess(target, sequence, in.readBoolean());
- }
-
- @Override
- default void writeExternal(final ObjectOutput out, final ExistsTransactionSuccess msg) throws IOException {
- out.writeBoolean(msg.getExists());
- }
- }
-
@java.io.Serial
private static final long serialVersionUID = 1L;
}
@Override
- protected SerialForm externalizableProxy(final ABIVersion version) {
- return ABIVersion.MAGNESIUM.lt(version) ? new ETS(this) : new ExistsTransactionSuccessProxyV1(this);
+ protected ETS externalizableProxy(final ABIVersion version) {
+ return new ETS(this);
}
@Override
+++ /dev/null
-/*
- * Copyright (c) 2016 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.cluster.access.commands;
-
-/**
- * Externalizable proxy for use with {@link ExistsTransactionSuccess}. It implements the initial (Boron) serialization
- * format.
- */
-@Deprecated(since = "7.0.0", forRemoval = true)
-final class ExistsTransactionSuccessProxyV1 extends AbstractTransactionSuccessProxy<ExistsTransactionSuccess>
- implements ExistsTransactionSuccess.SerialForm {
- @java.io.Serial
- private static final long serialVersionUID = 1L;
-
- // checkstyle flags the public modifier as redundant however it is explicitly needed for Java serialization to
- // be able to create instances via reflection.
- @SuppressWarnings("checkstyle:RedundantModifier")
- public ExistsTransactionSuccessProxyV1() {
- // For Externalizable
- }
-
- ExistsTransactionSuccessProxyV1(final ExistsTransactionSuccess request) {
- super(request);
- }
-}
import static com.google.common.base.Verify.verifyNotNull;
import static java.util.Objects.requireNonNull;
+import java.io.ObjectInput;
+import org.opendaylight.controller.cluster.access.concepts.TransactionIdentifier;
+
/**
* Externalizable proxy for use with {@link IncrementTransactionSequenceSuccess}. It implements the Chlorine SR2
* serialization format.
*/
-final class ITSS implements IncrementTransactionSequenceSuccess.SerialForm {
+final class ITSS implements TransactionSuccess.SerialForm<IncrementTransactionSequenceSuccess> {
@java.io.Serial
private static final long serialVersionUID = 1L;
this.message = requireNonNull(message);
}
+ @Override
+ public IncrementTransactionSequenceSuccess readExternal(final ObjectInput it, final TransactionIdentifier target,
+ final long sequence) {
+ return new IncrementTransactionSequenceSuccess(target, sequence);
+ }
+
@Override
public Object readResolve() {
return message();
@Override
protected SerialForm externalizableProxy(final ABIVersion version) {
- return ABIVersion.MAGNESIUM.lt(version) ? new ITSR(this) : new IncrementTransactionSequenceRequestProxyV1(this);
+ return new ITSR(this);
}
@Override
+++ /dev/null
-/*
- * Copyright (c) 2017 Pantheon Technologies, s.r.o. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.cluster.access.commands;
-
-@Deprecated(since = "7.0.0", forRemoval = true)
-final class IncrementTransactionSequenceRequestProxyV1
- extends AbstractReadTransactionRequestProxyV1<IncrementTransactionSequenceRequest>
- implements IncrementTransactionSequenceRequest.SerialForm {
- @java.io.Serial
- private static final long serialVersionUID = -7345885599575376005L;
-
- // checkstyle flags the public modifier as redundant however it is explicitly needed for Java serialization to
- // be able to create instances via reflection.
- @SuppressWarnings("checkstyle:RedundantModifier")
- public IncrementTransactionSequenceRequestProxyV1() {
- // For Externalizable
- }
-
- IncrementTransactionSequenceRequestProxyV1(final IncrementTransactionSequenceRequest request) {
- super(request);
- }
-}
*/
package org.opendaylight.controller.cluster.access.commands;
-import java.io.ObjectInput;
import org.opendaylight.controller.cluster.access.ABIVersion;
import org.opendaylight.controller.cluster.access.concepts.TransactionIdentifier;
* Successful reply to an {@link IncrementTransactionSequenceRequest}.
*/
public final class IncrementTransactionSequenceSuccess extends TransactionSuccess<IncrementTransactionSequenceSuccess> {
- interface SerialForm extends TransactionSuccess.SerialForm<IncrementTransactionSequenceSuccess> {
- @Override
- default IncrementTransactionSequenceSuccess readExternal(final ObjectInput it,
- final TransactionIdentifier target, final long sequence) {
- return new IncrementTransactionSequenceSuccess(target, sequence);
- }
- }
-
@java.io.Serial
private static final long serialVersionUID = 1L;
}
@Override
- protected SerialForm externalizableProxy(final ABIVersion version) {
- return ABIVersion.MAGNESIUM.lt(version) ? new ITSS(this) : new IncrementTransactionSequenceSuccessProxyV1(this);
+ protected ITSS externalizableProxy(final ABIVersion version) {
+ return new ITSS(this);
}
@Override
+++ /dev/null
-/*
- * Copyright (c) 2016 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.cluster.access.commands;
-
-/**
- * Externalizable proxy for use with {@link IncrementTransactionSequenceSuccess}. It implements the initial (Boron)
- * serialization format.
- */
-@Deprecated(since = "7.0.0", forRemoval = true)
-final class IncrementTransactionSequenceSuccessProxyV1
- extends AbstractTransactionSuccessProxy<IncrementTransactionSequenceSuccess>
- implements IncrementTransactionSequenceSuccess.SerialForm {
- @java.io.Serial
- private static final long serialVersionUID = 1L;
-
- // checkstyle flags the public modifier as redundant however it is explicitly needed for Java serialization to
- // be able to create instances via reflection.
- @SuppressWarnings("checkstyle:RedundantModifier")
- public IncrementTransactionSequenceSuccessProxyV1() {
- // For Externalizable
- }
-
- IncrementTransactionSequenceSuccessProxyV1(final IncrementTransactionSequenceSuccess request) {
- super(request);
- }
-}
@Override
protected SerialForm externalizableProxy(final ABIVersion version) {
- return ABIVersion.MAGNESIUM.lt(version) ? new HF(this) : new LocalHistoryFailureProxyV1(this);
+ return new HF(this);
}
}
+++ /dev/null
-/*
- * Copyright (c) 2016 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.cluster.access.commands;
-
-import org.opendaylight.controller.cluster.access.concepts.AbstractRequestFailureProxy;
-import org.opendaylight.controller.cluster.access.concepts.LocalHistoryIdentifier;
-
-/**
- * Externalizable proxy for use with {@link LocalHistoryFailure}. It implements the initial (Boron) serialization
- * format.
- */
-@Deprecated(since = "7.0.0", forRemoval = true)
-final class LocalHistoryFailureProxyV1
- extends AbstractRequestFailureProxy<LocalHistoryIdentifier, LocalHistoryFailure>
- implements LocalHistoryFailure.SerialForm {
- @java.io.Serial
- private static final long serialVersionUID = 1L;
-
- // checkstyle flags the public modifier as redundant however it is explicitly needed for Java serialization to
- // be able to create instances via reflection.
- @SuppressWarnings("checkstyle:RedundantModifier")
- public LocalHistoryFailureProxyV1() {
- // For Externalizable
- }
-
- LocalHistoryFailureProxyV1(final LocalHistoryFailure failure) {
- super(failure);
- }
-}
@Override
protected SerialForm externalizableProxy(final ABIVersion version) {
- return ABIVersion.MAGNESIUM.lt(version) ? new HS(this) : new LocalHistorySuccessProxyV1(this);
+ return new HS(this);
}
}
+++ /dev/null
-/*
- * Copyright (c) 2016 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.cluster.access.commands;
-
-import org.opendaylight.controller.cluster.access.concepts.AbstractSuccessProxy;
-import org.opendaylight.controller.cluster.access.concepts.LocalHistoryIdentifier;
-
-/**
- * Serialization proxy associated with {@link LocalHistorySuccess}.
- */
-@Deprecated(since = "7.0.0", forRemoval = true)
-final class LocalHistorySuccessProxyV1 extends AbstractSuccessProxy<LocalHistoryIdentifier, LocalHistorySuccess>
- implements LocalHistorySuccess.SerialForm {
- @java.io.Serial
- private static final long serialVersionUID = 1L;
-
- // checkstyle flags the public modifier as redundant however it is explicitly needed for Java serialization to
- // be able to create instances via reflection.
- @SuppressWarnings("checkstyle:RedundantModifier")
- public LocalHistorySuccessProxyV1() {
- // For Externalizable
- }
-
- LocalHistorySuccessProxyV1(final LocalHistorySuccess success) {
- super(success);
- }
-}
import static com.google.common.base.Verify.verifyNotNull;
import static java.util.Objects.requireNonNull;
+import java.io.IOException;
+import java.io.ObjectInput;
+import org.opendaylight.controller.cluster.access.concepts.TransactionIdentifier;
+
/**
* Externalizable proxy for use with {@link ModifyTransactionSuccess}. It implements the Chlorine SR2 serialization
* format.
*/
-final class MTS implements ModifyTransactionSuccess.SerialForm {
+final class MTS implements TransactionSuccess.SerialForm<ModifyTransactionSuccess> {
@java.io.Serial
private static final long serialVersionUID = 1L;
this.message = requireNonNull(message);
}
+ @Override
+ public ModifyTransactionSuccess readExternal(final ObjectInput in, final TransactionIdentifier target,
+ final long sequence) throws IOException {
+ return new ModifyTransactionSuccess(target, sequence);
+ }
+
@Override
public Object readResolve() {
return message();
import akka.actor.ActorRef;
import com.google.common.base.MoreObjects.ToStringHelper;
import com.google.common.collect.ImmutableList;
-import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import java.io.IOException;
import java.io.ObjectInput;
+import java.io.ObjectInputStream;
import java.io.ObjectOutput;
+import java.io.ObjectOutputStream;
+import java.io.ObjectStreamException;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
@java.io.Serial
private static final long serialVersionUID = 1L;
- @SuppressFBWarnings(value = "SE_BAD_FIELD", justification = "This field is not Serializable but this class "
- + "implements writeReplace to delegate serialization to a Proxy class and thus instances of this class "
- + "aren't serialized. FindBugs does not recognize this.")
private final List<TransactionModification> modifications;
private final PersistenceProtocol protocol;
@Override
protected SerialForm externalizableProxy(final ABIVersion version) {
- return ABIVersion.MAGNESIUM.lt(version) ? new MTR(this) : new ModifyTransactionRequestProxyV1(this);
+ return new MTR(this);
}
@Override
protected ModifyTransactionRequest cloneAsVersion(final ABIVersion version) {
return new ModifyTransactionRequest(this, version);
}
+
+ @java.io.Serial
+ private void readObject(final ObjectInputStream stream) throws IOException, ClassNotFoundException {
+ throwNSE();
+ }
+
+ @java.io.Serial
+ private void readObjectNoData() throws ObjectStreamException {
+ throwNSE();
+ }
+
+ @java.io.Serial
+ private void writeObject(final ObjectOutputStream stream) throws IOException {
+ throwNSE();
+ }
}
+++ /dev/null
-/*
- * Copyright (c) 2016 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.cluster.access.commands;
-
-/**
- * Externalizable proxy for use with {@link ExistsTransactionRequest}. It implements the initial (Boron) serialization
- * format.
- */
-@Deprecated(since = "7.0.0", forRemoval = true)
-final class ModifyTransactionRequestProxyV1 extends AbstractTransactionRequestProxy<ModifyTransactionRequest>
- implements ModifyTransactionRequest.SerialForm {
- @java.io.Serial
- private static final long serialVersionUID = 1L;
-
- // checkstyle flags the public modifier as redundant however it is explicitly needed for Java serialization to
- // be able to create instances via reflection.
- @SuppressWarnings("checkstyle:RedundantModifier")
- public ModifyTransactionRequestProxyV1() {
- // For Externalizable
- }
-
- ModifyTransactionRequestProxyV1(final ModifyTransactionRequest request) {
- super(request);
- }
-}
*/
package org.opendaylight.controller.cluster.access.commands;
-import java.io.IOException;
-import java.io.ObjectInput;
import org.opendaylight.controller.cluster.access.ABIVersion;
import org.opendaylight.controller.cluster.access.concepts.TransactionIdentifier;
* Response to a {@link ModifyTransactionRequest} which does not have a {@link PersistenceProtocol}.
*/
public final class ModifyTransactionSuccess extends TransactionSuccess<ModifyTransactionSuccess> {
- interface SerialForm extends TransactionSuccess.SerialForm<ModifyTransactionSuccess> {
- @Override
- default ModifyTransactionSuccess readExternal(final ObjectInput in, final TransactionIdentifier target,
- final long sequence) throws IOException {
- return new ModifyTransactionSuccess(target, sequence);
- }
- }
-
@java.io.Serial
private static final long serialVersionUID = 1L;
}
@Override
- protected SerialForm externalizableProxy(final ABIVersion version) {
- return ABIVersion.MAGNESIUM.lt(version) ? new MTS(this) : new ModifyTransactionSuccessProxyV1(this);
+ protected MTS externalizableProxy(final ABIVersion version) {
+ return new MTS(this);
}
@Override
+++ /dev/null
-/*
- * Copyright (c) 2016 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.cluster.access.commands;
-
-/**
- * Externalizable proxy for use with {@link ModifyTransactionSuccess}. It implements the initial (Boron) serialization
- * format.
- */
-@Deprecated(since = "7.0.0", forRemoval = true)
-final class ModifyTransactionSuccessProxyV1 extends AbstractTransactionSuccessProxy<ModifyTransactionSuccess>
- implements ModifyTransactionSuccess.SerialForm {
- @java.io.Serial
- private static final long serialVersionUID = 1L;
-
- // checkstyle flags the public modifier as redundant however it is explicitly needed for Java serialization to
- // be able to create instances via reflection.
- @SuppressWarnings("checkstyle:RedundantModifier")
- public ModifyTransactionSuccessProxyV1() {
- // For Externalizable
- }
-
- ModifyTransactionSuccessProxyV1(final ModifyTransactionSuccess success) {
- super(success);
- }
-}
@Override
protected SerialForm externalizableProxy(final ABIVersion version) {
- return ABIVersion.MAGNESIUM.lt(version) ? new PHR(this) : new PurgeLocalHistoryRequestProxyV1(this);
+ return new PHR(this);
}
@Override
+++ /dev/null
-/*
- * Copyright (c) 2016 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.cluster.access.commands;
-
-/**
- * Externalizable proxy for use with {@link PurgeLocalHistoryRequest}. It implements the initial (Boron) serialization
- * format.
- */
-@Deprecated(since = "7.0.0", forRemoval = true)
-final class PurgeLocalHistoryRequestProxyV1 extends AbstractLocalHistoryRequestProxy<PurgeLocalHistoryRequest>
- implements PurgeLocalHistoryRequest.SerialForm {
- @java.io.Serial
- private static final long serialVersionUID = 1L;
-
- // checkstyle flags the public modifier as redundant however it is explicitly needed for Java serialization to
- // be able to create instances via reflection.
- @SuppressWarnings("checkstyle:RedundantModifier")
- public PurgeLocalHistoryRequestProxyV1() {
- // For Externalizable
- }
-
- PurgeLocalHistoryRequestProxyV1(final PurgeLocalHistoryRequest request) {
- super(request);
- }
-}
import static com.google.common.base.Verify.verifyNotNull;
import static java.util.Objects.requireNonNull;
+import java.io.IOException;
+import java.io.ObjectInput;
+import java.io.ObjectOutput;
+import java.util.Optional;
+import org.opendaylight.controller.cluster.access.concepts.TransactionIdentifier;
+import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
+import org.opendaylight.yangtools.yang.data.codec.binfmt.NormalizedNodeDataInput;
+
/**
* Externalizable proxy for use with {@link ReadTransactionSuccess}. It implements the Chlorine SR2 serialization
* format.
*/
-final class RTS implements ReadTransactionSuccess.SerialForm {
+final class RTS implements TransactionSuccess.SerialForm<ReadTransactionSuccess> {
@java.io.Serial
private static final long serialVersionUID = 1L;
this.message = requireNonNull(message);
}
+ @Override
+ public ReadTransactionSuccess readExternal(final ObjectInput in, final TransactionIdentifier target,
+ final long sequence) throws IOException {
+ final Optional<NormalizedNode> data;
+ if (in.readBoolean()) {
+ data = Optional.of(NormalizedNodeDataInput.newDataInput(in).readNormalizedNode());
+ } else {
+ data = Optional.empty();
+ }
+ return new ReadTransactionSuccess(target, sequence, data);
+ }
+
+ @Override
+ public void writeExternal(final ObjectOutput out, final ReadTransactionSuccess msg) throws IOException {
+ TransactionSuccess.SerialForm.super.writeExternal(out, msg);
+
+ final var data = msg.getData();
+ if (data.isPresent()) {
+ out.writeBoolean(true);
+ try (var nnout = msg.getVersion().getStreamVersion().newDataOutput(out)) {
+ nnout.writeNormalizedNode(data.orElseThrow());
+ }
+ } else {
+ out.writeBoolean(false);
+ }
+ }
+
@Override
public Object readResolve() {
return message();
@Override
protected SerialForm externalizableProxy(final ABIVersion version) {
- return ABIVersion.MAGNESIUM.lt(version) ? new RTR(this) : new ReadTransactionRequestProxyV1(this);
+ return new RTR(this);
}
}
+++ /dev/null
-/*
- * Copyright (c) 2016 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.cluster.access.commands;
-
-/**
- * Externalizable proxy for use with {@link ReadTransactionRequest}. It implements the initial (Boron) serialization
- * format.
- */
-@Deprecated(since = "7.0.0", forRemoval = true)
-final class ReadTransactionRequestProxyV1 extends AbstractReadPathTransactionRequestProxyV1<ReadTransactionRequest>
- implements ReadTransactionRequest.SerialForm {
- @java.io.Serial
- private static final long serialVersionUID = 1L;
-
- // checkstyle flags the public modifier as redundant however it is explicitly needed for Java serialization to
- // be able to create instances via reflection.
- @SuppressWarnings("checkstyle:RedundantModifier")
- public ReadTransactionRequestProxyV1() {
- // For Externalizable
- }
-
- ReadTransactionRequestProxyV1(final ReadTransactionRequest request) {
- super(request);
- }
-}
import static java.util.Objects.requireNonNull;
-import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import java.io.IOException;
-import java.io.ObjectInput;
-import java.io.ObjectOutput;
+import java.io.ObjectInputStream;
+import java.io.ObjectOutputStream;
+import java.io.ObjectStreamException;
import java.util.Optional;
import org.opendaylight.controller.cluster.access.ABIVersion;
import org.opendaylight.controller.cluster.access.concepts.SliceableMessage;
import org.opendaylight.controller.cluster.access.concepts.TransactionIdentifier;
import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
-import org.opendaylight.yangtools.yang.data.codec.binfmt.NormalizedNodeDataInput;
/**
* Successful reply to an {@link ReadTransactionRequest}. It indicates presence of requested data via
*/
public final class ReadTransactionSuccess extends TransactionSuccess<ReadTransactionSuccess>
implements SliceableMessage {
- interface SerialForm extends TransactionSuccess.SerialForm<ReadTransactionSuccess> {
- @Override
- default ReadTransactionSuccess readExternal(final ObjectInput in, final TransactionIdentifier target,
- final long sequence) throws IOException {
- final Optional<NormalizedNode> data;
- if (in.readBoolean()) {
- data = Optional.of(NormalizedNodeDataInput.newDataInput(in).readNormalizedNode());
- } else {
- data = Optional.empty();
- }
- return new ReadTransactionSuccess(target, sequence, data);
- }
-
- @Override
- default void writeExternal(final ObjectOutput out, final ReadTransactionSuccess msg) throws IOException {
- TransactionSuccess.SerialForm.super.writeExternal(out, msg);
-
- final var data = msg.getData();
- if (data.isPresent()) {
- out.writeBoolean(true);
- try (var nnout = msg.getVersion().getStreamVersion().newDataOutput(out)) {
- nnout.writeNormalizedNode(data.orElseThrow());
- }
- } else {
- out.writeBoolean(false);
- }
- }
- }
-
@java.io.Serial
private static final long serialVersionUID = 1L;
- @SuppressFBWarnings(value = "SE_BAD_FIELD", justification = "interface-based best effort")
private final Optional<NormalizedNode> data;
private ReadTransactionSuccess(final ReadTransactionSuccess request, final ABIVersion version) {
}
@Override
- protected SerialForm externalizableProxy(final ABIVersion version) {
- return ABIVersion.MAGNESIUM.lt(version) ? new RTS(this) : new ReadTransactionSuccessProxyV1(this);
+ protected RTS externalizableProxy(final ABIVersion version) {
+ return new RTS(this);
}
@Override
protected ReadTransactionSuccess cloneAsVersion(final ABIVersion version) {
return new ReadTransactionSuccess(this, version);
}
+
+ @java.io.Serial
+ private void readObject(final ObjectInputStream stream) throws IOException, ClassNotFoundException {
+ throwNSE();
+ }
+
+ @java.io.Serial
+ private void readObjectNoData() throws ObjectStreamException {
+ throwNSE();
+ }
+
+ @java.io.Serial
+ private void writeObject(final ObjectOutputStream stream) throws IOException {
+ throwNSE();
+ }
}
+++ /dev/null
-/*
- * Copyright (c) 2016 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.cluster.access.commands;
-
-/**
- * Externalizable proxy for use with {@link ReadTransactionSuccess}. It implements the initial (Boron) serialization
- * format.
- */
-@Deprecated(since = "7.0.0", forRemoval = true)
-final class ReadTransactionSuccessProxyV1 extends AbstractTransactionSuccessProxy<ReadTransactionSuccess>
- implements ReadTransactionSuccess.SerialForm {
- @java.io.Serial
- private static final long serialVersionUID = 1L;
-
- // checkstyle flags the public modifier as redundant however it is explicitly needed for Java serialization to
- // be able to create instances via reflection.
- @SuppressWarnings("checkstyle:RedundantModifier")
- public ReadTransactionSuccessProxyV1() {
- // For Externalizable
- }
-
- ReadTransactionSuccessProxyV1(final ReadTransactionSuccess request) {
- super(request);
- }
-}
import static com.google.common.base.Verify.verifyNotNull;
import static java.util.Objects.requireNonNull;
+import java.io.ObjectInput;
+import org.opendaylight.controller.cluster.access.concepts.TransactionIdentifier;
+
/**
* Externalizable proxy for use with {@link SkipTransactionsResponse}. It implements the Chlorine SR2 serialization
* format.
*/
-final class STS implements SkipTransactionsResponse.SerialForm {
+final class STS implements TransactionSuccess.SerialForm<SkipTransactionsResponse> {
@java.io.Serial
private static final long serialVersionUID = 1L;
this.message = requireNonNull(message);
}
+ @Override
+ public SkipTransactionsResponse readExternal(final ObjectInput in, final TransactionIdentifier target,
+ final long sequence) {
+ return new SkipTransactionsResponse(target, sequence);
+ }
+
@Override
public Object readResolve() {
return message();
@Override
protected SerialForm externalizableProxy(final ABIVersion version) {
- return ABIVersion.MAGNESIUM.lt(version) ? new STR(this) : new SkipTransactionsRequestV1(this);
+ return new STR(this);
}
@Override
+++ /dev/null
-/*
- * Copyright (c) 2021 PANTHEON.tech, s.r.o. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.cluster.access.commands;
-
-/**
- * Externalizable proxy for use with {@link SkipTransactionsRequest}. It implements the initial
- * (Phosphorus SR1) serialization format.
- */
-@Deprecated(since = "7.0.0", forRemoval = true)
-final class SkipTransactionsRequestV1 extends AbstractTransactionRequestProxy<SkipTransactionsRequest>
- implements SkipTransactionsRequest.SerialForm {
- @java.io.Serial
- private static final long serialVersionUID = -7493419007644462643L;
-
- // checkstyle flags the public modifier as redundant however it is explicitly needed for Java serialization to
- // be able to create instances via reflection.
- @SuppressWarnings("checkstyle:RedundantModifier")
- public SkipTransactionsRequestV1() {
- // For Externalizable
- }
-
- SkipTransactionsRequestV1(final SkipTransactionsRequest request) {
- super(request);
- }
-}
*/
package org.opendaylight.controller.cluster.access.commands;
-import java.io.ObjectInput;
import org.opendaylight.controller.cluster.access.ABIVersion;
import org.opendaylight.controller.cluster.access.concepts.TransactionIdentifier;
*/
// FIXME: rename to SkipTransactionsSuccess
public final class SkipTransactionsResponse extends TransactionSuccess<SkipTransactionsResponse> {
- interface SerialForm extends TransactionSuccess.SerialForm<SkipTransactionsResponse> {
- @Override
- default SkipTransactionsResponse readExternal(final ObjectInput in, final TransactionIdentifier target,
- final long sequence) {
- return new SkipTransactionsResponse(target, sequence);
- }
- }
-
@java.io.Serial
private static final long serialVersionUID = 1L;
}
@Override
- protected SerialForm externalizableProxy(final ABIVersion version) {
- return ABIVersion.MAGNESIUM.lt(version) ? new STS(this) : new SkipTransactionsResponseProxyV1(this);
+ protected STS externalizableProxy(final ABIVersion version) {
+ return new STS(this);
}
@Override
+++ /dev/null
-/*
- * Copyright (c) 2021 PANTHEON.tech, s.r.o. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.cluster.access.commands;
-
-/**
- * Externalizable proxy for use with {@link SkipTransactionsResponse}. It implements the initial (Phosphorus SR1)
- * serialization format.
- */
-@Deprecated(since = "7.0.0", forRemoval = true)
-final class SkipTransactionsResponseProxyV1 extends AbstractTransactionSuccessProxy<SkipTransactionsResponse>
- implements SkipTransactionsResponse.SerialForm {
- @java.io.Serial
- private static final long serialVersionUID = 1L;
-
- // checkstyle flags the public modifier as redundant however it is explicitly needed for Java serialization to
- // be able to create instances via reflection.
- @SuppressWarnings("checkstyle:RedundantModifier")
- public SkipTransactionsResponseProxyV1() {
- // For Externalizable
- }
-
- SkipTransactionsResponseProxyV1(final SkipTransactionsResponse success) {
- super(success);
- }
-}
import static com.google.common.base.Verify.verifyNotNull;
import static java.util.Objects.requireNonNull;
+import java.io.ObjectInput;
+import org.opendaylight.controller.cluster.access.concepts.TransactionIdentifier;
+
/**
* Externalizable proxy for use with {@link TransactionAbortSuccess}. It implements the Chlorine SR2 serialization
* format.
*/
-final class TAS implements TransactionAbortSuccess.SerialForm {
+final class TAS implements TransactionSuccess.SerialForm<TransactionAbortSuccess> {
@java.io.Serial
private static final long serialVersionUID = 1L;
this.message = requireNonNull(message);
}
+ @Override
+ public TransactionAbortSuccess readExternal(final ObjectInput in, final TransactionIdentifier target,
+ final long sequence) {
+ return new TransactionAbortSuccess(target, sequence);
+ }
+
@Override
public Object readResolve() {
return message();
import static com.google.common.base.Verify.verifyNotNull;
import static java.util.Objects.requireNonNull;
+import java.io.ObjectInput;
+import org.opendaylight.controller.cluster.access.concepts.TransactionIdentifier;
+
/**
* Externalizable proxy for use with {@link TransactionCanCommitSuccess}. It implements the Chlorine SR2 serialization
* format.
*/
-final class TCCS implements TransactionCanCommitSuccess.SerialForm {
+final class TCCS implements TransactionSuccess.SerialForm<TransactionCanCommitSuccess> {
@java.io.Serial
private static final long serialVersionUID = 1L;
this.message = requireNonNull(message);
}
+ @Override
+ public TransactionCanCommitSuccess readExternal(final ObjectInput in, final TransactionIdentifier target,
+ final long sequence) {
+ return new TransactionCanCommitSuccess(target, sequence);
+ }
+
@Override
public Object readResolve() {
return message();
import static com.google.common.base.Verify.verifyNotNull;
import static java.util.Objects.requireNonNull;
+import java.io.ObjectInput;
+import org.opendaylight.controller.cluster.access.concepts.TransactionIdentifier;
+
/**
* Externalizable proxy for use with {@link TransactionCommitSuccess}. It implements the Chlorine SR2 serialization
* format.
*/
-final class TCS implements TransactionCommitSuccess.SerialForm {
+final class TCS implements TransactionSuccess.SerialForm<TransactionCommitSuccess> {
@java.io.Serial
private static final long serialVersionUID = 1L;
this.message = requireNonNull(message);
}
+ @Override
+ public TransactionCommitSuccess readExternal(final ObjectInput in, final TransactionIdentifier target,
+ final long sequence) {
+ return new TransactionCommitSuccess(target, sequence);
+ }
+
@Override
public Object readResolve() {
return message();
import static com.google.common.base.Verify.verifyNotNull;
import static java.util.Objects.requireNonNull;
+import java.io.IOException;
+import java.io.ObjectInput;
+import org.opendaylight.controller.cluster.access.concepts.TransactionIdentifier;
+
/**
* Externalizable proxy for use with {@link TransactionPreCommitSuccess}. It implements the Chlorine SR2 serialization
* format.
*/
-final class TPCS implements TransactionPreCommitSuccess.SerialForm {
+final class TPCS implements TransactionSuccess.SerialForm<TransactionPreCommitSuccess> {
@java.io.Serial
private static final long serialVersionUID = 1L;
this.message = requireNonNull(message);
}
+ @Override
+ public TransactionPreCommitSuccess readExternal(final ObjectInput in, final TransactionIdentifier target,
+ final long sequence) throws IOException {
+ return new TransactionPreCommitSuccess(target, sequence);
+ }
+
@Override
public Object readResolve() {
return message();
import static com.google.common.base.Verify.verifyNotNull;
import static java.util.Objects.requireNonNull;
+import java.io.ObjectInput;
+import org.opendaylight.controller.cluster.access.concepts.TransactionIdentifier;
+
/**
* Externalizable proxy for use with {@link TransactionPurgeResponse}. It implements the Chlorine SR2 serialization
* format.
*/
-final class TPS implements TransactionPurgeResponse.SerialForm {
+final class TPS implements TransactionSuccess.SerialForm<TransactionPurgeResponse> {
@java.io.Serial
private static final long serialVersionUID = 1L;
this.message = requireNonNull(message);
}
+ @Override
+ public TransactionPurgeResponse readExternal(final ObjectInput in, final TransactionIdentifier target,
+ final long sequence) {
+ return new TransactionPurgeResponse(target, sequence);
+ }
+
@Override
public Object readResolve() {
return message();
@Override
protected SerialForm externalizableProxy(final ABIVersion version) {
- return ABIVersion.MAGNESIUM.lt(version) ? new TAR(this) : new TransactionAbortRequestProxyV1(this);
+ return new TAR(this);
}
@Override
+++ /dev/null
-/*
- * Copyright (c) 2016 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.cluster.access.commands;
-
-/**
- * Externalizable proxy for use with {@link TransactionAbortRequest}. It implements the initial (Boron) serialization
- * format.
- */
-@Deprecated(since = "7.0.0", forRemoval = true)
-final class TransactionAbortRequestProxyV1 extends AbstractTransactionRequestProxy<TransactionAbortRequest>
- implements TransactionAbortRequest.SerialForm {
- @java.io.Serial
- private static final long serialVersionUID = 1L;
-
- // checkstyle flags the public modifier as redundant however it is explicitly needed for Java serialization to
- // be able to create instances via reflection.
- @SuppressWarnings("checkstyle:RedundantModifier")
- public TransactionAbortRequestProxyV1() {
- // For Externalizable
- }
-
- TransactionAbortRequestProxyV1(final TransactionAbortRequest request) {
- super(request);
- }
-}
*/
package org.opendaylight.controller.cluster.access.commands;
-import java.io.ObjectInput;
import org.opendaylight.controller.cluster.access.ABIVersion;
import org.opendaylight.controller.cluster.access.concepts.TransactionIdentifier;
* @author Robert Varga
*/
public final class TransactionAbortSuccess extends TransactionSuccess<TransactionAbortSuccess> {
- interface SerialForm extends TransactionSuccess.SerialForm<TransactionAbortSuccess> {
- @Override
- default TransactionAbortSuccess readExternal(final ObjectInput in, final TransactionIdentifier target,
- final long sequence) {
- return new TransactionAbortSuccess(target, sequence);
- }
- }
-
@java.io.Serial
private static final long serialVersionUID = 1L;
}
@Override
- protected SerialForm externalizableProxy(final ABIVersion version) {
- return ABIVersion.MAGNESIUM.lt(version) ? new TAS(this) : new TransactionAbortSuccessProxyV1(this);
+ protected TAS externalizableProxy(final ABIVersion version) {
+ return new TAS(this);
}
@Override
+++ /dev/null
-/*
- * Copyright (c) 2016 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.cluster.access.commands;
-
-/**
- * Externalizable proxy for use with {@link TransactionAbortSuccess}. It implements the initial (Boron)
- * serialization format.
- *
- * @author Robert Varga
- */
-@Deprecated(since = "7.0.0", forRemoval = true)
-final class TransactionAbortSuccessProxyV1 extends AbstractTransactionSuccessProxy<TransactionAbortSuccess>
- implements TransactionAbortSuccess.SerialForm {
- @java.io.Serial
- private static final long serialVersionUID = 1L;
-
- // checkstyle flags the public modifier as redundant however it is explicitly needed for Java serialization to
- // be able to create instances via reflection.
- @SuppressWarnings("checkstyle:RedundantModifier")
- public TransactionAbortSuccessProxyV1() {
- // For Externalizable
- }
-
- TransactionAbortSuccessProxyV1(final TransactionAbortSuccess success) {
- super(success);
- }
-}
*/
package org.opendaylight.controller.cluster.access.commands;
-import java.io.ObjectInput;
import org.opendaylight.controller.cluster.access.ABIVersion;
import org.opendaylight.controller.cluster.access.concepts.TransactionIdentifier;
* @author Robert Varga
*/
public final class TransactionCanCommitSuccess extends TransactionSuccess<TransactionCanCommitSuccess> {
- interface SerialForm extends TransactionSuccess.SerialForm<TransactionCanCommitSuccess> {
- @Override
- default TransactionCanCommitSuccess readExternal(final ObjectInput in, final TransactionIdentifier target,
- final long sequence) {
- return new TransactionCanCommitSuccess(target, sequence);
- }
- }
-
@java.io.Serial
private static final long serialVersionUID = 1L;
}
@Override
- protected SerialForm externalizableProxy(final ABIVersion version) {
- return ABIVersion.MAGNESIUM.lt(version) ? new TCCS(this) : new TransactionCanCommitSuccessProxyV1(this);
+ protected TCCS externalizableProxy(final ABIVersion version) {
+ return new TCCS(this);
}
@Override
+++ /dev/null
-/*
- * Copyright (c) 2016 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.cluster.access.commands;
-
-/**
- * Externalizable proxy for use with {@link TransactionCanCommitSuccess}. It implements the initial (Boron)
- * serialization format.
- */
-@Deprecated(since = "7.0.0", forRemoval = true)
-final class TransactionCanCommitSuccessProxyV1 extends AbstractTransactionSuccessProxy<TransactionCanCommitSuccess>
- implements TransactionCanCommitSuccess.SerialForm {
- @java.io.Serial
- private static final long serialVersionUID = 1L;
-
- // checkstyle flags the public modifier as redundant however it is explicitly needed for Java serialization to
- // be able to create instances via reflection.
- @SuppressWarnings("checkstyle:RedundantModifier")
- public TransactionCanCommitSuccessProxyV1() {
- // For Externalizable
- }
-
- TransactionCanCommitSuccessProxyV1(final TransactionCanCommitSuccess success) {
- super(success);
- }
-}
*/
package org.opendaylight.controller.cluster.access.commands;
-import java.io.ObjectInput;
import org.opendaylight.controller.cluster.access.ABIVersion;
import org.opendaylight.controller.cluster.access.concepts.TransactionIdentifier;
* @author Robert Varga
*/
public final class TransactionCommitSuccess extends TransactionSuccess<TransactionCommitSuccess> {
- interface SerialForm extends TransactionSuccess.SerialForm<TransactionCommitSuccess> {
- @Override
- default TransactionCommitSuccess readExternal(final ObjectInput in, final TransactionIdentifier target,
- final long sequence) {
- return new TransactionCommitSuccess(target, sequence);
- }
- }
-
@java.io.Serial
private static final long serialVersionUID = 1L;
}
@Override
- protected SerialForm externalizableProxy(final ABIVersion version) {
- return ABIVersion.MAGNESIUM.lt(version) ? new TCS(this) : new TransactionCommitSuccessProxyV1(this);
+ protected TCS externalizableProxy(final ABIVersion version) {
+ return new TCS(this);
}
@Override
+++ /dev/null
-/*
- * Copyright (c) 2016 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.cluster.access.commands;
-
-/**
- * Externalizable proxy for use with {@link TransactionCommitSuccess}. It implements the initial (Boron)
- * serialization format.
- */
-@Deprecated(since = "7.0.0", forRemoval = true)
-final class TransactionCommitSuccessProxyV1 extends AbstractTransactionSuccessProxy<TransactionCommitSuccess>
- implements TransactionCommitSuccess.SerialForm {
- @java.io.Serial
- private static final long serialVersionUID = 1L;
-
- // checkstyle flags the public modifier as redundant however it is explicitly needed for Java serialization to
- // be able to create instances via reflection.
- @SuppressWarnings("checkstyle:RedundantModifier")
- public TransactionCommitSuccessProxyV1() {
- // For Externalizable
- }
-
- TransactionCommitSuccessProxyV1(final TransactionCommitSuccess success) {
- super(success);
- }
-}
@Override
protected SerialForm externalizableProxy(final ABIVersion version) {
- return ABIVersion.MAGNESIUM.lt(version) ? new TDCR(this) : new TransactionDoCommitRequestProxyV1(this);
+ return new TDCR(this);
}
@Override
+++ /dev/null
-/*
- * Copyright (c) 2016 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.cluster.access.commands;
-
-/**
- * Externalizable proxy for use with {@link TransactionDoCommitRequest}. It implements the initial (Boron) serialization
- * format.
- */
-@Deprecated(since = "7.0.0", forRemoval = true)
-final class TransactionDoCommitRequestProxyV1 extends AbstractTransactionRequestProxy<TransactionDoCommitRequest>
- implements TransactionDoCommitRequest.SerialForm {
- @java.io.Serial
- private static final long serialVersionUID = 1L;
-
- // checkstyle flags the public modifier as redundant however it is explicitly needed for Java serialization to
- // be able to create instances via reflection.
- @SuppressWarnings("checkstyle:RedundantModifier")
- public TransactionDoCommitRequestProxyV1() {
- // For Externalizable
- }
-
- TransactionDoCommitRequestProxyV1(final TransactionDoCommitRequest request) {
- super(request);
- }
-}
@Override
protected SerialForm externalizableProxy(final ABIVersion version) {
- return ABIVersion.MAGNESIUM.lt(version) ? new TF(this) : new TransactionFailureProxyV1(this);
+ return new TF(this);
}
}
+++ /dev/null
-/*
- * Copyright (c) 2016 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.cluster.access.commands;
-
-import org.opendaylight.controller.cluster.access.concepts.AbstractRequestFailureProxy;
-import org.opendaylight.controller.cluster.access.concepts.TransactionIdentifier;
-
-/**
- * Externalizable proxy for use with {@link TransactionFailure}. It implements the initial (Boron) serialization
- * format.
- */
-@Deprecated(since = "7.0.0", forRemoval = true)
-final class TransactionFailureProxyV1 extends AbstractRequestFailureProxy<TransactionIdentifier, TransactionFailure>
- implements TransactionFailure.SerialForm {
- @java.io.Serial
- private static final long serialVersionUID = 1L;
-
- // checkstyle flags the public modifier as redundant however it is explicitly needed for Java serialization to
- // be able to create instances via reflection.
- @SuppressWarnings("checkstyle:RedundantModifier")
- public TransactionFailureProxyV1() {
- // For Externalizable
- }
-
- TransactionFailureProxyV1(final TransactionFailure failure) {
- super(failure);
- }
-}
@Override
protected SerialForm externalizableProxy(final ABIVersion version) {
- return ABIVersion.MAGNESIUM.lt(version) ? new TPCR(this) : new TransactionPreCommitRequestProxyV1(this);
+ return new TPCR(this);
}
@Override
+++ /dev/null
-/*
- * Copyright (c) 2016 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.cluster.access.commands;
-
-/**
- * Externalizable proxy for use with {@link TransactionPreCommitRequest}. It implements the initial (Boron)
- * serialization format.
- */
-@Deprecated(since = "7.0.0", forRemoval = true)
-final class TransactionPreCommitRequestProxyV1 extends AbstractTransactionRequestProxy<TransactionPreCommitRequest>
- implements TransactionPreCommitRequest.SerialForm {
- @java.io.Serial
- private static final long serialVersionUID = 1L;
-
- // checkstyle flags the public modifier as redundant however it is explicitly needed for Java serialization to
- // be able to create instances via reflection.
- @SuppressWarnings("checkstyle:RedundantModifier")
- public TransactionPreCommitRequestProxyV1() {
- // For Externalizable
- }
-
- TransactionPreCommitRequestProxyV1(final TransactionPreCommitRequest request) {
- super(request);
- }
-}
*/
package org.opendaylight.controller.cluster.access.commands;
-import java.io.IOException;
-import java.io.ObjectInput;
import org.opendaylight.controller.cluster.access.ABIVersion;
import org.opendaylight.controller.cluster.access.concepts.TransactionIdentifier;
* @author Robert Varga
*/
public final class TransactionPreCommitSuccess extends TransactionSuccess<TransactionPreCommitSuccess> {
- interface SerialForm extends TransactionSuccess.SerialForm<TransactionPreCommitSuccess> {
- @Override
- default TransactionPreCommitSuccess readExternal(final ObjectInput in, final TransactionIdentifier target,
- final long sequence) throws IOException {
- return new TransactionPreCommitSuccess(target, sequence);
- }
- }
-
@java.io.Serial
private static final long serialVersionUID = 1L;
}
@Override
- protected SerialForm externalizableProxy(final ABIVersion version) {
- return ABIVersion.MAGNESIUM.lt(version) ? new TPCS(this) : new TransactionPreCommitSuccessProxyV1(this);
+ protected TPCS externalizableProxy(final ABIVersion version) {
+ return new TPCS(this);
}
@Override
+++ /dev/null
-/*
- * Copyright (c) 2016 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.cluster.access.commands;
-
-/**
- * Externalizable proxy for use with {@link TransactionPreCommitSuccess}. It implements the initial (Boron)
- * serialization format.
- */
-@Deprecated(since = "7.0.0", forRemoval = true)
-final class TransactionPreCommitSuccessProxyV1 extends AbstractTransactionSuccessProxy<TransactionPreCommitSuccess>
- implements TransactionPreCommitSuccess.SerialForm {
- @java.io.Serial
- private static final long serialVersionUID = 1L;
-
- // checkstyle flags the public modifier as redundant however it is explicitly needed for Java serialization to
- // be able to create instances via reflection.
- @SuppressWarnings("checkstyle:RedundantModifier")
- public TransactionPreCommitSuccessProxyV1() {
- // For Externalizable
- }
-
- TransactionPreCommitSuccessProxyV1(final TransactionPreCommitSuccess success) {
- super(success);
- }
-}
@Override
protected SerialForm externalizableProxy(final ABIVersion version) {
- return ABIVersion.MAGNESIUM.lt(version) ? new TPR(this) : new TransactionPurgeRequestProxyV1(this);
+ return new TPR(this);
}
@Override
+++ /dev/null
-/*
- * Copyright (c) 2017 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.cluster.access.commands;
-
-/**
- * Externalizable proxy for use with {@link TransactionPurgeRequest}. It implements the initial (Boron)
- * serialization format.
- */
-@Deprecated(since = "7.0.0", forRemoval = true)
-final class TransactionPurgeRequestProxyV1 extends AbstractTransactionRequestProxy<TransactionPurgeRequest>
- implements TransactionPurgeRequest.SerialForm {
- @java.io.Serial
- private static final long serialVersionUID = 1L;
-
- // checkstyle flags the public modifier as redundant however it is explicitly needed for Java serialization to
- // be able to create instances via reflection.
- @SuppressWarnings("checkstyle:RedundantModifier")
- public TransactionPurgeRequestProxyV1() {
- // For Externalizable
- }
-
- TransactionPurgeRequestProxyV1(final TransactionPurgeRequest request) {
- super(request);
- }
-}
*/
package org.opendaylight.controller.cluster.access.commands;
-import java.io.ObjectInput;
import org.opendaylight.controller.cluster.access.ABIVersion;
import org.opendaylight.controller.cluster.access.concepts.TransactionIdentifier;
*/
// FIXME: rename to TransactionPurgeSuccess
public final class TransactionPurgeResponse extends TransactionSuccess<TransactionPurgeResponse> {
- interface SerialForm extends TransactionSuccess.SerialForm<TransactionPurgeResponse> {
- @Override
- default TransactionPurgeResponse readExternal(final ObjectInput in, final TransactionIdentifier target,
- final long sequence) {
- return new TransactionPurgeResponse(target, sequence);
- }
- }
-
@java.io.Serial
private static final long serialVersionUID = 1L;
}
@Override
- protected SerialForm externalizableProxy(final ABIVersion version) {
- return ABIVersion.MAGNESIUM.lt(version) ? new TPS(this) : new TransactionPurgeResponseProxyV1(this);
+ protected TPS externalizableProxy(final ABIVersion version) {
+ return new TPS(this);
}
@Override
+++ /dev/null
-/*
- * Copyright (c) 2017 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.cluster.access.commands;
-
-/**
- * Externalizable proxy for use with {@link TransactionPurgeResponse}. It implements the initial (Boron)
- * serialization format.
- */
-@Deprecated(since = "7.0.0", forRemoval = true)
-final class TransactionPurgeResponseProxyV1 extends AbstractTransactionSuccessProxy<TransactionPurgeResponse>
- implements TransactionPurgeResponse.SerialForm {
- @java.io.Serial
- private static final long serialVersionUID = 1L;
-
- // checkstyle flags the public modifier as redundant however it is explicitly needed for Java serialization to
- // be able to create instances via reflection.
- @SuppressWarnings("checkstyle:RedundantModifier")
- public TransactionPurgeResponseProxyV1() {
- // For Externalizable
- }
-
- TransactionPurgeResponseProxyV1(final TransactionPurgeResponse success) {
- super(success);
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2016 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.cluster.access.concepts;
-
-import static com.google.common.base.Verify.verifyNotNull;
-import static java.util.Objects.requireNonNull;
-
-@Deprecated(since = "7.0.0", forRemoval = true)
-abstract class AbstractEnvelopeProxy<T extends Message<?, ?>, E extends Envelope<T>>
- implements Envelope.SerialForm<T, E> {
- @java.io.Serial
- private static final long serialVersionUID = 1L;
-
- private E envelope;
-
- AbstractEnvelopeProxy() {
- // for Externalizable
- }
-
- AbstractEnvelopeProxy(final E envelope) {
- this.envelope = requireNonNull(envelope);
- }
-
- @Override
- public final E envelope() {
- return verifyNotNull(envelope);
- }
-
- @Override
- public final void setEnvelope(final E envelope) {
- this.envelope = requireNonNull(envelope);
- }
-
- @Override
- public final Object readResolve() {
- return envelope();
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2016 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.cluster.access.concepts;
-
-import static com.google.common.base.Verify.verifyNotNull;
-import static java.util.Objects.requireNonNull;
-
-import org.eclipse.jdt.annotation.NonNull;
-import org.opendaylight.yangtools.concepts.WritableIdentifier;
-
-/**
- * Abstract Externalizable proxy for use with {@link Message} subclasses.
- *
- * @param <T> Target identifier type
- * @param <C> Message class
- */
-@Deprecated(since = "7.0.0", forRemoval = true)
-abstract class AbstractMessageProxy<T extends WritableIdentifier, C extends Message<T, C>>
- implements Message.SerialForm<T, C> {
- @java.io.Serial
- private static final long serialVersionUID = 1L;
-
- private C message;
-
- protected AbstractMessageProxy() {
- // For Externalizable
- }
-
- AbstractMessageProxy(final @NonNull C message) {
- this.message = requireNonNull(message);
- }
-
- @Override
- public final C message() {
- return verifyNotNull(message);
- }
-
- @Override
- public final void setMessage(final C message) {
- this.message = requireNonNull(message);
- }
-
- @Override
- public final Object readResolve() {
- return message();
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2016 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.cluster.access.concepts;
-
-import org.eclipse.jdt.annotation.NonNull;
-import org.opendaylight.yangtools.concepts.WritableIdentifier;
-
-/**
- * Abstract Externalizable proxy for use with {@link RequestFailure} subclasses.
- *
- * @param <T> Target identifier type
- */
-@Deprecated(since = "7.0.0", forRemoval = true)
-public abstract class AbstractRequestFailureProxy<T extends WritableIdentifier, C extends RequestFailure<T, C>>
- extends AbstractResponseProxy<T, C> implements RequestFailure.SerialForm<T, C> {
- @java.io.Serial
- private static final long serialVersionUID = 1L;
-
- protected AbstractRequestFailureProxy() {
- // For Externalizable
- }
-
- protected AbstractRequestFailureProxy(final @NonNull C failure) {
- super(failure);
- }
-}
\ No newline at end of file
+++ /dev/null
-/*
- * Copyright (c) 2016 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.cluster.access.concepts;
-
-import org.eclipse.jdt.annotation.NonNull;
-import org.opendaylight.yangtools.concepts.WritableIdentifier;
-
-/**
- * Abstract Externalizable proxy for use with {@link Request} subclasses.
- *
- * @param <T> Target identifier type
- */
-@Deprecated(since = "7.0.0", forRemoval = true)
-public abstract class AbstractRequestProxy<T extends WritableIdentifier, C extends Request<T, C>>
- extends AbstractMessageProxy<T, C> implements Request.SerialForm<T, C> {
- @java.io.Serial
- private static final long serialVersionUID = 1L;
-
- protected AbstractRequestProxy() {
- // For Externalizable
- }
-
- protected AbstractRequestProxy(final @NonNull C request) {
- super(request);
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2016 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.cluster.access.concepts;
-
-@Deprecated(since = "7.0.0", forRemoval = true)
-abstract class AbstractResponseEnvelopeProxy<T extends Response<?, ?>, E extends ResponseEnvelope<T>>
- extends AbstractEnvelopeProxy<T, E> {
- @java.io.Serial
- private static final long serialVersionUID = 1L;
-
- AbstractResponseEnvelopeProxy() {
- // for Externalizable
- }
-
- AbstractResponseEnvelopeProxy(final E envelope) {
- super(envelope);
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2016 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.cluster.access.concepts;
-
-import org.eclipse.jdt.annotation.NonNull;
-import org.opendaylight.yangtools.concepts.WritableIdentifier;
-
-/**
- * Abstract Externalizable proxy class to use with {@link Response} subclasses.
- *
- * @author Robert Varga
- *
- * @param <T> Target identifier type
- * @param <C> Message class
- */
-@Deprecated(since = "7.0.0", forRemoval = true)
-abstract class AbstractResponseProxy<T extends WritableIdentifier, C extends Response<T, C>>
- extends AbstractMessageProxy<T, C> {
- @java.io.Serial
- private static final long serialVersionUID = 1L;
-
- protected AbstractResponseProxy() {
- // for Externalizable
- }
-
- AbstractResponseProxy(final @NonNull C response) {
- super(response);
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2016 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.cluster.access.concepts;
-
-import org.eclipse.jdt.annotation.NonNull;
-import org.opendaylight.yangtools.concepts.WritableIdentifier;
-
-/**
- * Abstract Externalizable proxy for use with {@link RequestSuccess} subclasses.
- *
- * @param <T> Target identifier type
- */
-@Deprecated(since = "7.0.0", forRemoval = true)
-public abstract class AbstractSuccessProxy<T extends WritableIdentifier, C extends RequestSuccess<T, C>>
- extends AbstractResponseProxy<T, C> {
- @java.io.Serial
- private static final long serialVersionUID = 1L;
-
- protected AbstractSuccessProxy() {
- // For Externalizable
- }
-
- protected AbstractSuccessProxy(final @NonNull C success) {
- super(success);
- }
-}
import static com.google.common.base.Verify.verifyNotNull;
import static java.util.Objects.requireNonNull;
+import java.io.Externalizable;
+import java.io.IOException;
+import java.io.ObjectInput;
+import java.io.ObjectOutput;
+import org.opendaylight.yangtools.concepts.WritableObjects;
+
/**
* Serialization proxy for {@link ClientIdentifier}.
*/
-final class CI implements ClientIdentifier.SerialForm {
+final class CI implements Externalizable {
@java.io.Serial
private static final long serialVersionUID = 1L;
}
@Override
- public ClientIdentifier identifier() {
- return verifyNotNull(identifier);
+ public void readExternal(final ObjectInput in) throws IOException {
+ identifier = new ClientIdentifier(FrontendIdentifier.readFrom(in), WritableObjects.readLong(in));
}
@Override
- public void setIdentifier(final ClientIdentifier identifier) {
- this.identifier = requireNonNull(identifier);
+ public void writeExternal(final ObjectOutput out) throws IOException {
+ identifier.getFrontendId().writeTo(out);
+ WritableObjects.writeLong(out, identifier.getGeneration());
}
- @Override
- public Object readResolve() {
- return identifier();
+ @java.io.Serial
+ private Object readResolve() {
+ return verifyNotNull(identifier);
}
}
*/
package org.opendaylight.controller.cluster.access.concepts;
-import static com.google.common.base.Verify.verifyNotNull;
import static java.util.Objects.requireNonNull;
import com.google.common.base.MoreObjects;
import java.io.DataInput;
import java.io.DataOutput;
-import java.io.Externalizable;
import java.io.IOException;
-import java.io.ObjectInput;
-import java.io.ObjectOutput;
import org.eclipse.jdt.annotation.NonNull;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.cds.types.rev191024.ClientGeneration;
import org.opendaylight.yangtools.concepts.WritableIdentifier;
* of a particular frontend.
*/
public final class ClientIdentifier implements WritableIdentifier {
- interface SerialForm extends Externalizable {
- @NonNull ClientIdentifier identifier();
-
- void setIdentifier(@NonNull ClientIdentifier identifier);
-
- @java.io.Serial
- Object readResolve();
-
- @Override
- default void readExternal(final ObjectInput in) throws IOException {
- setIdentifier(new ClientIdentifier(FrontendIdentifier.readFrom(in), WritableObjects.readLong(in)));
- }
-
- @Override
- default void writeExternal(final ObjectOutput out) throws IOException {
- final var id = identifier();
- id.getFrontendId().writeTo(out);
- WritableObjects.writeLong(out, id.getGeneration());
- }
- }
-
- @Deprecated(since = "7.0.0", forRemoval = true)
- private static final class Proxy implements SerialForm {
- @java.io.Serial
- private static final long serialVersionUID = 1L;
-
- private ClientIdentifier identifier;
-
- // checkstyle flags the public modifier as redundant however it is explicitly needed for Java serialization to
- // be able to create instances via reflection.
- @SuppressWarnings("checkstyle:RedundantModifier")
- public Proxy() {
- // Needed for Externalizable
- }
-
- Proxy(final ClientIdentifier identifier) {
- this.identifier = requireNonNull(identifier);
- }
-
- @Override
- public ClientIdentifier identifier() {
- return verifyNotNull(identifier);
- }
-
- @Override
- public void setIdentifier(final ClientIdentifier identifier) {
- this.identifier = requireNonNull(identifier);
- }
-
- @Override
- public Object readResolve() {
- return identifier();
- }
- }
-
@java.io.Serial
private static final long serialVersionUID = 1L;
import java.io.ObjectOutput;
import java.io.Serializable;
import org.eclipse.jdt.annotation.NonNull;
-import org.opendaylight.controller.cluster.access.ABIVersion;
import org.opendaylight.yangtools.concepts.Immutable;
import org.opendaylight.yangtools.concepts.WritableObjects;
@java.io.Serial
final Object writeReplace() {
- return ABIVersion.MAGNESIUM.lt(message.getVersion()) ? createProxy() : legacyProxy();
+ return createProxy();
}
abstract @NonNull SerialForm<T, ?> createProxy();
-
- @Deprecated(since = "7.0.0", forRemoval = true)
- abstract @NonNull AbstractEnvelopeProxy<T, ?> legacyProxy();
}
import static com.google.common.base.Verify.verifyNotNull;
import static java.util.Objects.requireNonNull;
+import java.io.ObjectInput;
+
/**
* Serialization proxy for {@link FailureEnvelope}.
*/
-final class FE implements FailureEnvelope.SerialForm {
+final class FE implements ResponseEnvelope.SerialForm<RequestFailure<?, ?>, FailureEnvelope> {
@java.io.Serial
private static final long serialVersionUID = 1L;
this.envelope = requireNonNull(envelope);
}
+ @Override
+ public FailureEnvelope readExternal(final ObjectInput in, final long sessionId, final long txSequence,
+ final RequestFailure<?, ?> message, final long executionTimeNanos) {
+ return new FailureEnvelope(message, sessionId, txSequence, executionTimeNanos);
+ }
+
@Override
public Object readResolve() {
return envelope();
import static com.google.common.base.Verify.verifyNotNull;
import static java.util.Objects.requireNonNull;
+import java.io.Externalizable;
+import java.io.IOException;
+import java.io.ObjectInput;
+import java.io.ObjectOutput;
+
/**
* Serialization proxy for {@link FrontendIdentifier}.
*/
-final class FI implements FrontendIdentifier.SerialForm {
+final class FI implements Externalizable {
@java.io.Serial
private static final long serialVersionUID = 1L;
}
@Override
- public FrontendIdentifier identifier() {
- return verifyNotNull(identifier);
+ public void readExternal(final ObjectInput in) throws IOException {
+ identifier = new FrontendIdentifier(MemberName.readFrom(in), FrontendType.readFrom(in));
}
@Override
- public void setIdentifier(final FrontendIdentifier identifier) {
- this.identifier = requireNonNull(identifier);
+ public void writeExternal(final ObjectOutput out) throws IOException {
+ identifier.getMemberName().writeTo(out);
+ identifier.getClientType().writeTo(out);
}
- @Override
- public Object readResolve() {
- return identifier();
+ @java.io.Serial
+ private Object readResolve() {
+ return verifyNotNull(identifier);
}
}
*/
package org.opendaylight.controller.cluster.access.concepts;
-import static com.google.common.base.Verify.verifyNotNull;
import static java.util.Objects.requireNonNull;
+import java.io.Externalizable;
+import java.io.IOException;
+import java.io.ObjectInput;
+import java.io.ObjectOutput;
+import java.nio.charset.StandardCharsets;
+
/**
* Serialization proxy for {@link FrontendType}.
*/
-final class FT implements FrontendType.SerialForm {
+final class FT implements Externalizable {
@java.io.Serial
private static final long serialVersionUID = 1L;
- private FrontendType type;
+ private byte[] serialized;
@SuppressWarnings("checkstyle:RedundantModifier")
public FT() {
// for Externalizable
}
- FT(final FrontendType type) {
- this.type = requireNonNull(type);
+ FT(final byte[] serialized) {
+ this.serialized = requireNonNull(serialized);
}
@Override
- public FrontendType type() {
- return verifyNotNull(type);
+ public void writeExternal(final ObjectOutput out) throws IOException {
+ out.writeInt(serialized.length);
+ out.write(serialized);
}
@Override
- public void setType(final FrontendType type) {
- this.type = requireNonNull(type);
+ public void readExternal(final ObjectInput in) throws IOException {
+ serialized = new byte[in.readInt()];
+ in.readFully(serialized);
}
- @Override
- public Object readResolve() {
- return type();
+ @java.io.Serial
+ private Object readResolve() {
+ // TODO: consider caching instances here
+ return new FrontendType(new String(serialized, StandardCharsets.UTF_8), serialized);
}
}
*/
package org.opendaylight.controller.cluster.access.concepts;
-import java.io.ObjectInput;
-
public final class FailureEnvelope extends ResponseEnvelope<RequestFailure<?, ?>> {
- interface SerialForm extends ResponseEnvelope.SerialForm<RequestFailure<?, ?>, FailureEnvelope> {
- @Override
- default FailureEnvelope readExternal(final ObjectInput in, final long sessionId, final long txSequence,
- final RequestFailure<?, ?> message, final long executionTimeNanos) {
- return new FailureEnvelope(message, sessionId, txSequence, executionTimeNanos);
- }
- }
-
@java.io.Serial
private static final long serialVersionUID = 1L;
FE createProxy() {
return new FE(this);
}
-
- @Override
- FailureEnvelopeProxy legacyProxy() {
- return new FailureEnvelopeProxy(this);
- }
}
+++ /dev/null
-/*
- * Copyright (c) 2016 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.cluster.access.concepts;
-
-@Deprecated(since = "7.0.0", forRemoval = true)
-final class FailureEnvelopeProxy extends AbstractResponseEnvelopeProxy<RequestFailure<?, ?>, FailureEnvelope>
- implements FailureEnvelope.SerialForm {
- @java.io.Serial
- private static final long serialVersionUID = 1L;
-
- // checkstyle flags the public modifier as redundant however it is explicitly needed for Java serialization to be
- // able to create instances via reflection.
- @SuppressWarnings("checkstyle:RedundantModifier")
- public FailureEnvelopeProxy() {
- // for Externalizable
- }
-
- FailureEnvelopeProxy(final FailureEnvelope envelope) {
- super(envelope);
- }
-}
*/
package org.opendaylight.controller.cluster.access.concepts;
-import static com.google.common.base.Verify.verifyNotNull;
import static java.util.Objects.requireNonNull;
import java.io.DataInput;
import java.io.DataOutput;
-import java.io.Externalizable;
import java.io.IOException;
-import java.io.ObjectInput;
-import java.io.ObjectOutput;
import java.util.Objects;
import org.eclipse.jdt.annotation.NonNull;
import org.opendaylight.yangtools.concepts.WritableIdentifier;
* A cluster-wide unique identifier of a frontend type located at a cluster member.
*/
public final class FrontendIdentifier implements WritableIdentifier {
- interface SerialForm extends Externalizable {
- @NonNull FrontendIdentifier identifier();
-
- void setIdentifier(@NonNull FrontendIdentifier identifier);
-
- @java.io.Serial
- Object readResolve();
-
- @Override
- default void writeExternal(final ObjectOutput out) throws IOException {
- final var id = identifier();
- id.memberName.writeTo(out);
- id.clientType.writeTo(out);
- }
-
- @Override
- default void readExternal(final ObjectInput in) throws IOException {
- setIdentifier(new FrontendIdentifier(MemberName.readFrom(in), FrontendType.readFrom(in)));
- }
- }
-
- @Deprecated(since = "7.0.0", forRemoval = true)
- private static final class Proxy implements SerialForm {
- @java.io.Serial
- private static final long serialVersionUID = 1L;
-
- private FrontendIdentifier identifier;
-
- // checkstyle flags the public modifier as redundant however it is explicitly needed for Java serialization to
- // be able to create instances via reflection.
- @SuppressWarnings("checkstyle:RedundantModifier")
- public Proxy() {
- // Needed for Externalizable
- }
-
- Proxy(final FrontendIdentifier identifier) {
- this.identifier = requireNonNull(identifier);
- }
-
- @Override
- public FrontendIdentifier identifier() {
- return verifyNotNull(identifier);
- }
-
- @Override
- public void setIdentifier(final FrontendIdentifier identifier) {
- this.identifier = requireNonNull(identifier);
- }
-
- @Override
- public Object readResolve() {
- return identifier();
- }
- }
-
@java.io.Serial
private static final long serialVersionUID = 1L;
}
public static @NonNull FrontendIdentifier readFrom(final DataInput in) throws IOException {
- final MemberName memberName = MemberName.readFrom(in);
- final FrontendType clientType = FrontendType.readFrom(in);
+ final var memberName = MemberName.readFrom(in);
+ final var clientType = FrontendType.readFrom(in);
return new FrontendIdentifier(memberName, clientType);
}
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import java.io.DataInput;
import java.io.DataOutput;
-import java.io.Externalizable;
import java.io.IOException;
-import java.io.ObjectInput;
-import java.io.ObjectOutput;
import java.nio.charset.StandardCharsets;
import java.util.regex.Pattern;
import org.eclipse.jdt.annotation.NonNull;
* discerned.
*/
public final class FrontendType implements Comparable<FrontendType>, WritableIdentifier {
- interface SerialForm extends Externalizable {
- @NonNull FrontendType type();
-
- void setType(@NonNull FrontendType type);
-
- @java.io.Serial
- Object readResolve();
-
- @Override
- default void writeExternal(final ObjectOutput out) throws IOException {
- final var serialized = type().getSerialized();
- out.writeInt(serialized.length);
- out.write(serialized);
- }
-
- @Override
- default void readExternal(final ObjectInput in) throws IOException {
- final var serialized = new byte[in.readInt()];
- in.readFully(serialized);
- // TODO: consider caching instances here
- setType(new FrontendType(new String(serialized, StandardCharsets.UTF_8), serialized));
- }
- }
-
- @Deprecated(since = "7.0.0", forRemoval = true)
- private static final class Proxy implements SerialForm {
- @java.io.Serial
- private static final long serialVersionUID = 1L;
-
- private FrontendType type;
-
- // checkstyle flags the public modifier as redundant however it is explicitly needed for Java serialization to
- // be able to create instances via reflection.
- @SuppressWarnings("checkstyle:RedundantModifier")
- public Proxy() {
- // For Externalizable
- }
-
- Proxy(final FrontendType type) {
- this.type = requireNonNull(type);
- }
-
- @Override
- public FrontendType type() {
- return verifyNotNull(type);
- }
-
- @Override
- public void setType(final FrontendType type) {
- this.type = requireNonNull(type);
- }
-
- @Override
- public Object readResolve() {
- return type();
- }
- }
-
@java.io.Serial
private static final long serialVersionUID = 1L;
private static final String SIMPLE_STRING_REGEX = "^[a-zA-Z0-9-_.*+:=,!~';]+$";
@java.io.Serial
private Object writeReplace() {
- return new FT(this);
+ return new FT(getSerialized());
}
}
import static com.google.common.base.Verify.verifyNotNull;
import static java.util.Objects.requireNonNull;
+import java.io.Externalizable;
+import java.io.IOException;
+import java.io.ObjectInput;
+import java.io.ObjectOutput;
+import org.opendaylight.yangtools.concepts.WritableObjects;
+
/**
* Serialization proxy for {@link LocalHistoryIdentifier}.
+ *
+ * @implNote
+ * cookie is currently required only for module-based sharding, which is implemented as part of normal
+ * DataBroker interfaces. For DOMDataTreeProducer cookie will always be zero, hence we may end up not needing
+ * cookie at all.
+ * We use WritableObjects.writeLongs() to output historyId and cookie (in that order). If we end up not needing
+ * the cookie at all, we can switch to writeLong() and use zero flags for compatibility.
*/
-final class HI implements LocalHistoryIdentifier.SerialForm {
+final class HI implements Externalizable {
@java.io.Serial
private static final long serialVersionUID = 1L;
}
@Override
- public LocalHistoryIdentifier identifier() {
- return verifyNotNull(identifier);
+ public void writeExternal(final ObjectOutput out) throws IOException {
+ identifier.getClientId().writeTo(out);
+ WritableObjects.writeLongs(out, identifier.getHistoryId(), identifier.getCookie());
}
@Override
- public void setIdentifier(final LocalHistoryIdentifier identifier) {
- this.identifier = requireNonNull(identifier);
+ public void readExternal(final ObjectInput in) throws IOException {
+ final var clientId = ClientIdentifier.readFrom(in);
+ final byte header = WritableObjects.readLongHeader(in);
+ final var historyId = WritableObjects.readFirstLong(in, header);
+ final var cookie = WritableObjects.readSecondLong(in, header);
+ identifier = new LocalHistoryIdentifier(clientId, historyId, cookie);
}
- @Override
- public Object readResolve() {
- return identifier();
+ @java.io.Serial
+ private Object readResolve() {
+ return verifyNotNull(identifier);
}
}
*/
package org.opendaylight.controller.cluster.access.concepts;
-import static com.google.common.base.Verify.verifyNotNull;
import static java.util.Objects.requireNonNull;
import com.google.common.base.MoreObjects;
import java.io.DataInput;
import java.io.DataOutput;
-import java.io.Externalizable;
import java.io.IOException;
-import java.io.ObjectInput;
-import java.io.ObjectOutput;
import org.eclipse.jdt.annotation.NonNull;
import org.opendaylight.yangtools.concepts.WritableIdentifier;
import org.opendaylight.yangtools.concepts.WritableObjects;
* - an unsigned long cookie, assigned by the client and meaningless on the backend, which just reflects it back
*/
public final class LocalHistoryIdentifier implements WritableIdentifier {
- /**
- * Serialized form of {@link LocalHistoryIdentifier}.
- *
- * @implNote
- * cookie is currently required only for module-based sharding, which is implemented as part of normal
- * DataBroker interfaces. For DOMDataTreeProducer cookie will always be zero, hence we may end up not needing
- * cookie at all.
- * We use WritableObjects.writeLongs() to output historyId and cookie (in that order). If we end up not needing
- * the cookie at all, we can switch to writeLong() and use zero flags for compatibility.
- */
- interface SerialForm extends Externalizable {
- @NonNull LocalHistoryIdentifier identifier();
-
- void setIdentifier(@NonNull LocalHistoryIdentifier identifier);
-
- @java.io.Serial
- Object readResolve();
-
- @Override
- default void writeExternal(final ObjectOutput out) throws IOException {
- final var id = identifier();
- id.getClientId().writeTo(out);
- WritableObjects.writeLongs(out, id.getHistoryId(), id.getCookie());
- }
-
- @Override
- default void readExternal(final ObjectInput in) throws IOException {
- final var clientId = ClientIdentifier.readFrom(in);
-
- final byte header = WritableObjects.readLongHeader(in);
- final var historyId = WritableObjects.readFirstLong(in, header);
- final var cookie = WritableObjects.readSecondLong(in, header);
- setIdentifier(new LocalHistoryIdentifier(clientId, historyId, cookie));
- }
- }
-
- @Deprecated(since = "7.0.0", forRemoval = true)
- private static final class Proxy implements SerialForm {
- @java.io.Serial
- private static final long serialVersionUID = 1L;
-
- private LocalHistoryIdentifier identifier;
-
- // checkstyle flags the public modifier as redundant however it is explicitly needed for Java serialization to
- // be able to create instances via reflection.
- @SuppressWarnings("checkstyle:RedundantModifier")
- public Proxy() {
- // For Externalizable
- }
-
- Proxy(final LocalHistoryIdentifier identifier) {
- this.identifier = requireNonNull(identifier);
- }
-
- @Override
- public LocalHistoryIdentifier identifier() {
- return verifyNotNull(identifier);
- }
-
- @Override
- public void setIdentifier(final LocalHistoryIdentifier identifier) {
- this.identifier = requireNonNull(identifier);
- }
-
- @Override
- public Object readResolve() {
- return identifier();
- }
- }
-
@java.io.Serial
private static final long serialVersionUID = 1L;
*/
package org.opendaylight.controller.cluster.access.concepts;
-import static com.google.common.base.Verify.verifyNotNull;
import static java.util.Objects.requireNonNull;
+import java.io.Externalizable;
+import java.io.IOException;
+import java.io.ObjectInput;
+import java.io.ObjectOutput;
+import java.nio.charset.StandardCharsets;
+
/**
* Serialization proxy for {@link MemberName}.
*/
-final class MN implements MemberName.SerialForm {
+final class MN implements Externalizable {
@java.io.Serial
private static final long serialVersionUID = 1L;
- private MemberName name;
+ private byte[] serialized;
@SuppressWarnings("checkstyle:RedundantModifier")
public MN() {
// for Externalizable
}
- MN(final MemberName name) {
- this.name = requireNonNull(name);
+ MN(final byte[] serialized) {
+ this.serialized = requireNonNull(serialized);
}
@Override
- public MemberName name() {
- return verifyNotNull(name);
+ public void writeExternal(final ObjectOutput out) throws IOException {
+ out.writeInt(serialized.length);
+ out.write(serialized);
}
@Override
- public void setName(final MemberName name) {
- this.name = requireNonNull(name);
+ public void readExternal(final ObjectInput in) throws IOException {
+ serialized = new byte[in.readInt()];
+ in.readFully(serialized);
}
- @Override
- public Object readResolve() {
- return name();
+ @java.io.Serial
+ private Object readResolve() {
+ // TODO: consider caching instances here
+ return new MemberName(new String(serialized, StandardCharsets.UTF_8), serialized);
}
}
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import java.io.DataInput;
import java.io.DataOutput;
-import java.io.Externalizable;
import java.io.IOException;
-import java.io.ObjectInput;
-import java.io.ObjectOutput;
import java.nio.charset.StandardCharsets;
import org.eclipse.jdt.annotation.NonNull;
import org.opendaylight.yangtools.concepts.WritableIdentifier;
* Type-safe encapsulation of a cluster member name.
*/
public final class MemberName implements Comparable<MemberName>, WritableIdentifier {
- interface SerialForm extends Externalizable {
- @NonNull MemberName name();
-
- void setName(@NonNull MemberName name);
-
- @java.io.Serial
- Object readResolve();
-
- @Override
- default void writeExternal(final ObjectOutput out) throws IOException {
- final var serialized = name().getSerialized();
- out.writeInt(serialized.length);
- out.write(serialized);
- }
-
- @Override
- default void readExternal(final ObjectInput in) throws IOException {
- final var serialized = new byte[in.readInt()];
- in.readFully(serialized);
- // TODO: consider caching instances here
- setName(new MemberName(new String(serialized, StandardCharsets.UTF_8), serialized));
- }
- }
-
- @Deprecated(since = "7.0.0", forRemoval = true)
- private static final class Proxy implements SerialForm {
- @java.io.Serial
- private static final long serialVersionUID = 1L;
-
- private MemberName name;
-
- // checkstyle flags the public modifier as redundant however it is explicitly needed for Java serialization to
- // be able to create instances via reflection.
- @SuppressWarnings("checkstyle:RedundantModifier")
- public Proxy() {
- // For Externalizable
- }
-
- Proxy(final MemberName name) {
- this.name = requireNonNull(name);
- }
-
- @Override
- public MemberName name() {
- return verifyNotNull(name);
- }
-
- @Override
- public void setName(final MemberName name) {
- this.name = requireNonNull(name);
- }
-
- @Override
- public Object readResolve() {
- return name();
- }
- }
-
@java.io.Serial
private static final long serialVersionUID = 1L;
@java.io.Serial
Object writeReplace() {
- return new MN(this);
+ return new MN(getSerialized());
}
}
import java.io.DataInput;
import java.io.Externalizable;
import java.io.IOException;
+import java.io.NotSerializableException;
import java.io.ObjectInput;
+import java.io.ObjectInputStream;
import java.io.ObjectOutput;
+import java.io.ObjectOutputStream;
+import java.io.ObjectStreamException;
import java.io.Serializable;
import org.eclipse.jdt.annotation.NonNull;
import org.opendaylight.controller.cluster.access.ABIVersion;
*/
@SuppressWarnings("unchecked")
public final @NonNull C toVersion(final @NonNull ABIVersion toVersion) {
- if (this.version == toVersion) {
+ if (version == toVersion) {
return (C)this;
}
return switch (toVersion) {
- case MAGNESIUM, CHLORINE_SR2 -> verifyNotNull(cloneAsVersion(toVersion));
+ case POTASSIUM -> verifyNotNull(cloneAsVersion(toVersion));
default -> throw new IllegalArgumentException("Unhandled ABI version " + toVersion);
};
}
protected final Object writeReplace() {
return externalizableProxy(version);
}
+
+ protected final void throwNSE() throws NotSerializableException {
+ throw new NotSerializableException(getClass().getName());
+ }
+
+ @java.io.Serial
+ private void readObject(final ObjectInputStream stream) throws IOException, ClassNotFoundException {
+ throwNSE();
+ }
+
+ @java.io.Serial
+ private void readObjectNoData() throws ObjectStreamException {
+ throwNSE();
+ }
+
+ @java.io.Serial
+ private void writeObject(final ObjectOutputStream stream) throws IOException {
+ throwNSE();
+ }
}
import static com.google.common.base.Verify.verifyNotNull;
import static java.util.Objects.requireNonNull;
+import java.io.ObjectInput;
+
/**
* Serialization proxy for {@link RequestEnvelope}.
*/
-final class RE implements RequestEnvelope.SerialForm {
+final class RE implements Envelope.SerialForm<Request<?, ?>, RequestEnvelope> {
@java.io.Serial
private static final long serialVersionUID = 1L;
this.envelope = requireNonNull(envelope);
}
+ @Override
+ public RequestEnvelope readExternal(final ObjectInput in, final long sessionId, final long txSequence,
+ final Request<?, ?> message) {
+ return new RequestEnvelope(message, sessionId, txSequence);
+ }
+
@Override
public Object readResolve() {
return envelope();
package org.opendaylight.controller.cluster.access.concepts;
import akka.actor.ActorRef;
-import java.io.ObjectInput;
public final class RequestEnvelope extends Envelope<Request<?, ?>> {
- interface SerialForm extends Envelope.SerialForm<Request<?, ?>, RequestEnvelope> {
- @Override
- default RequestEnvelope readExternal(final ObjectInput in, final long sessionId, final long txSequence,
- final Request<?, ?> message) {
- return new RequestEnvelope(message, sessionId, txSequence);
- }
- }
-
@java.io.Serial
private static final long serialVersionUID = 1L;
return new RE(this);
}
- @Override
- RequestEnvelopeProxy legacyProxy() {
- return new RequestEnvelopeProxy(this);
- }
-
/**
* Respond to this envelope with a {@link RequestFailure} caused by specified {@link RequestException}.
*
+++ /dev/null
-/*
- * Copyright (c) 2016 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.cluster.access.concepts;
-
-@Deprecated(since = "7.0.0", forRemoval = true)
-final class RequestEnvelopeProxy extends AbstractEnvelopeProxy<Request<?, ?>, RequestEnvelope>
- implements RequestEnvelope.SerialForm {
- @java.io.Serial
- private static final long serialVersionUID = 1L;
-
- // checkstyle flags the public modifier as redundant however it is explicitly needed for Java serialization to
- // be able to create instances via reflection.
- @SuppressWarnings("checkstyle:RedundantModifier")
- public RequestEnvelopeProxy() {
- // for Externalizable
- }
-
- RequestEnvelopeProxy(final RequestEnvelope envelope) {
- super(envelope);
- }
-}
/**
* Serialization proxy for {@link SuccessEnvelope}.
*/
-final class SE implements SuccessEnvelope.SerialForm {
+final class SE implements ResponseEnvelope.SerialForm<RequestSuccess<?, ?>, SuccessEnvelope> {
@java.io.Serial
private static final long serialVersionUID = 1L;
*/
package org.opendaylight.controller.cluster.access.concepts;
-import java.io.ObjectInput;
-
public final class SuccessEnvelope extends ResponseEnvelope<RequestSuccess<?, ?>> {
- interface SerialForm extends ResponseEnvelope.SerialForm<RequestSuccess<?, ?>, SuccessEnvelope> {
- @Override
- default SuccessEnvelope readExternal(final ObjectInput in, final long sessionId, final long txSequence,
- final RequestSuccess<?, ?> message, final long executionTimeNanos) {
- return new SuccessEnvelope(message, sessionId, txSequence, executionTimeNanos);
- }
- }
-
@java.io.Serial
private static final long serialVersionUID = 1L;
SE createProxy() {
return new SE(this);
}
-
- @Override
- SuccessEnvelopeProxy legacyProxy() {
- return new SuccessEnvelopeProxy(this);
- }
-
}
+++ /dev/null
-/*
- * Copyright (c) 2016 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.cluster.access.concepts;
-
-@Deprecated(since = "7.0.0", forRemoval = true)
-final class SuccessEnvelopeProxy extends AbstractResponseEnvelopeProxy<RequestSuccess<?, ?>, SuccessEnvelope>
- implements SuccessEnvelope.SerialForm {
- @java.io.Serial
- private static final long serialVersionUID = 1L;
-
- // checkstyle flags the public modifier as redundant however it is explicitly needed for Java serialization to
- // be able to create instances via reflection.
- @SuppressWarnings("checkstyle:RedundantModifier")
- public SuccessEnvelopeProxy() {
- // for Externalizable
- }
-
- SuccessEnvelopeProxy(final SuccessEnvelope envelope) {
- super(envelope);
- }
-}
import static com.google.common.base.Verify.verifyNotNull;
import static java.util.Objects.requireNonNull;
+import java.io.Externalizable;
+import java.io.IOException;
+import java.io.ObjectInput;
+import java.io.ObjectOutput;
+import org.opendaylight.yangtools.concepts.WritableObjects;
+
/**
* Serialization proxy for {@link TransactionIdentifier}.
*/
-final class TI implements TransactionIdentifier.SerialForm {
+final class TI implements Externalizable {
@java.io.Serial
private static final long serialVersionUID = 1L;
}
@Override
- public TransactionIdentifier identifier() {
- return verifyNotNull(identifier);
+ public void readExternal(final ObjectInput in) throws IOException {
+ identifier = new TransactionIdentifier(LocalHistoryIdentifier.readFrom(in), WritableObjects.readLong(in));
}
@Override
- public void setIdentifier(final TransactionIdentifier identifier) {
- this.identifier = requireNonNull(identifier);
+ public void writeExternal(final ObjectOutput out) throws IOException {
+ identifier.getHistoryId().writeTo(out);
+ WritableObjects.writeLong(out, identifier.getTransactionId());
}
- @Override
- public Object readResolve() {
- return identifier();
+ @java.io.Serial
+ private Object readResolve() {
+ return verifyNotNull(identifier);
}
}
*/
package org.opendaylight.controller.cluster.access.concepts;
-import static com.google.common.base.Verify.verifyNotNull;
import static java.util.Objects.requireNonNull;
import java.io.DataInput;
import java.io.DataOutput;
-import java.io.Externalizable;
import java.io.IOException;
-import java.io.ObjectInput;
-import java.io.ObjectOutput;
import org.eclipse.jdt.annotation.NonNull;
import org.opendaylight.yangtools.concepts.WritableIdentifier;
import org.opendaylight.yangtools.concepts.WritableObjects;
* Globally-unique identifier of a transaction.
*/
public final class TransactionIdentifier implements WritableIdentifier {
- interface SerialForm extends Externalizable {
- @NonNull TransactionIdentifier identifier();
-
- void setIdentifier(@NonNull TransactionIdentifier identifier);
-
- @java.io.Serial
- Object readResolve();
-
- @Override
- default void readExternal(final ObjectInput in) throws IOException {
- setIdentifier(new TransactionIdentifier(LocalHistoryIdentifier.readFrom(in), WritableObjects.readLong(in)));
- }
-
- @Override
- default void writeExternal(final ObjectOutput out) throws IOException {
- final var id = identifier();
- id.getHistoryId().writeTo(out);
- WritableObjects.writeLong(out, id.getTransactionId());
- }
- }
-
- @Deprecated(since = "7.0.0", forRemoval = true)
- private static final class Proxy implements SerialForm {
- @java.io.Serial
- private static final long serialVersionUID = 1L;
-
- private TransactionIdentifier identifier;
-
- // checkstyle flags the public modifier as redundant however it is explicitly needed for Java serialization to
- // be able to create instances via reflection.
- @SuppressWarnings("checkstyle:RedundantModifier")
- public Proxy() {
- // For Externalizable
- }
-
- Proxy(final TransactionIdentifier identifier) {
- this.identifier = requireNonNull(identifier);
- }
-
- @Override
- public @NonNull TransactionIdentifier identifier() {
- return verifyNotNull(identifier);
- }
-
- @Override
- public void setIdentifier(final TransactionIdentifier identifier) {
- this.identifier = requireNonNull(identifier);
- }
-
- @Override
- public Object readResolve() {
- return identifier();
- }
- }
-
@java.io.Serial
private static final long serialVersionUID = 1L;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThrows;
import static org.junit.Assert.assertTrue;
-import static org.opendaylight.controller.cluster.access.ABIVersion.MAGNESIUM;
+import static org.opendaylight.controller.cluster.access.ABIVersion.POTASSIUM;
import static org.opendaylight.controller.cluster.access.ABIVersion.TEST_FUTURE_VERSION;
import static org.opendaylight.controller.cluster.access.ABIVersion.TEST_PAST_VERSION;
@Test
public void testInvalidVersions() {
assertTrue(TEST_PAST_VERSION.compareTo(TEST_FUTURE_VERSION) < 0);
- assertTrue(TEST_PAST_VERSION.compareTo(MAGNESIUM) < 0);
- assertTrue(TEST_FUTURE_VERSION.compareTo(MAGNESIUM) > 0);
+ assertTrue(TEST_PAST_VERSION.compareTo(POTASSIUM) < 0);
+ assertTrue(TEST_FUTURE_VERSION.compareTo(POTASSIUM) > 0);
}
@Test
public void testMagnesiumVersion() throws Exception {
- assertEquals((short)8, MAGNESIUM.shortValue());
- assertEquals(MAGNESIUM, ABIVersion.valueOf(MAGNESIUM.shortValue()));
- assertEquals(MAGNESIUM, ABIVersion.readFrom(ByteStreams.newDataInput(writeVersion(MAGNESIUM))));
+ assertEquals((short)10, POTASSIUM.shortValue());
+ assertEquals(POTASSIUM, ABIVersion.valueOf(POTASSIUM.shortValue()));
+ assertEquals(POTASSIUM, ABIVersion.readFrom(ByteStreams.newDataInput(writeVersion(POTASSIUM))));
}
@Test
private static final AbortLocalTransactionRequest OBJECT = new AbortLocalTransactionRequest(TRANSACTION, ACTOR_REF);
public AbortLocalTransactionRequestTest() {
- super(OBJECT, 0, 0);
+ super(OBJECT);
}
@Override
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertThrows;
-import org.apache.commons.lang.SerializationUtils;
+import org.apache.commons.lang3.SerializationUtils;
import org.junit.Test;
import org.opendaylight.controller.cluster.access.ABIVersion;
public abstract class AbstractLocalTransactionRequestTest<T extends AbstractLocalTransactionRequest<T>>
extends AbstractTransactionRequestTest<T> {
- protected AbstractLocalTransactionRequestTest(final T object, final int baseSize, final int legacySize) {
- super(object, baseSize, legacySize);
+ protected AbstractLocalTransactionRequestTest(final T object) {
+ super(object, -1);
}
@Test
public void cloneAsVersionTest() {
- assertSame(object(), object().cloneAsVersion(ABIVersion.MAGNESIUM));
+ assertSame(object(), object().cloneAsVersion(ABIVersion.TEST_FUTURE_VERSION));
}
@Override
public abstract class AbstractReadTransactionRequestTest<T extends AbstractReadPathTransactionRequest<T>>
extends AbstractTransactionRequestTest<T> {
- protected static final YangInstanceIdentifier PATH = YangInstanceIdentifier.empty();
+ protected static final YangInstanceIdentifier PATH = YangInstanceIdentifier.of();
protected static final boolean SNAPSHOT_ONLY = true;
- protected AbstractReadTransactionRequestTest(final T object, final int baseSize, final int legacySize) {
- super(object, baseSize, legacySize);
+ protected AbstractReadTransactionRequestTest(final T object, final int baseSize) {
+ super(object, baseSize);
}
@Test
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
-import org.apache.commons.lang.SerializationUtils;
+import org.apache.commons.lang3.SerializationUtils;
import org.junit.Test;
-import org.opendaylight.controller.cluster.access.ABIVersion;
import org.opendaylight.controller.cluster.access.concepts.ClientIdentifier;
import org.opendaylight.controller.cluster.access.concepts.FrontendIdentifier;
import org.opendaylight.controller.cluster.access.concepts.FrontendType;
private final T object;
private final int expectedSize;
- private final int legacySize;
- protected AbstractRequestFailureTest(final T object, final int baseSize, final int legacySize) {
+ protected AbstractRequestFailureTest(final T object, final int baseSize) {
this.object = requireNonNull(object);
this.expectedSize = baseSize + CAUSE_SIZE;
- this.legacySize = legacySize + CAUSE_SIZE;
}
@Test
public void serializationTest() {
final var bytes = SerializationUtils.serialize(object);
assertEquals(expectedSize, bytes.length);
- assertEquals(legacySize, SerializationUtils.serialize(object.toVersion(ABIVersion.MAGNESIUM)).length);
@SuppressWarnings("unchecked")
final var deserialize = (T) SerializationUtils.deserialize(bytes);
import static java.util.Objects.requireNonNull;
import static org.junit.Assert.assertEquals;
-import org.apache.commons.lang.SerializationUtils;
+import org.apache.commons.lang3.SerializationUtils;
import org.eclipse.jdt.annotation.NonNull;
import org.junit.Test;
-import org.opendaylight.controller.cluster.access.ABIVersion;
import org.opendaylight.controller.cluster.access.concepts.ClientIdentifier;
import org.opendaylight.controller.cluster.access.concepts.FrontendIdentifier;
import org.opendaylight.controller.cluster.access.concepts.FrontendType;
private final @NonNull T object;
private final int expectedSize;
- private final int legacySize;
- protected AbstractRequestSuccessTest(final T object, final int expectedSize, final int legacySize) {
+ protected AbstractRequestSuccessTest(final T object, final int expectedSize) {
this.object = requireNonNull(object);
this.expectedSize = expectedSize;
- this.legacySize = legacySize;
}
@Test
public void serializationTest() {
final var bytes = SerializationUtils.serialize(object);
assertEquals(expectedSize, bytes.length);
- assertEquals(legacySize, SerializationUtils.serialize(object.toVersion(ABIVersion.MAGNESIUM)).length);
@SuppressWarnings("unchecked")
final var deserialize = (T) SerializationUtils.deserialize(bytes);
protected static final TransactionIdentifier TRANSACTION_IDENTIFIER = new TransactionIdentifier(
HISTORY_IDENTIFIER, 0);
- protected AbstractTransactionRequestTest(final T object, final int baseSize, final int legacySize) {
- super(object, baseSize, legacySize);
+ protected AbstractTransactionRequestTest(final T object, final int baseSize) {
+ super(object, baseSize);
}
@Test
protected static final TransactionIdentifier TRANSACTION_IDENTIFIER = new TransactionIdentifier(HISTORY_IDENTIFIER,
0);
- protected AbstractTransactionSuccessTest(final T object, final int expectedSize, final int legacySize) {
- super(object, expectedSize, legacySize);
+ protected AbstractTransactionSuccessTest(final T object, final int expectedSize) {
+ super(object, expectedSize);
}
}
ACTOR_REF, MODIFICATION, null, COORDINATED);
public CommitLocalTransactionRequestTest() {
- super(OBJECT, 0, 0);
+ super(OBJECT);
}
@Test
private static final ConnectClientFailure OBJECT = new ConnectClientFailure(CLIENT_IDENTIFIER, 0, CAUSE);
public ConnectClientFailureTest() {
- super(OBJECT, 99, 392);
+ super(OBJECT, 99);
}
@Test
CLIENT_IDENTIFIER, 0, ACTOR_REF, MIN_VERSION, MAX_VERSION);
public ConnectClientRequestTest() {
- super(OBJECT, 112, 310);
+ super(OBJECT, 112);
}
@Test
@Test
public void cloneAsVersionTest() {
- final var clone = OBJECT.cloneAsVersion(ABIVersion.MAGNESIUM);
+ final var clone = OBJECT.cloneAsVersion(ABIVersion.TEST_FUTURE_VERSION);
assertNotNull(clone);
- assertEquals(ABIVersion.MAGNESIUM, clone.getVersion());
+ assertEquals(ABIVersion.TEST_FUTURE_VERSION, clone.getVersion());
}
@Test
DataTreeConfiguration.DEFAULT_OPERATIONAL);
private static final ActorSystem SYSTEM = ActorSystem.create("test");
private static final ActorRef ACTOR_REF = TestProbe.apply(SYSTEM).ref();
- private static final int ACTOR_REF_SIZE = ACTOR_REF.path().toSerializationFormat().length();
private static final ActorSelection ACTOR_SELECTION = ActorSelection.apply(ACTOR_REF, "foo");
private static final List<ActorSelection> ALTERNATES = ImmutableList.of(ACTOR_SELECTION);
private static final int MAX_MESSAGES = 10;
ALTERNATES, TREE, MAX_MESSAGES);
public ConnectClientSuccessTest() {
- super(OBJECT, 146 + ACTOR_REF_SIZE, 432 + ACTOR_REF_SIZE);
+ super(OBJECT, 146 + ACTOR_REF.path().toSerializationFormat().length());
}
@Before
@Test
public void testGetDataTree() {
- final ReadOnlyDataTree tree = OBJECT.getDataTree().get();
+ final ReadOnlyDataTree tree = OBJECT.getDataTree().orElseThrow();
assertEquals(TREE, tree);
}
@Test
public void cloneAsVersionTest() {
- final var clone = OBJECT.cloneAsVersion(ABIVersion.MAGNESIUM);
+ final var clone = OBJECT.cloneAsVersion(ABIVersion.TEST_FUTURE_VERSION);
assertEquals(OBJECT.getSequence(), clone.getSequence());
assertEquals(OBJECT.getTarget(), clone.getTarget());
assertEquals(OBJECT.getAlternates(), clone.getAlternates());
ACTOR_REF, PATH, SNAPSHOT_ONLY);
public ExistsTransactionRequestTest() {
- super(OBJECT, 108, 620);
+ super(OBJECT, 108);
}
@Test
EXISTS);
public ExistsTransactionSuccessTest() {
- super(OBJECT, 99, 487);
+ super(OBJECT, 99);
}
@Test
@Test
public void cloneAsVersionTest() {
- final var clone = OBJECT.cloneAsVersion(ABIVersion.MAGNESIUM);
+ final var clone = OBJECT.cloneAsVersion(ABIVersion.TEST_FUTURE_VERSION);
assertEquals(OBJECT.getSequence(), clone.getSequence());
assertEquals(OBJECT.getTarget(), clone.getTarget());
assertEquals(OBJECT.getExists(), clone.getExists());
private static final LocalHistoryFailure OBJECT = new LocalHistoryFailure(HISTORY_IDENTIFIER, 0, CAUSE);
public LocalHistoryFailureTest() {
- super(OBJECT, 99, 392);
+ super(OBJECT, 99);
}
@Test
public void cloneAsVersionTest() {
- final var clone = OBJECT.cloneAsVersion(ABIVersion.MAGNESIUM);
+ final var clone = OBJECT.cloneAsVersion(ABIVersion.TEST_FUTURE_VERSION);
assertEquals(OBJECT.getSequence(), clone.getSequence());
assertEquals(OBJECT.getTarget(), clone.getTarget());
assertEquals(OBJECT.getCause(), clone.getCause());
private static final LocalHistorySuccess OBJECT = new LocalHistorySuccess(HISTORY_IDENTIFIER, 0);
public LocalHistorySuccessTest() {
- super(OBJECT, 96, 382);
+ super(OBJECT, 96);
}
@Test
public void cloneAsVersionTest() {
- final var clone = OBJECT.cloneAsVersion(ABIVersion.MAGNESIUM);
- assertEquals(ABIVersion.MAGNESIUM, clone.getVersion());
+ final var clone = OBJECT.cloneAsVersion(ABIVersion.TEST_FUTURE_VERSION);
+ assertEquals(ABIVersion.TEST_FUTURE_VERSION, clone.getVersion());
assertEquals(OBJECT.getSequence(), clone.getSequence());
assertEquals(OBJECT.getTarget(), clone.getTarget());
}
import org.opendaylight.controller.cluster.access.concepts.TransactionIdentifier;
import org.opendaylight.yangtools.yang.common.QName;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
-import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
+import org.opendaylight.yangtools.yang.data.spi.node.ImmutableNodes;
public class ModifyTransactionRequestBuilderTest {
-
private final MemberName memberName = MemberName.forName("member-1");
private final FrontendType frontendType = FrontendType.forName("test");
private final FrontendIdentifier frontendId = FrontendIdentifier.create(memberName, frontendType);
private final TransactionIdentifier transactionIdentifier =
new TransactionIdentifier(new LocalHistoryIdentifier(clientId, 0L), 0L);
private final ActorRef actorRef = ActorSystem.create("test").actorOf(Props.create(TestActors.EchoActor.class));
- private final NormalizedNode node = Builders.containerBuilder().withNodeIdentifier(
- YangInstanceIdentifier.NodeIdentifier.create(QName.create("namespace", "localName"))).build();
+ private final NormalizedNode node = ImmutableNodes.newContainerBuilder()
+ .withNodeIdentifier(new NodeIdentifier(QName.create("namespace", "localName")))
+ .build();
private final TransactionModification transactionModification =
- new TransactionWrite(YangInstanceIdentifier.empty(), node);
+ new TransactionWrite(YangInstanceIdentifier.of(), node);
private final ModifyTransactionRequestBuilder modifyTransactionRequestBuilder =
new ModifyTransactionRequestBuilder(transactionIdentifier, actorRef);
@Test
public void testGetIdentifier() {
- final TransactionIdentifier identifier = modifyTransactionRequestBuilder.getIdentifier();
+ final var identifier = modifyTransactionRequestBuilder.getIdentifier();
assertEquals(transactionIdentifier, identifier);
}
@Test
public void testBuildReady() {
modifyTransactionRequestBuilder.setReady();
- final ModifyTransactionRequest modifyTransactionRequest = modifyTransactionRequestBuilder.build();
- assertEquals(PersistenceProtocol.READY, modifyTransactionRequest.getPersistenceProtocol().get());
+ final var modifyTransactionRequest = modifyTransactionRequestBuilder.build();
+ assertEquals(PersistenceProtocol.READY, modifyTransactionRequest.getPersistenceProtocol().orElseThrow());
assertEquals(transactionModification, modifyTransactionRequest.getModifications().get(0));
}
@Test
public void testBuildAbort() {
modifyTransactionRequestBuilder.setAbort();
- final ModifyTransactionRequest modifyTransactionRequest = modifyTransactionRequestBuilder.build();
- assertEquals(PersistenceProtocol.ABORT, modifyTransactionRequest.getPersistenceProtocol().get());
+ final var modifyTransactionRequest = modifyTransactionRequestBuilder.build();
+ assertEquals(PersistenceProtocol.ABORT, modifyTransactionRequest.getPersistenceProtocol().orElseThrow());
assertTrue(modifyTransactionRequest.getModifications().isEmpty());
}
@Test
public void testBuildCommitTrue() {
modifyTransactionRequestBuilder.setCommit(true);
- final ModifyTransactionRequest modifyTransactionRequest = modifyTransactionRequestBuilder.build();
- assertEquals(PersistenceProtocol.THREE_PHASE, modifyTransactionRequest.getPersistenceProtocol().get());
+ final var modifyTransactionRequest = modifyTransactionRequestBuilder.build();
+ assertEquals(PersistenceProtocol.THREE_PHASE, modifyTransactionRequest.getPersistenceProtocol().orElseThrow());
}
@Test
public void testBuildCommitFalse() {
modifyTransactionRequestBuilder.setCommit(false);
- final ModifyTransactionRequest modifyTransactionRequest = modifyTransactionRequestBuilder.build();
- assertEquals(PersistenceProtocol.SIMPLE, modifyTransactionRequest.getPersistenceProtocol().get());
+ final var modifyTransactionRequest = modifyTransactionRequestBuilder.build();
+ assertEquals(PersistenceProtocol.SIMPLE, modifyTransactionRequest.getPersistenceProtocol().orElseThrow());
}
-
}
ACTOR_REF, List.of(), PROTOCOL);
public ModifyTransactionRequestEmptyTest() {
- super(OBJECT, 108, 408);
+ super(OBJECT, 108);
}
@Test
@Test
public void cloneAsVersionTest() {
- final var clone = OBJECT.cloneAsVersion(ABIVersion.MAGNESIUM);
+ final var clone = OBJECT.cloneAsVersion(ABIVersion.TEST_FUTURE_VERSION);
assertEquals(OBJECT.getSequence(), clone.getSequence());
assertEquals(OBJECT.getTarget(), clone.getTarget());
assertEquals(OBJECT.getReplyTo(), clone.getReplyTo());
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
-import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
+import org.opendaylight.yangtools.yang.data.spi.node.ImmutableNodes;
public class ModifyTransactionRequestTest extends AbstractTransactionRequestTest<ModifyTransactionRequest> {
- private static final ContainerNode NODE = Builders.containerBuilder().withNodeIdentifier(
- NodeIdentifier.create(QName.create("namespace", "localName"))).build();
+ private static final ContainerNode NODE = ImmutableNodes.newContainerBuilder()
+ .withNodeIdentifier(new NodeIdentifier(QName.create("namespace", "localName")))
+ .build();
private static final List<TransactionModification> MODIFICATIONS = List.of(
- new TransactionWrite(YangInstanceIdentifier.empty(), NODE));
+ new TransactionWrite(YangInstanceIdentifier.of(), NODE));
private static final PersistenceProtocol PROTOCOL = PersistenceProtocol.ABORT;
ACTOR_REF, MODIFICATIONS, PROTOCOL);
public ModifyTransactionRequestTest() {
- super(OBJECT, 140, 440);
+ super(OBJECT, 140);
}
@Test
@Test
public void cloneAsVersionTest() {
- final var clone = OBJECT.cloneAsVersion(ABIVersion.MAGNESIUM);
+ final var clone = OBJECT.cloneAsVersion(ABIVersion.TEST_FUTURE_VERSION);
assertEquals(OBJECT.getSequence(), clone.getSequence());
assertEquals(OBJECT.getTarget(), clone.getTarget());
assertEquals(OBJECT.getReplyTo(), clone.getReplyTo());
assertNotNull(deserialize.getModifications());
assertEquals(1, deserialize.getModifications().size());
final var modification = deserialize.getModifications().get(0);
- assertEquals(YangInstanceIdentifier.empty(), modification.getPath());
+ assertEquals(YangInstanceIdentifier.of(), modification.getPath());
assertEquals(TYPE_WRITE, modification.getType());
}
}
private static final ModifyTransactionSuccess OBJECT = new ModifyTransactionSuccess(TRANSACTION_IDENTIFIER, 0);
public ModifyTransactionSuccessTest() {
- super(OBJECT, 98, 486);
+ super(OBJECT, 98);
}
@Test
public void cloneAsVersionTest() {
- final var clone = OBJECT.cloneAsVersion(ABIVersion.MAGNESIUM);
- assertEquals(ABIVersion.MAGNESIUM, clone.getVersion());
+ final var clone = OBJECT.cloneAsVersion(ABIVersion.TEST_FUTURE_VERSION);
+ assertEquals(ABIVersion.TEST_FUTURE_VERSION, clone.getVersion());
assertEquals(OBJECT.getSequence(), clone.getSequence());
assertEquals(OBJECT.getTarget(), clone.getTarget());
}
ACTOR_REF, PATH, SNAPSHOT_ONLY);
public ReadTransactionRequestTest() {
- super(OBJECT, 108, 618);
+ super(OBJECT, 108);
}
@Test
Optional.empty());
public ReadTransactionSuccessNoDataTest() {
- super(OBJECT, 99, 485);
+ super(OBJECT, 99);
}
@Test
@Test
public void cloneAsVersionTest() {
- final var clone = OBJECT.cloneAsVersion(ABIVersion.MAGNESIUM);
+ final var clone = OBJECT.cloneAsVersion(ABIVersion.TEST_FUTURE_VERSION);
assertEquals(OBJECT.getSequence(), clone.getSequence());
assertEquals(OBJECT.getTarget(), clone.getTarget());
assertEquals(OBJECT.getData(), clone.getData());
import org.opendaylight.yangtools.yang.common.QName;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
-import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
+import org.opendaylight.yangtools.yang.data.spi.node.ImmutableNodes;
public class ReadTransactionSuccessTest extends AbstractTransactionSuccessTest<ReadTransactionSuccess> {
- private static final ContainerNode NODE = Builders.containerBuilder()
- .withNodeIdentifier(NodeIdentifier.create(QName.create("namespace", "localName")))
+ private static final ContainerNode NODE = ImmutableNodes.newContainerBuilder()
+ .withNodeIdentifier(new NodeIdentifier(QName.create("namespace", "localName")))
.build();
private static final ReadTransactionSuccess OBJECT = new ReadTransactionSuccess(TRANSACTION_IDENTIFIER, 0,
Optional.of(NODE));
public ReadTransactionSuccessTest() {
- super(OBJECT, 129, 515);
+ super(OBJECT, 129);
}
@Test
@Test
public void cloneAsVersionTest() {
- final var clone = OBJECT.cloneAsVersion(ABIVersion.MAGNESIUM);
+ final var clone = OBJECT.cloneAsVersion(ABIVersion.TEST_FUTURE_VERSION);
assertEquals(OBJECT.getSequence(), clone.getSequence());
assertEquals(OBJECT.getTarget(), clone.getTarget());
assertEquals(OBJECT.getData(), clone.getData());
ACTOR_REF, List.of(UnsignedLong.ONE));
public SkipTransactionsRequestTest() {
- super(OBJECT, 109, 403);
+ super(OBJECT, 109);
}
@Test
public void cloneAsVersionTest() {
- final var clone = OBJECT.cloneAsVersion(ABIVersion.MAGNESIUM);
+ final var clone = OBJECT.cloneAsVersion(ABIVersion.TEST_FUTURE_VERSION);
assertEquals(OBJECT.getSequence(), clone.getSequence());
assertEquals(OBJECT.getTarget(), clone.getTarget());
assertEquals(OBJECT.getReplyTo(), clone.getReplyTo());
private static final SkipTransactionsResponse OBJECT = new SkipTransactionsResponse(TRANSACTION_IDENTIFIER, 0);
public SkipTransactionsResponseTest() {
- super(OBJECT, 98, 486);
+ super(OBJECT, 98);
}
@Test
public void cloneAsVersionTest() {
- final var clone = OBJECT.cloneAsVersion(ABIVersion.MAGNESIUM);
+ final var clone = OBJECT.cloneAsVersion(ABIVersion.TEST_FUTURE_VERSION);
assertEquals(OBJECT.getSequence(), clone.getSequence());
assertEquals(OBJECT.getTarget(), clone.getTarget());
}
ACTOR_REF);
public TransactionAbortRequestTest() {
- super(OBJECT, 101, 400);
+ super(OBJECT, 101);
}
@Test
public void cloneAsVersionTest() {
- final var clone = OBJECT.cloneAsVersion(ABIVersion.MAGNESIUM);
+ final var clone = OBJECT.cloneAsVersion(ABIVersion.TEST_FUTURE_VERSION);
assertEquals(OBJECT.getSequence(), clone.getSequence());
assertEquals(OBJECT.getTarget(), clone.getTarget());
assertEquals(OBJECT.getReplyTo(), clone.getReplyTo());
private static final TransactionAbortSuccess OBJECT = new TransactionAbortSuccess(TRANSACTION_IDENTIFIER, 0);
public TransactionAbortSuccessTest() {
- super(OBJECT, 98, 485);
+ super(OBJECT, 98);
}
@Test
public void cloneAsVersionTest() {
- final var clone = OBJECT.cloneAsVersion(ABIVersion.MAGNESIUM);
+ final var clone = OBJECT.cloneAsVersion(ABIVersion.TEST_FUTURE_VERSION);
assertEquals(OBJECT.getSequence(), clone.getSequence());
assertEquals(OBJECT.getTarget(), clone.getTarget());
}
0);
public TransactionCanCommitSuccessTest() {
- super(OBJECT, 99, 489);
+ super(OBJECT, 99);
}
@Test
public void cloneAsVersionTest() {
- final var clone = OBJECT.cloneAsVersion(ABIVersion.MAGNESIUM);
+ final var clone = OBJECT.cloneAsVersion(ABIVersion.TEST_FUTURE_VERSION);
assertEquals(OBJECT.getSequence(), clone.getSequence());
assertEquals(OBJECT.getTarget(), clone.getTarget());
}
private static final TransactionCommitSuccess OBJECT = new TransactionCommitSuccess(TRANSACTION_IDENTIFIER, 0);
public TransactionCommitSuccessTest() {
- super(OBJECT, 98, 486);
+ super(OBJECT, 98);
}
@Test
public void cloneAsVersionTest() {
- final var clone = OBJECT.cloneAsVersion(ABIVersion.MAGNESIUM);
+ final var clone = OBJECT.cloneAsVersion(ABIVersion.TEST_FUTURE_VERSION);
assertEquals(OBJECT.getSequence(), clone.getSequence());
assertEquals(OBJECT.getTarget(), clone.getTarget());
}
ACTOR_REF);
public TransactionDoCommitRequestTest() {
- super(OBJECT, 102, 403);
+ super(OBJECT, 102);
}
@Test
public void cloneAsVersionTest() {
- final var clone = OBJECT.cloneAsVersion(ABIVersion.MAGNESIUM);
+ final var clone = OBJECT.cloneAsVersion(ABIVersion.TEST_FUTURE_VERSION);
assertEquals(OBJECT.getSequence(), clone.getSequence());
assertEquals(OBJECT.getTarget(), clone.getTarget());
assertEquals(OBJECT.getReplyTo(), clone.getReplyTo());
private static final TransactionFailure OBJECT = new TransactionFailure(TRANSACTION_IDENTIFIER, 0, CAUSE);
public TransactionFailureTest() {
- super(OBJECT, 100, 392);
+ super(OBJECT, 100);
}
@Test
public void cloneAsVersionTest() {
- final var clone = OBJECT.cloneAsVersion(ABIVersion.MAGNESIUM);
+ final var clone = OBJECT.cloneAsVersion(ABIVersion.TEST_FUTURE_VERSION);
assertEquals(OBJECT.getSequence(), clone.getSequence());
assertEquals(OBJECT.getTarget(), clone.getTarget());
assertEquals(OBJECT.getCause(), clone.getCause());
ACTOR_REF);
public TransactionPreCommitRequestTest() {
- super(OBJECT, 102, 404);
+ super(OBJECT, 102);
}
@Test
public void cloneAsVersionTest() {
- final var clone = OBJECT.cloneAsVersion(ABIVersion.MAGNESIUM);
+ final var clone = OBJECT.cloneAsVersion(ABIVersion.TEST_FUTURE_VERSION);
assertEquals(OBJECT.getSequence(), clone.getSequence());
assertEquals(OBJECT.getTarget(), clone.getTarget());
assertEquals(OBJECT.getReplyTo(), clone.getReplyTo());
0);
public TransactionPreCommitSuccessTest() {
- super(OBJECT, 99, 489);
+ super(OBJECT, 99);
}
@Test
public void cloneAsVersionTest() {
- final var clone = OBJECT.cloneAsVersion(ABIVersion.MAGNESIUM);
+ final var clone = OBJECT.cloneAsVersion(ABIVersion.TEST_FUTURE_VERSION);
assertEquals(OBJECT.getSequence(), clone.getSequence());
assertEquals(OBJECT.getTarget(), clone.getTarget());
}
ACTOR_REF);
public TransactionPurgeRequestTest() {
- super(OBJECT, 101, 400);
+ super(OBJECT, 101);
}
@Test
public void cloneAsVersionTest() {
- final var clone = OBJECT.cloneAsVersion(ABIVersion.MAGNESIUM);
+ final var clone = OBJECT.cloneAsVersion(ABIVersion.TEST_FUTURE_VERSION);
assertEquals(OBJECT.getSequence(), clone.getSequence());
assertEquals(OBJECT.getTarget(), clone.getTarget());
assertEquals(OBJECT.getReplyTo(), clone.getReplyTo());
private static final TransactionPurgeResponse OBJECT = new TransactionPurgeResponse(TRANSACTION_IDENTIFIER, 0);
public TransactionPurgeResponseTest() {
- super(OBJECT, 98, 486);
+ super(OBJECT, 98);
}
@Test
public void cloneAsVersionTest() {
- final var clone = OBJECT.cloneAsVersion(ABIVersion.MAGNESIUM);
+ final var clone = OBJECT.cloneAsVersion(ABIVersion.TEST_FUTURE_VERSION);
assertEquals(OBJECT.getSequence(), clone.getSequence());
assertEquals(OBJECT.getTarget(), clone.getTarget());
}
import static java.util.Objects.requireNonNull;
import static org.junit.jupiter.api.Assertions.assertEquals;
-import org.apache.commons.lang.SerializationUtils;
+import org.apache.commons.lang3.SerializationUtils;
import org.junit.Before;
import org.junit.Test;
import akka.serialization.JavaSerializer;
import akka.testkit.TestProbe;
import com.google.common.base.MoreObjects;
-import org.apache.commons.lang.SerializationUtils;
+import org.apache.commons.lang3.SerializationUtils;
import org.junit.Before;
import org.junit.Test;
-import org.opendaylight.controller.cluster.access.ABIVersion;
public abstract class AbstractRequestTest<T extends Request<?, T>> {
private static final ActorSystem SYSTEM = ActorSystem.create("test");
private final T object;
private final int expectedSize;
- private final int legacySize;
- protected AbstractRequestTest(final T object, final int baseSize, final int legacySize) {
+ protected AbstractRequestTest(final T object, final int baseSize) {
this.object = requireNonNull(object);
this.expectedSize = baseSize + ACTOR_REF_SIZE;
- this.legacySize = legacySize + ACTOR_REF_SIZE;
}
protected final T object() {
@Test
public void serializationTest() {
- assertEquals(legacySize, SerializationUtils.serialize(object.cloneAsVersion(ABIVersion.MAGNESIUM)).length);
-
final byte[] bytes = SerializationUtils.serialize(object);
assertEquals(expectedSize, bytes.length);
@SuppressWarnings("unchecked")
*/
package org.opendaylight.controller.cluster.access.concepts;
+import static com.google.common.base.Verify.verifyNotNull;
+import static java.util.Objects.requireNonNull;
import static org.junit.Assert.assertEquals;
import java.io.DataInput;
import java.io.IOException;
-import org.apache.commons.lang.SerializationUtils;
+import org.apache.commons.lang3.SerializationUtils;
import org.opendaylight.controller.cluster.access.ABIVersion;
import org.opendaylight.yangtools.concepts.WritableIdentifier;
final var cause = new RuntimeRequestException("msg", new RuntimeException());
final int causeSize = SerializationUtils.serialize(cause).length;
return new EnvelopeDetails<>(new FailureEnvelope(new MockFailure(OBJECT, cause, 42), 1L, 2L, 11L),
- causeSize + 485);
+ causeSize + 216);
}
@Override
assertEquals(expectedCause.isRetriable(), actualCause.isRetriable());
}
- private static class MockRequestFailureProxy extends AbstractRequestFailureProxy<WritableIdentifier, MockFailure> {
+ private static class MockRequestFailureProxy implements RequestFailure.SerialForm<WritableIdentifier, MockFailure> {
@java.io.Serial
private static final long serialVersionUID = 5015515628523887221L;
+ private MockFailure message;
+
@SuppressWarnings("checkstyle:RedundantModifier")
public MockRequestFailureProxy() {
//For Externalizable
}
private MockRequestFailureProxy(final MockFailure mockFailure) {
- super(mockFailure);
+ message = requireNonNull(mockFailure);
}
@Override
public WritableIdentifier readTarget(final DataInput in) throws IOException {
return TransactionIdentifier.readFrom(in);
}
+
+ @Override
+ public MockFailure message() {
+ return verifyNotNull(message);
+ }
+
+ @Override
+ public void setMessage(final MockFailure message) {
+ this.message = requireNonNull(message);
+ }
+
+ @Override
+ public Object readResolve() {
+ return message();
+ }
}
private static class MockFailure extends RequestFailure<WritableIdentifier, MockFailure> {
}
@Override
- protected AbstractRequestFailureProxy<WritableIdentifier, MockFailure> externalizableProxy(
+ protected RequestFailure.SerialForm<WritableIdentifier, MockFailure> externalizableProxy(
final ABIVersion version) {
return new MockRequestFailureProxy(this);
}
<parent>
<groupId>org.opendaylight.controller</groupId>
<artifactId>mdsal-parent</artifactId>
- <version>7.0.2-SNAPSHOT</version>
+ <version>9.0.3-SNAPSHOT</version>
<relativePath>../parent</relativePath>
</parent>
<packaging>bundle</packaging>
<dependencies>
+ <dependency>
+ <groupId>com.github.spotbugs</groupId>
+ <artifactId>spotbugs-annotations</artifactId>
+ <optional>true</optional>
+ </dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
</dependency>
+ <dependency>
+ <groupId>org.eclipse.jdt</groupId>
+ <artifactId>org.eclipse.jdt.annotation</artifactId>
+ </dependency>
<dependency>
<groupId>org.opendaylight.controller</groupId>
<artifactId>cds-access-api</artifactId>
<artifactId>concepts</artifactId>
</dependency>
<dependency>
- <groupId>org.opendaylight.yangtools</groupId>
- <artifactId>yang-common</artifactId>
+ <groupId>org.scala-lang</groupId>
+ <artifactId>scala-library</artifactId>
</dependency>
<dependency>
- <groupId>org.opendaylight.yangtools</groupId>
- <artifactId>yang-data-api</artifactId>
+ <groupId>org.checkerframework</groupId>
+ <artifactId>checker-qual</artifactId>
+ <optional>true</optional>
</dependency>
<dependency>
- <groupId>org.mockito</groupId>
- <artifactId>mockito-core</artifactId>
+ <groupId>com.typesafe</groupId>
+ <artifactId>config</artifactId>
+ <scope>test</scope>
</dependency>
<dependency>
<groupId>com.typesafe.akka</groupId>
<groupId>com.google.guava</groupId>
<artifactId>guava-testlib</artifactId>
</dependency>
+ <dependency>
+ <groupId>org.opendaylight.yangtools</groupId>
+ <artifactId>yang-common</artifactId>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.opendaylight.yangtools</groupId>
+ <artifactId>yang-data-api</artifactId>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.opendaylight.yangtools</groupId>
+ <artifactId>yang-data-impl</artifactId>
+ <scope>test</scope>
+ </dependency>
<dependency>
<groupId>org.opendaylight.controller</groupId>
<artifactId>sal-clustering-commons</artifactId>
// Private constructor to avoid code duplication.
private AbstractClientConnection(final AbstractClientConnection<T> oldConn, final TransmitQueue newQueue,
final String backendName) {
- this.context = oldConn.context;
- this.cookie = oldConn.cookie;
+ context = oldConn.context;
+ cookie = oldConn.cookie;
this.backendName = requireNonNull(backendName);
- this.queue = requireNonNull(newQueue);
+ queue = requireNonNull(newQueue);
// Will be updated in finishReplay if needed.
- this.lastReceivedTicks = oldConn.lastReceivedTicks;
+ lastReceivedTicks = oldConn.lastReceivedTicks;
}
// This constructor is only to be called by ConnectingClientConnection constructor.
this.context = requireNonNull(context);
this.cookie = requireNonNull(cookie);
this.backendName = requireNonNull(backendName);
- this.queue = new TransmitQueue.Halted(queueDepth);
- this.lastReceivedTicks = currentTime();
+ queue = new TransmitQueue.Halted(queueDepth);
+ lastReceivedTicks = currentTime();
}
// This constructor is only to be called (indirectly) by ReconnectingClientConnection constructor.
if (delay.isPresent()) {
// If there is new delay, schedule a timer
- scheduleTimer(delay.getAsLong());
+ scheduleTimer(delay.orElseThrow());
} else {
LOG.debug("{}: not scheduling timeout on {}", context.persistenceId(), this);
}
}
if (maybeEntry.isPresent()) {
- final TransmittedConnectionEntry entry = maybeEntry.get();
+ final TransmittedConnectionEntry entry = maybeEntry.orElseThrow();
LOG.debug("Completing {} with {}", entry, envelope);
entry.complete(envelope.getMessage());
}
* sessionId and if it does not match our current connection just ignore it.
*/
final Optional<T> optBackend = conn.getBackendInfo();
- if (optBackend.isPresent() && optBackend.get().getSessionId() != command.getSessionId()) {
+ if (optBackend.isPresent() && optBackend.orElseThrow().getSessionId() != command.getSessionId()) {
LOG.debug("{}: Mismatched current connection {} and envelope {}, ignoring response", persistenceId(),
conn, command);
return this;
final Long shard = oldConn.cookie();
LOG.info("{}: refreshing backend for shard {}", persistenceId(), shard);
- resolver().refreshBackendInfo(shard, conn.getBackendInfo().get()).whenComplete(
+ resolver().refreshBackendInfo(shard, conn.getBackendInfo().orElseThrow()).whenComplete(
(backend, failure) -> context().executeInActor(behavior -> {
backendConnectFinished(shard, conn, backend, failure);
return behavior;
import static com.google.common.base.Verify.verify;
import static com.google.common.base.Verify.verifyNotNull;
+import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.VarHandle;
import java.util.concurrent.CountDownLatch;
private final StampedLock lock = new StampedLock();
+ @SuppressFBWarnings(value = "UWF_UNWRITTEN_FIELD",
+ justification = "https://github.com/spotbugs/spotbugs/issues/2749")
private volatile CountDownLatch latch;
/**
}
public void unlockWrite(final long stamp) {
- final CountDownLatch local = (CountDownLatch) LATCH.getAndSet(this, null);
- verifyNotNull(local);
+ final var local = verifyNotNull((CountDownLatch) LATCH.getAndSet(this, null));
lock.unlockWrite(stamp);
local.countDown();
}
*
* <p>
* This class is not thread-safe, as it is expected to be guarded by {@link AbstractClientConnection}.
- *
- * @author Robert Varga
*/
-abstract class TransmitQueue {
+abstract sealed class TransmitQueue {
static final class Halted extends TransmitQueue {
// For ConnectingClientConnection.
Halted(final int targetDepth) {
return Optional.empty();
}
- final TransmittedConnectionEntry entry = maybeEntry.get();
+ final TransmittedConnectionEntry entry = maybeEntry.orElseThrow();
tracker.closeTask(now, entry.getEnqueuedTicks(), entry.getTxTicks(), envelope.getExecutionTimeNanos());
// We have freed up a slot, try to transmit something
return false;
}
- inflight.addLast(maybeTransmitted.get());
+ inflight.addLast(maybeTransmitted.orElseThrow());
return true;
}
*/
package org.opendaylight.controller.cluster.access.client;
+import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.ArgumentMatchers.any;
-import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.timeout;
import static org.mockito.Mockito.verify;
-import static org.mockito.Mockito.when;
import akka.actor.ActorRef;
import akka.actor.ActorSystem;
import akka.testkit.TestProbe;
import akka.testkit.javadsl.TestKit;
import com.typesafe.config.ConfigFactory;
-import java.lang.reflect.Field;
import java.util.Optional;
import java.util.concurrent.TimeUnit;
-import org.junit.After;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.mockito.Answers;
+import org.mockito.Mock;
+import org.mockito.junit.jupiter.MockitoExtension;
import org.opendaylight.controller.cluster.access.concepts.ClientIdentifier;
import org.opendaylight.controller.cluster.access.concepts.FrontendIdentifier;
import org.opendaylight.controller.cluster.access.concepts.FrontendType;
import org.opendaylight.controller.cluster.access.concepts.MemberName;
import scala.concurrent.duration.FiniteDuration;
-public class ActorBehaviorTest {
-
+@ExtendWith(MockitoExtension.class)
+class ActorBehaviorTest {
private static final String MEMBER_1_FRONTEND_TYPE_1 = "member-1-frontend-type-1";
private static final FiniteDuration TIMEOUT = FiniteDuration.create(5, TimeUnit.SECONDS);
+ @Mock
+ private InternalCommand<BackendInfo> cmd;
+ @Mock(answer = Answers.CALLS_REAL_METHODS)
+ private ClientActorBehavior<BackendInfo> initialBehavior;
+ @Mock
+ private AbstractClientActorContext ctx;
+
private ActorSystem system;
private TestProbe probe;
- private ClientActorBehavior<BackendInfo> initialBehavior;
private MockedSnapshotStore.SaveRequest saveRequest;
private FrontendIdentifier id;
private ActorRef mockedActor;
- @Before
- public void setUp() throws Exception {
- initialBehavior = createInitialBehaviorMock();
+ @BeforeEach
+ void beforeEach() throws Exception {
+ //persistenceId() in AbstractClientActorBehavior is final and can't be mocked
+ //use reflection to work around this
+ final var context = AbstractClientActorBehavior.class.getDeclaredField("context");
+ context.setAccessible(true);
+ context.set(initialBehavior, ctx);
+ final var persistenceId = AbstractClientActorContext.class.getDeclaredField("persistenceId");
+ persistenceId.setAccessible(true);
+ persistenceId.set(ctx, MEMBER_1_FRONTEND_TYPE_1);
+
system = ActorSystem.apply("system1");
final ActorRef storeRef = system.registerExtension(Persistence.lookup()).snapshotStoreFor(null,
ConfigFactory.empty());
saveRequest = handleRecovery(null);
}
- @After
- public void tearDown() {
+ @AfterEach
+ void afterEach() {
TestKit.shutdownActorSystem(system);
}
@Test
- public void testInitialBehavior() {
- final InternalCommand<BackendInfo> cmd = mock(InternalCommand.class);
- when(cmd.execute(any())).thenReturn(initialBehavior);
+ void testInitialBehavior() {
+ doReturn(initialBehavior).when(cmd).execute(any());
mockedActor.tell(cmd, ActorRef.noSender());
verify(cmd, timeout(1000)).execute(initialBehavior);
}
@Test
- public void testCommandStashing() {
+ void testCommandStashing() {
system.stop(mockedActor);
mockedActor = system.actorOf(MockedActor.props(id, initialBehavior));
- final InternalCommand<BackendInfo> cmd = mock(InternalCommand.class);
- when(cmd.execute(any())).thenReturn(initialBehavior);
+ doReturn(initialBehavior).when(cmd).execute(any());
//send messages before recovery is completed
mockedActor.tell(cmd, ActorRef.noSender());
mockedActor.tell(cmd, ActorRef.noSender());
}
@Test
- public void testRecoveryAfterRestart() {
+ void testRecoveryAfterRestart() {
system.stop(mockedActor);
mockedActor = system.actorOf(MockedActor.props(id, initialBehavior));
final MockedSnapshotStore.SaveRequest newSaveRequest =
handleRecovery(new SelectedSnapshot(saveRequest.getMetadata(), saveRequest.getSnapshot()));
- Assert.assertEquals(MEMBER_1_FRONTEND_TYPE_1, newSaveRequest.getMetadata().persistenceId());
+ assertEquals(MEMBER_1_FRONTEND_TYPE_1, newSaveRequest.getMetadata().persistenceId());
}
@Test
- public void testRecoveryAfterRestartFrontendIdMismatch() {
+ void testRecoveryAfterRestartFrontendIdMismatch() {
system.stop(mockedActor);
//start actor again
mockedActor = system.actorOf(MockedActor.props(id, initialBehavior));
}
@Test
- public void testRecoveryAfterRestartSaveSnapshotFail() {
+ void testRecoveryAfterRestartSaveSnapshotFail() {
system.stop(mockedActor);
mockedActor = system.actorOf(MockedActor.props(id, initialBehavior));
probe.watch(mockedActor);
}
@Test
- public void testRecoveryAfterRestartDeleteSnapshotsFail() {
+ void testRecoveryAfterRestartDeleteSnapshotsFail() {
system.stop(mockedActor);
mockedActor = system.actorOf(MockedActor.props(id, initialBehavior));
probe.watch(mockedActor);
probe.expectNoMessage();
}
- @SuppressWarnings("unchecked")
- private static ClientActorBehavior<BackendInfo> createInitialBehaviorMock() throws Exception {
- final ClientActorBehavior<BackendInfo> initialBehavior = mock(ClientActorBehavior.class);
- //persistenceId() in AbstractClientActorBehavior is final and can't be mocked
- //use reflection to work around this
- final Field context = AbstractClientActorBehavior.class.getDeclaredField("context");
- context.setAccessible(true);
- final AbstractClientActorContext ctx = mock(AbstractClientActorContext.class);
- context.set(initialBehavior, ctx);
- final Field persistenceId = AbstractClientActorContext.class.getDeclaredField("persistenceId");
- persistenceId.setAccessible(true);
- persistenceId.set(ctx, MEMBER_1_FRONTEND_TYPE_1);
- return initialBehavior;
- }
-
private MockedSnapshotStore.SaveRequest handleRecovery(final SelectedSnapshot savedState) {
probe.expectMsgClass(MockedSnapshotStore.LoadRequest.class);
//offer snapshot
}
private static class MockedActor extends AbstractClientActor {
-
private final ClientActorBehavior<?> initialBehavior;
private final ClientActorConfig mockConfig = AccessClientUtil.newMockClientActorConfig();
return mockConfig;
}
}
-
}
import org.opendaylight.controller.cluster.messaging.MessageSlice;
import org.opendaylight.yangtools.yang.common.QName;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
-import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
+import org.opendaylight.yangtools.yang.data.spi.node.ImmutableNodes;
public class ConnectedClientConnectionTest
extends AbstractClientConnectionTest<ConnectedClientConnection<BackendInfo>, BackendInfo> {
new TransactionIdentifier(new LocalHistoryIdentifier(CLIENT_ID, 0L), 0L);
ModifyTransactionRequestBuilder reqBuilder =
new ModifyTransactionRequestBuilder(identifier, replyToProbe.ref());
- reqBuilder.addModification(new TransactionWrite(YangInstanceIdentifier.empty(), Builders.containerBuilder()
- .withNodeIdentifier(YangInstanceIdentifier.NodeIdentifier.create(
- QName.create("namespace", "localName"))).build()));
+ reqBuilder.addModification(new TransactionWrite(YangInstanceIdentifier.of(),
+ ImmutableNodes.newContainerBuilder()
+ .withNodeIdentifier(new NodeIdentifier(QName.create("namespace", "localName")))
+ .build()));
reqBuilder.setSequence(0L);
final Request<?, ?> request = reqBuilder.build();
connection.sendRequest(request, callback);
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import org.opendaylight.controller.cluster.access.ABIVersion;
-import org.opendaylight.controller.cluster.access.concepts.AbstractRequestFailureProxy;
-import org.opendaylight.controller.cluster.access.concepts.AbstractRequestProxy;
import org.opendaylight.controller.cluster.access.concepts.FailureEnvelope;
import org.opendaylight.controller.cluster.access.concepts.Request;
import org.opendaylight.controller.cluster.access.concepts.RequestEnvelope;
}
@Override
- protected AbstractRequestFailureProxy<WritableIdentifier, MockFailure> externalizableProxy(
- final ABIVersion version) {
+ protected SerialForm<WritableIdentifier, MockFailure> externalizableProxy(final ABIVersion version) {
return null;
}
}
@Override
- protected AbstractRequestProxy<WritableIdentifier, MockRequest> externalizableProxy(final ABIVersion version) {
+ protected Request.SerialForm<WritableIdentifier, MockRequest> externalizableProxy(final ABIVersion version) {
return null;
}
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import org.opendaylight.controller.cluster.access.ABIVersion;
-import org.opendaylight.controller.cluster.access.concepts.AbstractRequestFailureProxy;
-import org.opendaylight.controller.cluster.access.concepts.AbstractRequestProxy;
import org.opendaylight.controller.cluster.access.concepts.Request;
import org.opendaylight.controller.cluster.access.concepts.RequestException;
import org.opendaylight.controller.cluster.access.concepts.RequestFailure;
}
@Override
- protected AbstractRequestFailureProxy<WritableIdentifier, MockFailure> externalizableProxy(
- final ABIVersion version) {
+ protected SerialForm<WritableIdentifier, MockFailure> externalizableProxy(final ABIVersion version) {
return null;
}
}
@Override
- protected AbstractRequestProxy<WritableIdentifier, MockRequest> externalizableProxy(final ABIVersion version) {
+ protected Request.SerialForm<WritableIdentifier, MockRequest> externalizableProxy(final ABIVersion version) {
return null;
}
Optional<TransmittedConnectionEntry> transmitted = queue.transmit(entry, now);
assertTrue(transmitted.isPresent());
- assertEquals(request, transmitted.get().getRequest());
- assertEquals(callback, transmitted.get().getCallback());
+ assertEquals(request, transmitted.orElseThrow().getRequest());
+ assertEquals(callback, transmitted.orElseThrow().getCallback());
final RequestEnvelope requestEnvelope = probe.expectMsgClass(RequestEnvelope.class);
assertEquals(request, requestEnvelope.getMessage());
<parent>
<groupId>org.opendaylight.controller</groupId>
<artifactId>mdsal-parent</artifactId>
- <version>7.0.2-SNAPSHOT</version>
+ <version>9.0.3-SNAPSHOT</version>
<relativePath>../parent</relativePath>
</parent>
<packaging>bundle</packaging>
<dependencies>
+ <dependency>
+ <groupId>org.eclipse.jdt</groupId>
+ <artifactId>org.eclipse.jdt.annotation</artifactId>
+ </dependency>
<dependency>
<groupId>org.opendaylight.yangtools</groupId>
<artifactId>concepts</artifactId>
*/
package org.opendaylight.controller.cluster.dom.api;
-import java.util.EventListener;
import org.eclipse.jdt.annotation.NonNull;
/**
* Listener for shard leader location changes.
*/
-public interface LeaderLocationListener extends EventListener {
+public interface LeaderLocationListener {
/**
* Invoked when shard leader location changes.
*
+++ /dev/null
-/*
- * Copyright (c) 2016 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.cluster.dom.api;
-
-import org.opendaylight.yangtools.concepts.ListenerRegistration;
-
-/**
- * Registration of a {@link LeaderLocationListener}.
- *
- * @param <T> Listener type
- */
-public interface LeaderLocationListenerRegistration<T extends LeaderLocationListener> extends ListenerRegistration<T> {
- // Just a specialization
-}
<parent>
<groupId>org.opendaylight.controller</groupId>
<artifactId>mdsal-parent</artifactId>
- <version>7.0.2-SNAPSHOT</version>
+ <version>9.0.3-SNAPSHOT</version>
<relativePath>../parent</relativePath>
</parent>
<artifactId>cds-mgmt-api</artifactId>
<packaging>bundle</packaging>
+ <dependencies>
+ <dependency>
+ <groupId>org.eclipse.jdt</groupId>
+ <artifactId>org.eclipse.jdt.annotation</artifactId>
+ </dependency>
+ </dependencies>
+
<build>
<plugins>
<plugin>
<parent>
<groupId>org.opendaylight.controller</groupId>
<artifactId>mdsal-parent</artifactId>
- <version>7.0.2-SNAPSHOT</version>
+ <version>9.0.3-SNAPSHOT</version>
<relativePath>../parent</relativePath>
</parent>
<dependencies>
<dependency>
- <groupId>com.google.guava</groupId>
- <artifactId>guava</artifactId>
+ <groupId>com.github.spotbugs</groupId>
+ <artifactId>spotbugs-annotations</artifactId>
+ <optional>true</optional>
</dependency>
<dependency>
- <groupId>com.typesafe</groupId>
- <artifactId>config</artifactId>
+ <groupId>com.google.guava</groupId>
+ <artifactId>guava</artifactId>
</dependency>
<dependency>
<groupId>org.opendaylight.controller</groupId>
<artifactId>scala-library</artifactId>
</dependency>
+ <dependency>
+ <groupId>com.typesafe.akka</groupId>
+ <artifactId>akka-testkit_2.13</artifactId>
+ </dependency>
<dependency>
<groupId>com.typesafe.akka</groupId>
<artifactId>akka-actor-testkit-typed_2.13</artifactId>
<artifactId>awaitility</artifactId>
</dependency>
+ <dependency>
+ <groupId>com.typesafe</groupId>
+ <artifactId>config</artifactId>
+ <scope>test</scope>
+ </dependency>
<dependency>
<groupId>org.opendaylight.mdsal</groupId>
<artifactId>mdsal-binding-dom-codec</artifactId>
<artifactId>mdsal-binding-generator</artifactId>
<scope>test</scope>
</dependency>
+ <dependency>
+ <groupId>org.opendaylight.mdsal</groupId>
+ <artifactId>mdsal-binding-runtime-api</artifactId>
+ <scope>test</scope>
+ </dependency>
<dependency>
<groupId>org.opendaylight.mdsal</groupId>
<artifactId>mdsal-binding-runtime-spi</artifactId>
</dependency>
<dependency>
<groupId>org.opendaylight.mdsal</groupId>
- <artifactId>mdsal-singleton-common-api</artifactId>
+ <artifactId>mdsal-singleton-api</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.opendaylight.mdsal</groupId>
- <artifactId>mdsal-singleton-dom-impl</artifactId>
+ <artifactId>mdsal-singleton-impl</artifactId>
<scope>test</scope>
</dependency>
import org.opendaylight.mdsal.eos.common.api.CandidateAlreadyRegisteredException;
import org.opendaylight.mdsal.eos.common.api.EntityOwnershipState;
import org.opendaylight.mdsal.eos.dom.api.DOMEntity;
-import org.opendaylight.mdsal.eos.dom.api.DOMEntityOwnershipCandidateRegistration;
import org.opendaylight.mdsal.eos.dom.api.DOMEntityOwnershipListener;
-import org.opendaylight.mdsal.eos.dom.api.DOMEntityOwnershipListenerRegistration;
import org.opendaylight.mdsal.eos.dom.api.DOMEntityOwnershipService;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.entity.owners.norev.GetEntities;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.entity.owners.norev.GetEntitiesInput;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.entity.owners.norev.GetEntitiesOutput;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.entity.owners.norev.GetEntity;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.entity.owners.norev.GetEntityInput;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.entity.owners.norev.GetEntityOutput;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.entity.owners.norev.GetEntityOwner;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.entity.owners.norev.GetEntityOwnerInput;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.entity.owners.norev.GetEntityOwnerOutput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.entity.owners.norev.OdlEntityOwnersService;
import org.opendaylight.yangtools.concepts.Registration;
import org.opendaylight.yangtools.yang.binding.RpcOutput;
import org.opendaylight.yangtools.yang.common.Empty;
*/
@Singleton
@Component(immediate = true, service = { DOMEntityOwnershipService.class, DataCenterControl.class })
-public class AkkaEntityOwnershipService implements DOMEntityOwnershipService, DataCenterControl, AutoCloseable,
- OdlEntityOwnersService {
+public class AkkaEntityOwnershipService implements DOMEntityOwnershipService, DataCenterControl, AutoCloseable {
private static final Logger LOG = LoggerFactory.getLogger(AkkaEntityOwnershipService.class);
private static final String DATACENTER_PREFIX = "dc";
private static final Duration DATACENTER_OP_TIMEOUT = Duration.ofSeconds(20);
throws ExecutionException, InterruptedException {
this(actorProvider.getActorSystem(), codecTree);
- reg = rpcProvider.registerRpcImplementation(OdlEntityOwnersService.class, this);
+ reg = rpcProvider.registerRpcImplementations(
+ (GetEntity) this::getEntity,
+ (GetEntities) this::getEntities,
+ (GetEntityOwner) this::getEntityOwner);
}
@PreDestroy
}
@Override
- public DOMEntityOwnershipCandidateRegistration registerCandidate(final DOMEntity entity)
+ public Registration registerCandidate(final DOMEntity entity)
throws CandidateAlreadyRegisteredException {
if (!registeredEntities.add(entity)) {
throw new CandidateAlreadyRegisteredException(entity);
}
@Override
- public DOMEntityOwnershipListenerRegistration registerListener(final String entityType,
- final DOMEntityOwnershipListener listener) {
+ public Registration registerListener(final String entityType, final DOMEntityOwnershipListener listener) {
LOG.debug("Registering listener {} for type {}", listener, entityType);
listenerRegistry.tell(new RegisterListener(entityType, listener));
AskPattern.ask(ownerSupervisor, DeactivateDataCenter::new, DATACENTER_OP_TIMEOUT, scheduler));
}
- @Override
- public ListenableFuture<RpcResult<GetEntitiesOutput>> getEntities(final GetEntitiesInput input) {
+ @VisibleForTesting
+ final ListenableFuture<RpcResult<GetEntitiesOutput>> getEntities(final GetEntitiesInput input) {
return toRpcFuture(AskPattern.ask(ownerStateChecker, GetEntitiesRequest::new, QUERY_TIMEOUT, scheduler),
reply -> reply.toOutput(iidCodec));
}
- @Override
- public ListenableFuture<RpcResult<GetEntityOutput>> getEntity(final GetEntityInput input) {
+ @VisibleForTesting
+ final ListenableFuture<RpcResult<GetEntityOutput>> getEntity(final GetEntityInput input) {
return toRpcFuture(AskPattern.ask(ownerStateChecker,
(final ActorRef<GetEntityReply> replyTo) -> new GetEntityRequest(replyTo, input), QUERY_TIMEOUT, scheduler),
GetEntityReply::toOutput);
}
- @Override
- public ListenableFuture<RpcResult<GetEntityOwnerOutput>> getEntityOwner(final GetEntityOwnerInput input) {
+ @VisibleForTesting
+ final ListenableFuture<RpcResult<GetEntityOwnerOutput>> getEntityOwner(final GetEntityOwnerInput input) {
return toRpcFuture(AskPattern.ask(ownerStateChecker,
(final ActorRef<GetEntityOwnerReply> replyTo) -> new GetEntityOwnerRequest(replyTo, input), QUERY_TIMEOUT,
scheduler), GetEntityOwnerReply::toOutput);
import static java.util.Objects.requireNonNull;
import org.opendaylight.mdsal.eos.dom.api.DOMEntity;
-import org.opendaylight.mdsal.eos.dom.api.DOMEntityOwnershipCandidateRegistration;
import org.opendaylight.yangtools.concepts.AbstractObjectRegistration;
-final class CandidateRegistration extends AbstractObjectRegistration<DOMEntity>
- implements DOMEntityOwnershipCandidateRegistration {
+final class CandidateRegistration extends AbstractObjectRegistration<DOMEntity> {
private final AkkaEntityOwnershipService service;
CandidateRegistration(final DOMEntity instance, final AkkaEntityOwnershipService service) {
import com.google.common.base.MoreObjects;
import org.eclipse.jdt.annotation.NonNull;
import org.opendaylight.mdsal.eos.dom.api.DOMEntityOwnershipListener;
-import org.opendaylight.mdsal.eos.dom.api.DOMEntityOwnershipListenerRegistration;
import org.opendaylight.yangtools.concepts.AbstractObjectRegistration;
-final class ListenerRegistration extends AbstractObjectRegistration<DOMEntityOwnershipListener>
- implements DOMEntityOwnershipListenerRegistration {
+final class ListenerRegistration extends AbstractObjectRegistration<DOMEntityOwnershipListener> {
private final AkkaEntityOwnershipService service;
private final @NonNull String entityType;
this.service = requireNonNull(service);
}
- @Override
- public String getEntityType() {
+ public String entityType() {
return entityType;
}
import org.opendaylight.controller.eos.akka.registry.listener.owner.command.OwnerChanged;
import org.opendaylight.controller.eos.akka.registry.listener.type.command.EntityOwnerChanged;
import org.opendaylight.controller.eos.akka.registry.listener.type.command.TypeListenerCommand;
-import org.opendaylight.mdsal.eos.common.api.EntityOwnershipChangeState;
+import org.opendaylight.mdsal.eos.common.api.EntityOwnershipStateChange;
import org.opendaylight.mdsal.eos.dom.api.DOMEntity;
-import org.opendaylight.mdsal.eos.dom.api.DOMEntityOwnershipChange;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
private void triggerNoOwnerNotification() {
LOG.debug("Triggering initial notification without an owner for: {}", entity);
-
- toNotify.tell(new EntityOwnerChanged(new DOMEntityOwnershipChange(
- entity, EntityOwnershipChangeState.REMOTE_OWNERSHIP_LOST_NO_OWNER)));
+ toNotify.tell(new EntityOwnerChanged(entity, EntityOwnershipStateChange.REMOTE_OWNERSHIP_LOST_NO_OWNER, false));
}
private Behavior<ListenerCommand> onOwnerChanged(final OwnerChanged ownerChanged) {
currentOwner = newOwner;
- toNotify.tell(new EntityOwnerChanged(new DOMEntityOwnershipChange(
- entity, EntityOwnershipChangeState.from(wasOwner, isOwner, hasOwner))));
+ toNotify.tell(new EntityOwnerChanged(entity, EntityOwnershipStateChange.from(wasOwner, isOwner, hasOwner),
+ false));
}
private void handleOwnerLost(final Replicator.Deleted<LWWRegister<String>> changed) {
LOG.debug("Owner lost for entity:{}, currentOwner: {}, wasOwner: {}", entity, currentOwner, wasOwner);
currentOwner = "";
- toNotify.tell(new EntityOwnerChanged(new DOMEntityOwnershipChange(
- entity, EntityOwnershipChangeState.from(wasOwner, false, false))));
+ toNotify.tell(new EntityOwnerChanged(entity, EntityOwnershipStateChange.from(wasOwner, false, false), false));
}
}
private Behavior<TypeListenerCommand> onOwnerChanged(final EntityOwnerChanged rsp) {
LOG.debug("{} : Entity-type: {} listener, owner change: {}", localMember, entityType, rsp);
-
- listener.ownershipChanged(rsp.getOwnershipChange());
+ listener.ownershipChanged(rsp.entity(), rsp.change(), false);
return this;
}
import static java.util.Objects.requireNonNull;
import com.google.common.base.MoreObjects;
-import org.eclipse.jdt.annotation.NonNull;
-import org.opendaylight.mdsal.eos.dom.api.DOMEntityOwnershipChange;
+import org.eclipse.jdt.annotation.NonNullByDefault;
+import org.opendaylight.controller.eos.akka.registry.listener.type.EntityTypeListenerActor;
+import org.opendaylight.mdsal.eos.common.api.EntityOwnershipStateChange;
+import org.opendaylight.mdsal.eos.dom.api.DOMEntity;
/**
- * Notification sent to EntityTypeListenerActor when there is an owner change for an Entity of a given type.
+ * Notification sent to {@link EntityTypeListenerActor} when there is an owner change for an Entity of a given type.
*/
+@NonNullByDefault
public final class EntityOwnerChanged extends TypeListenerCommand {
- private final @NonNull DOMEntityOwnershipChange ownershipChange;
+ private final DOMEntity entity;
+ private final EntityOwnershipStateChange change;
+ private final boolean inJeopardy;
- public EntityOwnerChanged(final DOMEntityOwnershipChange ownershipChange) {
- this.ownershipChange = requireNonNull(ownershipChange);
+ public EntityOwnerChanged(final DOMEntity entity, final EntityOwnershipStateChange change,
+ final boolean inJeopardy) {
+ this.entity = requireNonNull(entity);
+ this.change = requireNonNull(change);
+ this.inJeopardy = requireNonNull(inJeopardy);
}
- public @NonNull DOMEntityOwnershipChange getOwnershipChange() {
- return ownershipChange;
+ public DOMEntity entity() {
+ return entity;
+ }
+
+ public EntityOwnershipStateChange change() {
+ return change;
+ }
+
+ public boolean inJeopardy() {
+ return inJeopardy;
}
@Override
public String toString() {
- return MoreObjects.toStringHelper(this).add("ownershipChange", ownershipChange).toString();
+ return MoreObjects.toStringHelper(this)
+ .add("entity", entity)
+ .add("change", change)
+ .add("inJeopardy", inJeopardy)
+ .toString();
}
}
import org.opendaylight.controller.eos.akka.registry.candidate.command.CandidateRegistryCommand;
import org.opendaylight.controller.eos.akka.registry.candidate.command.RegisterCandidate;
import org.opendaylight.controller.eos.akka.registry.candidate.command.UnregisterCandidate;
+import org.opendaylight.controller.eos.akka.registry.listener.type.command.EntityOwnerChanged;
import org.opendaylight.controller.eos.akka.registry.listener.type.command.RegisterListener;
import org.opendaylight.controller.eos.akka.registry.listener.type.command.TypeListenerRegistryCommand;
import org.opendaylight.mdsal.binding.dom.codec.impl.BindingCodecContext;
import org.opendaylight.mdsal.binding.generator.impl.DefaultBindingRuntimeGenerator;
import org.opendaylight.mdsal.binding.runtime.api.BindingRuntimeGenerator;
import org.opendaylight.mdsal.binding.runtime.spi.BindingRuntimeHelpers;
+import org.opendaylight.mdsal.eos.common.api.EntityOwnershipStateChange;
import org.opendaylight.mdsal.eos.dom.api.DOMEntity;
-import org.opendaylight.mdsal.eos.dom.api.DOMEntityOwnershipChange;
import org.opendaylight.mdsal.eos.dom.api.DOMEntityOwnershipListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
await().until(() -> !listener.getChanges().isEmpty());
await().atMost(Duration.ofSeconds(10)).untilAsserted(() -> {
- final List<DOMEntityOwnershipChange> changes = listener.getChanges();
- final DOMEntityOwnershipChange domEntityOwnershipChange = listener.getChanges().get(changes.size() - 1);
- assertEquals(entity, domEntityOwnershipChange.getEntity());
+ final var changes = listener.getChanges();
+ final var domEntityOwnershipChange = listener.getChanges().get(changes.size() - 1);
+ assertEquals(entity, domEntityOwnershipChange.entity());
- assertEquals(hasOwner, domEntityOwnershipChange.getState().hasOwner());
- assertEquals(isOwner, domEntityOwnershipChange.getState().isOwner());
- assertEquals(wasOwner, domEntityOwnershipChange.getState().wasOwner());
+ assertEquals(hasOwner, domEntityOwnershipChange.change().hasOwner());
+ assertEquals(isOwner, domEntityOwnershipChange.change().isOwner());
+ assertEquals(wasOwner, domEntityOwnershipChange.change().wasOwner());
});
}
}
protected static final class MockEntityOwnershipListener implements DOMEntityOwnershipListener {
-
- private final Logger log;
-
- private final List<DOMEntityOwnershipChange> changes = new ArrayList<>();
+ private final List<EntityOwnerChanged> changes = new ArrayList<>();
private final String member;
+ private final Logger log;
public MockEntityOwnershipListener(final String member) {
log = LoggerFactory.getLogger("EOS-listener-" + member);
}
@Override
- public void ownershipChanged(final DOMEntityOwnershipChange ownershipChange) {
- log.info("{} Received ownershipCHanged: {}", member, ownershipChange);
+ public void ownershipChanged(final DOMEntity entity, final EntityOwnershipStateChange change,
+ final boolean inJeopardy) {
+ final var changed = new EntityOwnerChanged(entity, change, inJeopardy);
+ log.info("{} Received ownershipCHanged: {}", member, changed);
log.info("{} changes: {}", member, changes.size());
- changes.add(ownershipChange);
+ changes.add(changed);
}
- public List<DOMEntityOwnershipChange> getChanges() {
+ public List<EntityOwnerChanged> getChanges() {
return changes;
}
import akka.cluster.ddata.typed.javadsl.Replicator;
import com.typesafe.config.ConfigFactory;
import java.time.Duration;
+import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.CompletionStage;
import org.opendaylight.mdsal.eos.common.api.CandidateAlreadyRegisteredException;
import org.opendaylight.mdsal.eos.common.api.EntityOwnershipState;
import org.opendaylight.mdsal.eos.dom.api.DOMEntity;
-import org.opendaylight.mdsal.eos.dom.api.DOMEntityOwnershipCandidateRegistration;
-import org.opendaylight.mdsal.eos.dom.api.DOMEntityOwnershipListenerRegistration;
import org.opendaylight.mdsal.eos.dom.api.DOMEntityOwnershipService;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.entity.owners.norev.EntityName;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.entity.owners.norev.EntityType;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.entity.owners.norev.GetEntitiesInputBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.entity.owners.norev.GetEntitiesOutput;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.entity.owners.norev.GetEntityInputBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.entity.owners.norev.GetEntityOutput;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.entity.owners.norev.GetEntityOwnerInputBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.entity.owners.norev.GetEntityOwnerOutput;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.entity.owners.norev.NodeName;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.entity.owners.norev.get.entities.output.EntitiesKey;
import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NetworkTopology;
import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.Topology;
import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node;
+import org.opendaylight.yangtools.concepts.Registration;
import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.common.RpcResult;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
@Before
public void setUp() throws Exception {
system = ActorSystem.create("ClusterSystem", ConfigFactory.load());
- typedSystem = Adapter.toTyped(this.system);
+ typedSystem = Adapter.toTyped(system);
replicator = DistributedData.get(typedSystem).replicator();
service = new AkkaEntityOwnershipService(system, CODEC_CONTEXT);
final YangInstanceIdentifier entityId = YangInstanceIdentifier.of(QNAME);
final DOMEntity entity = new DOMEntity(ENTITY_TYPE, entityId);
- final DOMEntityOwnershipCandidateRegistration reg = service.registerCandidate(entity);
+ final Registration reg = service.registerCandidate(entity);
+ assertNotNull(reg);
- verifyEntityOwnershipCandidateRegistration(entity, reg);
verifyEntityCandidateRegistered(ENTITY_TYPE, entityId, "member-1");
try {
}
final DOMEntity entity2 = new DOMEntity(ENTITY_TYPE2, entityId);
- final DOMEntityOwnershipCandidateRegistration reg2 = service.registerCandidate(entity2);
+ final Registration reg2 = service.registerCandidate(entity2);
- verifyEntityOwnershipCandidateRegistration(entity2, reg2);
+ assertNotNull(reg2);
verifyEntityCandidateRegistered(ENTITY_TYPE2, entityId, "member-1");
}
final YangInstanceIdentifier entityId = YangInstanceIdentifier.of(QNAME);
final DOMEntity entity = new DOMEntity(ENTITY_TYPE, entityId);
- final DOMEntityOwnershipCandidateRegistration reg = service.registerCandidate(entity);
+ final Registration reg = service.registerCandidate(entity);
+ assertNotNull(reg);
- verifyEntityOwnershipCandidateRegistration(entity, reg);
verifyEntityCandidateRegistered(ENTITY_TYPE, entityId, "member-1");
reg.close();
final DOMEntity entity = new DOMEntity(ENTITY_TYPE, entityId);
final MockEntityOwnershipListener listener = new MockEntityOwnershipListener("member-1");
- final DOMEntityOwnershipListenerRegistration reg = service.registerListener(entity.getType(), listener);
+ final Registration reg = service.registerListener(entity.getType(), listener);
assertNotNull("EntityOwnershipListenerRegistration null", reg);
- assertEquals("getEntityType", entity.getType(), reg.getEntityType());
- assertEquals("getInstance", listener, reg.getInstance());
- final DOMEntityOwnershipCandidateRegistration candidate = service.registerCandidate(entity);
+ final Registration candidate = service.registerCandidate(entity);
verifyListenerState(listener, entity, true, true, false);
final int changes = listener.getChanges().size();
public void testGetOwnershipState() throws Exception {
final DOMEntity entity = new DOMEntity(ENTITY_TYPE, "one");
- final DOMEntityOwnershipCandidateRegistration registration = service.registerCandidate(entity);
+ final Registration registration = service.registerCandidate(entity);
verifyGetOwnershipState(service, entity, EntityOwnershipState.IS_OWNER);
final RunningContext runningContext = service.getRunningContext();
@Test
public void testEntityRetrievalWithYiid() throws Exception {
- final YangInstanceIdentifier entityId = YangInstanceIdentifier.create(new NodeIdentifier(NetworkTopology.QNAME),
+ final YangInstanceIdentifier entityId = YangInstanceIdentifier.of(new NodeIdentifier(NetworkTopology.QNAME),
new NodeIdentifier(Topology.QNAME),
NodeIdentifierWithPredicates.of(Topology.QNAME, QName.create(Topology.QNAME, "topology-id"), "test"),
new NodeIdentifier(Node.QNAME),
final DOMEntity entity = new DOMEntity(ENTITY_TYPE, entityId);
- final DOMEntityOwnershipCandidateRegistration reg = service.registerCandidate(entity);
+ final Registration reg = service.registerCandidate(entity);
- verifyEntityOwnershipCandidateRegistration(entity, reg);
+ assertNotNull(reg);
verifyEntityCandidateRegistered(ENTITY_TYPE, entityId, "member-1");
- RpcResult<GetEntityOutput> getEntityResult = service.getEntity(new GetEntityInputBuilder()
- .setName(new EntityName(CODEC_CONTEXT.fromYangInstanceIdentifier(entityId)))
- .setType(new EntityType(ENTITY_TYPE))
- .build())
- .get();
+ var result = service.getEntity(new GetEntityInputBuilder()
+ .setName(new EntityName(CODEC_CONTEXT.fromYangInstanceIdentifier(entityId)))
+ .setType(new EntityType(ENTITY_TYPE))
+ .build())
+ .get()
+ .getResult();
- assertEquals(getEntityResult.getResult().getOwnerNode().getValue(), "member-1");
- assertEquals(getEntityResult.getResult().getCandidateNodes().get(0).getValue(), "member-1");
+ assertEquals(result.getOwnerNode().getValue(), "member-1");
+ assertEquals(result.getCandidateNodes().get(0).getValue(), "member-1");
// we should not be able to retrieve the entity when using string
final String entityPathEncoded =
"/network-topology:network-topology/topology[topology-id='test']/node[node-id='test://test-node']";
- getEntityResult = service.getEntity(new GetEntityInputBuilder()
- .setName(new EntityName(entityPathEncoded))
- .setType(new EntityType(ENTITY_TYPE))
- .build())
- .get();
-
- assertNull(getEntityResult.getResult().getOwnerNode());
- assertTrue(getEntityResult.getResult().getCandidateNodes().isEmpty());
-
- final GetEntitiesOutput getEntitiesResult =
- service.getEntities(new GetEntitiesInputBuilder().build()).get().getResult();
-
- assertEquals(getEntitiesResult.getEntities().size(), 1);
- assertTrue(getEntitiesResult.getEntities().get(new EntitiesKey(
- new EntityName(CODEC_CONTEXT.fromYangInstanceIdentifier(entityId)), new EntityType(ENTITY_TYPE)))
- .getCandidateNodes().contains(new NodeName("member-1")));
- assertTrue(getEntitiesResult.getEntities().get(new EntitiesKey(
+ result = service.getEntity(new GetEntityInputBuilder()
+ .setName(new EntityName(entityPathEncoded))
+ .setType(new EntityType(ENTITY_TYPE))
+ .build())
+ .get()
+ .getResult();
+
+ assertNull(result.getOwnerNode());
+ assertEquals(List.of(), result.getCandidateNodes());
+
+ final var getEntitiesResult = service.getEntities(new GetEntitiesInputBuilder().build()).get().getResult();
+ final var entities = getEntitiesResult.nonnullEntities();
+ assertEquals(1, entities.size());
+ assertTrue(entities.get(new EntitiesKey(new EntityName(CODEC_CONTEXT.fromYangInstanceIdentifier(entityId)),
+ new EntityType(ENTITY_TYPE))).getCandidateNodes().contains(new NodeName("member-1")));
+ assertTrue(entities.get(new EntitiesKey(
new EntityName(CODEC_CONTEXT.fromYangInstanceIdentifier(entityId)),
new EntityType(ENTITY_TYPE)))
.getOwnerNode().getValue().equals("member-1"));
- final GetEntityOwnerOutput getOwnerResult = service.getEntityOwner(new GetEntityOwnerInputBuilder()
- .setName(new EntityName(CODEC_CONTEXT.fromYangInstanceIdentifier(entityId)))
- .setType(new EntityType(ENTITY_TYPE))
- .build())
- .get().getResult();
+ final var getOwnerResult = service.getEntityOwner(new GetEntityOwnerInputBuilder()
+ .setName(new EntityName(CODEC_CONTEXT.fromYangInstanceIdentifier(entityId)))
+ .setType(new EntityType(ENTITY_TYPE))
+ .build()).get().getResult();
assertEquals(getOwnerResult.getOwnerNode().getValue(), "member-1");
}
private static void verifyGetOwnershipState(final DOMEntityOwnershipService service, final DOMEntity entity,
final EntityOwnershipState expState) {
await().atMost(Duration.ofSeconds(5)).untilAsserted(() -> {
- final Optional<EntityOwnershipState> state = service.getOwnershipState(entity);
- assertTrue("getOwnershipState present", state.isPresent());
- assertEquals("EntityOwnershipState", expState, state.get());
+ assertEquals(Optional.of(expState), service.getOwnershipState(entity));
});
}
return success.get(CandidateRegistry.KEY).getEntries();
}
-
- private static void verifyEntityOwnershipCandidateRegistration(final DOMEntity entity,
- final DOMEntityOwnershipCandidateRegistration reg) {
- assertNotNull("EntityOwnershipCandidateRegistration null", reg);
- assertEquals("getInstance", entity, reg.getInstance());
- }
-}
\ No newline at end of file
+}
import org.junit.Before;
import org.junit.Test;
import org.opendaylight.mdsal.eos.dom.api.DOMEntity;
-import org.opendaylight.mdsal.eos.dom.api.DOMEntityOwnershipCandidateRegistration;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.entity.owners.norev.EntityName;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.entity.owners.norev.EntityType;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.entity.owners.norev.GetEntitiesInputBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.entity.owners.norev.GetEntitiesOutput;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.entity.owners.norev.GetEntityInputBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.entity.owners.norev.GetEntityOutput;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.entity.owners.norev.GetEntityOwnerInputBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.entity.owners.norev.GetEntityOwnerOutput;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.entity.owners.norev.NodeName;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.entity.owners.norev.get.entities.output.EntitiesKey;
import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NetworkTopology;
import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.Topology;
import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node;
+import org.opendaylight.yangtools.concepts.Registration;
import org.opendaylight.yangtools.yang.common.QName;
-import org.opendaylight.yangtools.yang.common.RpcResult;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
service2 = new AkkaEntityOwnershipService(system2, CODEC_CONTEXT);
// need to wait until all nodes are ready
- final Cluster cluster = Cluster.get(Adapter.toTyped(system2));
+ final var cluster = Cluster.get(Adapter.toTyped(system2));
Awaitility.await().atMost(Duration.ofSeconds(20)).until(() -> {
final List<Member> members = new ArrayList<>();
cluster.state().getMembers().forEach(members::add);
*/
@Test
public void testEntityRetrievalWithUnavailableSupervisor() throws Exception {
- final YangInstanceIdentifier entityId = YangInstanceIdentifier.create(new NodeIdentifier(NetworkTopology.QNAME),
+ final YangInstanceIdentifier entityId = YangInstanceIdentifier.of(new NodeIdentifier(NetworkTopology.QNAME),
new NodeIdentifier(Topology.QNAME),
NodeIdentifierWithPredicates.of(Topology.QNAME, QName.create(Topology.QNAME, "topology-id"), "test"),
new NodeIdentifier(Node.QNAME),
final DOMEntity entity = new DOMEntity(ENTITY_TYPE, entityId);
- final DOMEntityOwnershipCandidateRegistration reg = service1.registerCandidate(entity);
+ final Registration reg = service1.registerCandidate(entity);
await().untilAsserted(() -> {
- final RpcResult<GetEntityOutput> getEntityResult = service1.getEntity(new GetEntityInputBuilder()
- .setName(new EntityName(CODEC_CONTEXT.fromYangInstanceIdentifier(entityId)))
- .setType(new EntityType(ENTITY_TYPE))
- .build())
- .get();
+ final var getEntityResult = service1.getEntity(new GetEntityInputBuilder()
+ .setName(new EntityName(CODEC_CONTEXT.fromYangInstanceIdentifier(entityId)))
+ .setType(new EntityType(ENTITY_TYPE))
+ .build()).get();
assertEquals(getEntityResult.getResult().getOwnerNode().getValue(), "member-1");
assertEquals(getEntityResult.getResult().getCandidateNodes().get(0).getValue(), "member-1");
// keep this under ask timeout to make sure the singleton actor in the inactive datacenter responds with failure
// immediately, so that the rpc actor retries with distributed-data asap
await().atMost(Duration.ofSeconds(2)).untilAsserted(() -> {
- final GetEntitiesOutput getEntitiesResult =
- service2.getEntities(new GetEntitiesInputBuilder().build()).get().getResult();
-
- assertEquals(getEntitiesResult.getEntities().size(), 1);
- assertTrue(getEntitiesResult.getEntities().get(new EntitiesKey(
- new EntityName(CODEC_CONTEXT.fromYangInstanceIdentifier(entityId)),
- new EntityType(ENTITY_TYPE)))
- .getCandidateNodes().contains(new NodeName("member-1")));
- assertTrue(getEntitiesResult.getEntities().get(new EntitiesKey(
- new EntityName(CODEC_CONTEXT.fromYangInstanceIdentifier(entityId)),
- new EntityType(ENTITY_TYPE)))
- .getOwnerNode().getValue().equals("member-1"));
+ final var getEntitiesResult = service2.getEntities(new GetEntitiesInputBuilder().build()).get().getResult();
+ final var entities = getEntitiesResult.nonnullEntities();
+ assertEquals(1, entities.size());
+ assertTrue(entities.get(new EntitiesKey(
+ new EntityName(CODEC_CONTEXT.fromYangInstanceIdentifier(entityId)),
+ new EntityType(ENTITY_TYPE)))
+ .getCandidateNodes().contains(new NodeName("member-1")));
+ assertTrue(entities.get(new EntitiesKey(
+ new EntityName(CODEC_CONTEXT.fromYangInstanceIdentifier(entityId)),
+ new EntityType(ENTITY_TYPE)))
+ .getOwnerNode().getValue().equals("member-1"));
});
await().atMost(Duration.ofSeconds(2)).untilAsserted(() -> {
- final GetEntityOutput getEntityResult = service2.getEntity(new GetEntityInputBuilder()
- .setName(new EntityName(CODEC_CONTEXT.fromYangInstanceIdentifier(entityId)))
- .setType(new EntityType(ENTITY_TYPE))
- .build())
- .get().getResult();
+ final var getEntityResult = service2.getEntity(new GetEntityInputBuilder()
+ .setName(new EntityName(CODEC_CONTEXT.fromYangInstanceIdentifier(entityId)))
+ .setType(new EntityType(ENTITY_TYPE))
+ .build()).get().getResult();
assertEquals(getEntityResult.getOwnerNode().getValue(), "member-1");
assertEquals(getEntityResult.getCandidateNodes().get(0).getValue(), "member-1");
});
await().atMost(Duration.ofSeconds(2)).untilAsserted(() -> {
- final GetEntityOwnerOutput getOwnerResult = service2.getEntityOwner(new GetEntityOwnerInputBuilder()
- .setName(new EntityName(CODEC_CONTEXT.fromYangInstanceIdentifier(entityId)))
- .setType(new EntityType(ENTITY_TYPE))
- .build())
- .get().getResult();
+ final var getOwnerResult = service2.getEntityOwner(new GetEntityOwnerInputBuilder()
+ .setName(new EntityName(CODEC_CONTEXT.fromYangInstanceIdentifier(entityId)))
+ .setType(new EntityType(ENTITY_TYPE))
+ .build()).get().getResult();
assertEquals(getOwnerResult.getOwnerNode().getValue(), "member-1");
});
import org.junit.Before;
import org.junit.Test;
import org.opendaylight.controller.eos.akka.AbstractNativeEosTest;
-import org.opendaylight.mdsal.eos.dom.api.DOMEntityOwnershipService;
-import org.opendaylight.mdsal.singleton.common.api.ClusterSingletonService;
-import org.opendaylight.mdsal.singleton.common.api.ClusterSingletonServiceRegistration;
-import org.opendaylight.mdsal.singleton.common.api.ServiceGroupIdentifier;
-import org.opendaylight.mdsal.singleton.dom.impl.DOMClusterSingletonServiceProviderImpl;
+import org.opendaylight.mdsal.singleton.api.ClusterSingletonService;
+import org.opendaylight.mdsal.singleton.api.ServiceGroupIdentifier;
+import org.opendaylight.mdsal.singleton.impl.EOSClusterSingletonServiceProvider;
+import org.opendaylight.yangtools.concepts.Registration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
private MockNativeEntityOwnershipService node2;
private MockNativeEntityOwnershipService node3;
- private MockSingletonService singletonNode1;
- private MockSingletonService singletonNode2;
- private MockSingletonService singletonNode3;
+ private EOSClusterSingletonServiceProvider singletonNode1;
+ private EOSClusterSingletonServiceProvider singletonNode2;
+ private EOSClusterSingletonServiceProvider singletonNode3;
@Before
node2 = startupNativeService(2551, List.of("member-2"), THREE_NODE_SEED_NODES);
node3 = startupNativeService(2552, List.of("member-3"), THREE_NODE_SEED_NODES);
- singletonNode1 = new MockSingletonService(node1);
- singletonNode1.initializeProvider();
-
- singletonNode2 = new MockSingletonService(node2);
- singletonNode2.initializeProvider();
-
- singletonNode3 = new MockSingletonService(node3);
- singletonNode3.initializeProvider();
+ singletonNode1 = new EOSClusterSingletonServiceProvider(node1);
+ singletonNode2 = new EOSClusterSingletonServiceProvider(node2);
+ singletonNode3 = new EOSClusterSingletonServiceProvider(node3);
waitUntillNodeReady(node3);
}
@Test
public void testSingletonOwnershipHandoff() {
final MockClusterSingletonService service = new MockClusterSingletonService("member-1", "service-1");
- final ClusterSingletonServiceRegistration registration =
- singletonNode1.registerClusterSingletonService(service);
+ final Registration registration = singletonNode1.registerClusterSingletonService(service);
verifyServiceActive(service);
@Test
public void testSingletonOwnershipHandoffOnNodeShutdown() throws Exception {
MockClusterSingletonService service2 = new MockClusterSingletonService("member-2", "service-1");
- ClusterSingletonServiceRegistration registration2 =
- singletonNode2.registerClusterSingletonService(service2);
+ Registration registration2 = singletonNode2.registerClusterSingletonService(service2);
verifyServiceActive(service2);
final MockClusterSingletonService service3 = new MockClusterSingletonService("member-3", "service-1");
- final ClusterSingletonServiceRegistration registration3 =
- singletonNode3.registerClusterSingletonService(service3);
+ final Registration registration3 = singletonNode3.registerClusterSingletonService(service3);
verifyServiceInactive(service3, 2);
verifyServiceActive(service3);
node2 = startupNativeService(2551, List.of("member-1"), THREE_NODE_SEED_NODES);
- singletonNode2 = new MockSingletonService(node2);
- singletonNode2.initializeProvider();
+ singletonNode2 = new EOSClusterSingletonServiceProvider(node2);
waitUntillNodeReady(node2);
service2 = new MockClusterSingletonService("member-2", "service-1");
verifyServiceInactive(service2, 5);
}
- private void waitUntillNodeReady(MockNativeEntityOwnershipService node) {
+ private static void waitUntillNodeReady(final MockNativeEntityOwnershipService node) {
// need to wait until all nodes are ready
final Cluster cluster = Cluster.get(Adapter.toTyped(node.getActorSystem()));
Awaitility.await().atMost(Duration.ofSeconds(20)).until(() -> {
});
}
- private static void verifyServiceActive(MockClusterSingletonService service) {
+ private static void verifyServiceActive(final MockClusterSingletonService service) {
await().untilAsserted(() -> assertTrue(service.isActivated()));
}
- private static void verifyServiceActive(MockClusterSingletonService service, long delay) {
+ private static void verifyServiceActive(final MockClusterSingletonService service, final long delay) {
await().pollDelay(delay, TimeUnit.SECONDS).untilAsserted(() -> assertTrue(service.isActivated()));
}
- private static void verifyServiceInactive(MockClusterSingletonService service) {
+ private static void verifyServiceInactive(final MockClusterSingletonService service) {
await().untilAsserted(() -> assertFalse(service.isActivated()));
}
- private static void verifyServiceInactive(MockClusterSingletonService service, long delay) {
+ private static void verifyServiceInactive(final MockClusterSingletonService service, final long delay) {
await().pollDelay(delay, TimeUnit.SECONDS).untilAsserted(() -> assertFalse(service.isActivated()));
}
private final ServiceGroupIdentifier identifier;
private boolean activated = false;
- MockClusterSingletonService(String member, String identifier) {
+ MockClusterSingletonService(final String member, final String identifier) {
this.member = member;
- this.identifier = ServiceGroupIdentifier.create(identifier);
+ this.identifier = new ServiceGroupIdentifier(identifier);
}
@Override
return activated;
}
}
-
- private static class MockSingletonService extends DOMClusterSingletonServiceProviderImpl {
- MockSingletonService(DOMEntityOwnershipService entityOwnershipService) {
- super(entityOwnershipService);
- }
- }
}
<parent>
<groupId>org.opendaylight.odlparent</groupId>
<artifactId>bundle-parent</artifactId>
- <version>12.0.1</version>
+ <version>13.0.11</version>
<relativePath/>
</parent>
<groupId>org.opendaylight.controller</groupId>
<artifactId>mdsal-it-base</artifactId>
- <version>7.0.2-SNAPSHOT</version>
+ <version>9.0.3-SNAPSHOT</version>
<packaging>bundle</packaging>
<dependencyManagement>
<dependency>
<groupId>org.opendaylight.mdsal</groupId>
<artifactId>mdsal-artifacts</artifactId>
- <version>11.0.4</version>
+ <version>13.0.1</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<parent>
<groupId>org.opendaylight.odlparent</groupId>
<artifactId>bundle-parent</artifactId>
- <version>12.0.1</version>
+ <version>13.0.11</version>
<relativePath/>
</parent>
<groupId>org.opendaylight.controller</groupId>
<artifactId>mdsal-it-parent</artifactId>
- <version>7.0.2-SNAPSHOT</version>
+ <version>9.0.3-SNAPSHOT</version>
<packaging>pom</packaging>
<properties>
<dependency>
<groupId>org.opendaylight.controller</groupId>
<artifactId>controller-artifacts</artifactId>
- <version>7.0.2-SNAPSHOT</version>
+ <version>9.0.3-SNAPSHOT</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<groupId>org.osgi</groupId>
<artifactId>org.osgi.framework</artifactId>
</dependency>
- <dependency>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
- </dependency>
- <!-- Testing Dependencies -->
+ <!--
+ Unfortunately default mockito-inline does not work in OSGi.
+ See https://github.com/mockito/mockito/issues/2203#issuecomment-926372053
+ -->
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
+ <version>4.11.0</version>
<scope>test</scope>
</dependency>
</dependencies>
+
<build>
<plugins>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
- <!-- Overridden to have TCP channel support -->
- <version>3.0.0-M5</version>
<configuration>
<!-- Overridden to fix corruption, where the process would hang after test -->
<forkNode implementation="org.apache.maven.plugin.surefire.extensions.SurefireForkNodeFactory"/>
<artifactId>maven-dependency-plugin</artifactId>
<executions>
<execution>
- <id>unpack-karaf-resources</id>
- <goals>
- <goal>unpack-dependencies</goal>
- </goals>
- <phase>process-test-resources</phase>
- <configuration>
- <outputDirectory>${project.build.directory}/test-classes</outputDirectory>
- <groupId>org.opendaylight.controller</groupId>
- <includeArtifactIds>mockito-core,objenesis,mdsal-it-base</includeArtifactIds>
- <excludes>META-INF\/**</excludes>
- <ignorePermissions>false</ignorePermissions>
- </configuration>
+ <id>unpack-karaf-resources</id>
+ <goals>
+ <goal>unpack-dependencies</goal>
+ </goals>
+ <phase>process-test-resources</phase>
+ <configuration>
+ <outputDirectory>${project.build.directory}/test-classes</outputDirectory>
+ <groupId>org.opendaylight.controller</groupId>
+ <includeArtifactIds>mockito-core,byte-buddy,objenesis,mdsal-it-base</includeArtifactIds>
+ <excludes>META-INF\/**</excludes>
+ <ignorePermissions>false</ignorePermissions>
+ </configuration>
</execution>
- </executions>
+ </executions>
</plugin>
</plugins>
</build>
<parent>
<groupId>org.opendaylight.mdsal</groupId>
<artifactId>binding-parent</artifactId>
- <version>11.0.4</version>
+ <version>13.0.1</version>
<relativePath/>
</parent>
<groupId>org.opendaylight.controller</groupId>
<artifactId>mdsal-parent</artifactId>
- <version>7.0.2-SNAPSHOT</version>
+ <version>9.0.3-SNAPSHOT</version>
<packaging>pom</packaging>
<dependencyManagement>
<dependency>
<groupId>org.opendaylight.controller</groupId>
<artifactId>bundle-parent</artifactId>
- <version>7.0.2-SNAPSHOT</version>
+ <version>9.0.3-SNAPSHOT</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<parent>
<groupId>org.opendaylight.odlparent</groupId>
<artifactId>odlparent-lite</artifactId>
- <version>12.0.1</version>
+ <version>13.0.11</version>
<relativePath/>
</parent>
<groupId>org.opendaylight.controller</groupId>
<artifactId>mdsal-aggregator</artifactId>
- <version>7.0.2-SNAPSHOT</version>
+ <version>9.0.3-SNAPSHOT</version>
<packaging>pom</packaging>
<properties>
<parent>
<groupId>org.opendaylight.controller</groupId>
<artifactId>mdsal-parent</artifactId>
- <version>7.0.2-SNAPSHOT</version>
+ <version>9.0.3-SNAPSHOT</version>
<relativePath>../parent</relativePath>
</parent>
<packaging>bundle</packaging>
<dependencies>
+ <dependency>
+ <groupId>com.github.spotbugs</groupId>
+ <artifactId>spotbugs-annotations</artifactId>
+ <optional>true</optional>
+ </dependency>
<dependency>
<groupId>org.opendaylight.controller</groupId>
<artifactId>sal-akka-raft</artifactId>
public void createSnapshot(final ActorRef actorRef, final Optional<OutputStream> installSnapshotStream) {
try {
if (installSnapshotStream.isPresent()) {
- SerializationUtils.serialize((Serializable) state, installSnapshotStream.get());
+ SerializationUtils.serialize((Serializable) state, installSnapshotStream.orElseThrow());
}
} catch (RuntimeException e) {
LOG.error("Exception in creating snapshot", e);
}
@Override
- public int getSnapshotChunkSize() {
+ public int getMaximumMessageSliceSize() {
return 50;
}
}
import java.nio.charset.Charset;
import java.util.Arrays;
import java.util.HashMap;
-import java.util.List;
import java.util.Map;
import java.util.Optional;
import org.opendaylight.controller.cluster.example.messages.KeyValue;
withoutPeer("example-3"), Optional.empty()), "example-3");
- List<ActorRef> examples = Arrays.asList(example1Actor, example2Actor, example3Actor);
+ final var examples = Arrays.asList(example1Actor, example2Actor, example3Actor);
- ActorRef clientActor = ACTOR_SYSTEM.actorOf(ClientActor.props(example1Actor));
- BufferedReader br =
- new BufferedReader(new InputStreamReader(System.in, Charset.defaultCharset()));
+ final var clientActor = ACTOR_SYSTEM.actorOf(ClientActor.props(example1Actor));
+ final var br = new BufferedReader(new InputStreamReader(System.in, Charset.defaultCharset()));
System.out.println("Usage :");
System.out.println("s <1-3> to start a peer");
<parent>
<groupId>org.opendaylight.controller</groupId>
<artifactId>mdsal-parent</artifactId>
- <version>7.0.2-SNAPSHOT</version>
+ <version>9.0.3-SNAPSHOT</version>
<relativePath>../parent</relativePath>
</parent>
<packaging>bundle</packaging>
<dependencies>
+ <dependency>
+ <groupId>com.github.spotbugs</groupId>
+ <artifactId>spotbugs-annotations</artifactId>
+ <optional>true</optional>
+ </dependency>
+ <dependency>
+ <groupId>com.google.guava</groupId>
+ <artifactId>guava</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.eclipse.jdt</groupId>
+ <artifactId>org.eclipse.jdt.annotation</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.opendaylight.yangtools</groupId>
+ <artifactId>concepts</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.opendaylight.yangtools</groupId>
+ <artifactId>util</artifactId>
+ </dependency>
<dependency>
<groupId>org.opendaylight.controller</groupId>
<artifactId>sal-clustering-commons</artifactId>
<artifactId>commons-io</artifactId>
<scope>test</scope>
</dependency>
- <dependency>
- <groupId>commons-lang</groupId>
- <artifactId>commons-lang</artifactId>
- <scope>test</scope>
- </dependency>
</dependencies>
<build>
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
-
package org.opendaylight.controller.cluster.raft;
import akka.actor.ActorRef;
import org.opendaylight.yangtools.concepts.Identifier;
-public interface ClientRequestTracker {
- /**
- * Returns the client actor that should be sent a response when consensus is achieved.
- *
- * @return the client actor
- */
- ActorRef getClientActor();
-
- /**
- * Returns the identifier of the object that is to be replicated. For example a transaction identifier in the case
- * of a transaction.
- *
- * @return the identifier
- */
- Identifier getIdentifier();
-
- /**
- * Returns the index of the log entry that is to be replicated.
- *
- * @return the index
- */
- long getIndex();
+/**
+ * Consensus forwarding tracker.
+ *
+ * @param clientActor the client actor that should be sent a response when consensus is achieved
+ * @param identifier the identifier of the object that is to be replicated. For example a transaction identifier in the
+ * case of a transaction
+ * @param logIndex the index of the log entry that is to be replicated
+ */
+public record ClientRequestTracker(long logIndex, ActorRef clientActor, Identifier identifier) {
}
+++ /dev/null
-/*
- * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.cluster.raft;
-
-import akka.actor.ActorRef;
-import org.opendaylight.yangtools.concepts.Identifier;
-
-public class ClientRequestTrackerImpl implements ClientRequestTracker {
-
- private final ActorRef clientActor;
- private final Identifier identifier;
- private final long logIndex;
-
- public ClientRequestTrackerImpl(ActorRef clientActor, Identifier identifier, long logIndex) {
-
- this.clientActor = clientActor;
-
- this.identifier = identifier;
-
- this.logIndex = logIndex;
- }
-
- @Override
- public ActorRef getClientActor() {
- return clientActor;
- }
-
- @Override
- public long getIndex() {
- return logIndex;
- }
-
- @Override
- public Identifier getIdentifier() {
- return identifier;
- }
-}
*
* @return the maximum size (in bytes).
*/
- int getSnapshotChunkSize();
+ int getMaximumMessageSliceSize();
/**
* Returns the maximum number of journal log entries to batch on recovery before applying.
*/
private static final int ELECTION_TIME_MAX_VARIANCE = 100;
- private static final int SNAPSHOT_CHUNK_SIZE = 480 * 1024; // 480KiB
+ private static final int MAXIMUM_MESSAGE_SLICE_SIZE = 480 * 1024; // 480KiB
/**
// 0 means direct threshold if disabled
private int snapshotDataThreshold = 0;
- private int snapshotChunkSize = SNAPSHOT_CHUNK_SIZE;
+ private int maximumMessageSliceSize = MAXIMUM_MESSAGE_SLICE_SIZE;
private long electionTimeoutFactor = 2;
private long candidateElectionTimeoutDivisor = 1;
this.snapshotDataThreshold = snapshotDataThreshold;
}
- public void setSnapshotChunkSize(final int snapshotChunkSize) {
- this.snapshotChunkSize = snapshotChunkSize;
+ public void setMaximumMessageSliceSize(final int maximumMessageSliceSize) {
+ this.maximumMessageSliceSize = maximumMessageSliceSize;
}
public void setJournalRecoveryLogBatchSize(final int journalRecoveryLogBatchSize) {
}
@Override
- public int getSnapshotChunkSize() {
- return snapshotChunkSize;
+ public int getMaximumMessageSliceSize() {
+ return maximumMessageSliceSize;
}
@Override
*/
package org.opendaylight.controller.cluster.raft;
+import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkState;
import static java.util.Objects.requireNonNull;
private short payloadVersion = -1;
- // Assume the HELIUM_VERSION version initially for backwards compatibility until we obtain the follower's
- // actual version via AppendEntriesReply. Although we no longer support the Helium version, a pre-Boron
- // follower will not have the version field in AppendEntriesReply so it will be set to 0 which is
- // HELIUM_VERSION.
- private short raftVersion = RaftVersions.HELIUM_VERSION;
+ // Assume the FLUORINE_VERSION version initially, as we no longer support pre-Fluorine versions.
+ private short raftVersion = RaftVersions.FLUORINE_VERSION;
private final PeerInfo peerInfo;
*/
@VisibleForTesting
FollowerLogInformation(final PeerInfo peerInfo, final long matchIndex, final RaftActorContext context) {
- this.nextIndex = context.getCommitIndex();
+ nextIndex = context.getCommitIndex();
this.matchIndex = matchIndex;
this.context = context;
this.peerInfo = requireNonNull(peerInfo);
* @param raftVersion the raft version.
*/
public void setRaftVersion(final short raftVersion) {
+ checkArgument(raftVersion >= RaftVersions.FLUORINE_VERSION, "Unexpected version %s", raftVersion);
this.raftVersion = raftVersion;
}
* @param state the LeaderInstallSnapshotState
*/
public void setLeaderInstallSnapshotState(final @NonNull LeaderInstallSnapshotState state) {
- if (this.installSnapshotState == null) {
- this.installSnapshotState = requireNonNull(state);
+ if (installSnapshotState == null) {
+ installSnapshotState = requireNonNull(state);
}
}
import akka.persistence.JournalProtocol;
import akka.persistence.SnapshotProtocol;
import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableList;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
-import java.util.ArrayList;
-import java.util.Collection;
import java.util.HashMap;
-import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
context = new RaftActorContextImpl(getSelf(), getContext(), id,
new ElectionTermImpl(persistentProvider, id, LOG), -1, -1, peerAddresses,
- configParams.isPresent() ? configParams.get() : new DefaultConfigParamsImpl(),
+ configParams.isPresent() ? configParams.orElseThrow() : new DefaultConfigParamsImpl(),
delegatingPersistenceProvider, this::handleApplyState, LOG, this::executeInSelf);
context.setPayloadVersion(payloadVersion);
Optional<ActorRef> roleChangeNotifier = getRoleChangeNotifier();
if (getRaftState() == RaftState.Follower && roleChangeNotifier.isPresent()
&& leaderTransitioning.getLeaderId().equals(getCurrentBehavior().getLeaderId())) {
- roleChangeNotifier.get().tell(newLeaderStateChanged(getId(), null,
+ roleChangeNotifier.orElseThrow().tell(newLeaderStateChanged(getId(), null,
getCurrentBehavior().getLeaderPayloadVersion()), getSelf());
}
}
}
final RaftActorBehavior currentBehavior = context.getCurrentBehavior();
- OnDemandRaftState.AbstractBuilder<?, ?> builder = newOnDemandRaftStateBuilder()
+ final var builder = newOnDemandRaftStateBuilder()
.commitIndex(context.getCommitIndex())
.currentTerm(context.getTermInformation().getCurrentTerm())
.inMemoryJournalDataSize(replicatedLog().dataSize())
}
if (getCurrentBehavior() instanceof AbstractLeader leader) {
- Collection<String> followerIds = leader.getFollowerIds();
- List<FollowerInfo> followerInfoList = new ArrayList<>(followerIds.size());
- for (String id : followerIds) {
- final FollowerLogInformation info = leader.getFollower(id);
- followerInfoList.add(new FollowerInfo(id, info.getNextIndex(), info.getMatchIndex(),
- info.isFollowerActive(), DurationFormatUtils.formatDurationHMS(
- TimeUnit.NANOSECONDS.toMillis(info.nanosSinceLastActivity())),
- context.getPeerInfo(info.getId()).isVoting()));
- }
-
- builder.followerInfoList(followerInfoList);
+ builder.followerInfoList(leader.getFollowerIds().stream()
+ .map(leader::getFollower)
+ .map(info -> new FollowerInfo(info.getId(), info.getNextIndex(), info.getMatchIndex(),
+ info.isFollowerActive(), DurationFormatUtils.formatDurationHMS(
+ TimeUnit.NANOSECONDS.toMillis(info.nanosSinceLastActivity())),
+ context.getPeerInfo(info.getId()).isVoting()))
+ .collect(ImmutableList.toImmutableList()));
}
sender().tell(builder.build(), self());
if (!Objects.equals(lastLeaderId, currentBehavior.getLeaderId())
|| oldBehaviorState.getLeaderPayloadVersion() != currentBehavior.getLeaderPayloadVersion()) {
if (roleChangeNotifier.isPresent()) {
- roleChangeNotifier.get().tell(newLeaderStateChanged(getId(), currentBehavior.getLeaderId(),
+ roleChangeNotifier.orElseThrow().tell(newLeaderStateChanged(getId(), currentBehavior.getLeaderId(),
currentBehavior.getLeaderPayloadVersion()), getSelf());
}
if (roleChangeNotifier.isPresent()
&& (oldBehavior == null || oldBehavior.state() != currentBehavior.state())) {
- roleChangeNotifier.get().tell(new RoleChanged(getId(), oldBehaviorStateName ,
+ roleChangeNotifier.orElseThrow().tell(new RoleChanged(getId(), oldBehaviorStateName ,
currentBehavior.state().name()), getSelf());
}
}
if (wasAppended && hasFollowers()) {
// Send log entry for replication.
- getCurrentBehavior().handleMessage(getSelf(), new Replicate(clientActor, identifier, replicatedLogEntry,
- !batchHint));
+ getCurrentBehavior().handleMessage(getSelf(),
+ new Replicate(replicatedLogEntry.getIndex(), !batchHint, clientActor, identifier));
}
}
import akka.actor.Props;
import akka.cluster.Cluster;
import com.google.common.annotations.VisibleForTesting;
-import java.util.ArrayList;
+import com.google.common.collect.ImmutableList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
-import java.util.List;
import java.util.Map;
import java.util.Optional;
-import java.util.Set;
import java.util.concurrent.Executor;
import java.util.function.Consumer;
import java.util.function.LongSupplier;
this.lastApplied = lastApplied;
this.configParams = requireNonNull(configParams);
this.persistenceProvider = requireNonNull(persistenceProvider);
- this.log = requireNonNull(logger);
+ log = requireNonNull(logger);
this.applyStateConsumer = requireNonNull(applyStateConsumer);
fileBackedOutputStreamFactory = new FileBackedOutputStreamFactory(
@Override
public Logger getLogger() {
- return this.log;
+ return log;
}
@Override
@Override
public void updatePeerIds(final ServerConfigurationPayload serverConfig) {
- votingMember = true;
- boolean foundSelf = false;
- Set<String> currentPeers = new HashSet<>(this.getPeerIds());
- for (ServerInfo server : serverConfig.getServerConfig()) {
- if (getId().equals(server.getId())) {
- foundSelf = true;
- if (!server.isVoting()) {
- votingMember = false;
- }
+ boolean newVotingMember = false;
+ var currentPeers = new HashSet<>(getPeerIds());
+ for (var server : serverConfig.getServerConfig()) {
+ if (getId().equals(server.peerId())) {
+ newVotingMember = server.isVoting();
} else {
- VotingState votingState = server.isVoting() ? VotingState.VOTING : VotingState.NON_VOTING;
- if (!currentPeers.contains(server.getId())) {
- this.addToPeers(server.getId(), null, votingState);
+ final var votingState = server.isVoting() ? VotingState.VOTING : VotingState.NON_VOTING;
+ if (currentPeers.contains(server.peerId())) {
+ getPeerInfo(server.peerId()).setVotingState(votingState);
+ currentPeers.remove(server.peerId());
} else {
- this.getPeerInfo(server.getId()).setVotingState(votingState);
- currentPeers.remove(server.getId());
+ addToPeers(server.peerId(), null, votingState);
}
}
}
for (String peerIdToRemove : currentPeers) {
- this.removePeer(peerIdToRemove);
- }
-
- if (!foundSelf) {
- votingMember = false;
+ removePeer(peerIdToRemove);
}
+ votingMember = newVotingMember;
log.debug("{}: Updated server config: isVoting: {}, peers: {}", id, votingMember, peerInfoMap.values());
setDynamicServerConfigurationInUse();
@Override
public void setDynamicServerConfigurationInUse() {
- this.dynamicServerConfiguration = true;
+ dynamicServerConfiguration = true;
}
@Override
if (!isDynamicServerConfigurationInUse()) {
return null;
}
- Collection<PeerInfo> peers = getPeers();
- List<ServerInfo> newConfig = new ArrayList<>(peers.size() + 1);
- for (PeerInfo peer: peers) {
+ final var peers = getPeers();
+ final var newConfig = ImmutableList.<ServerInfo>builderWithExpectedSize(peers.size() + (includeSelf ? 1 : 0));
+ for (PeerInfo peer : peers) {
newConfig.add(new ServerInfo(peer.getId(), peer.isVoting()));
}
newConfig.add(new ServerInfo(getId(), votingMember));
}
- return new ServerConfigurationPayload(newConfig);
+ return new ServerConfigurationPayload(newConfig.build());
}
@Override
}
void setCurrentBehavior(final RaftActorBehavior behavior) {
- this.currentBehavior = requireNonNull(behavior);
+ currentBehavior = requireNonNull(behavior);
}
@Override
Optional<ActorRef> roleChangeNotifier = raftActor.getRoleChangeNotifier();
if (roleChangeNotifier.isPresent()) {
- roleChangeNotifier.get().tell(raftActor.newLeaderStateChanged(context.getId(), null,
+ roleChangeNotifier.orElseThrow().tell(raftActor.newLeaderStateChanged(context.getId(), null,
currentBehavior.getLeaderPayloadVersion()), raftActor.self());
}
import akka.actor.ActorRef;
import akka.actor.ActorSelection;
import akka.actor.Cancellable;
+import com.google.common.collect.ImmutableList;
import java.util.ArrayDeque;
-import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
-import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.UUID;
}
private boolean updateLocalPeerInfo() {
- List<ServerInfo> newServerInfoList = newServerInfoList();
+ final var newServerInfoList = newServerInfoList();
// Check if new voting state would leave us with no voting members.
boolean atLeastOneVoting = false;
return true;
}
- private List<ServerInfo> newServerInfoList() {
- Map<String, Boolean> serverVotingStatusMap = changeVotingStatusContext.getOperation()
- .getServerVotingStatusMap();
- List<ServerInfo> newServerInfoList = new ArrayList<>();
- for (String peerId: raftContext.getPeerIds()) {
- newServerInfoList.add(new ServerInfo(peerId, serverVotingStatusMap.containsKey(peerId)
- ? serverVotingStatusMap.get(peerId) : raftContext.getPeerInfo(peerId).isVoting()));
+ private ImmutableList<ServerInfo> newServerInfoList() {
+ final var serverVotingStatusMap = changeVotingStatusContext.getOperation().getServerVotingStatusMap();
+ final var peerInfos = raftContext.getPeers();
+ final var newServerInfoList = ImmutableList.<ServerInfo>builderWithExpectedSize(peerInfos.size() + 1);
+ for (var peerInfo : peerInfos) {
+ final var peerId = peerInfo.getId();
+ final var voting = serverVotingStatusMap.get(peerId);
+ newServerInfoList.add(new ServerInfo(peerId, voting != null ? voting : peerInfo.isVoting()));
}
- newServerInfoList.add(new ServerInfo(raftContext.getId(), serverVotingStatusMap.containsKey(
- raftContext.getId()) ? serverVotingStatusMap.get(raftContext.getId())
- : raftContext.isVotingMember()));
+ final var myId = raftContext.getId();
+ final var myVoting = serverVotingStatusMap.get(myId);
+ newServerInfoList.add(new ServerInfo(myId, myVoting != null ? myVoting : raftContext.isVotingMember()));
- return newServerInfoList;
+ return newServerInfoList.build();
}
}
* @author Thomas Pantelis
*/
public final class RaftVersions {
- @Deprecated(since = "7.0.0", forRemoval = true)
- public static final short HELIUM_VERSION = 0;
- @Deprecated(since = "7.0.0", forRemoval = true)
- public static final short LITHIUM_VERSION = 1;
- @Deprecated(since = "7.0.0", forRemoval = true)
- public static final short BORON_VERSION = 3;
+ // HELIUM_VERSION = 0
+ // LITHIUM_VERSION = 1
+ // BORON_VERSION = 3
public static final short FLUORINE_VERSION = 4;
public static final short ARGON_VERSION = 5;
public static final short CURRENT_VERSION = ARGON_VERSION;
private RaftVersions() {
-
+ // Hidden on purpose
}
}
*/
public SnapshotManager(final RaftActorContext context, final Logger logger) {
this.context = context;
- this.log = logger;
+ log = logger;
}
public boolean isApplying() {
newReplicatedToAllIndex, newReplicatedToAllTerm, unAppliedEntries, mandatoryTrim);
}
- private class AbstractSnapshotState implements SnapshotState {
+ private abstract class AbstractSnapshotState implements SnapshotState {
@Override
public boolean isCapturing() {
}
}
- private class Idle extends AbstractSnapshotState {
-
+ private final class Idle extends AbstractSnapshotState {
@Override
public boolean isCapturing() {
return false;
log.debug("{}: lastSequenceNumber prior to capture: {}", persistenceId(), lastSequenceNumber);
- SnapshotManager.this.currentState = CREATING;
+ currentState = CREATING;
try {
createSnapshotProcedure.accept(Optional.ofNullable(installSnapshotStream));
} catch (Exception e) {
- SnapshotManager.this.currentState = IDLE;
+ currentState = IDLE;
log.error("Error creating snapshot", e);
return false;
}
@Override
public void apply(final ApplySnapshot toApply) {
- SnapshotManager.this.applySnapshot = toApply;
+ applySnapshot = toApply;
lastSequenceNumber = context.getPersistenceProvider().getLastSequenceNumber();
context.getPersistenceProvider().saveSnapshot(toApply.getSnapshot());
- SnapshotManager.this.currentState = PERSISTING;
+ currentState = PERSISTING;
}
@Override
}
}
- private class Creating extends AbstractSnapshotState {
-
+ private final class Creating extends AbstractSnapshotState {
@Override
public void persist(final Snapshot.State snapshotState, final Optional<OutputStream> installSnapshotStream,
final long totalMemory) {
if (installSnapshotStream.isPresent()) {
if (context.getId().equals(currentBehavior.getLeaderId())) {
try {
- ByteSource snapshotBytes = ((FileBackedOutputStream)installSnapshotStream.get()).asByteSource();
+ ByteSource snapshotBytes = ((FileBackedOutputStream)installSnapshotStream.orElseThrow())
+ .asByteSource();
currentBehavior.handleMessage(context.getActor(),
new SendInstallSnapshot(snapshot, snapshotBytes));
} catch (IOException e) {
context.getId(), e);
}
} else {
- ((FileBackedOutputStream)installSnapshotStream.get()).cleanup();
+ ((FileBackedOutputStream)installSnapshotStream.orElseThrow()).cleanup();
}
}
captureSnapshot = null;
- SnapshotManager.this.currentState = PERSISTING;
+ currentState = PERSISTING;
}
@Override
}
- private class Persisting extends AbstractSnapshotState {
-
+ private final class Persisting extends AbstractSnapshotState {
@Override
@SuppressWarnings("checkstyle:IllegalCatch")
public void commit(final long sequenceNumber, final long timeStamp) {
private void snapshotComplete() {
lastSequenceNumber = -1;
applySnapshot = null;
- SnapshotManager.this.currentState = IDLE;
+ currentState = IDLE;
context.getActor().tell(SnapshotComplete.INSTANCE, context.getActor());
}
long getTerm();
}
- static class LastAppliedTermInformationReader implements TermInformationReader {
+ static final class LastAppliedTermInformationReader implements TermInformationReader {
private long index;
private long term;
LastAppliedTermInformationReader init(final ReplicatedLog log, final long originalIndex,
final ReplicatedLogEntry lastLogEntry, final boolean hasFollowers) {
ReplicatedLogEntry entry = log.get(originalIndex);
- this.index = -1L;
- this.term = -1L;
+ index = -1L;
+ term = -1L;
if (!hasFollowers) {
if (lastLogEntry != null) {
// since we have persisted the last-log-entry to persistent journal before the capture,
@Override
public long getIndex() {
- return this.index;
+ return index;
}
@Override
public long getTerm() {
- return this.term;
+ return term;
}
}
- private static class ReplicatedToAllTermInformationReader implements TermInformationReader {
+ private static final class ReplicatedToAllTermInformationReader implements TermInformationReader {
private long index;
private long term;
ReplicatedToAllTermInformationReader init(final ReplicatedLog log, final long originalIndex) {
ReplicatedLogEntry entry = log.get(originalIndex);
- this.index = -1L;
- this.term = -1L;
+ index = -1L;
+ term = -1L;
if (entry != null) {
index = entry.getIndex();
@Override
public long getIndex() {
- return this.index;
+ return index;
}
@Override
public long getTerm() {
- return this.term;
+ return term;
}
}
}
+++ /dev/null
-/*
- * Copyright (c) 2017 Inocybe Technologies and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.cluster.raft.base.messages;
-
-import static java.util.Objects.requireNonNull;
-
-import java.io.Externalizable;
-import java.io.ObjectInput;
-import java.io.ObjectOutput;
-
-/**
- * Abstract base that implements Externalizable with no-op methods that is intended for classes that use the
- * externalizable proxy pattern but have no data to serialize and read-resolve to a static instance.
- *
- * @author Thomas Pantelis
- */
-@Deprecated(since = "7.0.0", forRemoval = true)
-public abstract class EmptyExternalizableProxy implements Externalizable {
- private static final long serialVersionUID = 1L;
-
- private final Object readResolveTo;
-
- protected EmptyExternalizableProxy(final Object readResolveTo) {
- this.readResolveTo = requireNonNull(readResolveTo);
- }
-
- @Override
- public void writeExternal(final ObjectOutput out) {
- }
-
- @Override
- public void readExternal(final ObjectInput in) {
- }
-
- protected Object readResolve() {
- return readResolveTo;
- }
-}
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
-
package org.opendaylight.controller.cluster.raft.base.messages;
import akka.actor.ActorRef;
-import org.opendaylight.controller.cluster.raft.ReplicatedLogEntry;
import org.opendaylight.yangtools.concepts.Identifier;
-public class Replicate {
- private final ActorRef clientActor;
- private final Identifier identifier;
- private final ReplicatedLogEntry replicatedLogEntry;
- private final boolean sendImmediate;
-
- public Replicate(ActorRef clientActor, Identifier identifier, ReplicatedLogEntry replicatedLogEntry,
- boolean sendImmediate) {
- this.clientActor = clientActor;
- this.identifier = identifier;
- this.replicatedLogEntry = replicatedLogEntry;
- this.sendImmediate = sendImmediate;
- }
-
- public ActorRef getClientActor() {
- return clientActor;
- }
-
- public Identifier getIdentifier() {
- return identifier;
- }
-
- public ReplicatedLogEntry getReplicatedLogEntry() {
- return replicatedLogEntry;
- }
-
- public boolean isSendImmediate() {
- return sendImmediate;
- }
+public record Replicate(long logIndex, boolean sendImmediate, ActorRef clientActor, Identifier identifier) {
+ // Nothing else here
}
}
@java.io.Serial
+ @SuppressWarnings("static-method")
private Object readResolve() {
return INSTANCE;
}
-
- @Deprecated(since = "7.0.0", forRemoval = true)
- private static class Proxy extends EmptyExternalizableProxy {
- @java.io.Serial
- private static final long serialVersionUID = 1L;
-
- // checkstyle flags the public modifier as redundant which really doesn't make sense since it clearly isn't
- // redundant. It is explicitly needed for Java serialization to be able to create instances via reflection.
- @SuppressWarnings("checkstyle:RedundantModifier")
- public Proxy() {
- super(INSTANCE);
- }
- }
}
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
-import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import org.opendaylight.controller.cluster.messaging.MessageSlicer;
import org.opendaylight.controller.cluster.messaging.SliceOptions;
import org.opendaylight.controller.cluster.raft.ClientRequestTracker;
-import org.opendaylight.controller.cluster.raft.ClientRequestTrackerImpl;
import org.opendaylight.controller.cluster.raft.FollowerLogInformation;
import org.opendaylight.controller.cluster.raft.PeerInfo;
import org.opendaylight.controller.cluster.raft.RaftActorContext;
import org.opendaylight.controller.cluster.raft.RaftState;
+import org.opendaylight.controller.cluster.raft.RaftVersions;
import org.opendaylight.controller.cluster.raft.ReplicatedLogEntry;
import org.opendaylight.controller.cluster.raft.VotingState;
import org.opendaylight.controller.cluster.raft.base.messages.ApplyState;
import org.opendaylight.controller.cluster.raft.messages.IdentifiablePayload;
import org.opendaylight.controller.cluster.raft.messages.InstallSnapshot;
import org.opendaylight.controller.cluster.raft.messages.InstallSnapshotReply;
-import org.opendaylight.controller.cluster.raft.messages.Payload;
import org.opendaylight.controller.cluster.raft.messages.RaftRPC;
import org.opendaylight.controller.cluster.raft.messages.RequestVote;
import org.opendaylight.controller.cluster.raft.messages.RequestVoteReply;
super(context, state);
appendEntriesMessageSlicer = MessageSlicer.builder().logContext(logName())
- .messageSliceSize(context.getConfigParams().getSnapshotChunkSize())
+ .messageSliceSize(context.getConfigParams().getMaximumMessageSliceSize())
.expireStateAfterInactivity(context.getConfigParams().getElectionTimeOutInterval().toMillis() * 3,
TimeUnit.MILLISECONDS).build();
return this;
}
+ final var followerRaftVersion = appendEntriesReply.getRaftVersion();
+ if (followerRaftVersion < RaftVersions.FLUORINE_VERSION) {
+ log.warn("{}: handleAppendEntriesReply - ignoring reply from follower {} raft version {}", logName(),
+ followerId, followerRaftVersion);
+ return this;
+ }
+
final long lastActivityNanos = followerLogInformation.nanosSinceLastActivity();
if (lastActivityNanos > context.getConfigParams().getElectionTimeOutInterval().toNanos()) {
log.warn("{} : handleAppendEntriesReply delayed beyond election timeout, "
followerLogInformation.markFollowerActive();
followerLogInformation.setPayloadVersion(appendEntriesReply.getPayloadVersion());
- followerLogInformation.setRaftVersion(appendEntriesReply.getRaftVersion());
+ followerLogInformation.setRaftVersion(followerRaftVersion);
followerLogInformation.setNeedsLeaderAddress(appendEntriesReply.isNeedsLeaderAddress());
long followerLastLogIndex = appendEntriesReply.getLogLastIndex();
* @return the ClientRequestTracker or null if none available
*/
private ClientRequestTracker removeClientRequestTracker(final long logIndex) {
- final Iterator<ClientRequestTracker> it = trackers.iterator();
+ final var it = trackers.iterator();
while (it.hasNext()) {
- final ClientRequestTracker t = it.next();
- if (t.getIndex() == logIndex) {
+ final var tracker = it.next();
+ if (tracker.logIndex() == logIndex) {
it.remove();
- return t;
+ return tracker;
}
}
-
return null;
}
// If it does that means the leader wasn't dropped before the transaction applied.
// That means that this transaction can be safely applied as a local transaction since we
// have the ClientRequestTracker.
- final ClientRequestTracker tracker = removeClientRequestTracker(entry.getIndex());
+ final var tracker = removeClientRequestTracker(entry.getIndex());
if (tracker != null) {
- return new ApplyState(tracker.getClientActor(), tracker.getIdentifier(), entry);
+ return new ApplyState(tracker.clientActor(), tracker.identifier(), entry);
}
// Tracker is missing, this means that we switched behaviours between replicate and applystate
// and became the leader again,. We still want to apply this as a local modification because
// we have resumed leadership with that log entry having been committed.
- final Payload payload = entry.getData();
- if (payload instanceof IdentifiablePayload<?> identifiable) {
+ if (entry.getData() instanceof IdentifiablePayload<?> identifiable) {
return new ApplyState(null, identifiable.getIdentifier(), entry);
}
if (installSnapshotState.isLastChunk(reply.getChunkIndex())) {
//this was the last chunk reply
- long followerMatchIndex = snapshotHolder.get().getLastIncludedIndex();
+ long followerMatchIndex = snapshotHolder.orElseThrow().getLastIncludedIndex();
followerLogInformation.setMatchIndex(followerMatchIndex);
followerLogInformation.setNextIndex(followerMatchIndex + 1);
followerLogInformation.clearLeaderInstallSnapshotState();
}
private void replicate(final Replicate replicate) {
- long logIndex = replicate.getReplicatedLogEntry().getIndex();
+ final long logIndex = replicate.logIndex();
- log.debug("{}: Replicate message: identifier: {}, logIndex: {}, payload: {}, isSendImmediate: {}", logName(),
- replicate.getIdentifier(), logIndex, replicate.getReplicatedLogEntry().getData().getClass(),
- replicate.isSendImmediate());
+ log.debug("{}: Replicate message: identifier: {}, logIndex: {}, isSendImmediate: {}", logName(),
+ replicate.identifier(), logIndex, replicate.sendImmediate());
// Create a tracker entry we will use this later to notify the
// client actor
- if (replicate.getClientActor() != null) {
- trackers.add(new ClientRequestTrackerImpl(replicate.getClientActor(), replicate.getIdentifier(),
- logIndex));
+ final var clientActor = replicate.clientActor();
+ if (clientActor != null) {
+ trackers.add(new ClientRequestTracker(logIndex, clientActor, replicate.identifier()));
}
boolean applyModificationToState = !context.anyVotingPeers()
applyLogToStateMachine(logIndex);
}
- if (replicate.isSendImmediate() && !followerToLog.isEmpty()) {
+ if (replicate.sendImmediate() && !followerToLog.isEmpty()) {
sendAppendEntries(0, false);
}
}
// Try to get all the entries in the journal but not exceeding the max data size for a single AppendEntries
// message.
int maxEntries = (int) context.getReplicatedLog().size();
- final int maxDataSize = context.getConfigParams().getSnapshotChunkSize();
+ final int maxDataSize = context.getConfigParams().getMaximumMessageSliceSize();
final long followerNextIndex = followerLogInfo.getNextIndex();
List<ReplicatedLogEntry> entries = context.getReplicatedLog().getFrom(followerNextIndex,
maxEntries, maxDataSize);
getReplicatedToAllIndex(), followerId);
if (captureInitiated) {
followerLogInfo.setLeaderInstallSnapshotState(new LeaderInstallSnapshotState(
- context.getConfigParams().getSnapshotChunkSize(), logName()));
+ context.getConfigParams().getMaximumMessageSliceSize(), logName()));
}
return captureInitiated;
if (snapshotHolder.isPresent()) {
LeaderInstallSnapshotState installSnapshotState = followerLogInfo.getInstallSnapshotState();
if (installSnapshotState == null) {
- installSnapshotState = new LeaderInstallSnapshotState(context.getConfigParams().getSnapshotChunkSize(),
- logName());
+ installSnapshotState = new LeaderInstallSnapshotState(
+ context.getConfigParams().getMaximumMessageSliceSize(), logName());
followerLogInfo.setLeaderInstallSnapshotState(installSnapshotState);
}
try {
// Ensure the snapshot bytes are set - this is a no-op.
- installSnapshotState.setSnapshotBytes(snapshotHolder.get().getSnapshotBytes());
+ installSnapshotState.setSnapshotBytes(snapshotHolder.orElseThrow().getSnapshotBytes());
if (!installSnapshotState.canSendNextChunk()) {
return;
installSnapshotState.startChunkTimer();
followerActor.tell(
new InstallSnapshot(currentTerm(), context.getId(),
- snapshotHolder.get().getLastIncludedIndex(),
- snapshotHolder.get().getLastIncludedTerm(),
+ snapshotHolder.orElseThrow().getLastIncludedIndex(),
+ snapshotHolder.orElseThrow().getLastIncludedTerm(),
snapshotChunk,
chunkIndex,
installSnapshotState.getTotalChunks(),
return true;
}
- final Cluster cluster = maybeCluster.get();
+ final Cluster cluster = maybeCluster.orElseThrow();
final Set<Member> unreachable = cluster.state().getUnreachable();
log.debug("{}: Cluster state: {}", logName(), unreachable);
import akka.actor.ActorRef;
import akka.actor.ActorSelection;
-import java.util.ArrayList;
-import java.util.Collection;
+import com.google.common.collect.ImmutableList;
import org.opendaylight.controller.cluster.raft.PeerInfo;
import org.opendaylight.controller.cluster.raft.RaftActorContext;
import org.opendaylight.controller.cluster.raft.RaftState;
* </ul>
*/
public final class Candidate extends AbstractRaftActorBehavior {
-
- private int voteCount;
-
+ private final ImmutableList<String> votingPeers;
private final int votesRequired;
- private final Collection<String> votingPeers = new ArrayList<>();
+ private int voteCount;
public Candidate(final RaftActorContext context) {
super(context, RaftState.Candidate);
- for (PeerInfo peer: context.getPeers()) {
- if (peer.isVoting()) {
- votingPeers.add(peer.getId());
- }
- }
+ votingPeers = context.getPeers().stream()
+ .filter(PeerInfo::isVoting)
+ .map(PeerInfo::getId)
+ .collect(ImmutableList.toImmutableList());
log.debug("{}: Election: Candidate has following voting peers: {}", logName(), votingPeers);
return this;
}
- if (message instanceof RaftRPC) {
-
- RaftRPC rpc = (RaftRPC) message;
+ if (message instanceof RaftRPC rpc) {
log.debug("{}: RaftRPC message received {}, my term is {}", logName(), rpc,
context.getTermInformation().getCurrentTerm());
import com.google.common.base.Stopwatch;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import java.io.IOException;
-import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Optional;
leaderId = appendEntries.getLeaderId();
leaderPayloadVersion = appendEntries.getPayloadVersion();
- if (appendEntries.getLeaderAddress().isPresent()) {
- final String address = appendEntries.getLeaderAddress().get();
- log.debug("New leader address: {}", address);
-
- context.setPeerAddress(leaderId, address);
- context.getConfigParams().getPeerAddressResolver().setResolved(leaderId, address);
+ final var leaderAddress = appendEntries.leaderAddress();
+ if (leaderAddress != null) {
+ log.debug("New leader address: {}", leaderAddress);
+ context.setPeerAddress(leaderId, leaderAddress);
+ context.getConfigParams().getPeerAddressResolver().setResolved(leaderId, leaderAddress);
}
// First check if the logs are in sync or not
Address leaderAddress = leaderActor.anchorPath().address();
- CurrentClusterState state = cluster.get().state();
+ CurrentClusterState state = cluster.orElseThrow().state();
Set<Member> unreachable = state.getUnreachable();
log.debug("{}: Checking for leader {} in the cluster unreachable set {}", logName(), leaderAddress,
return false;
}
- final Cluster cluster = maybeCluster.get();
+ final Cluster cluster = maybeCluster.orElseThrow();
final Member selfMember = cluster.selfMember();
final CurrentClusterState state = cluster.state();
Snapshot snapshot = Snapshot.create(
context.getSnapshotManager().convertSnapshot(snapshotTracker.getSnapshotBytes()),
- new ArrayList<>(),
+ List.of(),
installSnapshot.getLastIncludedIndex(),
installSnapshot.getLastIncludedTerm(),
installSnapshot.getLastIncludedIndex(),
*/
package org.opendaylight.controller.cluster.raft.behaviors;
-import java.io.Externalizable;
-import java.io.IOException;
-import java.io.ObjectInput;
-import java.io.ObjectOutput;
import org.opendaylight.yangtools.util.AbstractStringIdentifier;
/**
*
* @author Thomas Pantelis
*/
-class FollowerIdentifier extends AbstractStringIdentifier<FollowerIdentifier> {
+final class FollowerIdentifier extends AbstractStringIdentifier<FollowerIdentifier> {
@java.io.Serial
private static final long serialVersionUID = 1L;
private Object writeReplace() {
return new FI(getValue());
}
-
- @Deprecated(since = "7.0.0", forRemoval = true)
- private static class Proxy implements Externalizable {
- @java.io.Serial
- private static final long serialVersionUID = 1L;
-
- private FollowerIdentifier identifier;
-
- // checkstyle flags the public modifier as redundant which really doesn't make sense since it clearly isn't
- // redundant. It is explicitly needed for Java serialization to be able to create instances via reflection.
- @SuppressWarnings("checkstyle:RedundantModifier")
- public Proxy() {
- }
-
- Proxy(final FollowerIdentifier identifier) {
- this.identifier = identifier;
- }
-
- @Override
- public void writeExternal(final ObjectOutput out) throws IOException {
- out.writeObject(identifier.getValue());
- }
-
- @Override
- public void readExternal(final ObjectInput in) throws IOException, ClassNotFoundException {
- identifier = new FollowerIdentifier((String) in.readObject());
- }
-
- @java.io.Serial
- private Object readResolve() {
- return identifier;
- }
- }
}
final Optional<String> requestedFollowerIdOptional
= leadershipTransferContext.transferCohort.getRequestedFollowerId();
- if (requestedFollowerIdOptional.isPresent() && !requestedFollowerIdOptional.get().equals(followerId)) {
+ if (requestedFollowerIdOptional.isPresent() && !requestedFollowerIdOptional.orElseThrow().equals(followerId)) {
// we want to transfer leadership to specific follower
return;
}
private final int snapshotChunkSize;
private final String logName;
private ByteSource snapshotBytes;
- private int offset = INITIAL_OFFSET;
+ private long offset = INITIAL_OFFSET;
// the next snapshot chunk is sent only if the replyReceivedForOffset matches offset
- private int replyReceivedForOffset = -1;
+ private long replyReceivedForOffset = -1;
// if replyStatus is false, the previous chunk is attempted
private boolean replyStatus = false;
private int chunkIndex = FIRST_CHUNK_INDEX;
chunkIndex = FIRST_CHUNK_INDEX;
}
- int incrementOffset() {
- // if offset is -1 doesnt matter whether it was the initial value or reset, move the offset to 0 to begin with
+ private long incrementOffset() {
+ // if offset is -1 doesn't matter whether it was the initial value or reset, move the offset to 0 to begin with
if (offset == INITIAL_OFFSET) {
offset = 0;
} else {
byte[] getNextChunk() throws IOException {
// increment offset to indicate next chunk is in flight, canSendNextChunk() wont let us hit this again until,
// markSendStatus() is called with either success or failure
- int start = incrementOffset();
+ final var start = incrementOffset();
if (replyStatus || currentChunk == null) {
int size = snapshotChunkSize;
if (snapshotChunkSize > snapshotSize) {
}
currentChunk = new byte[size];
- int numRead = snapshotInputStream.read(currentChunk);
+ final var numRead = snapshotInputStream.read(currentChunk);
if (numRead != size) {
throw new IOException(String.format(
- "The # of bytes read from the input stream, %d,"
- + "does not match the expected # %d", numRead, size));
+ "The # of bytes read from the input stream, %d, does not match the expected # %d",
+ numRead, size));
}
nextChunkHashCode = Arrays.hashCode(currentChunk);
throw new InvalidChunkException("Expected chunkIndex " + (lastChunkIndex + 1) + " got " + chunkIndex);
}
- if (maybeLastChunkHashCode.isPresent() && maybeLastChunkHashCode.getAsInt() != lastChunkHashCode) {
+ if (maybeLastChunkHashCode.isPresent() && maybeLastChunkHashCode.orElseThrow() != lastChunkHashCode) {
throw new InvalidChunkException("The hash code of the recorded last chunk does not match "
+ "the senders hash code, expected " + lastChunkHashCode + " was "
- + maybeLastChunkHashCode.getAsInt());
+ + maybeLastChunkHashCode.orElseThrow());
}
bufferedStream.write(chunk);
import akka.dispatch.ControlMessage;
import java.io.Serializable;
-import org.opendaylight.controller.cluster.raft.base.messages.EmptyExternalizableProxy;
/**
* Message sent to a raft actor to shutdown gracefully. If it's the leader it will transfer leadership to a
}
@java.io.Serial
+ @SuppressWarnings("static-method")
private Object readResolve() {
return INSTANCE;
}
-
- @Deprecated(since = "7.0.0", forRemoval = true)
- private static class Proxy extends EmptyExternalizableProxy {
- @java.io.Serial
- private static final long serialVersionUID = 1L;
-
- // checkstyle flags the public modifier as redundant which really doesn't make sense since it clearly isn't
- // redundant. It is explicitly needed for Java serialization to be able to create instances via reflection.
- @SuppressWarnings("checkstyle:RedundantModifier")
- public Proxy() {
- super(INSTANCE);
- }
- }
}
import static com.google.common.base.Verify.verifyNotNull;
import static java.util.Objects.requireNonNull;
+import com.google.common.collect.ImmutableList;
import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
-import java.util.ArrayList;
import org.opendaylight.controller.cluster.raft.RaftVersions;
import org.opendaylight.controller.cluster.raft.ReplicatedLogEntry;
import org.opendaylight.controller.cluster.raft.persisted.SimpleReplicatedLogEntry;
out.writeObject(e.getData());
}
- out.writeObject(appendEntries.getLeaderAddress().orElse(null));
+ out.writeObject(appendEntries.leaderAddress());
}
@Override
short payloadVersion = in.readShort();
int size = in.readInt();
- var entries = new ArrayList<ReplicatedLogEntry>(size);
+ var entries = ImmutableList.<ReplicatedLogEntry>builderWithExpectedSize(size);
for (int i = 0; i < size; i++) {
hdr = WritableObjects.readLongHeader(in);
entries.add(new SimpleReplicatedLogEntry(WritableObjects.readFirstLong(in, hdr),
String leaderAddress = (String)in.readObject();
- appendEntries = new AppendEntries(term, leaderId, prevLogIndex, prevLogTerm, entries, leaderCommit,
+ appendEntries = new AppendEntries(term, leaderId, prevLogIndex, prevLogTerm, entries.build(), leaderCommit,
replicatedToAllIndex, payloadVersion, RaftVersions.CURRENT_VERSION, leaderRaftVersion,
leaderAddress);
}
package org.opendaylight.controller.cluster.raft.messages;
public abstract class AbstractRaftRPC implements RaftRPC {
+ @java.io.Serial
private static final long serialVersionUID = -6061342433962854822L;
// term
}
// All implementations must use Externalizable Proxy pattern
+ @java.io.Serial
abstract Object writeReplace();
}
import static java.util.Objects.requireNonNull;
import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableList;
import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
-import java.util.ArrayList;
import java.util.List;
-import java.util.Optional;
import org.eclipse.jdt.annotation.NonNull;
import org.eclipse.jdt.annotation.Nullable;
import org.opendaylight.controller.cluster.raft.RaftVersions;
* Invoked by leader to replicate log entries (§5.3); also used as heartbeat (§5.2).
*/
public final class AppendEntries extends AbstractRaftRPC {
+ @java.io.Serial
private static final long serialVersionUID = 1L;
// So that follower can redirect clients
return payloadVersion;
}
- public Optional<String> getLeaderAddress() {
- return Optional.ofNullable(leaderAddress);
+ public @Nullable String leaderAddress() {
+ return leaderAddress;
}
public short getLeaderRaftVersion() {
@Override
Object writeReplace() {
- if (recipientRaftVersion <= RaftVersions.BORON_VERSION) {
- return new Proxy(this);
- }
- return recipientRaftVersion == RaftVersions.FLUORINE_VERSION ? new ProxyV2(this) : new AE(this);
+ return recipientRaftVersion <= RaftVersions.FLUORINE_VERSION ? new ProxyV2(this) : new AE(this);
}
/**
* Fluorine version that adds the leader address.
*/
private static class ProxyV2 implements Externalizable {
+ @java.io.Serial
private static final long serialVersionUID = 1L;
private AppendEntries appendEntries;
short payloadVersion = in.readShort();
int size = in.readInt();
- List<ReplicatedLogEntry> entries = new ArrayList<>(size);
+ var entries = ImmutableList.<ReplicatedLogEntry>builderWithExpectedSize(size);
for (int i = 0; i < size; i++) {
entries.add(new SimpleReplicatedLogEntry(in.readLong(), in.readLong(), (Payload) in.readObject()));
}
String leaderAddress = (String)in.readObject();
- appendEntries = new AppendEntries(term, leaderId, prevLogIndex, prevLogTerm, entries, leaderCommit,
+ appendEntries = new AppendEntries(term, leaderId, prevLogIndex, prevLogTerm, entries.build(), leaderCommit,
replicatedToAllIndex, payloadVersion, RaftVersions.CURRENT_VERSION, leaderRaftVersion,
leaderAddress);
}
- private Object readResolve() {
- return appendEntries;
- }
- }
-
- /**
- * Pre-Fluorine version.
- */
- @Deprecated
- private static class Proxy implements Externalizable {
- private static final long serialVersionUID = 1L;
-
- private AppendEntries appendEntries;
-
- // checkstyle flags the public modifier as redundant which really doesn't make sense since it clearly isn't
- // redundant. It is explicitly needed for Java serialization to be able to create instances via reflection.
- @SuppressWarnings("checkstyle:RedundantModifier")
- public Proxy() {
- }
-
- Proxy(final AppendEntries appendEntries) {
- this.appendEntries = appendEntries;
- }
-
- @Override
- public void writeExternal(final ObjectOutput out) throws IOException {
- out.writeLong(appendEntries.getTerm());
- out.writeObject(appendEntries.leaderId);
- out.writeLong(appendEntries.prevLogTerm);
- out.writeLong(appendEntries.prevLogIndex);
- out.writeLong(appendEntries.leaderCommit);
- out.writeLong(appendEntries.replicatedToAllIndex);
- out.writeShort(appendEntries.payloadVersion);
-
- out.writeInt(appendEntries.entries.size());
- for (ReplicatedLogEntry e: appendEntries.entries) {
- out.writeLong(e.getIndex());
- out.writeLong(e.getTerm());
- out.writeObject(e.getData());
- }
- }
-
- @Override
- public void readExternal(final ObjectInput in) throws IOException, ClassNotFoundException {
- long term = in.readLong();
- String leaderId = (String) in.readObject();
- long prevLogTerm = in.readLong();
- long prevLogIndex = in.readLong();
- long leaderCommit = in.readLong();
- long replicatedToAllIndex = in.readLong();
- short payloadVersion = in.readShort();
-
- int size = in.readInt();
- List<ReplicatedLogEntry> entries = new ArrayList<>(size);
- for (int i = 0; i < size; i++) {
- entries.add(new SimpleReplicatedLogEntry(in.readLong(), in.readLong(), (Payload) in.readObject()));
- }
-
- appendEntries = new AppendEntries(term, leaderId, prevLogIndex, prevLogTerm, entries, leaderCommit,
- replicatedToAllIndex, payloadVersion, RaftVersions.CURRENT_VERSION, RaftVersions.BORON_VERSION, null);
- }
-
+ @java.io.Serial
private Object readResolve() {
return appendEntries;
}
* Reply for the AppendEntries message.
*/
public final class AppendEntriesReply extends AbstractRaftRPC {
+ @java.io.Serial
private static final long serialVersionUID = -7487547356392536683L;
// true if follower contained entry matching
@Override
Object writeReplace() {
- if (recipientRaftVersion <= RaftVersions.BORON_VERSION) {
- return new Proxy(this);
- }
- return recipientRaftVersion == RaftVersions.FLUORINE_VERSION ? new Proxy2(this) : new AR(this);
+ return recipientRaftVersion <= RaftVersions.FLUORINE_VERSION ? new Proxy2(this) : new AR(this);
}
/**
* Fluorine version that adds the needsLeaderAddress flag.
*/
private static class Proxy2 implements Externalizable {
+ @java.io.Serial
private static final long serialVersionUID = 1L;
private AppendEntriesReply appendEntriesReply;
RaftVersions.CURRENT_VERSION);
}
- private Object readResolve() {
- return appendEntriesReply;
- }
- }
-
- /**
- * Pre-Fluorine version.
- */
- @Deprecated
- private static class Proxy implements Externalizable {
- private static final long serialVersionUID = 1L;
-
- private AppendEntriesReply appendEntriesReply;
-
- // checkstyle flags the public modifier as redundant which really doesn't make sense since it clearly isn't
- // redundant. It is explicitly needed for Java serialization to be able to create instances via reflection.
- @SuppressWarnings("checkstyle:RedundantModifier")
- public Proxy() {
- }
-
- Proxy(final AppendEntriesReply appendEntriesReply) {
- this.appendEntriesReply = appendEntriesReply;
- }
-
- @Override
- public void writeExternal(final ObjectOutput out) throws IOException {
- out.writeShort(appendEntriesReply.raftVersion);
- out.writeLong(appendEntriesReply.getTerm());
- out.writeObject(appendEntriesReply.followerId);
- out.writeBoolean(appendEntriesReply.success);
- out.writeLong(appendEntriesReply.logLastIndex);
- out.writeLong(appendEntriesReply.logLastTerm);
- out.writeShort(appendEntriesReply.payloadVersion);
- out.writeBoolean(appendEntriesReply.forceInstallSnapshot);
- }
-
- @Override
- public void readExternal(final ObjectInput in) throws IOException, ClassNotFoundException {
- short raftVersion = in.readShort();
- long term = in.readLong();
- String followerId = (String) in.readObject();
- boolean success = in.readBoolean();
- long logLastIndex = in.readLong();
- long logLastTerm = in.readLong();
- short payloadVersion = in.readShort();
- boolean forceInstallSnapshot = in.readBoolean();
-
- appendEntriesReply = new AppendEntriesReply(followerId, term, success, logLastIndex, logLastTerm,
- payloadVersion, forceInstallSnapshot, false, raftVersion, RaftVersions.CURRENT_VERSION);
- }
-
+ @java.io.Serial
private Object readResolve() {
return appendEntriesReply;
}
out.writeInt(installSnapshot.getTotalChunks());
if (lastChunkHashCode.isPresent()) {
- out.writeInt(lastChunkHashCode.getAsInt());
+ out.writeInt(lastChunkHashCode.orElseThrow());
}
if (serverConfig.isPresent()) {
- out.writeObject(serverConfig.get());
+ out.writeObject(serverConfig.orElseThrow());
}
out.writeObject(installSnapshot.getData());
import org.opendaylight.yangtools.concepts.Identifier;
public abstract class IdentifiablePayload<T extends Identifier> extends Payload implements Identifiable<T> {
+ @java.io.Serial
private static final long serialVersionUID = 1L;
-
}
* Message sent from a leader to install a snapshot chunk on a follower.
*/
public final class InstallSnapshot extends AbstractRaftRPC {
+ @java.io.Serial
private static final long serialVersionUID = 1L;
private final String leaderId;
private final Optional<ServerConfigurationPayload> serverConfig;
private final short recipientRaftVersion;
- @SuppressFBWarnings(value = "EI_EXPOSE_REP2", justification = "Stores a reference to an externally mutable byte[] "
- + "object but this is OK since this class is merely a DTO and does not process byte[] internally. "
- + "Also it would be inefficient to create a copy as the byte[] could be large.")
+ @SuppressFBWarnings(value = "EI_EXPOSE_REP2", justification = """
+ Stores a reference to an externally mutable byte[] object but this is OK since this class is merely a DTO and \
+ does not process byte[] internally. Also it would be inefficient to create a copy as the byte[] could be \
+ large.""")
public InstallSnapshot(final long term, final String leaderId, final long lastIncludedIndex,
final long lastIncludedTerm, final byte[] data, final int chunkIndex, final int totalChunks,
final OptionalInt lastChunkHashCode, final Optional<ServerConfigurationPayload> serverConfig,
return lastIncludedTerm;
}
- @SuppressFBWarnings(value = "EI_EXPOSE_REP", justification = "Exposes a mutable object stored in a field but "
- + "this is OK since this class is merely a DTO and does not process the byte[] internally. "
- + "Also it would be inefficient to create a return copy as the byte[] could be large.")
+ @SuppressFBWarnings(value = "EI_EXPOSE_REP", justification = """
+ Exposes a mutable object stored in a field but this is OK since this class is merely a DTO and does not \
+ process the byte[] internally. Also it would be inefficient to create a return copy as the byte[] could be \
+ large.""")
public byte[] getData() {
return data;
}
out.writeByte(installSnapshot.lastChunkHashCode.isPresent() ? 1 : 0);
if (installSnapshot.lastChunkHashCode.isPresent()) {
- out.writeInt(installSnapshot.lastChunkHashCode.getAsInt());
+ out.writeInt(installSnapshot.lastChunkHashCode.orElseThrow());
}
out.writeByte(installSnapshot.serverConfig.isPresent() ? 1 : 0);
if (installSnapshot.serverConfig.isPresent()) {
- out.writeObject(installSnapshot.serverConfig.get());
+ out.writeObject(installSnapshot.serverConfig.orElseThrow());
}
out.writeObject(installSnapshot.data);
*/
package org.opendaylight.controller.cluster.raft.messages;
-import java.io.Externalizable;
-import java.io.IOException;
-import java.io.ObjectInput;
-import java.io.ObjectOutput;
-
public final class InstallSnapshotReply extends AbstractRaftRPC {
+ @java.io.Serial
private static final long serialVersionUID = 642227896390779503L;
// The followerId - this will be used to figure out which follower is
Object writeReplace() {
return new IR(this);
}
-
- @Deprecated(since = "7.0.0", forRemoval = true)
- private static class Proxy implements Externalizable {
- @java.io.Serial
- private static final long serialVersionUID = 1L;
-
- private InstallSnapshotReply installSnapshotReply;
-
- // checkstyle flags the public modifier as redundant which really doesn't make sense since it clearly isn't
- // redundant. It is explicitly needed for Java serialization to be able to create instances via reflection.
- @SuppressWarnings("checkstyle:RedundantModifier")
- public Proxy() {
- }
-
- Proxy(final InstallSnapshotReply installSnapshotReply) {
- this.installSnapshotReply = installSnapshotReply;
- }
-
- @Override
- public void writeExternal(final ObjectOutput out) throws IOException {
- out.writeLong(installSnapshotReply.getTerm());
- out.writeObject(installSnapshotReply.followerId);
- out.writeInt(installSnapshotReply.chunkIndex);
- out.writeBoolean(installSnapshotReply.success);
- }
-
- @Override
- public void readExternal(final ObjectInput in) throws IOException, ClassNotFoundException {
- long term = in.readLong();
- String followerId = (String) in.readObject();
- int chunkIndex = in.readInt();
- boolean success = in.readBoolean();
-
- installSnapshotReply = new InstallSnapshotReply(term, followerId, chunkIndex, success);
- }
-
- @java.io.Serial
- private Object readResolve() {
- return installSnapshotReply;
- }
- }
}
* Similarly when state needs to be applied to the derived RaftActor it will be passed an instance of the Payload class.
*/
public abstract class Payload implements Serializable {
+ @java.io.Serial
private static final long serialVersionUID = 1L;
/**
*
* @return Serialization proxy
*/
+ @java.io.Serial
protected abstract Object writeReplace();
}
*/
package org.opendaylight.controller.cluster.raft.messages;
-import java.io.Externalizable;
-import java.io.IOException;
-import java.io.ObjectInput;
-import java.io.ObjectOutput;
-
/**
* Invoked by candidates to gather votes (§5.2).
*/
public final class RequestVote extends AbstractRaftRPC {
+ @java.io.Serial
private static final long serialVersionUID = -6967509186297108657L;
// candidate requesting vote
Object writeReplace() {
return new RV(this);
}
-
- @Deprecated(since = "7.0.0", forRemoval = true)
- private static class Proxy implements Externalizable {
- @java.io.Serial
- private static final long serialVersionUID = 1L;
-
- private RequestVote requestVote;
-
- // checkstyle flags the public modifier as redundant which really doesn't make sense since it clearly isn't
- // redundant. It is explicitly needed for Java serialization to be able to create instances via reflection.
- @SuppressWarnings("checkstyle:RedundantModifier")
- public Proxy() {
- }
-
- Proxy(final RequestVote requestVote) {
- this.requestVote = requestVote;
- }
-
- @Override
- public void writeExternal(final ObjectOutput out) throws IOException {
- out.writeLong(requestVote.getTerm());
- out.writeObject(requestVote.candidateId);
- out.writeLong(requestVote.lastLogIndex);
- out.writeLong(requestVote.lastLogTerm);
- }
-
- @Override
- public void readExternal(final ObjectInput in) throws IOException, ClassNotFoundException {
- long term = in.readLong();
- String candidateId = (String) in.readObject();
- long lastLogIndex = in.readLong();
- long lastLogTerm = in.readLong();
-
- requestVote = new RequestVote(term, candidateId, lastLogIndex, lastLogTerm);
- }
-
- @java.io.Serial
- private Object readResolve() {
- return requestVote;
- }
- }
}
*/
package org.opendaylight.controller.cluster.raft.messages;
-import java.io.Externalizable;
-import java.io.IOException;
-import java.io.ObjectInput;
-import java.io.ObjectOutput;
-
public final class RequestVoteReply extends AbstractRaftRPC {
+ @java.io.Serial
private static final long serialVersionUID = 8427899326488775660L;
// true means candidate received vote
Object writeReplace() {
return new VR(this);
}
-
- @Deprecated(since = "7.0.0", forRemoval = true)
- private static class Proxy implements Externalizable {
- @java.io.Serial
- private static final long serialVersionUID = 1L;
-
- private RequestVoteReply requestVoteReply;
-
- // checkstyle flags the public modifier as redundant which really doesn't make sense since it clearly isn't
- // redundant. It is explicitly needed for Java serialization to be able to create instances via reflection.
- @SuppressWarnings("checkstyle:RedundantModifier")
- public Proxy() {
- }
-
- Proxy(final RequestVoteReply requestVoteReply) {
- this.requestVoteReply = requestVoteReply;
- }
-
- @Override
- public void writeExternal(final ObjectOutput out) throws IOException {
- out.writeLong(requestVoteReply.getTerm());
- out.writeBoolean(requestVoteReply.voteGranted);
- }
-
- @Override
- public void readExternal(final ObjectInput in) throws IOException {
- long term = in.readLong();
- boolean voteGranted = in.readBoolean();
-
- requestVoteReply = new RequestVoteReply(term, voteGranted);
- }
-
- @java.io.Serial
- private Object readResolve() {
- return requestVoteReply;
- }
- }
}
package org.opendaylight.controller.cluster.raft.persisted;
import akka.dispatch.ControlMessage;
-import java.io.Externalizable;
-import java.io.IOException;
-import java.io.ObjectInput;
-import java.io.ObjectOutput;
import java.io.Serializable;
/**
*
* @author Thomas Pantelis
*/
-public sealed class ApplyJournalEntries implements Serializable, ControlMessage {
- @Deprecated(since = "7.0.0", forRemoval = true)
- private static final class Legacy extends ApplyJournalEntries implements LegacySerializable {
- @java.io.Serial
- private static final long serialVersionUID = 1L;
-
- Legacy(final long toIndex) {
- super(toIndex);
- }
- }
-
- @Deprecated(since = "7.0.0", forRemoval = true)
- private static final class Proxy implements Externalizable {
- @java.io.Serial
- private static final long serialVersionUID = 1L;
-
- private ApplyJournalEntries applyEntries = null;
-
- // checkstyle flags the public modifier as redundant which really doesn't make sense since it clearly isn't
- // redundant. It is explicitly needed for Java serialization to be able to create instances via reflection.
- @SuppressWarnings("checkstyle:RedundantModifier")
- public Proxy() {
- // For Externalizable
- }
-
- @Override
- public void writeExternal(final ObjectOutput out) throws IOException {
- out.writeLong(applyEntries.toIndex);
- }
-
- @Override
- public void readExternal(final ObjectInput in) throws IOException {
- applyEntries = new Legacy(in.readLong());
- }
-
- @java.io.Serial
- private Object readResolve() {
- return applyEntries;
- }
- }
-
+public final class ApplyJournalEntries implements Serializable, ControlMessage {
@java.io.Serial
private static final long serialVersionUID = 1L;
this.toIndex = toIndex;
}
- public final long getToIndex() {
+ public long getToIndex() {
return toIndex;
}
- @java.io.Serial
- public final Object writeReplace() {
- return new AJE(this);
- }
-
@Override
- public final String toString() {
+ public String toString() {
return "ApplyJournalEntries [toIndex=" + toIndex + "]";
}
+
+ @java.io.Serial
+ private Object writeReplace() {
+ return new AJE(this);
+ }
}
*/
package org.opendaylight.controller.cluster.raft.persisted;
-import java.io.Externalizable;
-import java.io.IOException;
-import java.io.ObjectInput;
-import java.io.ObjectOutput;
import java.io.Serializable;
/**
*
* @author Thomas Pantelis
*/
-public sealed class DeleteEntries implements Serializable {
- @Deprecated(since = "7.0.0", forRemoval = true)
- private static final class Legacy extends DeleteEntries implements LegacySerializable {
- @java.io.Serial
- private static final long serialVersionUID = 1L;
-
- Legacy(final long fromIndex) {
- super(fromIndex);
- }
- }
-
- @Deprecated(since = "7.0.0", forRemoval = true)
- private static final class Proxy implements Externalizable {
- @java.io.Serial
- private static final long serialVersionUID = 1L;
-
- private DeleteEntries deleteEntries = null;
-
- // checkstyle flags the public modifier as redundant which really doesn't make sense since it clearly isn't
- // redundant. It is explicitly needed for Java serialization to be able to create instances via reflection.
- @SuppressWarnings("checkstyle:RedundantModifier")
- public Proxy() {
- // For Externalizable
- }
-
- @Override
- public void writeExternal(final ObjectOutput out) throws IOException {
- out.writeLong(deleteEntries.fromIndex);
- }
-
- @Override
- public void readExternal(final ObjectInput in) throws IOException {
- deleteEntries = new Legacy(in.readLong());
- }
-
- @java.io.Serial
- private Object readResolve() {
- return deleteEntries;
- }
- }
-
+public final class DeleteEntries implements Serializable {
@java.io.Serial
private static final long serialVersionUID = 1L;
this.fromIndex = fromIndex;
}
- public final long getFromIndex() {
+ public long getFromIndex() {
return fromIndex;
}
- @java.io.Serial
- public final Object writeReplace() {
- return new DE(this);
- }
-
@Override
- public final String toString() {
+ public String toString() {
return "DeleteEntries [fromIndex=" + fromIndex + "]";
}
+
+ @java.io.Serial
+ private Object writeReplace() {
+ return new DE(this);
+ }
}
* @author Thomas Pantelis
*/
public final class EmptyState implements Snapshot.State {
+ @java.io.Serial
private static final long serialVersionUID = 1L;
public static final EmptyState INSTANCE = new EmptyState();
private EmptyState() {
+ // Hidden on purpose
}
+ @java.io.Serial
@SuppressWarnings("static-method")
private Object readResolve() {
return INSTANCE;
package org.opendaylight.controller.cluster.raft.persisted;
import akka.dispatch.ControlMessage;
-import java.io.Serializable;
import org.apache.commons.lang3.SerializationUtils;
import org.eclipse.jdt.annotation.NonNull;
import org.opendaylight.controller.cluster.raft.messages.Payload;
*
* @author Thomas Pantelis
*/
-// FIXME: do not implement MigratedSerializable once Proxy is gone
-public final class NoopPayload extends Payload implements ControlMessage, MigratedSerializable {
- // There is no need for Externalizable
- @Deprecated(since = "7.0.0", forRemoval = true)
- private static final class Proxy implements Serializable {
- @java.io.Serial
- private static final long serialVersionUID = 1L;
- private static final @NonNull NoopPayload INSTANCE = new NoopPayload(true);
-
- @java.io.Serial
- private Object readResolve() {
- return INSTANCE;
- }
- }
-
+public final class NoopPayload extends Payload implements ControlMessage {
@java.io.Serial
private static final long serialVersionUID = 1L;
private static final @NonNull NP PROXY = new NP();
// Estimate to how big the proxy is. Note this includes object stream overhead, so it is a bit conservative
private static final int PROXY_SIZE = SerializationUtils.serialize(PROXY).length;
- public static final @NonNull NoopPayload INSTANCE = new NoopPayload(false);
-
- private final boolean migrated;
+ public static final @NonNull NoopPayload INSTANCE = new NoopPayload();
- private NoopPayload(final boolean migrated) {
- this.migrated = migrated;
+ private NoopPayload() {
+ // Hidden on purpose
}
@Override
}
@Override
- public boolean isMigrated() {
- return migrated;
- }
-
- // FIXME: protected once not MigratedSerializable
- @Override
- public Object writeReplace() {
+ protected Object writeReplace() {
return PROXY;
}
}
import static com.google.common.base.Verify.verifyNotNull;
import static java.util.Objects.requireNonNull;
+import com.google.common.collect.ImmutableList;
import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
-import java.util.ArrayList;
import org.opendaylight.controller.cluster.raft.ReplicatedLogEntry;
import org.opendaylight.controller.cluster.raft.messages.Payload;
import org.opendaylight.controller.cluster.raft.persisted.Snapshot.State;
ServerConfigurationPayload serverConfig = (ServerConfigurationPayload) in.readObject();
int size = in.readInt();
- var unAppliedEntries = new ArrayList<ReplicatedLogEntry>(size);
+ var unAppliedEntries = ImmutableList.<ReplicatedLogEntry>builderWithExpectedSize(size);
for (int i = 0; i < size; i++) {
hdr = WritableObjects.readLongHeader(in);
unAppliedEntries.add(new SimpleReplicatedLogEntry(
State state = (State) in.readObject();
- snapshot = Snapshot.create(state, unAppliedEntries, lastIndex, lastTerm, lastAppliedIndex, lastAppliedTerm,
- electionTerm, electionVotedFor, serverConfig);
+ snapshot = Snapshot.create(state, unAppliedEntries.build(), lastIndex, lastTerm, lastAppliedIndex,
+ lastAppliedTerm, electionTerm, electionVotedFor, serverConfig);
}
@java.io.Serial
import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
-import java.util.ArrayList;
import java.util.List;
import org.eclipse.jdt.annotation.NonNull;
import org.opendaylight.controller.cluster.raft.messages.Payload;
*/
public final class ServerConfigurationPayload extends Payload implements PersistentPayload {
private static final class Proxy implements Externalizable {
+ @java.io.Serial
private static final long serialVersionUID = 1L;
private List<ServerInfo> serverConfig;
@Override
public void writeExternal(final ObjectOutput out) throws IOException {
out.writeInt(serverConfig.size());
- for (ServerInfo i : serverConfig) {
- out.writeObject(i.getId());
- out.writeBoolean(i.isVoting());
+ for (var serverInfo : serverConfig) {
+ out.writeObject(serverInfo.peerId());
+ out.writeBoolean(serverInfo.isVoting());
}
}
@Override
public void readExternal(final ObjectInput in) throws IOException, ClassNotFoundException {
final int size = in.readInt();
- serverConfig = new ArrayList<>(size);
+
+ final var builder = ImmutableList.<ServerInfo>builderWithExpectedSize(size);
for (int i = 0; i < size; ++i) {
final String id = (String) in.readObject();
final boolean voting = in.readBoolean();
- serverConfig.add(new ServerInfo(id, voting));
+ builder.add(new ServerInfo(id, voting));
}
+ serverConfig = builder.build();
}
+ @java.io.Serial
private Object readResolve() {
return new ServerConfigurationPayload(serverConfig);
}
}
private static final Logger LOG = LoggerFactory.getLogger(ServerConfigurationPayload.class);
+ @java.io.Serial
private static final long serialVersionUID = 1L;
@SuppressFBWarnings(value = "SE_BAD_FIELD", justification = "This field is not Serializable but this class "
}
@Override
- public boolean equals(Object obj) {
- if (this == obj) {
- return true;
- }
-
- if (obj == null) {
- return false;
- }
-
- if (getClass() != obj.getClass()) {
- return false;
- }
-
- ServerConfigurationPayload other = (ServerConfigurationPayload) obj;
- return serverConfig.equals(other.serverConfig);
+ public boolean equals(final Object obj) {
+ return this == obj || obj instanceof ServerConfigurationPayload other
+ && serverConfig.equals(other.serverConfig);
}
@Override
*
* @author Thomas Pantelis
*/
-public final class ServerInfo {
- private final @NonNull String id;
- private final boolean isVoting;
-
- public ServerInfo(final @NonNull String id, final boolean isVoting) {
- this.id = requireNonNull(id);
- this.isVoting = isVoting;
- }
-
- public @NonNull String getId() {
- return id;
- }
-
- public boolean isVoting() {
- return isVoting;
- }
-
- @Override
- public int hashCode() {
- final int prime = 31;
- int result = 1;
- result = prime * result + Boolean.hashCode(isVoting);
- result = prime * result + id.hashCode();
- return result;
- }
-
- @Override
- public boolean equals(final Object obj) {
- return this == obj || obj instanceof ServerInfo other && isVoting == other.isVoting && id.equals(other.id);
- }
-
- @Override
- public String toString() {
- return "ServerInfo [id=" + id + ", isVoting=" + isVoting + "]";
+public record ServerInfo(@NonNull String peerId, boolean isVoting) {
+ public ServerInfo {
+ requireNonNull(peerId);
}
}
\ No newline at end of file
import static java.util.Objects.requireNonNull;
-import java.io.Externalizable;
-import java.io.IOException;
-import java.io.ObjectInput;
-import java.io.ObjectOutput;
import java.io.Serializable;
import org.apache.commons.lang3.SerializationUtils;
import org.opendaylight.controller.cluster.raft.ReplicatedLogEntry;
*
* @author Thomas Pantelis
*/
-public sealed class SimpleReplicatedLogEntry implements ReplicatedLogEntry, Serializable {
- @Deprecated(since = "7.0.0", forRemoval = true)
- private static final class Legacy extends SimpleReplicatedLogEntry implements LegacySerializable {
- @java.io.Serial
- private static final long serialVersionUID = 1L;
-
- Legacy(final long index, final long term, final Payload payload) {
- super(index, term, payload);
- }
- }
-
- @Deprecated(since = "7.0.0", forRemoval = true)
- private static final class Proxy implements Externalizable {
- @java.io.Serial
- private static final long serialVersionUID = 1L;
-
- private long index;
- private long term;
- private Payload data;
-
- // checkstyle flags the public modifier as redundant which really doesn't make sense since it clearly isn't
- // redundant. It is explicitly needed for Java serialization to be able to create instances via reflection.
- @SuppressWarnings("checkstyle:RedundantModifier")
- public Proxy() {
- // For Externalizable
- }
-
- Proxy(final SimpleReplicatedLogEntry replicatedLogEntry) {
- index = replicatedLogEntry.getIndex();
- term = replicatedLogEntry.getTerm();
- data = replicatedLogEntry.getData();
- }
-
- @Override
- public void writeExternal(final ObjectOutput out) throws IOException {
- out.writeLong(index);
- out.writeLong(term);
- out.writeObject(data);
- }
-
- @Override
- public void readExternal(final ObjectInput in) throws IOException, ClassNotFoundException {
- index = in.readLong();
- term = in.readLong();
- data = (Payload) in.readObject();
- }
-
- @java.io.Serial
- private Object readResolve() {
- return new Legacy(index, term, data);
- }
- }
-
+public final class SimpleReplicatedLogEntry implements ReplicatedLogEntry, Serializable {
@java.io.Serial
private static final long serialVersionUID = 1L;
// Estimate to how big the proxy is. Note this includes object stream overhead, so it is a bit conservative.
}
@Override
- public final Payload getData() {
+ public Payload getData() {
return payload;
}
@Override
- public final long getTerm() {
+ public long getTerm() {
return term;
}
@Override
- public final long getIndex() {
+ public long getIndex() {
return index;
}
@Override
- public final int size() {
+ public int size() {
return payload.size();
}
@Override
- public final int serializedSize() {
+ public int serializedSize() {
return PROXY_SIZE + payload.serializedSize();
}
@Override
- public final boolean isPersistencePending() {
+ public boolean isPersistencePending() {
return persistencePending;
}
@Override
- public final void setPersistencePending(final boolean pending) {
+ public void setPersistencePending(final boolean pending) {
persistencePending = pending;
}
- @java.io.Serial
- public final Object writeReplace() {
- return new LE(this);
- }
-
@Override
- public final int hashCode() {
+ public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + payload.hashCode();
}
@Override
- public final boolean equals(final Object obj) {
+ public boolean equals(final Object obj) {
return this == obj || obj instanceof SimpleReplicatedLogEntry other && index == other.index
&& term == other.term && payload.equals(other.payload);
}
@Override
- public final String toString() {
+ public String toString() {
return "SimpleReplicatedLogEntry [index=" + index + ", term=" + term + ", payload=" + payload + "]";
}
+
+ @java.io.Serial
+ private Object writeReplace() {
+ return new LE(this);
+ }
}
*/
package org.opendaylight.controller.cluster.raft.persisted;
-import java.io.Externalizable;
-import java.io.IOException;
-import java.io.ObjectInput;
-import java.io.ObjectOutput;
import java.io.Serializable;
-import java.util.ArrayList;
import java.util.List;
import org.opendaylight.controller.cluster.raft.ReplicatedLogEntry;
-import org.opendaylight.controller.cluster.raft.messages.Payload;
/**
* Represents a snapshot of the raft data.
*
* @author Thomas Pantelis
*/
-public sealed class Snapshot implements Serializable {
+public final class Snapshot implements Serializable {
/**
* Implementations of this interface are used as the state payload for a snapshot.
*
}
}
- @Deprecated(since = "7.0.0", forRemoval = true)
- private static final class Legacy extends Snapshot implements LegacySerializable {
- @java.io.Serial
- private static final long serialVersionUID = 1L;
-
- Legacy(final State state, final List<ReplicatedLogEntry> unAppliedEntries, final long lastIndex,
- final long lastTerm, final long lastAppliedIndex, final long lastAppliedTerm, final long electionTerm,
- final String electionVotedFor, final ServerConfigurationPayload serverConfig) {
- super(state, unAppliedEntries, lastIndex, lastTerm, lastAppliedIndex, lastAppliedTerm, electionTerm,
- electionVotedFor, serverConfig);
- }
- }
-
- @Deprecated(since = "7.0.0", forRemoval = true)
- private static final class Proxy implements Externalizable {
- @java.io.Serial
- private static final long serialVersionUID = 1L;
-
- private Snapshot snapshot = null;
-
- // checkstyle flags the public modifier as redundant which really doesn't make sense since it clearly isn't
- // redundant. It is explicitly needed for Java serialization to be able to create instances via reflection.
- @SuppressWarnings("checkstyle:RedundantModifier")
- public Proxy() {
- // For Externalizable
- }
-
- @Override
- public void writeExternal(final ObjectOutput out) throws IOException {
- out.writeLong(snapshot.lastIndex);
- out.writeLong(snapshot.lastTerm);
- out.writeLong(snapshot.lastAppliedIndex);
- out.writeLong(snapshot.lastAppliedTerm);
- out.writeLong(snapshot.electionTerm);
- out.writeObject(snapshot.electionVotedFor);
- out.writeObject(snapshot.serverConfig);
-
- out.writeInt(snapshot.unAppliedEntries.size());
- for (ReplicatedLogEntry e: snapshot.unAppliedEntries) {
- out.writeLong(e.getIndex());
- out.writeLong(e.getTerm());
- out.writeObject(e.getData());
- }
-
- out.writeObject(snapshot.state);
- }
-
- @Override
- public void readExternal(final ObjectInput in) throws IOException, ClassNotFoundException {
- long lastIndex = in.readLong();
- long lastTerm = in.readLong();
- long lastAppliedIndex = in.readLong();
- long lastAppliedTerm = in.readLong();
- long electionTerm = in.readLong();
- String electionVotedFor = (String) in.readObject();
- ServerConfigurationPayload serverConfig = (ServerConfigurationPayload) in.readObject();
-
- int size = in.readInt();
- var unAppliedEntries = new ArrayList<ReplicatedLogEntry>(size);
- for (int i = 0; i < size; i++) {
- unAppliedEntries.add(new SimpleReplicatedLogEntry(in.readLong(), in.readLong(),
- (Payload) in.readObject()));
- }
-
- State state = (State) in.readObject();
-
- snapshot = new Legacy(state, unAppliedEntries, lastIndex, lastTerm, lastAppliedIndex, lastAppliedTerm,
- electionTerm, electionVotedFor, serverConfig);
- }
-
- @java.io.Serial
- private Object readResolve() {
- return snapshot;
- }
- }
-
@java.io.Serial
private static final long serialVersionUID = 1L;
private final String electionVotedFor;
private final ServerConfigurationPayload serverConfig;
- Snapshot(final State state, final List<ReplicatedLogEntry> unAppliedEntries, final long lastIndex,
+ private Snapshot(final State state, final List<ReplicatedLogEntry> unAppliedEntries, final long lastIndex,
final long lastTerm, final long lastAppliedIndex, final long lastAppliedTerm, final long electionTerm,
final String electionVotedFor, final ServerConfigurationPayload serverConfig) {
this.state = state;
return serverConfig;
}
- @java.io.Serial
- public final Object writeReplace() {
- return new SS(this);
- }
-
@Override
- public final String toString() {
+ public String toString() {
return "Snapshot [lastIndex=" + lastIndex + ", lastTerm=" + lastTerm + ", lastAppliedIndex=" + lastAppliedIndex
+ ", lastAppliedTerm=" + lastAppliedTerm + ", unAppliedEntries size=" + unAppliedEntries.size()
+ ", state=" + state + ", electionTerm=" + electionTerm + ", electionVotedFor="
+ electionVotedFor + ", ServerConfigPayload=" + serverConfig + "]";
}
+
+ @java.io.Serial
+ private Object writeReplace() {
+ return new SS(this);
+ }
}
*/
package org.opendaylight.controller.cluster.raft.persisted;
-import java.io.Externalizable;
-import java.io.IOException;
-import java.io.ObjectInput;
-import java.io.ObjectOutput;
import java.io.Serializable;
/**
* Message class to persist election term information.
*/
-public sealed class UpdateElectionTerm implements Serializable {
- @Deprecated(since = "7.0.0", forRemoval = true)
- private static final class Legacy extends UpdateElectionTerm implements LegacySerializable {
- @java.io.Serial
- private static final long serialVersionUID = 1L;
-
- Legacy(final long currentTerm, final String votedFor) {
- super(currentTerm, votedFor);
- }
- }
-
- @Deprecated(since = "7.0.0", forRemoval = true)
- private static final class Proxy implements Externalizable {
- @java.io.Serial
- private static final long serialVersionUID = 1L;
-
- private UpdateElectionTerm updateElectionTerm = null;
-
- // checkstyle flags the public modifier as redundant which really doesn't make sense since it clearly isn't
- // redundant. It is explicitly needed for Java serialization to be able to create instances via reflection.
- @SuppressWarnings("checkstyle:RedundantModifier")
- public Proxy() {
- // For Externalizable
- }
-
- @Override
- public void writeExternal(final ObjectOutput out) throws IOException {
- out.writeLong(updateElectionTerm.currentTerm);
- out.writeObject(updateElectionTerm.votedFor);
- }
-
- @Override
- public void readExternal(final ObjectInput in) throws IOException, ClassNotFoundException {
- updateElectionTerm = new Legacy(in.readLong(), (String) in.readObject());
- }
-
- @java.io.Serial
- private Object readResolve() {
- return updateElectionTerm;
- }
- }
-
+public final class UpdateElectionTerm implements Serializable {
@java.io.Serial
private static final long serialVersionUID = 1L;
this.votedFor = votedFor;
}
- public final long getCurrentTerm() {
+ public long getCurrentTerm() {
return currentTerm;
}
- public final String getVotedFor() {
+ public String getVotedFor() {
return votedFor;
}
- @java.io.Serial
- public final Object writeReplace() {
- return new UT(this);
- }
-
@Override
- public final String toString() {
+ public String toString() {
return "UpdateElectionTerm [currentTerm=" + currentTerm + ", votedFor=" + votedFor + "]";
}
+
+ @java.io.Serial
+ private Object writeReplace() {
+ return new UT(this);
+ }
}
*/
package org.opendaylight.controller.cluster.raft;
-import static akka.pattern.Patterns.ask;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import akka.actor.Terminated;
import akka.dispatch.Dispatchers;
import akka.dispatch.Mailboxes;
+import akka.pattern.Patterns;
import akka.testkit.TestActorRef;
import akka.testkit.javadsl.TestKit;
import akka.util.Timeout;
import com.google.common.base.Stopwatch;
-import com.google.common.collect.ImmutableMap;
import com.google.common.util.concurrent.Uninterruptibles;
import java.io.OutputStream;
import java.time.Duration;
import java.util.ArrayList;
-import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;
@Override
@SuppressWarnings("checkstyle:IllegalCatch")
public void createSnapshot(final ActorRef actorRef, final Optional<OutputStream> installSnapshotStream) {
- MockSnapshotState snapshotState = new MockSnapshotState(new ArrayList<>(getState()));
+ MockSnapshotState snapshotState = new MockSnapshotState(List.copyOf(getState()));
if (installSnapshotStream.isPresent()) {
- SerializationUtils.serialize(snapshotState, installSnapshotStream.get());
+ SerializationUtils.serialize(snapshotState, installSnapshotStream.orElseThrow());
}
actorRef.tell(new CaptureSnapshotReply(snapshotState, installSnapshotStream), actorRef);
}
// FIXME: this is an arbitrary limit. Document interactions and/or improve them to improve maintainability
- protected static final int SNAPSHOT_CHUNK_SIZE = 700;
+ protected static final int MAXIMUM_MESSAGE_SLICE_SIZE = 700;
protected final Logger testLog = LoggerFactory.getLogger(getClass());
protected String follower2Id = factory.generateActorId("follower");
protected TestActorRef<TestRaftActor> follower2Actor;
protected ActorRef follower2CollectorActor;
- protected RaftActorBehavior follower2;
+ protected RaftActorBehavior follower2;
protected RaftActorContext follower2Context;
- protected ImmutableMap<String, String> peerAddresses;
+ protected Map<String, String> peerAddresses;
protected long initialTerm = 5;
protected long currentTerm;
protected int snapshotBatchCount = 4;
- protected int snapshotChunkSize = SNAPSHOT_CHUNK_SIZE;
+ protected int maximumMessageSliceSize = MAXIMUM_MESSAGE_SLICE_SIZE;
protected List<MockPayload> expSnapshotState = new ArrayList<>();
configParams.setSnapshotBatchCount(snapshotBatchCount);
configParams.setSnapshotDataThresholdPercentage(70);
configParams.setIsolatedLeaderCheckInterval(new FiniteDuration(1, TimeUnit.DAYS));
- configParams.setSnapshotChunkSize(snapshotChunkSize);
+ configParams.setMaximumMessageSliceSize(maximumMessageSliceSize);
return configParams;
}
protected TestActorRef<TestRaftActor> newTestRaftActor(final String id, final Map<String, String> newPeerAddresses,
final ConfigParams configParams) {
return newTestRaftActor(id, TestRaftActor.newBuilder().peerAddresses(newPeerAddresses != null
- ? newPeerAddresses : Collections.<String, String>emptyMap()).config(configParams));
+ ? newPeerAddresses : Map.of()).config(configParams));
}
protected TestActorRef<TestRaftActor> newTestRaftActor(final String id, final TestRaftActor.Builder builder) {
Stopwatch sw = Stopwatch.createStarted();
while (sw.elapsed(TimeUnit.SECONDS) <= 5) {
try {
- OnDemandRaftState raftState = (OnDemandRaftState)Await.result(ask(raftActor,
+ OnDemandRaftState raftState = (OnDemandRaftState)Await.result(Patterns.ask(raftActor,
GetOnDemandRaftState.INSTANCE, timeout), timeout.duration());
verifier.accept(raftState);
return;
import akka.pattern.Patterns;
import akka.testkit.TestActorRef;
import akka.testkit.javadsl.TestKit;
-import com.google.common.collect.ImmutableMap;
-import java.util.Arrays;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
+import java.util.Map;
import java.util.concurrent.TimeUnit;
import org.junit.Test;
import org.opendaylight.controller.cluster.notifications.LeaderStateChanged;
private void createRaftActors() {
testLog.info("createRaftActors starting");
- final Snapshot snapshot = Snapshot.create(EmptyState.INSTANCE, Collections.emptyList(), -1, -1, -1, -1,
+ final Snapshot snapshot = Snapshot.create(EmptyState.INSTANCE, List.of(), -1, -1, -1, -1,
1, null, new org.opendaylight.controller.cluster.raft.persisted.ServerConfigurationPayload(
- Arrays.asList(new ServerInfo(leaderId, true), new ServerInfo(follower1Id, true),
+ List.of(new ServerInfo(leaderId, true), new ServerInfo(follower1Id, true),
new ServerInfo(follower2Id, true), new ServerInfo(follower3Id, false))));
InMemorySnapshotStore.addSnapshot(leaderId, snapshot);
follower1NotifierActor = factory.createActor(MessageCollectorActor.props(),
factory.generateActorId(follower1Id + "-notifier"));
follower1Actor = newTestRaftActor(follower1Id, TestRaftActor.newBuilder().peerAddresses(
- ImmutableMap.of(leaderId, testActorPath(leaderId), follower2Id, testActorPath(follower2Id),
+ Map.of(leaderId, testActorPath(leaderId), follower2Id, testActorPath(follower2Id),
follower3Id, testActorPath(follower3Id)))
.config(newFollowerConfigParams()).roleChangeNotifier(follower1NotifierActor));
follower2NotifierActor = factory.createActor(MessageCollectorActor.props(),
factory.generateActorId(follower2Id + "-notifier"));
follower2Actor = newTestRaftActor(follower2Id,TestRaftActor.newBuilder().peerAddresses(
- ImmutableMap.of(leaderId, testActorPath(leaderId), follower1Id, follower1Actor.path().toString(),
+ Map.of(leaderId, testActorPath(leaderId), follower1Id, follower1Actor.path().toString(),
follower3Id, testActorPath(follower3Id)))
.config(newFollowerConfigParams()).roleChangeNotifier(follower2NotifierActor));
follower3NotifierActor = factory.createActor(MessageCollectorActor.props(),
factory.generateActorId(follower3Id + "-notifier"));
follower3Actor = newTestRaftActor(follower3Id,TestRaftActor.newBuilder().peerAddresses(
- ImmutableMap.of(leaderId, testActorPath(leaderId), follower1Id, follower1Actor.path().toString(),
+ Map.of(leaderId, testActorPath(leaderId), follower1Id, follower1Actor.path().toString(),
follower2Id, follower2Actor.path().toString()))
.config(newFollowerConfigParams()).roleChangeNotifier(follower3NotifierActor));
- peerAddresses = ImmutableMap.<String, String>builder()
- .put(follower1Id, follower1Actor.path().toString())
- .put(follower2Id, follower2Actor.path().toString())
- .put(follower3Id, follower3Actor.path().toString()).build();
+ peerAddresses = Map.of(
+ follower1Id, follower1Actor.path().toString(),
+ follower2Id, follower2Actor.path().toString(),
+ follower3Id, follower3Actor.path().toString());
leaderConfigParams = newLeaderConfigParams();
leaderConfigParams.setElectionTimeoutFactor(3);
import java.util.Collections;
import java.util.List;
import java.util.Map;
+import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
super(builder.id, builder.peerAddresses != null ? builder.peerAddresses :
Collections.emptyMap(), Optional.ofNullable(builder.config), PAYLOAD_VERSION);
state = Collections.synchronizedList(new ArrayList<>());
- this.actorDelegate = mock(RaftActor.class);
- this.recoveryCohortDelegate = mock(RaftActorRecoveryCohort.class);
+ actorDelegate = mock(RaftActor.class);
+ recoveryCohortDelegate = mock(RaftActorRecoveryCohort.class);
- this.snapshotCohortDelegate = builder.snapshotCohort != null ? builder.snapshotCohort :
+ snapshotCohortDelegate = builder.snapshotCohort != null ? builder.snapshotCohort :
mock(RaftActorSnapshotCohort.class);
if (builder.dataPersistenceProvider == null) {
- setPersistence(builder.persistent.isPresent() ? builder.persistent.get() : true);
+ setPersistence(builder.persistent.isPresent() ? builder.persistent.orElseThrow() : true);
} else {
setPersistence(builder.dataPersistenceProvider);
}
}
private void applySnapshotState(final Snapshot.State newState) {
- if (newState instanceof MockSnapshotState) {
+ if (newState instanceof MockSnapshotState mockState) {
state.clear();
- state.addAll(((MockSnapshotState)newState).getState());
+ state.addAll(mockState.getState());
}
}
}
@Override public String persistenceId() {
- return this.getId();
+ return getId();
}
protected void newBehavior(final RaftActorBehavior newBehavior) {
}
public static List<Object> fromState(final Snapshot.State from) {
- if (from instanceof MockSnapshotState) {
- return ((MockSnapshotState)from).getState();
+ if (from instanceof MockSnapshotState mockState) {
+ return mockState.getState();
}
throw new IllegalStateException("Unexpected snapshot State: " + from);
}
public ReplicatedLog getReplicatedLog() {
- return this.getRaftActorContext().getReplicatedLog();
+ return getRaftActorContext().getReplicatedLog();
}
@Override
}
public T id(final String newId) {
- this.id = newId;
+ id = newId;
return self();
}
public T peerAddresses(final Map<String, String> newPeerAddresses) {
- this.peerAddresses = newPeerAddresses;
+ peerAddresses = newPeerAddresses;
return self();
}
public T config(final ConfigParams newConfig) {
- this.config = newConfig;
+ config = newConfig;
return self();
}
public T dataPersistenceProvider(final DataPersistenceProvider newDataPersistenceProvider) {
- this.dataPersistenceProvider = newDataPersistenceProvider;
+ dataPersistenceProvider = newDataPersistenceProvider;
return self();
}
public T roleChangeNotifier(final ActorRef newRoleChangeNotifier) {
- this.roleChangeNotifier = newRoleChangeNotifier;
+ roleChangeNotifier = newRoleChangeNotifier;
return self();
}
public T snapshotMessageSupport(final RaftActorSnapshotMessageSupport newSnapshotMessageSupport) {
- this.snapshotMessageSupport = newSnapshotMessageSupport;
+ snapshotMessageSupport = newSnapshotMessageSupport;
return self();
}
public T restoreFromSnapshot(final Snapshot newRestoreFromSnapshot) {
- this.restoreFromSnapshot = newRestoreFromSnapshot;
+ restoreFromSnapshot = newRestoreFromSnapshot;
return self();
}
public T persistent(final Optional<Boolean> newPersistent) {
- this.persistent = newPersistent;
+ persistent = newPersistent;
return self();
}
public T pauseLeaderFunction(final Function<Runnable, Void> newPauseLeaderFunction) {
- this.pauseLeaderFunction = newPauseLeaderFunction;
+ pauseLeaderFunction = newPauseLeaderFunction;
return self();
}
public T snapshotCohort(final RaftActorSnapshotCohort newSnapshotCohort) {
- this.snapshotCohort = newSnapshotCohort;
+ snapshotCohort = newSnapshotCohort;
return self();
}
@Override
public int hashCode() {
- final int prime = 31;
- int result = 1;
- result = prime * result + (state == null ? 0 : state.hashCode());
- return result;
+ return Objects.hash(state);
}
@Override
return false;
}
MockSnapshotState other = (MockSnapshotState) obj;
- if (state == null) {
- if (other.state != null) {
- return false;
- }
- } else if (!state.equals(other.state)) {
+ if (!Objects.equals(state, other.state)) {
return false;
}
return true;
import static org.junit.Assert.assertEquals;
import akka.actor.ActorRef;
-import com.google.common.collect.ImmutableMap;
-import com.google.common.collect.Sets;
-import java.util.Arrays;
+import java.util.List;
+import java.util.Map;
import java.util.Optional;
+import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.junit.Test;
import org.opendaylight.controller.cluster.notifications.LeaderStateChanged;
//
// We also add another voting follower actor into the mix even though it shoildn't affect the
// outcome.
- ServerConfigurationPayload persistedServerConfig = new ServerConfigurationPayload(Arrays.asList(
+ ServerConfigurationPayload persistedServerConfig = new ServerConfigurationPayload(List.of(
new ServerInfo(leaderId, true), new ServerInfo(follower1Id, false),
new ServerInfo(follower2Id, true), new ServerInfo("downPeer", false)));
SimpleReplicatedLogEntry persistedServerConfigEntry = new SimpleReplicatedLogEntry(0, currentTerm,
DefaultConfigParamsImpl follower2ConfigParams = newFollowerConfigParams();
follower2ConfigParams.setCustomRaftPolicyImplementationClass(DisableElectionsRaftPolicy.class.getName());
follower2Actor = newTestRaftActor(follower2Id, TestRaftActor.newBuilder().peerAddresses(
- ImmutableMap.of(leaderId, testActorPath(leaderId), follower1Id, follower1Actor.path().toString()))
+ Map.of(leaderId, testActorPath(leaderId), follower1Id, follower1Actor.path().toString()))
.config(follower2ConfigParams).persistent(Optional.of(false)));
TestRaftActor follower2Instance = follower2Actor.underlyingActor();
follower2Instance.waitForRecoveryComplete();
follower2CollectorActor = follower2Instance.collectorActor();
- peerAddresses = ImmutableMap.of(follower1Id, follower1Actor.path().toString(),
+ peerAddresses = Map.of(follower1Id, follower1Actor.path().toString(),
follower2Id, follower2Actor.path().toString());
createNewLeaderActor();
// Set up a persisted ServerConfigurationPayload with the leader voting and the follower non-voting.
- ServerConfigurationPayload persistedServerConfig = new ServerConfigurationPayload(Arrays.asList(
+ ServerConfigurationPayload persistedServerConfig = new ServerConfigurationPayload(List.of(
new ServerInfo(leaderId, true), new ServerInfo(follower1Id, false)));
SimpleReplicatedLogEntry persistedServerConfigEntry = new SimpleReplicatedLogEntry(0, persistedTerm,
persistedServerConfig);
DefaultConfigParamsImpl followerConfigParams = newFollowerConfigParams();
follower1Actor = newTestRaftActor(follower1Id, follower1Builder.peerAddresses(
- ImmutableMap.of(leaderId, testActorPath(leaderId))).config(followerConfigParams)
+ Map.of(leaderId, testActorPath(leaderId))).config(followerConfigParams)
.persistent(Optional.of(false)));
- peerAddresses = ImmutableMap.<String, String>builder()
- .put(follower1Id, follower1Actor.path().toString()).build();
+ peerAddresses = Map.of(follower1Id, follower1Actor.path().toString());
leaderConfigParams = newLeaderConfigParams();
leaderActor = newTestRaftActor(leaderId, TestRaftActor.newBuilder().peerAddresses(peerAddresses)
currentTerm = persistedTerm + 1;
assertEquals("Leader term", currentTerm, leaderContext.getTermInformation().getCurrentTerm());
- assertEquals("Leader server config", Sets.newHashSet(persistedServerConfig.getServerConfig()),
- Sets.newHashSet(leaderContext.getPeerServerInfo(true).getServerConfig()));
+ assertEquals("Leader server config", Set.copyOf(persistedServerConfig.getServerConfig()),
+ Set.copyOf(leaderContext.getPeerServerInfo(true).getServerConfig()));
assertEquals("Leader isVotingMember", true, leaderContext.isVotingMember());
// Verify follower's context after startup
MessageCollectorActor.expectFirstMatching(follower1CollectorActor, AppendEntries.class);
assertEquals("Follower term", currentTerm, follower1Context.getTermInformation().getCurrentTerm());
- assertEquals("Follower server config", Sets.newHashSet(persistedServerConfig.getServerConfig()),
- Sets.newHashSet(follower1Context.getPeerServerInfo(true).getServerConfig()));
+ assertEquals("Follower server config", Set.copyOf(persistedServerConfig.getServerConfig()),
+ Set.copyOf(follower1Context.getPeerServerInfo(true).getServerConfig()));
assertEquals("FollowerisVotingMember", false, follower1Context.isVotingMember());
}
}
import akka.actor.Props;
import akka.testkit.TestActorRef;
-import com.google.common.collect.ImmutableMap;
import com.google.common.util.concurrent.MoreExecutors;
-import java.util.Arrays;
import java.util.HashMap;
+import java.util.List;
import java.util.Map;
import org.junit.After;
import org.junit.Test;
DefaultConfigParamsImpl configParams = new DefaultConfigParamsImpl();
RaftActorContextImpl context = new RaftActorContextImpl(actor, actor.underlyingActor().getContext(),
"test", new ElectionTermImpl(createProvider(), "test", LOG), -1, -1,
- new HashMap<>(ImmutableMap.of("peer1", "peerAddress1")), configParams,
+ Map.of("peer1", "peerAddress1"), configParams,
createProvider(), applyState -> { }, LOG, MoreExecutors.directExecutor());
context.setPeerAddress("peer1", "peerAddress1_1");
public void testUpdatePeerIds() {
RaftActorContextImpl context = new RaftActorContextImpl(actor, actor.underlyingActor().getContext(),
"self", new ElectionTermImpl(createProvider(), "test", LOG), -1, -1,
- new HashMap<>(ImmutableMap.of("peer1", "peerAddress1")),
+ Map.of("peer1", "peerAddress1"),
new DefaultConfigParamsImpl(), createProvider(), applyState -> { }, LOG,
MoreExecutors.directExecutor());
- context.updatePeerIds(new ServerConfigurationPayload(Arrays.asList(new ServerInfo("self", false),
+ context.updatePeerIds(new ServerConfigurationPayload(List.of(new ServerInfo("self", false),
new ServerInfo("peer2", true), new ServerInfo("peer3", false))));
verifyPeerInfo(context, "peer1", null);
verifyPeerInfo(context, "peer2", true);
verifyPeerInfo(context, "peer3", false);
assertEquals("isVotingMember", false, context.isVotingMember());
- context.updatePeerIds(new ServerConfigurationPayload(Arrays.asList(new ServerInfo("self", true),
+ context.updatePeerIds(new ServerConfigurationPayload(List.of(new ServerInfo("self", true),
new ServerInfo("peer2", true), new ServerInfo("peer3", true))));
verifyPeerInfo(context, "peer2", true);
verifyPeerInfo(context, "peer3", true);
assertEquals("isVotingMember", true, context.isVotingMember());
- context.updatePeerIds(new ServerConfigurationPayload(Arrays.asList(new ServerInfo("peer2", true),
+ context.updatePeerIds(new ServerConfigurationPayload(List.of(new ServerInfo("peer2", true),
new ServerInfo("peer3", true))));
verifyPeerInfo(context, "peer2", true);
verifyPeerInfo(context, "peer3", true);
PeerInfo peerInfo = context.getPeerInfo(peerId);
if (voting != null) {
assertNotNull("Expected peer " + peerId, peerInfo);
- assertEquals("getVotingState for " + peerId, voting.booleanValue()
+ assertEquals("getVotingState for " + peerId, voting
? VotingState.VOTING : VotingState.NON_VOTING, peerInfo.getVotingState());
} else {
assertNull("Unexpected peer " + peerId, peerInfo);
}
static class TestNonPersistentPayload extends Payload {
+ @java.io.Serial
private static final long serialVersionUID = 1L;
@Override
}
static class TestPersistentPayload extends TestNonPersistentPayload implements PersistentPayload {
+ @java.io.Serial
private static final long serialVersionUID = 1L;
-
}
}
import akka.testkit.TestActorRef;
import akka.testkit.javadsl.TestKit;
import com.google.common.base.Stopwatch;
-import com.google.common.collect.ImmutableMap;
-import com.google.common.collect.ImmutableSet;
import com.google.common.io.ByteSource;
import com.google.common.util.concurrent.MoreExecutors;
import java.io.OutputStream;
import java.time.Duration;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
+import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.apache.commons.lang3.SerializationUtils;
import org.junit.After;
followerActorContext.setCurrentBehavior(follower);
TestActorRef<MockLeaderRaftActor> leaderActor = actorFactory.createTestActor(
- MockLeaderRaftActor.props(ImmutableMap.of(FOLLOWER_ID, followerActor.path().toString()),
+ MockLeaderRaftActor.props(Map.of(FOLLOWER_ID, followerActor.path().toString()),
followerActorContext).withDispatcher(Dispatchers.DefaultDispatcherId()),
actorFactory.generateActorId(LEADER_ID));
AddServerReply addServerReply = testKit.expectMsgClass(Duration.ofSeconds(5), AddServerReply.class);
assertEquals("getStatus", ServerChangeStatus.OK, addServerReply.getStatus());
- assertEquals("getLeaderHint", LEADER_ID, addServerReply.getLeaderHint().get());
+ assertEquals("getLeaderHint", LEADER_ID, addServerReply.getLeaderHint().orElseThrow());
// Verify ServerConfigurationPayload entry in leader's log
// Verify new server config was applied in both followers
- assertEquals("Follower peers", ImmutableSet.of(LEADER_ID, NEW_SERVER_ID), followerActorContext.getPeerIds());
+ assertEquals("Follower peers", Set.of(LEADER_ID, NEW_SERVER_ID), followerActorContext.getPeerIds());
- assertEquals("New follower peers", ImmutableSet.of(LEADER_ID, FOLLOWER_ID),
- newFollowerActorContext.getPeerIds());
+ assertEquals("New follower peers", Set.of(LEADER_ID, FOLLOWER_ID), newFollowerActorContext.getPeerIds());
assertEquals("Follower commit index", 3, followerActorContext.getCommitIndex());
assertEquals("Follower last applied index", 3, followerActorContext.getLastApplied());
0, 2, 1).build());
TestActorRef<MockLeaderRaftActor> leaderActor = actorFactory.createTestActor(
- MockLeaderRaftActor.props(ImmutableMap.<String, String>of(),
- initialActorContext).withDispatcher(Dispatchers.DefaultDispatcherId()),
+ MockLeaderRaftActor.props(Map.of(), initialActorContext)
+ .withDispatcher(Dispatchers.DefaultDispatcherId()),
actorFactory.generateActorId(LEADER_ID));
MockLeaderRaftActor leaderRaftActor = leaderActor.underlyingActor();
AddServerReply addServerReply = testKit.expectMsgClass(Duration.ofSeconds(5), AddServerReply.class);
assertEquals("getStatus", ServerChangeStatus.OK, addServerReply.getStatus());
- assertEquals("getLeaderHint", LEADER_ID, addServerReply.getLeaderHint().get());
+ assertEquals("getLeaderHint", LEADER_ID, addServerReply.getLeaderHint().orElseThrow());
// Verify ServerConfigurationPayload entry in leader's log
// Verify new server config was applied in the new follower
- assertEquals("New follower peers", ImmutableSet.of(LEADER_ID), newFollowerActorContext.getPeerIds());
+ assertEquals("New follower peers", Set.of(LEADER_ID), newFollowerActorContext.getPeerIds());
LOG.info("testAddServerWithNoExistingFollower ending");
}
RaftActorContext initialActorContext = new MockRaftActorContext();
TestActorRef<MockLeaderRaftActor> leaderActor = actorFactory.createTestActor(
- MockLeaderRaftActor.props(ImmutableMap.<String, String>of(),
- initialActorContext).withDispatcher(Dispatchers.DefaultDispatcherId()),
+ MockLeaderRaftActor.props(Map.of(), initialActorContext)
+ .withDispatcher(Dispatchers.DefaultDispatcherId()),
actorFactory.generateActorId(LEADER_ID));
MockLeaderRaftActor leaderRaftActor = leaderActor.underlyingActor();
AddServerReply addServerReply = testKit.expectMsgClass(Duration.ofSeconds(5), AddServerReply.class);
assertEquals("getStatus", ServerChangeStatus.OK, addServerReply.getStatus());
- assertEquals("getLeaderHint", LEADER_ID, addServerReply.getLeaderHint().get());
+ assertEquals("getLeaderHint", LEADER_ID, addServerReply.getLeaderHint().orElseThrow());
// Verify ServerConfigurationPayload entry in leader's log
// Verify new server config was applied in the new follower
- assertEquals("New follower peers", ImmutableSet.of(LEADER_ID), newFollowerActorContext.getPeerIds());
+ assertEquals("New follower peers", Set.of(LEADER_ID), newFollowerActorContext.getPeerIds());
assertNoneMatching(newFollowerCollectorActor, InstallSnapshot.class, 500);
RaftActorContext initialActorContext = new MockRaftActorContext();
TestActorRef<MockLeaderRaftActor> leaderActor = actorFactory.createTestActor(
- MockLeaderRaftActor.props(ImmutableMap.<String, String>of(),
- initialActorContext).withDispatcher(Dispatchers.DefaultDispatcherId()),
+ MockLeaderRaftActor.props(Map.of(), initialActorContext)
+ .withDispatcher(Dispatchers.DefaultDispatcherId()),
actorFactory.generateActorId(LEADER_ID));
MockLeaderRaftActor leaderRaftActor = leaderActor.underlyingActor();
// Verify ServerConfigurationPayload entry in the new follower
expectMatching(newFollowerCollectorActor, ApplyState.class, 2);
- assertEquals("New follower peers", ImmutableSet.of(LEADER_ID, NEW_SERVER_ID2),
- newFollowerActorContext.getPeerIds());
+ assertEquals("New follower peers", Set.of(LEADER_ID, NEW_SERVER_ID2), newFollowerActorContext.getPeerIds());
LOG.info("testAddServerWithOperationInProgress ending");
}
RaftActorContext initialActorContext = new MockRaftActorContext();
TestActorRef<MockLeaderRaftActor> leaderActor = actorFactory.createTestActor(
- MockLeaderRaftActor.props(ImmutableMap.<String, String>of(),
- initialActorContext).withDispatcher(Dispatchers.DefaultDispatcherId()),
+ MockLeaderRaftActor.props(Map.of(), initialActorContext)
+ .withDispatcher(Dispatchers.DefaultDispatcherId()),
actorFactory.generateActorId(LEADER_ID));
MockLeaderRaftActor leaderRaftActor = leaderActor.underlyingActor();
AddServerReply addServerReply = testKit.expectMsgClass(Duration.ofSeconds(5), AddServerReply.class);
assertEquals("getStatus", ServerChangeStatus.OK, addServerReply.getStatus());
- assertEquals("getLeaderHint", LEADER_ID, addServerReply.getLeaderHint().get());
+ assertEquals("getLeaderHint", LEADER_ID, addServerReply.getLeaderHint().orElseThrow());
expectFirstMatching(newFollowerCollectorActor, ApplySnapshot.class);
RaftActorContext initialActorContext = new MockRaftActorContext();
TestActorRef<MockLeaderRaftActor> leaderActor = actorFactory.createTestActor(
- MockLeaderRaftActor.props(ImmutableMap.<String, String>of(),
- initialActorContext).withDispatcher(Dispatchers.DefaultDispatcherId()),
+ MockLeaderRaftActor.props(Map.of(), initialActorContext)
+ .withDispatcher(Dispatchers.DefaultDispatcherId()),
actorFactory.generateActorId(LEADER_ID));
MockLeaderRaftActor leaderRaftActor = leaderActor.underlyingActor();
RaftActorContext initialActorContext = new MockRaftActorContext();
TestActorRef<MockLeaderRaftActor> leaderActor = actorFactory.createTestActor(
- MockLeaderRaftActor.props(ImmutableMap.<String, String>of(),
- initialActorContext).withDispatcher(Dispatchers.DefaultDispatcherId()),
+ MockLeaderRaftActor.props(Map.of(), initialActorContext)
+ .withDispatcher(Dispatchers.DefaultDispatcherId()),
actorFactory.generateActorId(LEADER_ID));
MockLeaderRaftActor leaderRaftActor = leaderActor.underlyingActor();
RaftActorContext initialActorContext = new MockRaftActorContext();
TestActorRef<MockLeaderRaftActor> leaderActor = actorFactory.createTestActor(
- MockLeaderRaftActor.props(ImmutableMap.<String, String>of(),
- initialActorContext).withDispatcher(Dispatchers.DefaultDispatcherId()),
+ MockLeaderRaftActor.props(Map.of(), initialActorContext)
+ .withDispatcher(Dispatchers.DefaultDispatcherId()),
actorFactory.generateActorId(LEADER_ID));
MockLeaderRaftActor leaderRaftActor = leaderActor.underlyingActor();
RaftActorContext initialActorContext = new MockRaftActorContext();
TestActorRef<MockLeaderRaftActor> leaderActor = actorFactory.createTestActor(
- MockLeaderRaftActor.props(ImmutableMap.<String, String>of(),
- initialActorContext).withDispatcher(Dispatchers.DefaultDispatcherId()),
+ MockLeaderRaftActor.props(Map.of(), initialActorContext)
+ .withDispatcher(Dispatchers.DefaultDispatcherId()),
actorFactory.generateActorId(LEADER_ID));
MockLeaderRaftActor leaderRaftActor = leaderActor.underlyingActor();
configParams.setHeartBeatInterval(new FiniteDuration(1, TimeUnit.DAYS));
TestActorRef<MockRaftActor> noLeaderActor = actorFactory.createTestActor(
- MockRaftActor.builder().id(LEADER_ID).peerAddresses(ImmutableMap.of(FOLLOWER_ID,
+ MockRaftActor.builder().id(LEADER_ID).peerAddresses(Map.of(FOLLOWER_ID,
followerActor.path().toString())).config(configParams).persistent(Optional.of(false))
.props().withDispatcher(Dispatchers.DefaultDispatcherId()),
actorFactory.generateActorId(LEADER_ID));
RaftActorContext initialActorContext = new MockRaftActorContext();
TestActorRef<MockLeaderRaftActor> leaderActor = actorFactory.createTestActor(
- MockLeaderRaftActor.props(ImmutableMap.<String, String>of(),
- initialActorContext).withDispatcher(Dispatchers.DefaultDispatcherId()),
+ MockLeaderRaftActor.props(Map.of(), initialActorContext)
+ .withDispatcher(Dispatchers.DefaultDispatcherId()),
actorFactory.generateActorId(LEADER_ID));
MockLeaderRaftActor leaderRaftActor = leaderActor.underlyingActor();
// The first AddServer should succeed with OK even though consensus wasn't reached
AddServerReply addServerReply = testKit.expectMsgClass(Duration.ofSeconds(5), AddServerReply.class);
assertEquals("getStatus", ServerChangeStatus.OK, addServerReply.getStatus());
- assertEquals("getLeaderHint", LEADER_ID, addServerReply.getLeaderHint().get());
+ assertEquals("getLeaderHint", LEADER_ID, addServerReply.getLeaderHint().orElseThrow());
// Verify ServerConfigurationPayload entry in leader's log
verifyServerConfigurationPayloadEntry(leaderActorContext.getReplicatedLog(), votingServer(LEADER_ID),
RaftActorContext initialActorContext = new MockRaftActorContext();
TestActorRef<MockLeaderRaftActor> leaderActor = actorFactory.createTestActor(
- MockLeaderRaftActor.props(ImmutableMap.of(FOLLOWER_ID, followerActor.path().toString()),
+ MockLeaderRaftActor.props(Map.of(FOLLOWER_ID, followerActor.path().toString()),
initialActorContext).withDispatcher(Dispatchers.DefaultDispatcherId()),
actorFactory.generateActorId(LEADER_ID));
MessageCollectorActor.props(), actorFactory.generateActorId(LEADER_ID));
TestActorRef<MockRaftActor> followerRaftActor = actorFactory.createTestActor(
- MockRaftActor.builder().id(FOLLOWER_ID).peerAddresses(ImmutableMap.of(LEADER_ID,
+ MockRaftActor.builder().id(FOLLOWER_ID).peerAddresses(Map.of(LEADER_ID,
leaderActor.path().toString())).config(configParams).persistent(Optional.of(false))
.props().withDispatcher(Dispatchers.DefaultDispatcherId()),
actorFactory.generateActorId(FOLLOWER_ID));
followerRaftActor.underlyingActor().waitForInitializeBehaviorComplete();
- followerRaftActor.tell(new AppendEntries(1, LEADER_ID, 0, 1, Collections.<ReplicatedLogEntry>emptyList(),
- -1, -1, (short)0), leaderActor);
+ followerRaftActor.tell(new AppendEntries(1, LEADER_ID, 0, 1, List.of(), -1, -1, (short)0), leaderActor);
followerRaftActor.tell(new AddServer(NEW_SERVER_ID, newFollowerRaftActor.path().toString(), true),
testKit.getRef());
DefaultConfigParamsImpl configParams = new DefaultConfigParamsImpl();
configParams.setHeartBeatInterval(new FiniteDuration(1, TimeUnit.DAYS));
TestActorRef<MockRaftActor> noLeaderActor = actorFactory.createTestActor(
- MockRaftActor.builder().id(LEADER_ID).peerAddresses(ImmutableMap.of(FOLLOWER_ID,
+ MockRaftActor.builder().id(LEADER_ID).peerAddresses(Map.of(FOLLOWER_ID,
followerActor.path().toString())).config(configParams).persistent(Optional.of(false))
.props().withDispatcher(Dispatchers.DefaultDispatcherId()),
actorFactory.generateActorId(LEADER_ID));
noLeaderActor.underlyingActor());
ReplicatedLogEntry serverConfigEntry = new SimpleReplicatedLogEntry(1, 1,
- new ServerConfigurationPayload(Collections.<ServerInfo>emptyList()));
+ new ServerConfigurationPayload(List.of()));
boolean handled = support.handleMessage(new ApplyState(null, null, serverConfigEntry), ActorRef.noSender());
assertEquals("Message handled", true, handled);
configParams.setHeartBeatInterval(new FiniteDuration(1, TimeUnit.DAYS));
TestActorRef<MockRaftActor> leaderActor = actorFactory.createTestActor(
- MockRaftActor.builder().id(LEADER_ID).peerAddresses(ImmutableMap.of(FOLLOWER_ID,
+ MockRaftActor.builder().id(LEADER_ID).peerAddresses(Map.of(FOLLOWER_ID,
followerActor.path().toString())).config(configParams).persistent(Optional.of(false))
.props().withDispatcher(Dispatchers.DefaultDispatcherId()),
actorFactory.generateActorId(LEADER_ID));
RaftActorContext initialActorContext = new MockRaftActorContext();
TestActorRef<MockLeaderRaftActor> leaderActor = actorFactory.createTestActor(
- MockLeaderRaftActor.props(ImmutableMap.of(FOLLOWER_ID, followerActor.path().toString()),
+ MockLeaderRaftActor.props(Map.of(FOLLOWER_ID, followerActor.path().toString()),
initialActorContext).withDispatcher(Dispatchers.DefaultDispatcherId()),
actorFactory.generateActorId(LEADER_ID));
MessageCollectorActor.props(), actorFactory.generateActorId(LEADER_ID));
TestActorRef<MockRaftActor> followerRaftActor = actorFactory.createTestActor(
- MockRaftActor.builder().id(FOLLOWER_ID).peerAddresses(ImmutableMap.of(LEADER_ID,
+ MockRaftActor.builder().id(FOLLOWER_ID).peerAddresses(Map.of(LEADER_ID,
leaderActor.path().toString())).config(configParams).persistent(Optional.of(false))
.props().withDispatcher(Dispatchers.DefaultDispatcherId()),
actorFactory.generateActorId(FOLLOWER_ID));
followerRaftActor.underlyingActor().waitForInitializeBehaviorComplete();
- followerRaftActor.tell(new AppendEntries(1, LEADER_ID, 0, 1, Collections.<ReplicatedLogEntry>emptyList(),
- -1, -1, (short)0), leaderActor);
+ followerRaftActor.tell(new AppendEntries(1, LEADER_ID, 0, 1, List.of(), -1, -1, (short)0), leaderActor);
followerRaftActor.tell(new RemoveServer(FOLLOWER_ID), testKit.getRef());
expectFirstMatching(leaderActor, RemoveServer.class);
final String downNodeId = "downNode";
TestActorRef<MockLeaderRaftActor> leaderActor = actorFactory.createTestActor(MockLeaderRaftActor.props(
- ImmutableMap.of(FOLLOWER_ID, follower1ActorPath, FOLLOWER_ID2, follower2ActorPath, downNodeId, ""),
+ Map.of(FOLLOWER_ID, follower1ActorPath, FOLLOWER_ID2, follower2ActorPath, downNodeId, ""),
initialActorContext).withDispatcher(Dispatchers.DefaultDispatcherId()),
actorFactory.generateActorId(LEADER_ID));
ActorRef follower1Collector = actorFactory.createActor(
MessageCollectorActor.props(), actorFactory.generateActorId("collector"));
final TestActorRef<CollectingMockRaftActor> follower1Actor = actorFactory.createTestActor(
- CollectingMockRaftActor.props(FOLLOWER_ID, ImmutableMap.of(LEADER_ID, leaderActor.path().toString(),
+ CollectingMockRaftActor.props(FOLLOWER_ID, Map.of(LEADER_ID, leaderActor.path().toString(),
FOLLOWER_ID2, follower2ActorPath, downNodeId, ""), configParams, NO_PERSISTENCE,
follower1Collector).withDispatcher(Dispatchers.DefaultDispatcherId()), follower1ActorId);
ActorRef follower2Collector = actorFactory.createActor(
MessageCollectorActor.props(), actorFactory.generateActorId("collector"));
final TestActorRef<CollectingMockRaftActor> follower2Actor = actorFactory.createTestActor(
- CollectingMockRaftActor.props(FOLLOWER_ID2, ImmutableMap.of(LEADER_ID, leaderActor.path().toString(),
+ CollectingMockRaftActor.props(FOLLOWER_ID2, Map.of(LEADER_ID, leaderActor.path().toString(),
FOLLOWER_ID, follower1ActorPath, downNodeId, ""), configParams, NO_PERSISTENCE,
follower2Collector).withDispatcher(Dispatchers.DefaultDispatcherId()), follower2ActorId);
RaftActorContext initialActorContext = new MockRaftActorContext();
TestActorRef<MockLeaderRaftActor> leaderActor = actorFactory.createTestActor(
- MockLeaderRaftActor.props(ImmutableMap.of(FOLLOWER_ID, followerActorPath),
+ MockLeaderRaftActor.props(Map.of(FOLLOWER_ID, followerActorPath),
initialActorContext).withDispatcher(Dispatchers.DefaultDispatcherId()),
actorFactory.generateActorId(LEADER_ID));
final ActorRef followerCollector =
actorFactory.createActor(MessageCollectorActor.props(), actorFactory.generateActorId("collector"));
actorFactory.createTestActor(
- CollectingMockRaftActor.props(FOLLOWER_ID, ImmutableMap.of(LEADER_ID, leaderActor.path().toString()),
+ CollectingMockRaftActor.props(FOLLOWER_ID, Map.of(LEADER_ID, leaderActor.path().toString()),
configParams, NO_PERSISTENCE, followerCollector)
.withDispatcher(Dispatchers.DefaultDispatcherId()),
followerActorId);
LOG.info("testRemoveServerLeaderWithNoFollowers starting");
TestActorRef<MockLeaderRaftActor> leaderActor = actorFactory.createTestActor(
- MockLeaderRaftActor.props(Collections.<String, String>emptyMap(),
+ MockLeaderRaftActor.props(Map.of(),
new MockRaftActorContext()).withDispatcher(Dispatchers.DefaultDispatcherId()),
actorFactory.generateActorId(LEADER_ID));
final String follower2ActorPath = actorFactory.createTestActorPath(follower2ActorId);
TestActorRef<MockLeaderRaftActor> leaderActor = actorFactory.createTestActor(
- MockLeaderRaftActor.props(ImmutableMap.of(FOLLOWER_ID, follower1ActorPath,
+ MockLeaderRaftActor.props(Map.of(FOLLOWER_ID, follower1ActorPath,
FOLLOWER_ID2, follower2ActorPath), new MockRaftActorContext())
.withDispatcher(Dispatchers.DefaultDispatcherId()), actorFactory.generateActorId(LEADER_ID));
ActorRef leaderCollector = newLeaderCollectorActor(leaderActor.underlyingActor());
ActorRef follower1Collector = actorFactory.createActor(
MessageCollectorActor.props(), actorFactory.generateActorId("collector"));
final TestActorRef<CollectingMockRaftActor> follower1RaftActor = actorFactory.createTestActor(
- CollectingMockRaftActor.props(FOLLOWER_ID, ImmutableMap.of(LEADER_ID, leaderActor.path().toString(),
+ CollectingMockRaftActor.props(FOLLOWER_ID, Map.of(LEADER_ID, leaderActor.path().toString(),
FOLLOWER_ID2, follower2ActorPath), configParams, NO_PERSISTENCE, follower1Collector)
.withDispatcher(Dispatchers.DefaultDispatcherId()), follower1ActorId);
ActorRef follower2Collector = actorFactory.createActor(
MessageCollectorActor.props(), actorFactory.generateActorId("collector"));
final TestActorRef<CollectingMockRaftActor> follower2RaftActor = actorFactory.createTestActor(
- CollectingMockRaftActor.props(FOLLOWER_ID2, ImmutableMap.of(LEADER_ID, leaderActor.path().toString(),
+ CollectingMockRaftActor.props(FOLLOWER_ID2, Map.of(LEADER_ID, leaderActor.path().toString(),
FOLLOWER_ID, follower1ActorPath), configParams, NO_PERSISTENCE, follower2Collector)
.withDispatcher(Dispatchers.DefaultDispatcherId()), follower2ActorId);
// Send first ChangeServersVotingStatus message
- leaderActor.tell(new ChangeServersVotingStatus(ImmutableMap.of(FOLLOWER_ID, false, FOLLOWER_ID2, false)),
+ leaderActor.tell(new ChangeServersVotingStatus(Map.of(FOLLOWER_ID, false, FOLLOWER_ID2, false)),
testKit.getRef());
ServerChangeReply reply = testKit.expectMsgClass(Duration.ofSeconds(5), ServerChangeReply.class);
assertEquals("getStatus", ServerChangeStatus.OK, reply.getStatus());
// Send second ChangeServersVotingStatus message
- leaderActor.tell(new ChangeServersVotingStatus(ImmutableMap.of(FOLLOWER_ID, true)), testKit.getRef());
+ leaderActor.tell(new ChangeServersVotingStatus(Map.of(FOLLOWER_ID, true)), testKit.getRef());
reply = testKit.expectMsgClass(Duration.ofSeconds(5), ServerChangeReply.class);
assertEquals("getStatus", ServerChangeStatus.OK, reply.getStatus());
final String follower2ActorPath = actorFactory.createTestActorPath(follower2ActorId);
TestActorRef<MockLeaderRaftActor> leaderActor = actorFactory.createTestActor(
- MockLeaderRaftActor.props(ImmutableMap.of(FOLLOWER_ID, follower1ActorPath,
+ MockLeaderRaftActor.props(Map.of(FOLLOWER_ID, follower1ActorPath,
FOLLOWER_ID2, follower2ActorPath), new MockRaftActorContext())
.withDispatcher(Dispatchers.DefaultDispatcherId()), actorFactory.generateActorId(LEADER_ID));
ActorRef leaderCollector = newLeaderCollectorActor(leaderActor.underlyingActor());
ActorRef follower1Collector = actorFactory.createActor(
MessageCollectorActor.props(), actorFactory.generateActorId("collector"));
final TestActorRef<CollectingMockRaftActor> follower1RaftActor = actorFactory.createTestActor(
- CollectingMockRaftActor.props(FOLLOWER_ID, ImmutableMap.of(LEADER_ID, leaderActor.path().toString(),
+ CollectingMockRaftActor.props(FOLLOWER_ID, Map.of(LEADER_ID, leaderActor.path().toString(),
FOLLOWER_ID2, follower2ActorPath), configParams, NO_PERSISTENCE, follower1Collector)
.withDispatcher(Dispatchers.DefaultDispatcherId()), follower1ActorId);
ActorRef follower2Collector = actorFactory.createActor(
MessageCollectorActor.props(), actorFactory.generateActorId("collector"));
final TestActorRef<CollectingMockRaftActor> follower2RaftActor = actorFactory.createTestActor(
- CollectingMockRaftActor.props(FOLLOWER_ID2, ImmutableMap.of(LEADER_ID, leaderActor.path().toString(),
+ CollectingMockRaftActor.props(FOLLOWER_ID2, Map.of(LEADER_ID, leaderActor.path().toString(),
FOLLOWER_ID, follower1ActorPath), configParams, NO_PERSISTENCE, follower2Collector)
.withDispatcher(Dispatchers.DefaultDispatcherId()), follower2ActorId);
// Send ChangeServersVotingStatus message
- leaderActor.tell(new ChangeServersVotingStatus(ImmutableMap.of(LEADER_ID, false)), testKit.getRef());
+ leaderActor.tell(new ChangeServersVotingStatus(Map.of(LEADER_ID, false)), testKit.getRef());
ServerChangeReply reply = testKit.expectMsgClass(Duration.ofSeconds(5), ServerChangeReply.class);
assertEquals("getStatus", ServerChangeStatus.OK, reply.getStatus());
LOG.info("testChangeLeaderToNonVotingInSingleNode starting");
TestActorRef<MockLeaderRaftActor> leaderActor = actorFactory.createTestActor(
- MockLeaderRaftActor.props(ImmutableMap.of(), new MockRaftActorContext())
+ MockLeaderRaftActor.props(Map.of(), new MockRaftActorContext())
.withDispatcher(Dispatchers.DefaultDispatcherId()), actorFactory.generateActorId(LEADER_ID));
- leaderActor.tell(new ChangeServersVotingStatus(ImmutableMap.of(LEADER_ID, false)), testKit.getRef());
+ leaderActor.tell(new ChangeServersVotingStatus(Map.of(LEADER_ID, false)), testKit.getRef());
ServerChangeReply reply = testKit.expectMsgClass(Duration.ofSeconds(5), ServerChangeReply.class);
assertEquals("getStatus", ServerChangeStatus.INVALID_REQUEST, reply.getStatus());
// via the server config. The server config will also contain 2 voting peers that are down (ie no
// actors created).
- ServerConfigurationPayload persistedServerConfig = new ServerConfigurationPayload(Arrays.asList(
+ ServerConfigurationPayload persistedServerConfig = new ServerConfigurationPayload(List.of(
new ServerInfo(node1ID, false), new ServerInfo(node2ID, false),
new ServerInfo("downNode1", true), new ServerInfo("downNode2", true)));
SimpleReplicatedLogEntry persistedServerConfigEntry = new SimpleReplicatedLogEntry(0, 1, persistedServerConfig);
ActorRef node1Collector = actorFactory.createActor(
MessageCollectorActor.props(), actorFactory.generateActorId("collector"));
TestActorRef<CollectingMockRaftActor> node1RaftActorRef = actorFactory.createTestActor(
- CollectingMockRaftActor.props(node1ID, ImmutableMap.<String, String>of(), configParams,
+ CollectingMockRaftActor.props(node1ID, Map.of(), configParams,
PERSISTENT, node1Collector).withDispatcher(Dispatchers.DefaultDispatcherId()), node1ID);
CollectingMockRaftActor node1RaftActor = node1RaftActorRef.underlyingActor();
ActorRef node2Collector = actorFactory.createActor(
MessageCollectorActor.props(), actorFactory.generateActorId("collector"));
TestActorRef<CollectingMockRaftActor> node2RaftActorRef = actorFactory.createTestActor(
- CollectingMockRaftActor.props(node2ID, ImmutableMap.<String, String>of(), configParams,
+ CollectingMockRaftActor.props(node2ID, Map.of(), configParams,
PERSISTENT, node2Collector).withDispatcher(Dispatchers.DefaultDispatcherId()), node2ID);
CollectingMockRaftActor node2RaftActor = node2RaftActorRef.underlyingActor();
// First send the message such that node1 has no peer address for node2 - should fail.
- ChangeServersVotingStatus changeServers = new ChangeServersVotingStatus(ImmutableMap.of(node1ID, true,
+ ChangeServersVotingStatus changeServers = new ChangeServersVotingStatus(Map.of(node1ID, true,
node2ID, true, "downNode1", false, "downNode2", false));
node1RaftActorRef.tell(changeServers, testKit.getRef());
ServerChangeReply reply = testKit.expectMsgClass(Duration.ofSeconds(5), ServerChangeReply.class);
long term = node1RaftActor.getRaftActorContext().getTermInformation().getCurrentTerm();
node1RaftActorRef.tell(new AppendEntries(term, "downNode1", -1L, -1L,
- Collections.<ReplicatedLogEntry>emptyList(), 0, -1, (short)1), ActorRef.noSender());
+ List.of(), 0, -1, (short)1), ActorRef.noSender());
// Wait for the ElectionTimeout to clear the leaderId. The leaderId must be null so on the next
// ChangeServersVotingStatus message, it will try to elect a leader.
? actorFactory.createTestActorPath(node1ID) : peerId.equals(node2ID)
? actorFactory.createTestActorPath(node2ID) : null;
- ServerConfigurationPayload persistedServerConfig = new ServerConfigurationPayload(Arrays.asList(
+ ServerConfigurationPayload persistedServerConfig = new ServerConfigurationPayload(List.of(
new ServerInfo(node1ID, false), new ServerInfo(node2ID, true)));
SimpleReplicatedLogEntry persistedServerConfigEntry = new SimpleReplicatedLogEntry(0, 1, persistedServerConfig);
ActorRef node1Collector = actorFactory.createActor(
MessageCollectorActor.props(), actorFactory.generateActorId("collector"));
TestActorRef<CollectingMockRaftActor> node1RaftActorRef = actorFactory.createTestActor(
- CollectingMockRaftActor.props(node1ID, ImmutableMap.<String, String>of(), configParams1,
+ CollectingMockRaftActor.props(node1ID, Map.of(), configParams1,
PERSISTENT, node1Collector).withDispatcher(Dispatchers.DefaultDispatcherId()), node1ID);
final CollectingMockRaftActor node1RaftActor = node1RaftActorRef.underlyingActor();
ActorRef node2Collector = actorFactory.createActor(
MessageCollectorActor.props(), actorFactory.generateActorId("collector"));
TestActorRef<CollectingMockRaftActor> node2RaftActorRef = actorFactory.createTestActor(
- CollectingMockRaftActor.props(node2ID, ImmutableMap.<String, String>of(), configParams2,
+ CollectingMockRaftActor.props(node2ID, Map.of(), configParams2,
PERSISTENT, node2Collector).withDispatcher(Dispatchers.DefaultDispatcherId()), node2ID);
CollectingMockRaftActor node2RaftActor = node2RaftActorRef.underlyingActor();
node2RaftActor.setDropMessageOfType(RequestVote.class);
- ChangeServersVotingStatus changeServers = new ChangeServersVotingStatus(ImmutableMap.of(node1ID, true));
+ ChangeServersVotingStatus changeServers = new ChangeServersVotingStatus(Map.of(node1ID, true));
node1RaftActorRef.tell(changeServers, testKit.getRef());
ServerChangeReply reply = testKit.expectMsgClass(Duration.ofSeconds(5), ServerChangeReply.class);
assertEquals("getStatus", ServerChangeStatus.NO_LEADER, reply.getStatus());
- assertEquals("Server config", ImmutableSet.of(nonVotingServer(node1ID), votingServer(node2ID)),
- new HashSet<>(node1RaftActor.getRaftActorContext().getPeerServerInfo(true).getServerConfig()));
+ assertEquals("Server config", Set.of(nonVotingServer(node1ID), votingServer(node2ID)),
+ Set.copyOf(node1RaftActor.getRaftActorContext().getPeerServerInfo(true).getServerConfig()));
assertEquals("getRaftState", RaftState.Follower, node1RaftActor.getRaftState());
LOG.info("testChangeToVotingWithNoLeaderAndElectionTimeout ending");
configParams.setElectionTimeoutFactor(3);
configParams.setPeerAddressResolver(peerAddressResolver);
- ServerConfigurationPayload persistedServerConfig = new ServerConfigurationPayload(Arrays.asList(
+ ServerConfigurationPayload persistedServerConfig = new ServerConfigurationPayload(List.of(
new ServerInfo(node1ID, false), new ServerInfo(node2ID, false)));
SimpleReplicatedLogEntry persistedServerConfigEntry = new SimpleReplicatedLogEntry(0, 1, persistedServerConfig);
ActorRef node1Collector = actorFactory.createActor(
MessageCollectorActor.props(), actorFactory.generateActorId("collector"));
TestActorRef<CollectingMockRaftActor> node1RaftActorRef = actorFactory.createTestActor(
- CollectingMockRaftActor.props(node1ID, ImmutableMap.<String, String>of(), configParams,
+ CollectingMockRaftActor.props(node1ID, Map.of(), configParams,
PERSISTENT, node1Collector).withDispatcher(Dispatchers.DefaultDispatcherId()), node1ID);
final CollectingMockRaftActor node1RaftActor = node1RaftActorRef.underlyingActor();
ActorRef node2Collector = actorFactory.createActor(
MessageCollectorActor.props(), actorFactory.generateActorId("collector"));
TestActorRef<CollectingMockRaftActor> node2RaftActorRef = actorFactory.createTestActor(
- CollectingMockRaftActor.props(node2ID, ImmutableMap.<String, String>of(), configParams,
+ CollectingMockRaftActor.props(node2ID, Map.of(), configParams,
PERSISTENT, node2Collector).withDispatcher(Dispatchers.DefaultDispatcherId()), node2ID);
final CollectingMockRaftActor node2RaftActor = node2RaftActorRef.underlyingActor();
// forward the request to node2.
ChangeServersVotingStatus changeServers = new ChangeServersVotingStatus(
- ImmutableMap.of(node1ID, true, node2ID, true));
+ Map.of(node1ID, true, node2ID, true));
node1RaftActorRef.tell(changeServers, testKit.getRef());
ServerChangeReply reply = testKit.expectMsgClass(Duration.ofSeconds(5), ServerChangeReply.class);
assertEquals("getStatus", ServerChangeStatus.OK, reply.getStatus());
? actorFactory.createTestActorPath(node1ID) : peerId.equals(node2ID)
? actorFactory.createTestActorPath(node2ID) : null);
- ServerConfigurationPayload persistedServerConfig = new ServerConfigurationPayload(Arrays.asList(
+ ServerConfigurationPayload persistedServerConfig = new ServerConfigurationPayload(List.of(
new ServerInfo(node1ID, false), new ServerInfo(node2ID, true)));
SimpleReplicatedLogEntry persistedServerConfigEntry = new SimpleReplicatedLogEntry(0, 1, persistedServerConfig);
ActorRef node1Collector = actorFactory.createActor(
MessageCollectorActor.props(), actorFactory.generateActorId("collector"));
TestActorRef<CollectingMockRaftActor> node1RaftActorRef = actorFactory.createTestActor(
- CollectingMockRaftActor.props(node1ID, ImmutableMap.<String, String>of(), configParams,
+ CollectingMockRaftActor.props(node1ID, Map.of(), configParams,
PERSISTENT, node1Collector).withDispatcher(Dispatchers.DefaultDispatcherId()), node1ID);
final CollectingMockRaftActor node1RaftActor = node1RaftActorRef.underlyingActor();
ActorRef node2Collector = actorFactory.createActor(
MessageCollectorActor.props(), actorFactory.generateActorId("collector"));
TestActorRef<CollectingMockRaftActor> node2RaftActorRef = actorFactory.createTestActor(
- CollectingMockRaftActor.props(node2ID, ImmutableMap.<String, String>of(), configParams,
+ CollectingMockRaftActor.props(node2ID, Map.of(), configParams,
PERSISTENT, node2Collector).withDispatcher(Dispatchers.DefaultDispatcherId()), node2ID);
CollectingMockRaftActor node2RaftActor = node2RaftActorRef.underlyingActor();
node2RaftActor.setDropMessageOfType(RequestVote.class);
- ChangeServersVotingStatus changeServers = new ChangeServersVotingStatus(ImmutableMap.of(node1ID, true,
+ ChangeServersVotingStatus changeServers = new ChangeServersVotingStatus(Map.of(node1ID, true,
node2ID, true));
node1RaftActorRef.tell(changeServers, testKit.getRef());
ReplicatedLogEntry logEntry = log.get(log.lastIndex());
assertEquals("Last log entry payload class", ServerConfigurationPayload.class, logEntry.getData().getClass());
ServerConfigurationPayload payload = (ServerConfigurationPayload)logEntry.getData();
- assertEquals("Server config", ImmutableSet.copyOf(expected), new HashSet<>(payload.getServerConfig()));
+ assertEquals("Server config", Set.of(expected), Set.copyOf(payload.getServerConfig()));
}
private static RaftActorContextImpl newFollowerContext(final String id,
ElectionTermImpl termInfo = new ElectionTermImpl(noPersistence, id, LOG);
termInfo.update(1, LEADER_ID);
return new RaftActorContextImpl(actor, actor.underlyingActor().getContext(),
- id, termInfo, -1, -1, ImmutableMap.of(LEADER_ID, ""), configParams,
+ id, termInfo, -1, -1, Map.of(LEADER_ID, ""), configParams,
noPersistence, applyState -> actor.tell(applyState, actor), LOG, MoreExecutors.directExecutor());
}
AbstractMockRaftActor(final String id, final Map<String, String> peerAddresses,
final Optional<ConfigParams> config, final boolean persistent, final ActorRef collectorActor) {
- super(builder().id(id).peerAddresses(peerAddresses).config(config.get())
+ super(builder().id(id).peerAddresses(peerAddresses).config(config.orElseThrow())
.persistent(Optional.of(persistent)));
this.collectorActor = collectorActor;
}
@Override
@SuppressWarnings("checkstyle:IllegalCatch")
public void createSnapshot(final ActorRef actorRef, final Optional<OutputStream> installSnapshotStream) {
- MockSnapshotState snapshotState = new MockSnapshotState(new ArrayList<>(getState()));
+ MockSnapshotState snapshotState = new MockSnapshotState(List.copyOf(getState()));
if (installSnapshotStream.isPresent()) {
- SerializationUtils.serialize(snapshotState, installSnapshotStream.get());
+ SerializationUtils.serialize(snapshotState, installSnapshotStream.orElseThrow());
}
actorRef.tell(new CaptureSnapshotReply(snapshotState, installSnapshotStream), actorRef);
public static class MockNewFollowerRaftActor extends AbstractMockRaftActor {
public MockNewFollowerRaftActor(final ConfigParams config, final ActorRef collectorActor) {
- super(NEW_SERVER_ID, new HashMap<>(), Optional.of(config), NO_PERSISTENCE, collectorActor);
+ super(NEW_SERVER_ID, Map.of(), Optional.of(config), NO_PERSISTENCE, collectorActor);
setPersistence(false);
}
import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.timeout;
import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
import akka.actor.ActorRef;
import akka.actor.PoisonPill;
import akka.protobuf.ByteString;
import akka.testkit.TestActorRef;
import akka.testkit.javadsl.TestKit;
-import com.google.common.collect.ImmutableMap;
import com.google.common.util.concurrent.Uninterruptibles;
import java.io.ByteArrayOutputStream;
import java.io.ObjectOutputStream;
import java.time.Duration;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
// log entry.
config.setHeartBeatInterval(new FiniteDuration(1, TimeUnit.DAYS));
- ImmutableMap<String, String> peerAddresses = ImmutableMap.<String, String>builder()
- .put("member1", "address").build();
+ Map<String, String> peerAddresses = Map.of("member1", "address");
ActorRef followerActor = factory.createActor(MockRaftActor.props(persistenceId,
peerAddresses, config), persistenceId);
kit.watch(followerActor);
- List<ReplicatedLogEntry> snapshotUnappliedEntries = new ArrayList<>();
- ReplicatedLogEntry entry1 = new SimpleReplicatedLogEntry(4, 1, new MockRaftActorContext.MockPayload("E"));
- snapshotUnappliedEntries.add(entry1);
+ List<ReplicatedLogEntry> snapshotUnappliedEntries = List.of(
+ new SimpleReplicatedLogEntry(4, 1, new MockRaftActorContext.MockPayload("E")));
int lastAppliedDuringSnapshotCapture = 3;
int lastIndexDuringSnapshotCapture = 4;
// 4 messages as part of snapshot, which are applied to state
- MockSnapshotState snapshotState = new MockSnapshotState(Arrays.asList(
+ MockSnapshotState snapshotState = new MockSnapshotState(List.of(
new MockRaftActorContext.MockPayload("A"),
new MockRaftActorContext.MockPayload("B"),
new MockRaftActorContext.MockPayload("C"),
InMemorySnapshotStore.addSnapshot(persistenceId, snapshot);
// add more entries after snapshot is taken
- List<ReplicatedLogEntry> entries = new ArrayList<>();
ReplicatedLogEntry entry2 = new SimpleReplicatedLogEntry(5, 1, new MockRaftActorContext.MockPayload("F", 2));
ReplicatedLogEntry entry3 = new SimpleReplicatedLogEntry(6, 1, new MockRaftActorContext.MockPayload("G", 3));
ReplicatedLogEntry entry4 = new SimpleReplicatedLogEntry(7, 1, new MockRaftActorContext.MockPayload("H", 4));
- entries.add(entry2);
- entries.add(entry3);
- entries.add(entry4);
final int lastAppliedToState = 5;
final int lastIndex = 7;
mockRaftActor.waitForRecoveryComplete();
RaftActorContext context = mockRaftActor.getRaftActorContext();
- assertEquals("Journal log size", snapshotUnappliedEntries.size() + entries.size(),
+ assertEquals("Journal log size", snapshotUnappliedEntries.size() + 3,
context.getReplicatedLog().size());
assertEquals("Journal data size", 10, context.getReplicatedLog().dataSize());
assertEquals("Last index", lastIndex, context.getReplicatedLog().lastIndex());
config.setHeartBeatInterval(new FiniteDuration(1, TimeUnit.DAYS));
TestActorRef<MockRaftActor> ref = factory.createTestActor(MockRaftActor.props(persistenceId,
- ImmutableMap.<String, String>builder().put("member1", "address").build(),
- config, createProvider()), persistenceId);
+ Map.of("member1", "address"), config, createProvider()), persistenceId);
MockRaftActor mockRaftActor = ref.underlyingActor();
InMemoryJournal.addWriteMessagesCompleteLatch(persistenceId, 1);
TestActorRef<MockRaftActor> ref = factory.createTestActor(MockRaftActor.props(persistenceId,
- ImmutableMap.<String, String>builder().put("member1", "address").build(),
- config, createProvider())
+ Map.of("member1", "address"), config, createProvider())
.withDispatcher(Dispatchers.DefaultDispatcherId()), persistenceId);
InMemoryJournal.waitForWriteMessagesComplete(persistenceId);
factory.killActor(ref, kit);
config.setHeartBeatInterval(new FiniteDuration(1, TimeUnit.DAYS));
- ref = factory.createTestActor(MockRaftActor.props(persistenceId,
- ImmutableMap.<String, String>builder().put("member1", "address").build(), config,
+ ref = factory.createTestActor(MockRaftActor.props(persistenceId, Map.of("member1", "address"), config,
createProvider()).withDispatcher(Dispatchers.DefaultDispatcherId()),
factory.generateActorId("follower-"));
config.setHeartBeatInterval(new FiniteDuration(1, TimeUnit.DAYS));
TestActorRef<MockRaftActor> mockActorRef = factory.createTestActor(MockRaftActor.props(persistenceId,
- Collections.<String, String>emptyMap(), config), persistenceId);
+ Map.of(), config), persistenceId);
MockRaftActor mockRaftActor = mockActorRef.underlyingActor();
mockRaftActor.setRaftActorRecoverySupport(mockSupport);
Snapshot snapshot = Snapshot.create(ByteState.of(new byte[]{1}),
- Collections.<ReplicatedLogEntry>emptyList(), 3, 1, 3, 1, -1, null, null);
+ List.of(), 3, 1, 3, 1, -1, null, null);
SnapshotOffer snapshotOffer = new SnapshotOffer(new SnapshotMetadata("test", 6, 12345), snapshot);
mockRaftActor.handleRecover(snapshotOffer);
ApplySnapshot applySnapshot = new ApplySnapshot(
Snapshot.create(null, null, 0, 0, 0, 0, 0, persistenceId, null));
- doReturn(true).when(mockSupport).handleSnapshotMessage(same(applySnapshot), any(ActorRef.class));
+ when(mockSupport.handleSnapshotMessage(same(applySnapshot), any(ActorRef.class))).thenReturn(true);
mockRaftActor.handleCommand(applySnapshot);
CaptureSnapshotReply captureSnapshotReply = new CaptureSnapshotReply(ByteState.empty(), Optional.empty());
- doReturn(true).when(mockSupport).handleSnapshotMessage(same(captureSnapshotReply), any(ActorRef.class));
+ when(mockSupport.handleSnapshotMessage(same(captureSnapshotReply), any(ActorRef.class))).thenReturn(true);
mockRaftActor.handleCommand(captureSnapshotReply);
SaveSnapshotSuccess saveSnapshotSuccess = new SaveSnapshotSuccess(new SnapshotMetadata("", 0L, 0L));
- doReturn(true).when(mockSupport).handleSnapshotMessage(same(saveSnapshotSuccess), any(ActorRef.class));
+ when(mockSupport.handleSnapshotMessage(same(saveSnapshotSuccess), any(ActorRef.class))).thenReturn(true);
mockRaftActor.handleCommand(saveSnapshotSuccess);
SaveSnapshotFailure saveSnapshotFailure = new SaveSnapshotFailure(new SnapshotMetadata("", 0L, 0L),
new Throwable());
- doReturn(true).when(mockSupport).handleSnapshotMessage(same(saveSnapshotFailure), any(ActorRef.class));
+ when(mockSupport.handleSnapshotMessage(same(saveSnapshotFailure), any(ActorRef.class))).thenReturn(true);
mockRaftActor.handleCommand(saveSnapshotFailure);
- doReturn(true).when(mockSupport).handleSnapshotMessage(same(RaftActorSnapshotMessageSupport.COMMIT_SNAPSHOT),
- any(ActorRef.class));
+ when(mockSupport.handleSnapshotMessage(same(RaftActorSnapshotMessageSupport.COMMIT_SNAPSHOT),
+ any(ActorRef.class))).thenReturn(true);
mockRaftActor.handleCommand(RaftActorSnapshotMessageSupport.COMMIT_SNAPSHOT);
- doReturn(true).when(mockSupport).handleSnapshotMessage(same(GetSnapshot.INSTANCE), any(ActorRef.class));
+ when(mockSupport.handleSnapshotMessage(same(GetSnapshot.INSTANCE), any(ActorRef.class))).thenReturn(true);
mockRaftActor.handleCommand(GetSnapshot.INSTANCE);
verify(mockSupport).handleSnapshotMessage(same(applySnapshot), any(ActorRef.class));
DataPersistenceProvider dataPersistenceProvider = mock(DataPersistenceProvider.class);
TestActorRef<MockRaftActor> mockActorRef = factory.createTestActor(MockRaftActor.props(persistenceId,
- Collections.<String, String>emptyMap(), config, dataPersistenceProvider), persistenceId);
+ Map.of(), config, dataPersistenceProvider), persistenceId);
MockRaftActor mockRaftActor = mockActorRef.underlyingActor();
DataPersistenceProvider dataPersistenceProvider = mock(DataPersistenceProvider.class);
TestActorRef<MockRaftActor> mockActorRef = factory.createTestActor(MockRaftActor.props(persistenceId,
- Collections.<String, String>emptyMap(), config, dataPersistenceProvider), persistenceId);
+ Map.of(), config, dataPersistenceProvider), persistenceId);
MockRaftActor mockRaftActor = mockActorRef.underlyingActor();
String persistenceId = factory.generateActorId("notifier-");
factory.createActor(MockRaftActor.builder().id(persistenceId)
- .peerAddresses(ImmutableMap.of("leader", "fake/path"))
+ .peerAddresses(Map.of("leader", "fake/path"))
.config(config).roleChangeNotifier(notifierActor).props());
List<RoleChanged> matches = null;
DataPersistenceProvider dataPersistenceProvider = mock(DataPersistenceProvider.class);
- Map<String, String> peerAddresses = new HashMap<>();
- peerAddresses.put(follower1Id, followerActor1.path().toString());
+ Map<String, String> peerAddresses = Map.of(follower1Id, followerActor1.path().toString());
TestActorRef<MockRaftActor> mockActorRef = factory.createTestActor(
MockRaftActor.props(persistenceId, peerAddresses, config, dataPersistenceProvider), persistenceId);
assertEquals(8, leaderActor.getReplicatedLog().size());
- MockSnapshotState snapshotState = new MockSnapshotState(Arrays.asList(
+ MockSnapshotState snapshotState = new MockSnapshotState(List.of(
new MockRaftActorContext.MockPayload("foo-0"),
new MockRaftActorContext.MockPayload("foo-1"),
new MockRaftActorContext.MockPayload("foo-2"),
DataPersistenceProvider dataPersistenceProvider = mock(DataPersistenceProvider.class);
- Map<String, String> peerAddresses = new HashMap<>();
- peerAddresses.put(leaderId, leaderActor1.path().toString());
+ Map<String, String> peerAddresses = Map.of(leaderId, leaderActor1.path().toString());
TestActorRef<MockRaftActor> mockActorRef = factory.createTestActor(
MockRaftActor.props(persistenceId, peerAddresses, config, dataPersistenceProvider), persistenceId);
assertEquals(6, followerActor.getReplicatedLog().size());
//fake snapshot on index 6
- List<ReplicatedLogEntry> entries = Arrays.asList(
- (ReplicatedLogEntry) new SimpleReplicatedLogEntry(6, 1, new MockRaftActorContext.MockPayload("foo-6")));
+ List<ReplicatedLogEntry> entries = List.of(
+ new SimpleReplicatedLogEntry(6, 1, new MockRaftActorContext.MockPayload("foo-6")));
followerActor.handleCommand(new AppendEntries(1, leaderId, 5, 1, entries, 5, 5, (short)0));
assertEquals(7, followerActor.getReplicatedLog().size());
//fake snapshot on index 7
assertEquals(RaftState.Follower, followerActor.getCurrentBehavior().state());
- entries = Arrays.asList((ReplicatedLogEntry) new SimpleReplicatedLogEntry(7, 1,
+ entries = List.of(new SimpleReplicatedLogEntry(7, 1,
new MockRaftActorContext.MockPayload("foo-7")));
followerActor.handleCommand(new AppendEntries(1, leaderId, 6, 1, entries, 6, 6, (short) 0));
assertEquals(8, followerActor.getReplicatedLog().size());
assertEquals(RaftState.Follower, followerActor.getCurrentBehavior().state());
- ByteString snapshotBytes = fromObject(Arrays.asList(
+ ByteString snapshotBytes = fromObject(List.of(
new MockRaftActorContext.MockPayload("foo-0"),
new MockRaftActorContext.MockPayload("foo-1"),
new MockRaftActorContext.MockPayload("foo-2"),
assertEquals(3, followerActor.getReplicatedLog().size()); //indexes 5,6,7 left in the log
assertEquals(7, followerActor.getReplicatedLog().lastIndex());
- entries = Arrays.asList((ReplicatedLogEntry) new SimpleReplicatedLogEntry(8, 1,
- new MockRaftActorContext.MockPayload("foo-7")));
+ entries = List.of(new SimpleReplicatedLogEntry(8, 1, new MockRaftActorContext.MockPayload("foo-7")));
// send an additional entry 8 with leaderCommit = 7
followerActor.handleCommand(new AppendEntries(1, leaderId, 7, 1, entries, 7, 7, (short) 0));
DataPersistenceProvider dataPersistenceProvider = mock(DataPersistenceProvider.class);
- Map<String, String> peerAddresses = new HashMap<>();
- peerAddresses.put(follower1Id, followerActor1.path().toString());
- peerAddresses.put(follower2Id, followerActor2.path().toString());
+ Map<String, String> peerAddresses = Map.of(
+ follower1Id, followerActor1.path().toString(),
+ follower2Id, followerActor2.path().toString());
TestActorRef<MockRaftActor> mockActorRef = factory.createTestActor(
MockRaftActor.props(persistenceId, peerAddresses, config, dataPersistenceProvider), persistenceId);
assertEquals("Fake snapshot should not happen when Initiate is in progress", 5,
leaderActor.getReplicatedLog().size());
- ByteString snapshotBytes = fromObject(Arrays.asList(
+ ByteString snapshotBytes = fromObject(List.of(
new MockRaftActorContext.MockPayload("foo-0"),
new MockRaftActorContext.MockPayload("foo-1"),
new MockRaftActorContext.MockPayload("foo-2"),
DataPersistenceProvider dataPersistenceProvider = createProvider();
- Map<String, String> peerAddresses = ImmutableMap.<String, String>builder().put("member1", "address").build();
+ Map<String, String> peerAddresses = Map.of("member1", "address");
TestActorRef<MockRaftActor> mockActorRef = factory.createTestActor(
MockRaftActor.props(persistenceId, peerAddresses, config, dataPersistenceProvider), persistenceId);
DataPersistenceProvider dataPersistenceProvider = createProvider();
- Map<String, String> peerAddresses = ImmutableMap.<String, String>builder().put("member1", "address").build();
+ Map<String, String> peerAddresses = Map.of("member1", "address");
TestActorRef<MockRaftActor> mockActorRef = factory.createTestActor(
MockRaftActor.props(persistenceId, peerAddresses, config, dataPersistenceProvider), persistenceId);
DataPersistenceProvider dataPersistenceProvider = createProvider();
- Map<String, String> peerAddresses = ImmutableMap.<String, String>builder().build();
+ Map<String, String> peerAddresses = Map.of();
TestActorRef<MockRaftActor> mockActorRef = factory.createTestActor(
MockRaftActor.props(persistenceId, peerAddresses, config, dataPersistenceProvider), persistenceId);
public void testUpdateConfigParam() {
DefaultConfigParamsImpl emptyConfig = new DefaultConfigParamsImpl();
String persistenceId = factory.generateActorId("follower-");
- ImmutableMap<String, String> peerAddresses =
- ImmutableMap.<String, String>builder().put("member1", "address").build();
+ Map<String, String> peerAddresses = Map.of("member1", "address");
DataPersistenceProvider dataPersistenceProvider = mock(DataPersistenceProvider.class);
TestActorRef<MockRaftActor> actorRef = factory.createTestActor(
new MockRaftActorContext.MockPayload("C")));
TestActorRef<MockRaftActor> raftActorRef = factory.createTestActor(MockRaftActor.props(persistenceId,
- ImmutableMap.<String, String>builder().put("member1", "address").build(), config)
+ Map.of("member1", "address"), config)
.withDispatcher(Dispatchers.DefaultDispatcherId()), persistenceId);
MockRaftActor mockRaftActor = raftActorRef.underlyingActor();
DefaultConfigParamsImpl config = new DefaultConfigParamsImpl();
config.setCustomRaftPolicyImplementationClass(DisableElectionsRaftPolicy.class.getName());
- List<ReplicatedLogEntry> snapshotUnappliedEntries = new ArrayList<>();
- snapshotUnappliedEntries.add(new SimpleReplicatedLogEntry(4, 1, new MockRaftActorContext.MockPayload("E")));
+ List<ReplicatedLogEntry> snapshotUnappliedEntries = List.of(
+ new SimpleReplicatedLogEntry(4, 1, new MockRaftActorContext.MockPayload("E")));
int snapshotLastApplied = 3;
int snapshotLastIndex = 4;
- MockSnapshotState snapshotState = new MockSnapshotState(Arrays.asList(
+ MockSnapshotState snapshotState = new MockSnapshotState(List.of(
new MockRaftActorContext.MockPayload("A"),
new MockRaftActorContext.MockPayload("B"),
new MockRaftActorContext.MockPayload("C"),
// Test with data persistence disabled
- snapshot = Snapshot.create(EmptyState.INSTANCE, Collections.<ReplicatedLogEntry>emptyList(),
+ snapshot = Snapshot.create(EmptyState.INSTANCE, List.of(),
-1, -1, -1, -1, 5, "member-1", null);
persistenceId = factory.generateActorId("test-actor-");
DefaultConfigParamsImpl config = new DefaultConfigParamsImpl();
config.setCustomRaftPolicyImplementationClass(DisableElectionsRaftPolicy.class.getName());
- List<MockPayload> state = Arrays.asList(new MockRaftActorContext.MockPayload("A"));
+ List<MockPayload> state = List.of(new MockRaftActorContext.MockPayload("A"));
Snapshot snapshot = Snapshot.create(ByteState.of(fromObject(state).toByteArray()),
- Arrays.<ReplicatedLogEntry>asList(), 5, 2, 5, 2, 2, "member-1", null);
+ List.of(), 5, 2, 5, 2, 2, "member-1", null);
InMemoryJournal.addEntry(persistenceId, 1, new SimpleReplicatedLogEntry(0, 1,
new MockRaftActorContext.MockPayload("B")));
String persistenceId = factory.generateActorId("test-actor-");
InMemoryJournal.addEntry(persistenceId, 1, new SimpleReplicatedLogEntry(0, 1,
- new ServerConfigurationPayload(Arrays.asList(new ServerInfo(persistenceId, false)))));
+ new ServerConfigurationPayload(List.of(new ServerInfo(persistenceId, false)))));
TestActorRef<MockRaftActor> raftActorRef = factory.createTestActor(MockRaftActor.builder().id(persistenceId)
.config(config).props().withDispatcher(Dispatchers.DefaultDispatcherId()), persistenceId);
mockRaftActor.waitForInitializeBehaviorComplete();
- raftActorRef.tell(new AppendEntries(1L, "leader", 0L, 1L, Collections.<ReplicatedLogEntry>emptyList(),
+ raftActorRef.tell(new AppendEntries(1L, "leader", 0L, 1L, List.of(),
0L, -1L, (short)1), ActorRef.noSender());
LeaderStateChanged leaderStateChange = MessageCollectorActor.expectFirstMatching(
notifierActor, LeaderStateChanged.class);
doReturn(true).when(mockPersistenceProvider).isRecoveryApplicable();
TestActorRef<MockRaftActor> leaderActorRef = factory.createTestActor(
- MockRaftActor.props(leaderId, ImmutableMap.of(followerId, followerActor.path().toString()), config,
+ MockRaftActor.props(leaderId, Map.of(followerId, followerActor.path().toString()), config,
mockPersistenceProvider), leaderId);
MockRaftActor leaderActor = leaderActorRef.underlyingActor();
leaderActor.waitForInitializeBehaviorComplete();
config.setIsolatedLeaderCheckInterval(new FiniteDuration(1, TimeUnit.DAYS));
TestActorRef<MockRaftActor> leaderActorRef = factory.createTestActor(
- MockRaftActor.props(leaderId, ImmutableMap.of(followerId, followerActor.path().toString()), config),
+ MockRaftActor.props(leaderId, Map.of(followerId, followerActor.path().toString()), config),
leaderId);
MockRaftActor leaderActor = leaderActorRef.underlyingActor();
leaderActor.waitForInitializeBehaviorComplete();
TestRaftActor.Builder builder = TestRaftActor.newBuilder()
.id(leaderId)
- .peerAddresses(ImmutableMap.of(followerId,
- mockFollowerActorRef.path().toString()))
+ .peerAddresses(Map.of(followerId, mockFollowerActorRef.path().toString()))
.config(config)
.collectorActor(factory.createActor(
MessageCollectorActor.props(), factory.generateActorId(leaderId + "-collector")));
*/
package org.opendaylight.controller.cluster.raft;
+import static org.junit.Assert.fail;
+
import akka.actor.ActorRef;
import akka.actor.ActorSystem;
import akka.pattern.Patterns;
import com.google.common.util.concurrent.Uninterruptibles;
import java.util.Optional;
import java.util.concurrent.TimeUnit;
-import org.junit.Assert;
import org.opendaylight.controller.cluster.raft.client.messages.FindLeader;
import org.opendaylight.controller.cluster.raft.client.messages.FindLeaderReply;
import org.slf4j.Logger;
public RaftActorTestKit(final ActorSystem actorSystem, final String actorName) {
super(actorSystem);
- raftActor = this.getSystem().actorOf(MockRaftActor.builder().id(actorName).props(), actorName);
+ raftActor = getSystem().actorOf(MockRaftActor.builder().id(actorName).props(), actorName);
}
public ActorRef getRaftActor() {
Uninterruptibles.sleepUninterruptibly(50, TimeUnit.MILLISECONDS);
}
- Assert.fail("Leader not found for actorRef " + actorRef.path());
+ fail("Leader not found for actorRef " + actorRef.path());
}
}
import akka.actor.ActorRef;
import akka.persistence.SaveSnapshotSuccess;
import akka.testkit.TestActorRef;
-import com.google.common.collect.ImmutableMap;
-import com.google.common.collect.Lists;
import java.util.List;
+import java.util.Map;
import org.junit.Before;
import org.junit.Test;
import org.opendaylight.controller.cluster.raft.persisted.ApplyJournalEntries;
String persistenceId = factory.generateActorId("singleNode");
TestActorRef<AbstractRaftActorIntegrationTest.TestRaftActor> singleNodeActorRef =
- newTestRaftActor(persistenceId, ImmutableMap.<String, String>builder().build(), leaderConfigParams);
+ newTestRaftActor(persistenceId, Map.of(), leaderConfigParams);
waitUntilLeader(singleNodeActorRef);
assertEquals("Last applied", 5, singleNodeContext.getLastApplied());
- assertEquals("Incorrect State after snapshot success is received ", Lists.newArrayList(payload0, payload1,
- payload2, payload3, payload4, payload5), singleNodeActorRef.underlyingActor().getState());
+ assertEquals("Incorrect State after snapshot success is received ",
+ List.of(payload0, payload1, payload2, payload3, payload4, payload5),
+ singleNodeActorRef.underlyingActor().getState());
InMemoryJournal.waitForWriteMessagesComplete(persistenceId);
assertEquals(1, persistedSnapshots.size());
List<Object> snapshottedState = MockRaftActor.fromState(persistedSnapshots.get(0).getState());
- assertEquals("Incorrect Snapshot", Lists.newArrayList(payload0, payload1, payload2, payload3),
- snapshottedState);
+ assertEquals("Incorrect Snapshot", List.of(payload0, payload1, payload2, payload3), snapshottedState);
//recovery logic starts
killActor(singleNodeActorRef);
- singleNodeActorRef = newTestRaftActor(persistenceId,
- ImmutableMap.<String, String>builder().build(), leaderConfigParams);
+ singleNodeActorRef = newTestRaftActor(persistenceId, Map.of(), leaderConfigParams);
singleNodeActorRef.underlyingActor().waitForRecoveryComplete();
- assertEquals("Incorrect State after Recovery ", Lists.newArrayList(payload0, payload1, payload2, payload3,
- payload4, payload5), singleNodeActorRef.underlyingActor().getState());
-
+ assertEquals("Incorrect State after Recovery ",
+ List.of(payload0, payload1, payload2, payload3, payload4, payload5),
+ singleNodeActorRef.underlyingActor().getState());
}
}
import akka.actor.ActorRef;
import akka.persistence.SaveSnapshotSuccess;
-import com.google.common.collect.ImmutableMap;
-import java.util.Arrays;
-import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.junit.Before;
@Before
public void setup() {
- follower1Actor = newTestRaftActor(follower1Id, ImmutableMap.of(leaderId, testActorPath(leaderId)),
+ follower1Actor = newTestRaftActor(follower1Id, Map.of(leaderId, testActorPath(leaderId)),
newFollowerConfigParams());
- Map<String, String> leaderPeerAddresses = new HashMap<>();
- leaderPeerAddresses.put(follower1Id, follower1Actor.path().toString());
- leaderPeerAddresses.put(follower2Id, "");
-
leaderConfigParams = newLeaderConfigParams();
- leaderActor = newTestRaftActor(leaderId, leaderPeerAddresses, leaderConfigParams);
+ leaderActor = newTestRaftActor(leaderId, Map.of(follower1Id, follower1Actor.path().toString(), follower2Id, ""),
+ leaderConfigParams);
follower1CollectorActor = follower1Actor.underlyingActor().collectorActor();
leaderCollectorActor = leaderActor.underlyingActor().collectorActor();
assertEquals("Leader commit index", 4, leaderContext.getCommitIndex());
assertEquals("Leader last applied", 4, leaderContext.getLastApplied());
- assertEquals("Leader state", Arrays.asList(payload0, payload1, payload2, payload3, payload4),
+ assertEquals("Leader state", List.of(payload0, payload1, payload2, payload3, payload4),
leaderActor.underlyingActor().getState());
}
assertEquals("Leader commit index", 4, leaderContext.getCommitIndex());
assertEquals("Leader last applied", 4, leaderContext.getLastApplied());
- assertEquals("Leader state", Arrays.asList(payload0, payload1, payload2, payload3, payload4),
+ assertEquals("Leader state", List.of(payload0, payload1, payload2, payload3, payload4),
leaderActor.underlyingActor().getState());
}
leader = leaderActor.underlyingActor().getCurrentBehavior();
- follower2Actor = newTestRaftActor(follower2Id, ImmutableMap.of(leaderId, testActorPath(leaderId)),
- newFollowerConfigParams());
+ follower2Actor = newTestRaftActor(follower2Id,
+ Map.of(leaderId, testActorPath(leaderId)), newFollowerConfigParams());
follower2CollectorActor = follower2Actor.underlyingActor().collectorActor();
leaderActor.tell(new SetPeerAddress(follower2Id, follower2Actor.path().toString()), ActorRef.noSender());
InMemoryJournal.clear();
- follower2Actor = newTestRaftActor(follower2Id, ImmutableMap.of(leaderId, testActorPath(leaderId)),
- newFollowerConfigParams());
+ follower2Actor = newTestRaftActor(follower2Id,
+ Map.of(leaderId, testActorPath(leaderId)), newFollowerConfigParams());
TestRaftActor follower2Underlying = follower2Actor.underlyingActor();
follower2CollectorActor = follower2Underlying.collectorActor();
follower2Context = follower2Underlying.getRaftActorContext();
// Wait for the follower to persist the snapshot.
MessageCollectorActor.expectFirstMatching(follower2CollectorActor, SaveSnapshotSuccess.class);
- final List<MockPayload> expFollowerState = Arrays.asList(payload0, payload1, payload2);
+ final List<MockPayload> expFollowerState = List.of(payload0, payload1, payload2);
assertEquals("Follower commit index", 2, follower2Context.getCommitIndex());
assertEquals("Follower last applied", 2, follower2Context.getLastApplied());
killActor(follower2Actor);
- follower2Actor = newTestRaftActor(follower2Id, ImmutableMap.of(leaderId, testActorPath(leaderId)),
+ follower2Actor = newTestRaftActor(follower2Id, Map.of(leaderId, testActorPath(leaderId)),
newFollowerConfigParams());
follower2Underlying = follower2Actor.underlyingActor();
import akka.japi.Procedure;
import com.google.common.util.concurrent.MoreExecutors;
-import java.util.Collections;
+import java.util.Map;
import java.util.function.Consumer;
import org.junit.Before;
import org.junit.Test;
@Before
public void setup() {
context = new RaftActorContextImpl(null, null, "test",
- new ElectionTermImpl(mockPersistence, "test", LOG), -1, -1, Collections.emptyMap(),
+ new ElectionTermImpl(mockPersistence, "test", LOG), -1, -1, Map.of(),
configParams, mockPersistence, applyState -> { }, LOG, MoreExecutors.directExecutor());
}
import static org.junit.Assert.assertEquals;
import akka.persistence.SaveSnapshotSuccess;
-import com.google.common.collect.ImmutableMap;
import java.util.List;
+import java.util.Map;
import org.junit.Test;
import org.opendaylight.controller.cluster.raft.MockRaftActorContext.MockPayload;
import org.opendaylight.controller.cluster.raft.base.messages.ApplyState;
DefaultConfigParamsImpl followerConfigParams = newFollowerConfigParams();
followerConfigParams.setSnapshotBatchCount(snapshotBatchCount);
- follower1Actor = newTestRaftActor(follower1Id, ImmutableMap.of(leaderId, testActorPath(leaderId),
+ follower1Actor = newTestRaftActor(follower1Id, Map.of(leaderId, testActorPath(leaderId),
follower2Id, testActorPath(follower2Id)), followerConfigParams);
- follower2Actor = newTestRaftActor(follower2Id, ImmutableMap.of(leaderId, testActorPath(leaderId),
+ follower2Actor = newTestRaftActor(follower2Id, Map.of(leaderId, testActorPath(leaderId),
follower1Id, testActorPath(follower1Id)), followerConfigParams);
- peerAddresses = ImmutableMap.<String, String>builder()
- .put(follower1Id, follower1Actor.path().toString())
- .put(follower2Id, follower2Actor.path().toString()).build();
+ peerAddresses = Map.of(
+ follower1Id, follower1Actor.path().toString(),
+ follower2Id, follower2Actor.path().toString());
leaderConfigParams = newLeaderConfigParams();
leaderActor = newTestRaftActor(leaderId, peerAddresses, leaderConfigParams);
package org.opendaylight.controller.cluster.raft;
import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertTrue;
import akka.actor.ActorRef;
import akka.persistence.SaveSnapshotSuccess;
-import com.google.common.collect.ImmutableMap;
import com.google.common.util.concurrent.Uninterruptibles;
-import java.util.Arrays;
-import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.apache.commons.lang3.SerializationUtils;
import org.eclipse.jdt.annotation.Nullable;
-import org.junit.Assert;
import org.junit.Test;
import org.opendaylight.controller.cluster.raft.MockRaftActorContext.MockPayload;
import org.opendaylight.controller.cluster.raft.base.messages.ApplySnapshot;
InMemoryJournal.addEntry(leaderId, 1, new UpdateElectionTerm(initialTerm, leaderId));
// Create the leader and 2 follower actors.
- follower1Actor = newTestRaftActor(follower1Id, ImmutableMap.of(leaderId, testActorPath(leaderId),
+ follower1Actor = newTestRaftActor(follower1Id, Map.of(leaderId, testActorPath(leaderId),
follower2Id, testActorPath(follower2Id)), newFollowerConfigParams());
- follower2Actor = newTestRaftActor(follower2Id, ImmutableMap.of(leaderId, testActorPath(leaderId),
+ follower2Actor = newTestRaftActor(follower2Id, Map.of(leaderId, testActorPath(leaderId),
follower1Id, testActorPath(follower1Id)), newFollowerConfigParams());
- Map<String, String> leaderPeerAddresses = ImmutableMap.<String, String>builder()
- .put(follower1Id, follower1Actor.path().toString())
- .put(follower2Id, follower2Actor.path().toString()).build();
+ Map<String, String> leaderPeerAddresses = Map.of(
+ follower1Id, follower1Actor.path().toString(),
+ follower2Id, follower2Actor.path().toString());
leaderConfigParams = newLeaderConfigParams();
leaderActor = newTestRaftActor(leaderId, leaderPeerAddresses, leaderConfigParams);
follower2 = follower2Actor.underlyingActor().getCurrentBehavior();
currentTerm = leaderContext.getTermInformation().getCurrentTerm();
- assertEquals("Current term > " + initialTerm, true, currentTerm > initialTerm);
+ assertTrue("Current term > " + initialTerm, currentTerm > initialTerm);
leaderCollectorActor = leaderActor.underlyingActor().collectorActor();
follower1CollectorActor = follower1Actor.underlyingActor().collectorActor();
}
private void setupFollower2() {
- follower2Actor = newTestRaftActor(follower2Id, ImmutableMap.of(leaderId, testActorPath(leaderId),
+ follower2Actor = newTestRaftActor(follower2Id, Map.of(leaderId, testActorPath(leaderId),
follower1Id, testActorPath(follower1Id)), newFollowerConfigParams());
follower2Context = follower2Actor.underlyingActor().getRaftActorContext();
// to catch it up because no snapshotting was done so the follower's next index was present in the log.
InstallSnapshot installSnapshot = MessageCollectorActor.getFirstMatching(follower2CollectorActor,
InstallSnapshot.class);
- Assert.assertNull("Follower 2 received unexpected InstallSnapshot", installSnapshot);
+ assertNull("Follower 2 received unexpected InstallSnapshot", installSnapshot);
testLog.info("testReplicationsWithLaggingFollowerCaughtUpViaAppendEntries complete");
}
// Verify the leader did not try to install a snapshot to catch up follower 2.
InstallSnapshot installSnapshot = MessageCollectorActor.getFirstMatching(follower2CollectorActor,
InstallSnapshot.class);
- Assert.assertNull("Follower 2 received unexpected InstallSnapshot", installSnapshot);
+ assertNull("Follower 2 received unexpected InstallSnapshot", installSnapshot);
// Ensure there's at least 1 more heartbeat.
MessageCollectorActor.clearMessages(leaderCollectorActor);
// Send a server config change to test that the install snapshot includes the server config.
- ServerConfigurationPayload serverConfig = new ServerConfigurationPayload(Arrays.asList(
+ ServerConfigurationPayload serverConfig = new ServerConfigurationPayload(List.of(
new ServerInfo(leaderId, true),
new ServerInfo(follower1Id, false),
new ServerInfo(follower2Id, false)));
// Verify a snapshot is not triggered.
CaptureSnapshot captureSnapshot = MessageCollectorActor.getFirstMatching(leaderCollectorActor,
CaptureSnapshot.class);
- Assert.assertNull("Leader received unexpected CaptureSnapshot", captureSnapshot);
+ assertNull("Leader received unexpected CaptureSnapshot", captureSnapshot);
expSnapshotState.add(payload1);
verifyApplyState(applyState, leaderCollectorActor, payload3.toString(), currentTerm, 3, payload3);
captureSnapshot = MessageCollectorActor.getFirstMatching(leaderCollectorActor, CaptureSnapshot.class);
- Assert.assertNull("Leader received unexpected CaptureSnapshot", captureSnapshot);
+ assertNull("Leader received unexpected CaptureSnapshot", captureSnapshot);
// Verify the follower 1 applies the state.
applyState = MessageCollectorActor.expectFirstMatching(follower1CollectorActor, ApplyState.class);
// This is OK - the next snapshot should delete it. In production, even if the system restarted
// before another snapshot, they would both get applied which wouldn't hurt anything.
List<Snapshot> persistedSnapshots = InMemorySnapshotStore.getSnapshots(leaderId, Snapshot.class);
- Assert.assertTrue("Expected at least 1 persisted snapshots", persistedSnapshots.size() > 0);
+ assertFalse("Expected at least 1 persisted snapshots", persistedSnapshots.isEmpty());
Snapshot persistedSnapshot = persistedSnapshots.get(persistedSnapshots.size() - 1);
verifySnapshot("Persisted", persistedSnapshot, currentTerm, lastAppliedIndex, currentTerm, lastAppliedIndex);
List<ReplicatedLogEntry> unAppliedEntry = persistedSnapshot.getUnAppliedEntries();
assertEquals("Persisted Snapshot getUnAppliedEntries size", 0, unAppliedEntry.size());
int snapshotSize = SerializationUtils.serialize(persistedSnapshot.getState()).length;
- final int expTotalChunks = snapshotSize / SNAPSHOT_CHUNK_SIZE
- + (snapshotSize % SNAPSHOT_CHUNK_SIZE > 0 ? 1 : 0);
+ final int expTotalChunks = snapshotSize / MAXIMUM_MESSAGE_SLICE_SIZE
+ + (snapshotSize % MAXIMUM_MESSAGE_SLICE_SIZE > 0 ? 1 : 0);
InstallSnapshot installSnapshot = MessageCollectorActor.expectFirstMatching(follower2CollectorActor,
InstallSnapshot.class);
assertEquals("InstallSnapshotReply getTerm", currentTerm, installSnapshotReply.getTerm());
assertEquals("InstallSnapshotReply getChunkIndex", index++, installSnapshotReply.getChunkIndex());
assertEquals("InstallSnapshotReply getFollowerId", follower2Id, installSnapshotReply.getFollowerId());
- assertEquals("InstallSnapshotReply isSuccess", true, installSnapshotReply.isSuccess());
+ assertTrue("InstallSnapshotReply isSuccess", installSnapshotReply.isSuccess());
}
// Verify follower 2 applies the snapshot.
verifyLeadersTrimmedLog(lastAppliedIndex);
if (expServerConfig != null) {
- Set<ServerInfo> expServerInfo = new HashSet<>(expServerConfig.getServerConfig());
+ Set<ServerInfo> expServerInfo = Set.copyOf(expServerConfig.getServerConfig());
assertEquals("Leader snapshot server config", expServerInfo,
- new HashSet<>(persistedSnapshot.getServerConfiguration().getServerConfig()));
+ Set.copyOf(persistedSnapshot.getServerConfiguration().getServerConfig()));
assertEquals("Follower 2 snapshot server config", expServerInfo,
- new HashSet<>(applySnapshot.getSnapshot().getServerConfiguration().getServerConfig()));
+ Set.copyOf(applySnapshot.getSnapshot().getServerConfiguration().getServerConfig()));
ServerConfigurationPayload follower2ServerConfig = follower2Context.getPeerServerInfo(true);
assertNotNull("Follower 2 server config is null", follower2ServerConfig);
assertEquals("Follower 2 server config", expServerInfo,
- new HashSet<>(follower2ServerConfig.getServerConfig()));
+ Set.copyOf(follower2ServerConfig.getServerConfig()));
}
MessageCollectorActor.clearMessages(leaderCollectorActor);
// Verify the leaders's persisted journal log - it should only contain the last 2 ReplicatedLogEntries
// added after the snapshot as the persisted journal should've been purged to the snapshot
// sequence number.
- verifyPersistedJournal(leaderId, Arrays.asList(new SimpleReplicatedLogEntry(5, currentTerm, payload5),
- new SimpleReplicatedLogEntry(6, currentTerm, payload6)));
+ verifyPersistedJournal(leaderId, List.of(
+ new SimpleReplicatedLogEntry(5, currentTerm, payload5),
+ new SimpleReplicatedLogEntry(6, currentTerm, payload6)));
// Verify the leaders's persisted journal contains an ApplyJournalEntries for at least the last entry index.
List<ApplyJournalEntries> persistedApplyJournalEntries =
}
}
- Assert.assertTrue(String.format("ApplyJournalEntries with index %d not found in leader's persisted journal", 6),
- found);
+ assertTrue("ApplyJournalEntries with index 6 not found in leader's persisted journal", found);
// Verify follower 1 applies the 3 log entries.
applyStates = MessageCollectorActor.expectMatching(follower1CollectorActor, ApplyState.class, 3);
}
private void sendInitialPayloadsReplicatedToAllFollowers(final String... data) {
-
// Send the payloads.
for (String d: data) {
expSnapshotState.add(sendPayloadData(leaderActor, d));
int numEntries = data.length;
// Verify the leader got consensus and applies each log entry even though follower 2 didn't respond.
- List<ApplyState> applyStates = MessageCollectorActor.expectMatching(leaderCollectorActor,
- ApplyState.class, numEntries);
+ final var leaderStates = MessageCollectorActor.expectMatching(leaderCollectorActor,
+ ApplyState.class, numEntries);
for (int i = 0; i < expSnapshotState.size(); i++) {
- MockPayload payload = expSnapshotState.get(i);
- verifyApplyState(applyStates.get(i), leaderCollectorActor, payload.toString(), currentTerm, i, payload);
+ final MockPayload payload = expSnapshotState.get(i);
+ verifyApplyState(leaderStates.get(i), leaderCollectorActor, payload.toString(), currentTerm, i, payload);
}
// Verify follower 1 applies each log entry.
- applyStates = MessageCollectorActor.expectMatching(follower1CollectorActor, ApplyState.class, numEntries);
+ final var follower1States = MessageCollectorActor.expectMatching(follower1CollectorActor,
+ ApplyState.class, numEntries);
for (int i = 0; i < expSnapshotState.size(); i++) {
- MockPayload payload = expSnapshotState.get(i);
- verifyApplyState(applyStates.get(i), null, null, currentTerm, i, payload);
+ final MockPayload payload = expSnapshotState.get(i);
+ verifyApplyState(follower1States.get(i), null, null, currentTerm, i, payload);
}
// Verify follower 2 applies each log entry.
- applyStates = MessageCollectorActor.expectMatching(follower2CollectorActor, ApplyState.class, numEntries);
+ final var follower2States = MessageCollectorActor.expectMatching(follower2CollectorActor,
+ ApplyState.class, numEntries);
for (int i = 0; i < expSnapshotState.size(); i++) {
- MockPayload payload = expSnapshotState.get(i);
- verifyApplyState(applyStates.get(i), null, null, currentTerm, i, payload);
+ final MockPayload payload = expSnapshotState.get(i);
+ verifyApplyState(follower2States.get(i), null, null, currentTerm, i, payload);
}
// Ensure there's at least 1 more heartbeat.
import static org.opendaylight.controller.cluster.raft.utils.MessageCollectorActor.expectMatching;
-import com.google.common.collect.ImmutableMap;
import java.util.List;
+import java.util.Map;
import org.junit.Test;
import org.opendaylight.controller.cluster.raft.MockRaftActorContext.MockPayload;
import org.opendaylight.controller.cluster.raft.base.messages.ApplyState;
// Create the leader and 2 follower actors.
- snapshotChunkSize = 20;
+ maximumMessageSliceSize = 20;
DefaultConfigParamsImpl followerConfigParams = newFollowerConfigParams();
followerConfigParams.setSnapshotBatchCount(snapshotBatchCount);
- follower1Actor = newTestRaftActor(follower1Id, ImmutableMap.of(leaderId, testActorPath(leaderId),
+ follower1Actor = newTestRaftActor(follower1Id, Map.of(leaderId, testActorPath(leaderId),
follower2Id, testActorPath(follower2Id)), followerConfigParams);
- follower2Actor = newTestRaftActor(follower2Id, ImmutableMap.of(leaderId, testActorPath(leaderId),
+ follower2Actor = newTestRaftActor(follower2Id, Map.of(leaderId, testActorPath(leaderId),
follower1Id, testActorPath(follower1Id)), followerConfigParams);
- peerAddresses = ImmutableMap.<String, String>builder()
- .put(follower1Id, follower1Actor.path().toString())
- .put(follower2Id, follower2Actor.path().toString()).build();
+ peerAddresses = Map.of(
+ follower1Id, follower1Actor.path().toString(),
+ follower2Id, follower2Actor.path().toString());
leaderConfigParams = newLeaderConfigParams();
leaderActor = newTestRaftActor(leaderId, peerAddresses, leaderConfigParams);
// Send a large payload that exceeds the size threshold and needs to be sliced.
- MockPayload largePayload = sendPayloadData(leaderActor, "large", snapshotChunkSize + 1);
+ MockPayload largePayload = sendPayloadData(leaderActor, "large", maximumMessageSliceSize + 1);
// Then send a small payload that does not need to be sliced.
- MockPayload smallPayload = sendPayloadData(leaderActor, "normal", snapshotChunkSize - 1);
+ MockPayload smallPayload = sendPayloadData(leaderActor, "normal", maximumMessageSliceSize - 1);
final List<ApplyState> leaderApplyState = expectMatching(leaderCollectorActor, ApplyState.class, 2);
verifyApplyState(leaderApplyState.get(0), leaderCollectorActor,
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
-
package org.opendaylight.controller.cluster.raft;
import static org.junit.Assert.assertArrayEquals;
import akka.actor.ActorRef;
import akka.persistence.SnapshotSelectionCriteria;
import java.io.OutputStream;
-import java.util.Arrays;
+import java.util.List;
import java.util.Optional;
import java.util.function.Consumer;
import org.junit.After;
8L, 2L, new MockRaftActorContext.MockPayload());
doReturn(lastAppliedEntry).when(mockReplicatedLog).get(8L);
- doReturn(Arrays.asList(lastLogEntry)).when(mockReplicatedLog).getFrom(9L);
+ doReturn(List.of(lastLogEntry)).when(mockReplicatedLog).getFrom(9L);
// when replicatedToAllIndex = -1
snapshotManager.capture(lastLogEntry, -1);
assertEquals("getLastAppliedTerm", 2L, snapshot.getLastAppliedTerm());
assertEquals("getLastAppliedIndex", 8L, snapshot.getLastAppliedIndex());
assertEquals("getState", snapshotState, snapshot.getState());
- assertEquals("getUnAppliedEntries", Arrays.asList(lastLogEntry), snapshot.getUnAppliedEntries());
+ assertEquals("getUnAppliedEntries", List.of(lastLogEntry), snapshot.getUnAppliedEntries());
assertEquals("electionTerm", mockElectionTerm.getCurrentTerm(), snapshot.getElectionTerm());
assertEquals("electionVotedFor", mockElectionTerm.getVotedFor(), snapshot.getElectionVotedFor());
Optional<OutputStream> installSnapshotStream = installSnapshotStreamCapture.getValue();
assertEquals("isPresent", true, installSnapshotStream.isPresent());
- installSnapshotStream.get().write(snapshotState.getBytes());
+ installSnapshotStream.orElseThrow().write(snapshotState.getBytes());
snapshotManager.persist(snapshotState, installSnapshotStream, Runtime.getRuntime().totalMemory());
*/
package org.opendaylight.controller.cluster.raft;
+import static org.junit.Assert.assertTrue;
+
import akka.actor.Actor;
import akka.actor.ActorIdentity;
import akka.actor.ActorRef;
import com.google.common.base.Stopwatch;
import com.google.common.util.concurrent.Uninterruptibles;
import java.time.Duration;
-import java.util.LinkedList;
+import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
-import org.junit.Assert;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import scala.concurrent.Await;
private static final Logger LOG = LoggerFactory.getLogger(TestActorFactory.class);
private final ActorSystem system;
- List<ActorRef> createdActors = new LinkedList<>();
+ private final List<ActorRef> createdActors = new ArrayList<>();
private static int actorCount = 1;
public TestActorFactory(final ActorSystem system) {
ActorSelection actorSelection = system.actorSelection(actorRef.path().toString());
Future<Object> future = Patterns.ask(actorSelection, new Identify(""), timeout);
ActorIdentity reply = (ActorIdentity)Await.result(future, timeout.duration());
- Assert.assertTrue("Identify returned non-present", reply.getActorRef().isPresent());
+ assertTrue("Identify returned non-present", reply.getActorRef().isPresent());
return;
} catch (Exception | AssertionError e) {
Uninterruptibles.sleepUninterruptibly(100, TimeUnit.MILLISECONDS);
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertSame;
-import org.apache.commons.lang.SerializationUtils;
+import org.apache.commons.lang3.SerializationUtils;
import org.junit.Test;
/**
import static org.junit.Assert.assertEquals;
-import org.apache.commons.lang.SerializationUtils;
+import org.apache.commons.lang3.SerializationUtils;
import org.junit.Test;
/**
*/
package org.opendaylight.controller.cluster.raft.behaviors;
+import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import akka.testkit.TestActorRef;
import akka.testkit.javadsl.TestKit;
import com.google.common.base.Stopwatch;
-import com.google.common.collect.ImmutableList;
-import com.google.common.collect.ImmutableMap;
import com.google.common.io.ByteSource;
import com.google.common.util.concurrent.Uninterruptibles;
import java.io.OutputStream;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.HashMap;
import java.util.List;
+import java.util.Map;
import java.util.Optional;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import org.junit.After;
-import org.junit.Assert;
import org.junit.Test;
import org.opendaylight.controller.cluster.raft.DefaultConfigParamsImpl;
import org.opendaylight.controller.cluster.raft.MockRaftActor;
Uninterruptibles.sleepUninterruptibly(context.getConfigParams()
.getElectionTimeOutInterval().toMillis() - 100, TimeUnit.MILLISECONDS);
- follower.handleMessage(leaderActor, new AppendEntries(1, "leader", -1, -1, Collections.emptyList(),
+ follower.handleMessage(leaderActor, new AppendEntries(1, "leader", -1, -1, List.of(),
-1, -1, (short) 1));
Uninterruptibles.sleepUninterruptibly(130, TimeUnit.MILLISECONDS);
Uninterruptibles.sleepUninterruptibly(context.getConfigParams()
.getElectionTimeOutInterval().toMillis() - 150, TimeUnit.MILLISECONDS);
- follower.handleMessage(leaderActor, new AppendEntries(1, "leader", -1, -1, Collections.emptyList(),
+ follower.handleMessage(leaderActor, new AppendEntries(1, "leader", -1, -1, List.of(),
-1, -1, (short) 1));
Uninterruptibles.sleepUninterruptibly(200, TimeUnit.MILLISECONDS);
context.getReplicatedLog().append(newReplicatedLogEntry(1,100, "bar"));
context.getReplicatedLog().setSnapshotIndex(99);
- List<ReplicatedLogEntry> entries = Arrays.asList(
- newReplicatedLogEntry(2, 101, "foo"));
+ List<ReplicatedLogEntry> entries = List.of(newReplicatedLogEntry(2, 101, "foo"));
- Assert.assertEquals(1, context.getReplicatedLog().size());
+ assertEquals(1, context.getReplicatedLog().size());
// The new commitIndex is 101
AppendEntries appendEntries = new AppendEntries(2, "leader-1", 100, 1, entries, 101, 100, (short)0);
MockRaftActorContext context = createActorContext();
- List<ReplicatedLogEntry> entries = Arrays.asList(
- newReplicatedLogEntry(2, 101, "foo"));
+ List<ReplicatedLogEntry> entries = List.of(newReplicatedLogEntry(2, 101, "foo"));
// The new commitIndex is 101
AppendEntries appendEntries = new AppendEntries(2, "leader-1", -1, -1, entries, 101, 100, (short) 0);
context.getReplicatedLog().append(newReplicatedLogEntry(1, 100, "bar"));
context.getReplicatedLog().setSnapshotIndex(99);
- List<ReplicatedLogEntry> entries = Arrays.asList(
- newReplicatedLogEntry(2, 101, "foo"));
+ List<ReplicatedLogEntry> entries = List.of(newReplicatedLogEntry(2, 101, "foo"));
// The new commitIndex is 101
AppendEntries appendEntries = new AppendEntries(2, "leader-1", -1, -1, entries, 101, 100, (short) 0);
context.getReplicatedLog().clear(0,2);
context.getReplicatedLog().setSnapshotIndex(100);
- List<ReplicatedLogEntry> entries = Arrays.asList(
- newReplicatedLogEntry(2, 101, "foo"));
+ List<ReplicatedLogEntry> entries = List.of(newReplicatedLogEntry(2, 101, "foo"));
// The new commitIndex is 101
AppendEntries appendEntries = new AppendEntries(2, "leader-1", -1, -1, entries, 101, 100, (short) 0);
context.getReplicatedLog().clear(0,2);
context.getReplicatedLog().setSnapshotIndex(100);
- List<ReplicatedLogEntry> entries = Arrays.asList(
- newReplicatedLogEntry(2, 105, "foo"));
+ List<ReplicatedLogEntry> entries = List.of(newReplicatedLogEntry(2, 105, "foo"));
// The new commitIndex is 101
AppendEntries appendEntries = new AppendEntries(2, "leader-1", -1, -1, entries, 105, 100, (short) 0);
MockRaftActorContext context = createActorContext();
- List<ReplicatedLogEntry> entries = Arrays.asList(
- newReplicatedLogEntry(2, 101, "foo"));
+ List<ReplicatedLogEntry> entries = List.of(newReplicatedLogEntry(2, 101, "foo"));
// The new commitIndex is 101
AppendEntries appendEntries = new AppendEntries(2, "leader-1", 100, 1, entries, 101, 100, (short)0);
context.setCommitIndex(101);
setLastLogEntry(context, 1, 101, new MockRaftActorContext.MockPayload(""));
- entries = Arrays.asList(newReplicatedLogEntry(2, 101, "foo"));
+ entries = List.of(newReplicatedLogEntry(2, 101, "foo"));
// The new commitIndex is 101
appendEntries = new AppendEntries(2, "leader-1", 101, 1, entries, 102, 101, (short)0);
MockRaftActorContext context = createActorContext();
- List<ReplicatedLogEntry> entries = Arrays.asList(
- newReplicatedLogEntry(2, 101, "foo"));
+ List<ReplicatedLogEntry> entries = List.of(newReplicatedLogEntry(2, 101, "foo"));
// The new commitIndex is 101
AppendEntries appendEntries = new AppendEntries(2, "leader-1", 100, 1, entries, 101, 100, (short)0);
setLastLogEntry(context, 1, 100,
new MockRaftActorContext.MockPayload(""));
- entries = Arrays.asList(
- newReplicatedLogEntry(2, 101, "foo"));
+ entries = List.of(newReplicatedLogEntry(2, 101, "foo"));
// leader-2 is becoming the leader now and it says the commitIndex is 45
appendEntries = new AppendEntries(2, "leader-2", 45, 1, entries, 46, 100, (short)0);
MockRaftActorContext context = createActorContext();
- List<ReplicatedLogEntry> entries = Arrays.asList(
- newReplicatedLogEntry(2, 101, "foo"));
+ List<ReplicatedLogEntry> entries = List.of(newReplicatedLogEntry(2, 101, "foo"));
// The new commitIndex is 101
AppendEntries appendEntries = new AppendEntries(2, "leader-1", 100, 1, entries, 101, 100, (short)0);
setLastLogEntry(context, 1, 101,
new MockRaftActorContext.MockPayload(""));
- entries = Arrays.asList(
- newReplicatedLogEntry(2, 101, "foo"));
+ entries = List.of(newReplicatedLogEntry(2, 101, "foo"));
// The new commitIndex is 101
appendEntries = new AppendEntries(2, "leader-1", 101, 1, entries, 102, 101, (short)0);
setLastLogEntry(context, 1, 100,
new MockRaftActorContext.MockPayload(""));
- entries = Arrays.asList(
- newReplicatedLogEntry(2, 101, "foo"));
+ entries = List.of(newReplicatedLogEntry(2, 101, "foo"));
// leader-2 is becoming the leader now and it says the commitIndex is 45
appendEntries = new AppendEntries(2, "leader-2", 45, 1, entries, 46, 100, (short)0);
new MockRaftActorContext.MockPayload(""));
context.getReplicatedLog().setSnapshotIndex(99);
- List<ReplicatedLogEntry> entries = Arrays.<ReplicatedLogEntry>asList(
- newReplicatedLogEntry(2, 101, "foo"));
+ List<ReplicatedLogEntry> entries = List.of(newReplicatedLogEntry(2, 101, "foo"));
// The new commitIndex is 101
AppendEntries appendEntries = new AppendEntries(2, "leader-1", 100, 1, entries, 101, 100, (short)0);
MockRaftActorContext context = createActorContext();
- AppendEntries appendEntries = new AppendEntries(2, "leader", 0, 2, Collections.emptyList(), 101, -1, (short)0);
+ AppendEntries appendEntries = new AppendEntries(2, "leader", 0, 2, List.of(), 101, -1, (short)0);
follower = createBehavior(context);
RaftActorBehavior newBehavior = follower.handleMessage(leaderActor, appendEntries);
- Assert.assertSame(follower, newBehavior);
+ assertSame(follower, newBehavior);
AppendEntriesReply reply = MessageCollectorActor.expectFirstMatching(leaderActor,
AppendEntriesReply.class);
context.getReplicatedLog().setSnapshotIndex(4);
context.getReplicatedLog().setSnapshotTerm(3);
- AppendEntries appendEntries = new AppendEntries(3, "leader", 1, 3, Collections.emptyList(), 8, -1, (short)0);
+ AppendEntries appendEntries = new AppendEntries(3, "leader", 1, 3, List.of(), 8, -1, (short)0);
follower = createBehavior(context);
RaftActorBehavior newBehavior = follower.handleMessage(leaderActor, appendEntries);
- Assert.assertSame(follower, newBehavior);
+ assertSame(follower, newBehavior);
AppendEntriesReply reply = MessageCollectorActor.expectFirstMatching(leaderActor, AppendEntriesReply.class);
context.setReplicatedLog(log);
// Prepare the entries to be sent with AppendEntries
- List<ReplicatedLogEntry> entries = new ArrayList<>();
- entries.add(newReplicatedLogEntry(1, 3, "three"));
- entries.add(newReplicatedLogEntry(1, 4, "four"));
+ List<ReplicatedLogEntry> entries = List.of(
+ newReplicatedLogEntry(1, 3, "three"), newReplicatedLogEntry(1, 4, "four"));
// Send appendEntries with the same term as was set on the receiver
// before the new behavior was created (1 in this case)
RaftActorBehavior newBehavior = follower.handleMessage(leaderActor, appendEntries);
- Assert.assertSame(follower, newBehavior);
+ assertSame(follower, newBehavior);
assertEquals("Next index", 5, log.last().getIndex() + 1);
assertEquals("Entry 3", entries.get(0), log.get(3));
context.setReplicatedLog(log);
// Prepare the entries to be sent with AppendEntries
- List<ReplicatedLogEntry> entries = new ArrayList<>();
- entries.add(newReplicatedLogEntry(2, 2, "two-1"));
- entries.add(newReplicatedLogEntry(2, 3, "three"));
+ List<ReplicatedLogEntry> entries = List.of(
+ newReplicatedLogEntry(2, 2, "two-1"), newReplicatedLogEntry(2, 3, "three"));
// Send appendEntries with the same term as was set on the receiver
// before the new behavior was created (1 in this case)
RaftActorBehavior newBehavior = follower.handleMessage(leaderActor, appendEntries);
- Assert.assertSame(follower, newBehavior);
+ assertSame(follower, newBehavior);
// The entry at index 2 will be found out-of-sync with the leader
// and will be removed
context.setReplicatedLog(log);
// Prepare the entries to be sent with AppendEntries
- List<ReplicatedLogEntry> entries = new ArrayList<>();
- entries.add(newReplicatedLogEntry(2, 2, "two-1"));
- entries.add(newReplicatedLogEntry(2, 3, "three"));
+ List<ReplicatedLogEntry> entries = List.of(
+ newReplicatedLogEntry(2, 2, "two-1"), newReplicatedLogEntry(2, 3, "three"));
// Send appendEntries with the same term as was set on the receiver
// before the new behavior was created (1 in this case)
RaftActorBehavior newBehavior = follower.handleMessage(leaderActor, appendEntries);
- Assert.assertSame(follower, newBehavior);
+ assertSame(follower, newBehavior);
expectAndVerifyAppendEntriesReply(2, false, context.getId(), 1, 2, true);
}
context.setReplicatedLog(log);
// Prepare the entries to be sent with AppendEntries
- List<ReplicatedLogEntry> entries = new ArrayList<>();
- entries.add(newReplicatedLogEntry(1, 4, "four"));
+ List<ReplicatedLogEntry> entries = List.of(newReplicatedLogEntry(1, 4, "four"));
AppendEntries appendEntries = new AppendEntries(1, "leader", 3, 1, entries, 4, -1, (short)0);
RaftActorBehavior newBehavior = follower.handleMessage(leaderActor, appendEntries);
- Assert.assertSame(follower, newBehavior);
+ assertSame(follower, newBehavior);
expectAndVerifyAppendEntriesReply(1, false, context.getId(), 1, 2);
}
context.setReplicatedLog(log);
// Send the last entry again.
- List<ReplicatedLogEntry> entries = Arrays.asList(newReplicatedLogEntry(1, 1, "one"));
+ List<ReplicatedLogEntry> entries = List.of(newReplicatedLogEntry(1, 1, "one"));
follower = createBehavior(context);
// Send the last entry again and also a new one.
- entries = Arrays.asList(newReplicatedLogEntry(1, 1, "one"), newReplicatedLogEntry(1, 2, "two"));
+ entries = List.of(newReplicatedLogEntry(1, 1, "one"), newReplicatedLogEntry(1, 2, "two"));
MessageCollectorActor.clearMessages(leaderActor);
follower.handleMessage(leaderActor, new AppendEntries(1, "leader", 0, 1, entries, 2, -1, (short)0));
context.setReplicatedLog(log);
// Prepare the entries to be sent with AppendEntries
- List<ReplicatedLogEntry> entries = new ArrayList<>();
- entries.add(newReplicatedLogEntry(1, 4, "four"));
+ List<ReplicatedLogEntry> entries = List.of(newReplicatedLogEntry(1, 4, "four"));
AppendEntries appendEntries = new AppendEntries(1, "leader", 3, 1, entries, 4, 3, (short)0);
RaftActorBehavior newBehavior = follower.handleMessage(leaderActor, appendEntries);
- Assert.assertSame(follower, newBehavior);
+ assertSame(follower, newBehavior);
expectAndVerifyAppendEntriesReply(1, true, context.getId(), 1, 4);
}
snapshot.getLastAppliedIndex());
assertEquals("getLastTerm", lastInstallSnapshot.getLastIncludedTerm(), snapshot.getLastTerm());
assertEquals("getState type", ByteState.class, snapshot.getState().getClass());
- Assert.assertArrayEquals("getState", bsSnapshot.toByteArray(), ((ByteState)snapshot.getState()).getBytes());
+ assertArrayEquals("getState", bsSnapshot.toByteArray(), ((ByteState)snapshot.getState()).getBytes());
assertEquals("getElectionTerm", 1, snapshot.getElectionTerm());
assertEquals("getElectionVotedFor", "leader", snapshot.getElectionVotedFor());
applySnapshot.getCallback().onSuccess();
// Send an append entry
AppendEntries appendEntries = new AppendEntries(1, "leader", 1, 1,
- Arrays.asList(newReplicatedLogEntry(2, 1, "3")), 2, -1, (short)1);
+ List.of(newReplicatedLogEntry(2, 1, "3")), 2, -1, (short)1);
follower.handleMessage(leaderActor, appendEntries);
// Send appendEntries with a new term and leader.
AppendEntries appendEntries = new AppendEntries(2, "new-leader", 1, 1,
- Arrays.asList(newReplicatedLogEntry(2, 2, "3")), 2, -1, (short)1);
+ List.of(newReplicatedLogEntry(2, 2, "3")), 2, -1, (short)1);
follower.handleMessage(leaderActor, appendEntries);
setLastLogEntry(context, 1, 101,
new MockRaftActorContext.MockPayload(""));
- List<ReplicatedLogEntry> entries = Arrays.asList(
- newReplicatedLogEntry(2, 101, "foo"));
+ List<ReplicatedLogEntry> entries = List.of(newReplicatedLogEntry(2, 101, "foo"));
// The new commitIndex is 101
AppendEntries appendEntries = new AppendEntries(2, "leader", 101, 1, entries, 102, 101, (short)0);
@Test
public void testFollowerSchedulesElectionIfNonVoting() {
MockRaftActorContext context = createActorContext();
- context.updatePeerIds(new ServerConfigurationPayload(Arrays.asList(new ServerInfo(context.getId(), false))));
+ context.updatePeerIds(new ServerConfigurationPayload(List.of(new ServerInfo(context.getId(), false))));
((DefaultConfigParamsImpl)context.getConfigParams()).setHeartBeatInterval(
FiniteDuration.apply(100, TimeUnit.MILLISECONDS));
((DefaultConfigParamsImpl)context.getConfigParams()).setElectionTimeoutFactor(1);
final AtomicReference<MockRaftActor> followerRaftActor = new AtomicReference<>();
RaftActorSnapshotCohort snapshotCohort = newRaftActorSnapshotCohort(followerRaftActor);
Builder builder = MockRaftActor.builder().persistent(Optional.of(true)).id(id)
- .peerAddresses(ImmutableMap.of("leader", "")).config(config).snapshotCohort(snapshotCohort);
+ .peerAddresses(Map.of("leader", "")).config(config).snapshotCohort(snapshotCohort);
TestActorRef<MockRaftActor> followerActorRef = actorFactory.createTestActor(builder.props()
.withDispatcher(Dispatchers.DefaultDispatcherId()), id);
followerRaftActor.set(followerActorRef.underlyingActor());
InMemoryJournal.addDeleteMessagesCompleteLatch(id);
InMemoryJournal.addWriteMessagesCompleteLatch(id, 1, ApplyJournalEntries.class);
- List<ReplicatedLogEntry> entries = Arrays.asList(
+ List<ReplicatedLogEntry> entries = List.of(
newReplicatedLogEntry(1, 0, "one"), newReplicatedLogEntry(1, 1, "two"));
AppendEntries appendEntries = new AppendEntries(1, "leader", -1, -1, entries, 1, -1, (short)0);
assertEquals("Snapshot getLastAppliedIndex", 1, snapshot.getLastAppliedIndex());
assertEquals("Snapshot getLastTerm", 1, snapshot.getLastTerm());
assertEquals("Snapshot getLastIndex", 1, snapshot.getLastIndex());
- assertEquals("Snapshot state", ImmutableList.of(entries.get(0).getData(), entries.get(1).getData()),
+ assertEquals("Snapshot state", List.of(entries.get(0).getData(), entries.get(1).getData()),
MockRaftActor.fromState(snapshot.getState()));
}
final AtomicReference<MockRaftActor> followerRaftActor = new AtomicReference<>();
RaftActorSnapshotCohort snapshotCohort = newRaftActorSnapshotCohort(followerRaftActor);
Builder builder = MockRaftActor.builder().persistent(Optional.of(true)).id(id)
- .peerAddresses(ImmutableMap.of("leader", "")).config(config).snapshotCohort(snapshotCohort);
+ .peerAddresses(Map.of("leader", "")).config(config).snapshotCohort(snapshotCohort);
TestActorRef<MockRaftActor> followerActorRef = actorFactory.createTestActor(builder.props()
.withDispatcher(Dispatchers.DefaultDispatcherId()), id);
followerRaftActor.set(followerActorRef.underlyingActor());
InMemoryJournal.addDeleteMessagesCompleteLatch(id);
InMemoryJournal.addWriteMessagesCompleteLatch(id, 1, ApplyJournalEntries.class);
- List<ReplicatedLogEntry> entries = Arrays.asList(
+ List<ReplicatedLogEntry> entries = List.of(
newReplicatedLogEntry(1, 0, "one"), newReplicatedLogEntry(1, 1, "two"),
newReplicatedLogEntry(1, 2, "three"));
assertEquals("Snapshot getLastAppliedIndex", 2, snapshot.getLastAppliedIndex());
assertEquals("Snapshot getLastTerm", 1, snapshot.getLastTerm());
assertEquals("Snapshot getLastIndex", 2, snapshot.getLastIndex());
- assertEquals("Snapshot state", ImmutableList.of(entries.get(0).getData(), entries.get(1).getData(),
+ assertEquals("Snapshot state", List.of(entries.get(0).getData(), entries.get(1).getData(),
entries.get(2).getData()), MockRaftActor.fromState(snapshot.getState()));
assertEquals("Journal size", 0, followerRaftActor.get().getReplicatedLog().size());
assertEquals("Last index", 2, followerRaftActor.get().getReplicatedLog().lastIndex());
assertEquals("Last applied index", 2, followerRaftActor.get().getRaftActorContext().getLastApplied());
assertEquals("Commit index", 2, followerRaftActor.get().getRaftActorContext().getCommitIndex());
- assertEquals("State", ImmutableList.of(entries.get(0).getData(), entries.get(1).getData(),
+ assertEquals("State", List.of(entries.get(0).getData(), entries.get(1).getData(),
entries.get(2).getData()), followerRaftActor.get().getState());
}
final AtomicReference<MockRaftActor> followerRaftActor = new AtomicReference<>();
RaftActorSnapshotCohort snapshotCohort = newRaftActorSnapshotCohort(followerRaftActor);
Builder builder = MockRaftActor.builder().persistent(Optional.of(true)).id(id)
- .peerAddresses(ImmutableMap.of("leader", "")).config(config).snapshotCohort(snapshotCohort);
+ .peerAddresses(Map.of("leader", "")).config(config).snapshotCohort(snapshotCohort);
TestActorRef<MockRaftActor> followerActorRef = actorFactory.createTestActor(builder.props()
.withDispatcher(Dispatchers.DefaultDispatcherId()), id);
followerRaftActor.set(followerActorRef.underlyingActor());
InMemoryJournal.addDeleteMessagesCompleteLatch(id);
InMemoryJournal.addWriteMessagesCompleteLatch(id, 1, ApplyJournalEntries.class);
- List<ReplicatedLogEntry> entries = Arrays.asList(
+ List<ReplicatedLogEntry> entries = List.of(
newReplicatedLogEntry(1, 0, "one"), newReplicatedLogEntry(1, 1, "two"),
newReplicatedLogEntry(1, 2, "three"));
assertEquals("Snapshot getLastAppliedIndex", 0, snapshot.getLastAppliedIndex());
assertEquals("Snapshot getLastTerm", 1, snapshot.getLastTerm());
assertEquals("Snapshot getLastIndex", 2, snapshot.getLastIndex());
- assertEquals("Snapshot state", ImmutableList.of(entries.get(0).getData()),
+ assertEquals("Snapshot state", List.of(entries.get(0).getData()),
MockRaftActor.fromState(snapshot.getState()));
}
follower = createBehavior(context);
follower.handleMessage(leaderActor,
- new AppendEntries(1, "leader", -1, -1, Collections.emptyList(), -1, -1, (short)0));
+ new AppendEntries(1, "leader", -1, -1, List.of(), -1, -1, (short)0));
AppendEntriesReply reply = MessageCollectorActor.expectFirstMatching(leaderActor, AppendEntriesReply.class);
assertTrue(reply.isNeedsLeaderAddress());
PeerAddressResolver mockResolver = mock(PeerAddressResolver.class);
((DefaultConfigParamsImpl)context.getConfigParams()).setPeerAddressResolver(mockResolver);
- follower.handleMessage(leaderActor, new AppendEntries(1, "leader", -1, -1, Collections.emptyList(), -1, -1,
+ follower.handleMessage(leaderActor, new AppendEntries(1, "leader", -1, -1, List.of(), -1, -1,
(short)0, RaftVersions.CURRENT_VERSION, leaderActor.path().toString()));
reply = MessageCollectorActor.expectFirstMatching(leaderActor, AppendEntriesReply.class);
int size = chunkSize;
if (chunkSize > snapshotLength) {
size = snapshotLength;
- } else {
- if (start + chunkSize > snapshotLength) {
- size = snapshotLength - start;
- }
+ } else if (start + chunkSize > snapshotLength) {
+ size = snapshotLength - start;
}
byte[] nextChunk = new byte[size];
}
private ByteString createSnapshot() {
- HashMap<String, String> followerSnapshot = new HashMap<>();
- followerSnapshot.put("1", "A");
- followerSnapshot.put("2", "B");
- followerSnapshot.put("3", "C");
-
- return toByteString(followerSnapshot);
+ return toByteString(Map.of("1", "A", "2", "B", "3", "C"));
}
@Override
--- /dev/null
+/*
+ * Copyright (c) 2023 PANTHEON.tech, s.r.o. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.controller.cluster.raft.behaviors;
+
+import static org.junit.Assert.assertEquals;
+
+import com.google.common.io.ByteSource;
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.Arrays;
+import java.util.Objects;
+import org.junit.Test;
+
+public class LeaderInstallSnapshotStateTest {
+ // Prime number on purpose
+ private static final int CHUNK_SIZE = 9_999_991;
+ // More than Integer.MAX_VALUE
+ private static final long SIZE = 4_294_967_294L;
+
+ @Test
+ public void testSnapshotLongerThanInteger() throws IOException {
+ try (var fts = new LeaderInstallSnapshotState(CHUNK_SIZE, "test")) {
+ fts.setSnapshotBytes(new MockByteSource(SIZE));
+
+ int chunkIndex = 0;
+ long offset = 0;
+ long expectedChunkSize = CHUNK_SIZE;
+ while (offset < SIZE) {
+ offset = offset + CHUNK_SIZE;
+ if (offset > SIZE) {
+ // We reached last chunk
+ expectedChunkSize = CHUNK_SIZE - (offset - SIZE);
+ offset = SIZE;
+ }
+ chunkIndex ++;
+ final byte[] chunk = fts.getNextChunk();
+ assertEquals("byte size not matching for chunk:", expectedChunkSize, chunk.length);
+ assertEquals("chunk index not matching", chunkIndex, fts.getChunkIndex());
+ fts.markSendStatus(true);
+ if (!fts.isLastChunk(chunkIndex)) {
+ fts.incrementChunkIndex();
+ }
+ }
+
+ assertEquals("totalChunks not matching", chunkIndex, fts.getTotalChunks());
+ }
+ }
+
+ private static final class MockByteSource extends ByteSource {
+ private final long size;
+
+ private MockByteSource(final long size) {
+ this.size = size;
+ }
+
+ @Override
+ public long size() {
+ return size;
+ }
+
+ @Override
+ public InputStream openStream() {
+ return new MockInputStream(size);
+ }
+ }
+
+ private static final class MockInputStream extends InputStream {
+ private long remaining;
+
+ MockInputStream(final long size) {
+ remaining = size;
+ }
+
+ @Override
+ public int read() {
+ if (remaining > 0) {
+ remaining--;
+ return 0;
+ }
+ return -1;
+ }
+
+ @Override
+ public int read(final byte[] bytes, final int off, final int len) {
+ Objects.checkFromIndexSize(off, len, bytes.length);
+ if (remaining <= 0) {
+ return -1;
+ }
+ final int count = len <= remaining ? len : (int) remaining;
+ Arrays.fill(bytes, off, off + count, (byte) 0);
+ remaining -= count;
+ return count;
+ }
+ }
+}
import akka.protobuf.ByteString;
import akka.testkit.TestActorRef;
import akka.testkit.javadsl.TestKit;
-import com.google.common.collect.ImmutableList;
-import com.google.common.collect.ImmutableMap;
import com.google.common.io.ByteSource;
import com.google.common.util.concurrent.Uninterruptibles;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Arrays;
-import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
+import java.util.OptionalInt;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import org.apache.commons.lang3.SerializationUtils;
private RaftActorBehavior sendReplicate(final MockRaftActorContext actorContext, final long term, final long index,
final Payload payload) {
- SimpleReplicatedLogEntry newEntry = new SimpleReplicatedLogEntry(index, term, payload);
- actorContext.getReplicatedLog().append(newEntry);
- return leader.handleMessage(leaderActor, new Replicate(null, null, newEntry, true));
+ actorContext.getReplicatedLog().append(new SimpleReplicatedLogEntry(index, term, payload));
+ return leader.handleMessage(leaderActor, new Replicate(index, true, null, null));
}
@Test
final int messageNr) {
final AppendEntries commitReq = allMessages.get(2 * messageNr + 1);
assertEquals(lastIndex + messageNr + 1, commitReq.getLeaderCommit());
- assertEquals(ImmutableList.of(), commitReq.getEntries());
+ assertEquals(List.of(), commitReq.getEntries());
}
private static void assertRequestEntry(final long lastIndex, final List<AppendEntries> allMessages,
actorContext.setLastApplied(0);
- long newLogIndex = actorContext.getReplicatedLog().lastIndex() + 1;
- long term = actorContext.getTermInformation().getCurrentTerm();
- ReplicatedLogEntry newEntry = new SimpleReplicatedLogEntry(
- newLogIndex, term, new MockRaftActorContext.MockPayload("foo"));
+ final long newLogIndex = actorContext.getReplicatedLog().lastIndex() + 1;
+ final long term = actorContext.getTermInformation().getCurrentTerm();
+ final var data = new MockRaftActorContext.MockPayload("foo");
- actorContext.getReplicatedLog().append(newEntry);
+ actorContext.getReplicatedLog().append(new SimpleReplicatedLogEntry(newLogIndex, term, data));
final Identifier id = new MockIdentifier("state-id");
- RaftActorBehavior raftBehavior = leader.handleMessage(leaderActor,
- new Replicate(leaderActor, id, newEntry, true));
+ final var raftBehavior = leader.handleMessage(leaderActor, new Replicate(newLogIndex, true, leaderActor, id));
// State should not change
assertTrue(raftBehavior instanceof Leader);
// We should get 2 ApplyState messages - 1 for new log entry and 1 for the previous
// one since lastApplied state is 0.
- List<ApplyState> applyStateList = MessageCollectorActor.getAllMatching(
- leaderActor, ApplyState.class);
+ final var applyStateList = MessageCollectorActor.getAllMatching(leaderActor, ApplyState.class);
assertEquals("ApplyState count", newLogIndex, applyStateList.size());
for (int i = 0; i <= newLogIndex - 1; i++) {
}
ApplyState last = applyStateList.get((int) newLogIndex - 1);
- assertEquals("getData", newEntry.getData(), last.getReplicatedLogEntry().getData());
+ assertEquals("getData", data, last.getReplicatedLogEntry().getData());
assertEquals("getIdentifier", id, last.getIdentifier());
}
final MockRaftActorContext actorContext = createActorContextWithFollower();
- Map<String, String> leadersSnapshot = new HashMap<>();
- leadersSnapshot.put("1", "A");
- leadersSnapshot.put("2", "B");
- leadersSnapshot.put("3", "C");
-
//clears leaders log
actorContext.getReplicatedLog().removeFrom(0);
//update follower timestamp
leader.markFollowerActive(FOLLOWER_ID);
- ByteString bs = toByteString(leadersSnapshot);
+ ByteString bs = toByteString(Map.of("1", "A", "2", "B", "3", "C"));
leader.setSnapshotHolder(new SnapshotHolder(Snapshot.create(ByteState.of(bs.toByteArray()),
- Collections.<ReplicatedLogEntry>emptyList(), commitIndex, snapshotTerm, commitIndex, snapshotTerm,
+ List.of(), commitIndex, snapshotTerm, commitIndex, snapshotTerm,
-1, null, null), ByteSource.wrap(bs.toByteArray())));
LeaderInstallSnapshotState fts = new LeaderInstallSnapshotState(
- actorContext.getConfigParams().getSnapshotChunkSize(), leader.logName());
+ actorContext.getConfigParams().getMaximumMessageSliceSize(), leader.logName());
fts.setSnapshotBytes(ByteSource.wrap(bs.toByteArray()));
leader.getFollower(FOLLOWER_ID).setLeaderInstallSnapshotState(fts);
MessageCollectorActor.expectFirstMatching(followerActor, AppendEntries.class);
// new entry
- SimpleReplicatedLogEntry entry =
- new SimpleReplicatedLogEntry(newEntryIndex, currentTerm,
- new MockRaftActorContext.MockPayload("D"));
-
- actorContext.getReplicatedLog().append(entry);
+ actorContext.getReplicatedLog().append(
+ new SimpleReplicatedLogEntry(newEntryIndex, currentTerm, new MockRaftActorContext.MockPayload("D")));
//update follower timestamp
leader.markFollowerActive(FOLLOWER_ID);
// this should invoke a sendinstallsnapshot as followersLastIndex < snapshotIndex
RaftActorBehavior raftBehavior = leader.handleMessage(
- leaderActor, new Replicate(null, new MockIdentifier("state-id"), entry, true));
+ leaderActor, new Replicate(newEntryIndex, true, null, new MockIdentifier("state-id")));
assertTrue(raftBehavior instanceof Leader);
leader.setSnapshotHolder(null);
// new entry
- SimpleReplicatedLogEntry entry = new SimpleReplicatedLogEntry(newEntryIndex, currentTerm,
- new MockRaftActorContext.MockPayload("D"));
-
- actorContext.getReplicatedLog().append(entry);
+ actorContext.getReplicatedLog().append(
+ new SimpleReplicatedLogEntry(newEntryIndex, currentTerm, new MockRaftActorContext.MockPayload("D")));
//update follower timestamp
leader.markFollowerActive(FOLLOWER_ID);
- leader.handleMessage(leaderActor, new Replicate(null, new MockIdentifier("state-id"), entry, true));
+ leader.handleMessage(leaderActor, new Replicate(newEntryIndex, true, null, new MockIdentifier("state-id")));
assertEquals("isCapturing", true, actorContext.getSnapshotManager().isCapturing());
assertEquals(2, cs.getLastTerm());
// if an initiate is started again when first is in progress, it shouldnt initiate Capture
- leader.handleMessage(leaderActor, new Replicate(null, new MockIdentifier("state-id"), entry, true));
+ leader.handleMessage(leaderActor, new Replicate(newEntryIndex, true, null, new MockIdentifier("state-id")));
assertSame("CaptureSnapshot instance", cs, actorContext.getSnapshotManager().getCaptureSnapshot());
}
}
// new entry
- SimpleReplicatedLogEntry entry = new SimpleReplicatedLogEntry(newEntryIndex, currentTerm,
- new MockRaftActorContext.MockPayload("D"));
-
- actorContext.getReplicatedLog().append(entry);
+ actorContext.getReplicatedLog().append(
+ new SimpleReplicatedLogEntry(newEntryIndex, currentTerm, new MockRaftActorContext.MockPayload("D")));
//update follower timestamp
leader.markFollowerActive(FOLLOWER_ID);
MessageCollectorActor.clearMessages(followerActor);
// Sending Replicate message should not initiate another capture since the first is in progress.
- leader.handleMessage(leaderActor, new Replicate(null, new MockIdentifier("state-id"), entry, true));
+ leader.handleMessage(leaderActor, new Replicate(newEntryIndex, true, null, new MockIdentifier("state-id")));
assertSame("CaptureSnapshot instance", cs, actorContext.getSnapshotManager().getCaptureSnapshot());
// Similarly sending another AppendEntriesReply to force a snapshot should not initiate another capture.
// Now simulate the CaptureSnapshotReply to initiate snapshot install - the first chunk should be sent.
final byte[] bytes = new byte[]{1, 2, 3};
- installSnapshotStream.get().get().write(bytes);
+ installSnapshotStream.get().orElseThrow().write(bytes);
actorContext.getSnapshotManager().persist(ByteState.of(bytes), installSnapshotStream.get(),
Runtime.getRuntime().totalMemory());
MessageCollectorActor.expectFirstMatching(followerActor, InstallSnapshot.class);
leader.getFollower(FOLLOWER_ID).setNextIndex(0);
byte[] bytes = toByteString(leadersSnapshot).toByteArray();
- Snapshot snapshot = Snapshot.create(ByteState.of(bytes), Collections.<ReplicatedLogEntry>emptyList(),
+ Snapshot snapshot = Snapshot.create(ByteState.of(bytes), List.of(),
lastAppliedIndex, snapshotTerm, lastAppliedIndex, snapshotTerm, -1, null, null);
RaftActorBehavior raftBehavior = leader.handleMessage(leaderActor,
leader.getFollower(FOLLOWER_ID).setNextIndex(-1);
byte[] bytes = toByteString(leadersSnapshot).toByteArray();
- Snapshot snapshot = Snapshot.create(ByteState.of(bytes), Collections.<ReplicatedLogEntry>emptyList(),
+ Snapshot snapshot = Snapshot.create(ByteState.of(bytes), List.of(),
lastAppliedIndex, snapshotTerm, lastAppliedIndex, snapshotTerm, -1, null, null);
RaftActorBehavior raftBehavior = leader.handleMessage(leaderActor,
ByteString bs = toByteString(leadersSnapshot);
leader.setSnapshotHolder(new SnapshotHolder(Snapshot.create(ByteState.of(bs.toByteArray()),
- Collections.<ReplicatedLogEntry>emptyList(), commitIndex, snapshotTerm, commitIndex, snapshotTerm,
+ List.of(), commitIndex, snapshotTerm, commitIndex, snapshotTerm,
-1, null, null), ByteSource.wrap(bs.toByteArray())));
LeaderInstallSnapshotState fts = new LeaderInstallSnapshotState(
- actorContext.getConfigParams().getSnapshotChunkSize(), leader.logName());
+ actorContext.getConfigParams().getMaximumMessageSliceSize(), leader.logName());
fts.setSnapshotBytes(ByteSource.wrap(bs.toByteArray()));
leader.getFollower(FOLLOWER_ID).setLeaderInstallSnapshotState(fts);
while (!fts.isLastChunk(fts.getChunkIndex())) {
DefaultConfigParamsImpl configParams = new DefaultConfigParamsImpl() {
@Override
- public int getSnapshotChunkSize() {
+ public int getMaximumMessageSliceSize() {
return 50;
}
};
ByteString bs = toByteString(leadersSnapshot);
Snapshot snapshot = Snapshot.create(ByteState.of(bs.toByteArray()),
- Collections.<ReplicatedLogEntry>emptyList(), commitIndex, snapshotTerm, commitIndex, snapshotTerm,
- -1, null, null);
+ List.of(), commitIndex, snapshotTerm, commitIndex, snapshotTerm, -1, null, null);
leader.handleMessage(leaderActor, new SendInstallSnapshot(snapshot, ByteSource.wrap(bs.toByteArray())));
actorContext.setConfigParams(new DefaultConfigParamsImpl() {
@Override
- public int getSnapshotChunkSize() {
+ public int getMaximumMessageSliceSize() {
return 50;
}
});
ByteString bs = toByteString(leadersSnapshot);
Snapshot snapshot = Snapshot.create(ByteState.of(bs.toByteArray()),
- Collections.<ReplicatedLogEntry>emptyList(), commitIndex, snapshotTerm, commitIndex, snapshotTerm,
- -1, null, null);
+ List.of(), commitIndex, snapshotTerm, commitIndex, snapshotTerm, -1, null, null);
Uninterruptibles.sleepUninterruptibly(1, TimeUnit.SECONDS);
leader.handleMessage(leaderActor, new SendInstallSnapshot(snapshot, ByteSource.wrap(bs.toByteArray())));
actorContext.setConfigParams(new DefaultConfigParamsImpl() {
@Override
- public int getSnapshotChunkSize() {
+ public int getMaximumMessageSliceSize() {
return 50;
}
});
ByteString bs = toByteString(leadersSnapshot);
Snapshot snapshot = Snapshot.create(ByteState.of(bs.toByteArray()),
- Collections.<ReplicatedLogEntry>emptyList(), commitIndex, snapshotTerm, commitIndex, snapshotTerm,
- -1, null, null);
+ List.of(), commitIndex, snapshotTerm, commitIndex, snapshotTerm, -1, null, null);
leader.handleMessage(leaderActor, new SendInstallSnapshot(snapshot, ByteSource.wrap(bs.toByteArray())));
assertEquals(1, installSnapshot.getChunkIndex());
assertEquals(3, installSnapshot.getTotalChunks());
- assertEquals(LeaderInstallSnapshotState.INITIAL_LAST_CHUNK_HASH_CODE,
- installSnapshot.getLastChunkHashCode().getAsInt());
+ assertEquals(OptionalInt.of(LeaderInstallSnapshotState.INITIAL_LAST_CHUNK_HASH_CODE),
+ installSnapshot.getLastChunkHashCode());
final int hashCode = Arrays.hashCode(installSnapshot.getData());
assertEquals(2, installSnapshot.getChunkIndex());
assertEquals(3, installSnapshot.getTotalChunks());
- assertEquals(hashCode, installSnapshot.getLastChunkHashCode().getAsInt());
+ assertEquals(OptionalInt.of(hashCode), installSnapshot.getLastChunkHashCode());
}
@Test
private MockRaftActorContext createActorContextWithFollower() {
MockRaftActorContext actorContext = createActorContext();
- actorContext.setPeerAddresses(ImmutableMap.<String, String>builder().put(FOLLOWER_ID,
- followerActor.path().toString()).build());
+ actorContext.setPeerAddresses(Map.of(FOLLOWER_ID, followerActor.path().toString()));
return actorContext;
}
DefaultConfigParamsImpl followerConfig = new DefaultConfigParamsImpl();
followerConfig.setElectionTimeoutFactor(10000);
followerActorContext.setConfigParams(followerConfig);
- followerActorContext.setPeerAddresses(ImmutableMap.of(LEADER_ID, leaderActor.path().toString()));
+ followerActorContext.setPeerAddresses(Map.of(LEADER_ID, leaderActor.path().toString()));
return followerActorContext;
}
final MockRaftActorContext leaderActorContext = createActorContext();
MockRaftActorContext followerActorContext = createActorContext(FOLLOWER_ID, followerActor);
- followerActorContext.setPeerAddresses(ImmutableMap.of(LEADER_ID, leaderActor.path().toString()));
+ followerActorContext.setPeerAddresses(Map.of(LEADER_ID, leaderActor.path().toString()));
Follower follower = new Follower(followerActorContext);
followerActor.underlyingActor().setBehavior(follower);
FollowerLogInformation followerInfo = leader.getFollower(FOLLOWER_ID);
assertEquals(payloadVersion, leader.getLeaderPayloadVersion());
- assertEquals(RaftVersions.HELIUM_VERSION, followerInfo.getRaftVersion());
+ assertEquals(RaftVersions.FLUORINE_VERSION, followerInfo.getRaftVersion());
AppendEntriesReply reply = new AppendEntriesReply(FOLLOWER_ID, 1, true, 2, 1, payloadVersion);
((DefaultConfigParamsImpl)leaderActorContext.getConfigParams()).setHeartBeatInterval(
new FiniteDuration(1000, TimeUnit.SECONDS));
// Note: the size here depends on estimate
- ((DefaultConfigParamsImpl)leaderActorContext.getConfigParams()).setSnapshotChunkSize(246);
+ ((DefaultConfigParamsImpl)leaderActorContext.getConfigParams()).setMaximumMessageSliceSize(246);
leaderActorContext.setReplicatedLog(
new MockRaftActorContext.MockReplicatedLogBuilder().createEntries(0, 4, 1).build());
logStart("testReplicationWithPayloadSizeThatExceedsThreshold");
final int serializedSize = SerializationUtils.serialize(new AppendEntries(1, LEADER_ID, -1, -1,
- Arrays.asList(new SimpleReplicatedLogEntry(0, 1,
+ List.of(new SimpleReplicatedLogEntry(0, 1,
new MockRaftActorContext.MockPayload("large"))), 0, -1, (short)0)).length;
final MockRaftActorContext.MockPayload largePayload =
new MockRaftActorContext.MockPayload("large", serializedSize);
MockRaftActorContext leaderActorContext = createActorContextWithFollower();
((DefaultConfigParamsImpl)leaderActorContext.getConfigParams()).setHeartBeatInterval(
new FiniteDuration(300, TimeUnit.MILLISECONDS));
- ((DefaultConfigParamsImpl)leaderActorContext.getConfigParams()).setSnapshotChunkSize(serializedSize - 50);
+ ((DefaultConfigParamsImpl)leaderActorContext.getConfigParams()).setMaximumMessageSliceSize(serializedSize - 50);
leaderActorContext.setReplicatedLog(new MockRaftActorContext.MockReplicatedLogBuilder().build());
leaderActorContext.setCommitIndex(-1);
leaderActorContext.setLastApplied(-1);
((DefaultConfigParamsImpl)leaderActorContext.getConfigParams()).setHeartBeatInterval(
new FiniteDuration(100, TimeUnit.MILLISECONDS));
((DefaultConfigParamsImpl)leaderActorContext.getConfigParams()).setElectionTimeoutFactor(1);
- ((DefaultConfigParamsImpl)leaderActorContext.getConfigParams()).setSnapshotChunkSize(10);
+ ((DefaultConfigParamsImpl)leaderActorContext.getConfigParams()).setMaximumMessageSliceSize(10);
leaderActorContext.setReplicatedLog(new MockRaftActorContext.MockReplicatedLogBuilder().build());
leaderActorContext.setCommitIndex(-1);
leaderActorContext.setLastApplied(-1);
MessageCollectorActor.clearMessages(followerActor);
sendReplicate(leaderActorContext, term, 0, new MockRaftActorContext.MockPayload("large",
- leaderActorContext.getConfigParams().getSnapshotChunkSize() + 1));
+ leaderActorContext.getConfigParams().getMaximumMessageSliceSize() + 1));
MessageCollectorActor.expectFirstMatching(followerActor, MessageSlice.class);
// Sleep for at least 3 * election timeout so the slicing state expires.
// Initial heartbeat shouldn't have the leader address
AppendEntries appendEntries = MessageCollectorActor.expectFirstMatching(followerActor, AppendEntries.class);
- assertFalse(appendEntries.getLeaderAddress().isPresent());
+ assertNull(appendEntries.leaderAddress());
MessageCollectorActor.clearMessages(followerActor);
// Send AppendEntriesReply indicating the follower needs the leader address
leader.handleMessage(leaderActor, SendHeartBeat.INSTANCE);
appendEntries = MessageCollectorActor.expectFirstMatching(followerActor, AppendEntries.class);
- assertTrue(appendEntries.getLeaderAddress().isPresent());
- assertEquals(leaderActor.path().toString(), appendEntries.getLeaderAddress().get());
+ assertEquals(leaderActor.path().toString(), appendEntries.leaderAddress());
MessageCollectorActor.clearMessages(followerActor);
// Send AppendEntriesReply indicating the follower does not need the leader address
leader.handleMessage(leaderActor, SendHeartBeat.INSTANCE);
appendEntries = MessageCollectorActor.expectFirstMatching(followerActor, AppendEntries.class);
- assertFalse(appendEntries.getLeaderAddress().isPresent());
+ assertNull(appendEntries.leaderAddress());
}
@Override
private static class MockConfigParamsImpl extends DefaultConfigParamsImpl {
private final long electionTimeOutIntervalMillis;
- private final int snapshotChunkSize;
+ private final int maximumMessageSliceSize;
- MockConfigParamsImpl(final long electionTimeOutIntervalMillis, final int snapshotChunkSize) {
+ MockConfigParamsImpl(final long electionTimeOutIntervalMillis, final int maximumMessageSliceSize) {
this.electionTimeOutIntervalMillis = electionTimeOutIntervalMillis;
- this.snapshotChunkSize = snapshotChunkSize;
+ this.maximumMessageSliceSize = maximumMessageSliceSize;
}
@Override
}
@Override
- public int getSnapshotChunkSize() {
- return snapshotChunkSize;
+ public int getMaximumMessageSliceSize() {
+ return maximumMessageSliceSize;
}
}
}
import akka.protobuf.ByteString;
import com.google.common.io.ByteSource;
import java.io.IOException;
-import java.io.Serializable;
import java.util.Arrays;
import java.util.HashMap;
-import java.util.Map;
import java.util.OptionalInt;
import org.apache.commons.lang3.SerializationUtils;
import org.junit.Before;
public class SnapshotTrackerTest {
private static final Logger LOG = LoggerFactory.getLogger(SnapshotTrackerTest.class);
+ private final HashMap<String, String> data = new HashMap<>();
+
@Mock
private RaftActorContext mockContext;
private FileBackedOutputStream fbos;
- private Map<String, String> data;
private ByteString byteString;
private byte[] chunk1;
private byte[] chunk2;
@Before
public void setup() {
- data = new HashMap<>();
data.put("key1", "value1");
data.put("key2", "value2");
data.put("key3", "value3");
- byteString = ByteString.copyFrom(SerializationUtils.serialize((Serializable) data));
+ byteString = ByteString.copyFrom(SerializationUtils.serialize(data));
chunk1 = getNextChunk(byteString, 0, 10);
chunk2 = getNextChunk(byteString, 10, 10);
chunk3 = getNextChunk(byteString, 20, byteString.size());
int start = offset;
if (size > snapshotLength) {
size = snapshotLength;
- } else {
- if (start + size > snapshotLength) {
- size = snapshotLength - start;
- }
+ } else if (start + size > snapshotLength) {
+ size = snapshotLength - start;
}
byte[] nextChunk = new byte[size];
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertSame;
-import org.apache.commons.lang.SerializationUtils;
+import org.apache.commons.lang3.SerializationUtils;
import org.junit.Test;
/**
import static org.junit.Assert.assertEquals;
-import org.apache.commons.lang.SerializationUtils;
+import org.apache.commons.lang3.SerializationUtils;
import org.junit.Test;
import org.opendaylight.controller.cluster.raft.RaftVersions;
assertEquals("isForceInstallSnapshot", expected.isForceInstallSnapshot(), cloned.isForceInstallSnapshot());
assertEquals("isNeedsLeaderAddress", expected.isNeedsLeaderAddress(), cloned.isNeedsLeaderAddress());
}
-
- @Test
- @Deprecated
- public void testPreFluorineSerialization() {
- final var expected = new AppendEntriesReply("follower", 5, true, 100, 4, (short)6, true, true,
- RaftVersions.BORON_VERSION);
-
- final var bytes = SerializationUtils.serialize(expected);
- assertEquals(141, bytes.length);
- final var cloned = (AppendEntriesReply) SerializationUtils.deserialize(bytes);
-
- assertEquals("getTerm", expected.getTerm(), cloned.getTerm());
- assertEquals("getFollowerId", expected.getFollowerId(), cloned.getFollowerId());
- assertEquals("getLogLastTerm", expected.getLogLastTerm(), cloned.getLogLastTerm());
- assertEquals("getLogLastIndex", expected.getLogLastIndex(), cloned.getLogLastIndex());
- assertEquals("getPayloadVersion", expected.getPayloadVersion(), cloned.getPayloadVersion());
- assertEquals("getRaftVersion", expected.getRaftVersion(), cloned.getRaftVersion());
- assertEquals("isForceInstallSnapshot", expected.isForceInstallSnapshot(), cloned.isForceInstallSnapshot());
- assertEquals("isNeedsLeaderAddress", false, cloned.isNeedsLeaderAddress());
- }
}
package org.opendaylight.controller.cluster.raft.messages;
import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
import java.util.Iterator;
import java.util.List;
-import org.apache.commons.lang.SerializationUtils;
+import org.apache.commons.lang3.SerializationUtils;
import org.junit.Test;
import org.opendaylight.controller.cluster.raft.MockRaftActorContext.MockPayload;
import org.opendaylight.controller.cluster.raft.RaftVersions;
verifyAppendEntries(expected, cloned, RaftVersions.CURRENT_VERSION);
}
- @Test
- @Deprecated
- public void testPreFluorineSerialization() {
- ReplicatedLogEntry entry1 = new SimpleReplicatedLogEntry(1, 2, new MockPayload("payload1"));
-
- ReplicatedLogEntry entry2 = new SimpleReplicatedLogEntry(3, 4, new MockPayload("payload2"));
-
- short payloadVersion = 5;
-
- final var expected = new AppendEntries(5L, "node1", 7L, 8L, List.of(entry1, entry2), 10L, -1,
- payloadVersion, RaftVersions.BORON_VERSION, "leader address");
-
- final var bytes = SerializationUtils.serialize(expected);
- assertEquals(350, bytes.length);
- final var cloned = (AppendEntries) SerializationUtils.deserialize(bytes);
-
- verifyAppendEntries(expected, cloned, RaftVersions.BORON_VERSION);
- }
-
private static void verifyAppendEntries(final AppendEntries expected, final AppendEntries actual,
final short recipientRaftVersion) {
assertEquals("getLeaderId", expected.getLeaderId(), actual.getLeaderId());
verifyReplicatedLogEntry(iter.next(), e);
}
- if (recipientRaftVersion > RaftVersions.BORON_VERSION) {
- assertEquals("getLeaderAddress", expected.getLeaderAddress(), actual.getLeaderAddress());
- assertEquals("getLeaderRaftVersion", RaftVersions.CURRENT_VERSION, actual.getLeaderRaftVersion());
- } else {
- assertFalse(actual.getLeaderAddress().isPresent());
- assertEquals("getLeaderRaftVersion", RaftVersions.BORON_VERSION, actual.getLeaderRaftVersion());
- }
+ assertEquals("getLeaderAddress", expected.leaderAddress(), actual.leaderAddress());
+ assertEquals("getLeaderRaftVersion", RaftVersions.CURRENT_VERSION, actual.getLeaderRaftVersion());
}
private static void verifyReplicatedLogEntry(final ReplicatedLogEntry expected, final ReplicatedLogEntry actual) {
import static org.junit.Assert.assertEquals;
-import org.apache.commons.lang.SerializationUtils;
+import org.apache.commons.lang3.SerializationUtils;
import org.junit.Test;
/**
import java.util.List;
import java.util.Optional;
import java.util.OptionalInt;
-import org.apache.commons.lang.SerializationUtils;
+import org.apache.commons.lang3.SerializationUtils;
import org.junit.Test;
import org.opendaylight.controller.cluster.raft.RaftVersions;
import org.opendaylight.controller.cluster.raft.persisted.ServerConfigurationPayload;
assertEquals("getServerConfig present", expected.getServerConfig().isPresent(),
actual.getServerConfig().isPresent());
if (expected.getServerConfig().isPresent()) {
- assertEquals("getServerConfig", expected.getServerConfig().get().getServerConfig(),
- actual.getServerConfig().get().getServerConfig());
+ assertEquals("getServerConfig", expected.getServerConfig().orElseThrow().getServerConfig(),
+ actual.getServerConfig().orElseThrow().getServerConfig());
}
}
}
import static org.junit.Assert.assertEquals;
-import org.apache.commons.lang.SerializationUtils;
+import org.apache.commons.lang3.SerializationUtils;
import org.junit.Test;
/**
import static org.junit.Assert.assertEquals;
-import org.apache.commons.lang.SerializationUtils;
+import org.apache.commons.lang3.SerializationUtils;
import org.junit.Test;
/**
import static org.junit.Assert.assertEquals;
-import org.apache.commons.lang.SerializationUtils;
+import org.apache.commons.lang3.SerializationUtils;
import org.junit.Test;
/**
import static org.junit.Assert.assertEquals;
-import org.apache.commons.lang.SerializationUtils;
+import org.apache.commons.lang3.SerializationUtils;
import org.junit.Test;
/**
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertSame;
-import org.apache.commons.lang.SerializationUtils;
+import org.apache.commons.lang3.SerializationUtils;
import org.junit.Test;
/**
import static org.junit.Assert.assertTrue;
import java.util.List;
-import org.apache.commons.lang.SerializationUtils;
+import org.apache.commons.lang3.SerializationUtils;
import org.junit.Test;
/**
import static org.junit.Assert.assertEquals;
-import org.apache.commons.lang.SerializationUtils;
+import org.apache.commons.lang3.SerializationUtils;
import org.junit.Test;
import org.opendaylight.controller.cluster.raft.MockRaftActorContext;
import static org.junit.Assert.assertEquals;
import java.util.List;
-import org.apache.commons.lang.SerializationUtils;
+import org.apache.commons.lang3.SerializationUtils;
import org.junit.Test;
import org.opendaylight.controller.cluster.raft.MockRaftActorContext.MockPayload;
import org.opendaylight.controller.cluster.raft.ReplicatedLogEntry;
import static org.junit.Assert.assertEquals;
-import org.apache.commons.lang.SerializationUtils;
+import org.apache.commons.lang3.SerializationUtils;
import org.junit.Test;
/**
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
-import org.apache.commons.lang.SerializationUtils;
+import org.apache.commons.lang3.SerializationUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import scala.Option;
final Class<?> ofType;
WriteMessagesComplete(final int count, final Class<?> ofType) {
- this.latch = new CountDownLatch(count);
+ latch = new CountDownLatch(count);
this.ofType = ofType;
}
}
<parent>
<groupId>org.opendaylight.controller</groupId>
<artifactId>mdsal-parent</artifactId>
- <version>7.0.2-SNAPSHOT</version>
+ <version>9.0.3-SNAPSHOT</version>
<relativePath>../parent</relativePath>
</parent>
<packaging>bundle</packaging>
<dependencies>
- <!-- Akka -->
<dependency>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>repackaged-akka</artifactId>
- </dependency>
- <dependency>
- <groupId>com.typesafe.akka</groupId>
- <artifactId>akka-testkit_2.13</artifactId>
+ <groupId>com.google.guava</groupId>
+ <artifactId>guava</artifactId>
</dependency>
<dependency>
- <groupId>com.typesafe.akka</groupId>
- <artifactId>akka-persistence-tck_2.13</artifactId>
+ <groupId>com.typesafe</groupId>
+ <artifactId>config</artifactId>
</dependency>
-
- <!-- Codahale -->
<dependency>
<groupId>io.dropwizard.metrics</groupId>
<artifactId>metrics-core</artifactId>
</dependency>
-
- <!-- Scala -->
<dependency>
- <groupId>org.scala-lang</groupId>
- <artifactId>scala-library</artifactId>
+ <groupId>org.eclipse.jdt</groupId>
+ <artifactId>org.eclipse.jdt.annotation</artifactId>
</dependency>
-
- <!-- Clustering commons for metrics -->
<dependency>
<groupId>org.opendaylight.controller</groupId>
- <artifactId>sal-clustering-commons</artifactId>
- </dependency>
-
- <!-- Atomix -->
- <dependency>
- <groupId>io.atomix</groupId>
<artifactId>atomix-storage</artifactId>
- <version>3.1.12</version>
- <scope>provided</scope>
- </dependency>
- <dependency>
- <groupId>io.atomix</groupId>
- <artifactId>atomix-utils</artifactId>
- <version>3.1.12</version>
- <scope>provided</scope>
</dependency>
<dependency>
- <groupId>com.esotericsoftware</groupId>
- <artifactId>kryo</artifactId>
- <version>4.0.2</version>
- <scope>provided</scope>
+ <groupId>org.opendaylight.controller</groupId>
+ <artifactId>repackaged-akka</artifactId>
</dependency>
<dependency>
- <groupId>com.esotericsoftware</groupId>
- <artifactId>minlog</artifactId>
- <version>1.3.1</version>
- <scope>provided</scope>
+ <groupId>org.opendaylight.controller</groupId>
+ <artifactId>sal-clustering-commons</artifactId>
</dependency>
<dependency>
- <groupId>com.esotericsoftware</groupId>
- <artifactId>reflectasm</artifactId>
- <version>1.11.8</version>
- <scope>provided</scope>
+ <groupId>org.scala-lang</groupId>
+ <artifactId>scala-library</artifactId>
</dependency>
+
<dependency>
- <groupId>org.ow2.asm</groupId>
- <artifactId>asm</artifactId>
- <version>5.2</version>
- <scope>provided</scope>
+ <groupId>com.typesafe.akka</groupId>
+ <artifactId>akka-testkit_2.13</artifactId>
</dependency>
<dependency>
- <groupId>org.objenesis</groupId>
- <artifactId>objenesis</artifactId>
- <version>2.6</version>
- <scope>provided</scope>
+ <groupId>com.typesafe.akka</groupId>
+ <artifactId>akka-persistence-tck_2.13</artifactId>
</dependency>
-
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
</dependency>
</dependencies>
- <build>
- <plugins>
- <plugin>
- <groupId>org.apache.felix</groupId>
- <artifactId>maven-bundle-plugin</artifactId>
- <extensions>true</extensions>
- <configuration>
- <instructions>
- <Bundle-Name>${project.groupId}.${project.artifactId}</Bundle-Name>
- <Import-Package>
- !COM.newmonics.*,
- !android.os,
- *
- </Import-Package>
- <Embed-Dependency>
- <!-- atomix.io is using an older Guava, and Kryo is using ancient objenesis,
- so let's embed it to prevent duplicates -->
- *;inline=true;groupId=io.atomix,
- *;inline=true;groupId=com.esotericsoftware,
- *;inline=true;groupId=org.objenesis,
- *;inline=true;groupId=org.ow2.asm,
- </Embed-Dependency>
- </instructions>
- </configuration>
- </plugin>
- </plugins>
- </build>
-
<scm>
<connection>scm:git:http://git.opendaylight.org/gerrit/controller.git</connection>
<developerConnection>scm:git:ssh://git.opendaylight.org:29418/controller.git</developerConnection>
import org.eclipse.jdt.annotation.NonNull;
import org.opendaylight.controller.akka.segjournal.SegmentedJournalActor.ReplayMessages;
import org.opendaylight.controller.akka.segjournal.SegmentedJournalActor.WriteMessages;
+import org.opendaylight.controller.akka.segjournal.SegmentedJournalActor.WrittenMessages;
/**
* Abstraction of a data journal. This provides a unified interface towards {@link SegmentedJournalActor}, allowing
/**
* Handle a request to store some messages.
*
- * @param message Request message
- * @return number of bytes written
+ * @param message {@link WriteMessages} message
+ * @return a {@link WrittenMessages} object
+ */
+ abstract @NonNull WrittenMessages handleWriteMessages(@NonNull WriteMessages message);
+
+ /**
+ * Flush all messages to durable storage.
*/
- abstract long handleWriteMessages(@NonNull WriteMessages message);
+ abstract void flush();
}
import static java.util.Objects.requireNonNull;
import akka.persistence.PersistentRepr;
-import io.atomix.storage.journal.JournalSegment;
/**
* A single entry in the data journal. We do not store {@code persistenceId} for each entry, as that is a
- * journal-invariant, nor do we store {@code sequenceNr}, as that information is maintained by {@link JournalSegment}'s
- * index.
- *
- * @author Robert Varga
+ * journal-invariant, nor do we store {@code sequenceNr}, as that information is maintained by a particular journal
+ * segment's index.
*/
-abstract class DataJournalEntry {
+abstract sealed class DataJournalEntry {
/**
* A single data journal entry on its way to the backing file.
*/
--- /dev/null
+/*
+ * Copyright (c) 2019 Pantheon Technologies, s.r.o. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.controller.akka.segjournal;
+
+import static java.util.Objects.requireNonNull;
+
+import akka.actor.ActorSystem;
+import akka.actor.ExtendedActorSystem;
+import akka.persistence.PersistentRepr;
+import akka.serialization.JavaSerializer;
+import com.google.common.base.VerifyException;
+import io.atomix.storage.journal.JournalSerdes.EntryInput;
+import io.atomix.storage.journal.JournalSerdes.EntryOutput;
+import io.atomix.storage.journal.JournalSerdes.EntrySerdes;
+import java.io.IOException;
+import java.util.concurrent.Callable;
+import org.opendaylight.controller.akka.segjournal.DataJournalEntry.FromPersistence;
+import org.opendaylight.controller.akka.segjournal.DataJournalEntry.ToPersistence;
+
+/**
+ * Kryo serializer for {@link DataJournalEntry}. Each {@link SegmentedJournalActor} has its own instance, as well as
+ * a nested JavaSerializer to handle the payload.
+ *
+ * <p>
+ * Since we are persisting only parts of {@link PersistentRepr}, this class asymmetric by design:
+ * {@link #write(EntryOutput, DataJournalEntry)} only accepts {@link ToPersistence} subclass, which is a wrapper
+ * around a {@link PersistentRepr}, while {@link #read(EntryInput)} produces an {@link FromPersistence}, which
+ * needs further processing to reconstruct a {@link PersistentRepr}.
+ */
+final class DataJournalEntrySerdes implements EntrySerdes<DataJournalEntry> {
+ private final ExtendedActorSystem actorSystem;
+
+ DataJournalEntrySerdes(final ActorSystem actorSystem) {
+ this.actorSystem = requireNonNull((ExtendedActorSystem) actorSystem);
+ }
+
+ @Override
+ public void write(final EntryOutput output, final DataJournalEntry entry) throws IOException {
+ if (entry instanceof ToPersistence toPersistence) {
+ final var repr = toPersistence.repr();
+ output.writeString(repr.manifest());
+ output.writeString(repr.writerUuid());
+ output.writeObject(repr.payload());
+ } else {
+ throw new VerifyException("Unexpected entry " + entry);
+ }
+ }
+
+ @Override
+ public DataJournalEntry read(final EntryInput input) throws IOException {
+ return new FromPersistence(input.readString(), input.readString(),
+ JavaSerializer.currentSystem().withValue(actorSystem, (Callable<Object>) input::readObject));
+ }
+}
+++ /dev/null
-/*
- * Copyright (c) 2019 Pantheon Technologies, s.r.o. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.akka.segjournal;
-
-import static com.google.common.base.Verify.verify;
-import static java.util.Objects.requireNonNull;
-
-import akka.actor.ActorSystem;
-import akka.actor.ExtendedActorSystem;
-import akka.persistence.PersistentRepr;
-import com.esotericsoftware.kryo.Kryo;
-import com.esotericsoftware.kryo.Serializer;
-import com.esotericsoftware.kryo.io.Input;
-import com.esotericsoftware.kryo.io.Output;
-import com.esotericsoftware.kryo.serializers.JavaSerializer;
-import java.util.concurrent.Callable;
-import org.opendaylight.controller.akka.segjournal.DataJournalEntry.FromPersistence;
-import org.opendaylight.controller.akka.segjournal.DataJournalEntry.ToPersistence;
-
-/**
- * Kryo serializer for {@link DataJournalEntry}. Each {@link SegmentedJournalActor} has its own instance, as well as
- * a nested JavaSerializer to handle the payload.
- *
- * <p>
- * Since we are persisting only parts of {@link PersistentRepr}, this class asymmetric by design:
- * {@link #write(Kryo, Output, DataJournalEntry)} only accepts {@link ToPersistence} subclass, which is a wrapper
- * around a {@link PersistentRepr}, while {@link #read(Kryo, Input, Class)} produces an {@link FromPersistence}, which
- * needs further processing to reconstruct a {@link PersistentRepr}.
- *
- * @author Robert Varga
- */
-final class DataJournalEntrySerializer extends Serializer<DataJournalEntry> {
- private final JavaSerializer serializer = new JavaSerializer();
- private final ExtendedActorSystem actorSystem;
-
- DataJournalEntrySerializer(final ActorSystem actorSystem) {
- this.actorSystem = requireNonNull((ExtendedActorSystem) actorSystem);
- }
-
- @Override
- public void write(final Kryo kryo, final Output output, final DataJournalEntry object) {
- verify(object instanceof ToPersistence);
- final PersistentRepr repr = ((ToPersistence) object).repr();
- output.writeString(repr.manifest());
- output.writeString(repr.writerUuid());
- serializer.write(kryo, output, repr.payload());
- }
-
- @Override
- public DataJournalEntry read(final Kryo kryo, final Input input, final Class<DataJournalEntry> type) {
- final String manifest = input.readString();
- final String uuid = input.readString();
- final Object payload = akka.serialization.JavaSerializer.currentSystem().withValue(actorSystem,
- (Callable<Object>)() -> serializer.read(kryo, input, type));
- return new FromPersistence(manifest, uuid, payload);
- }
-}
*/
package org.opendaylight.controller.akka.segjournal;
-import static com.google.common.base.Verify.verify;
-
import akka.actor.ActorSystem;
-import akka.persistence.AtomicWrite;
import akka.persistence.PersistentRepr;
import com.codahale.metrics.Histogram;
-import io.atomix.storage.StorageLevel;
-import io.atomix.storage.journal.Indexed;
+import com.google.common.base.VerifyException;
+import io.atomix.storage.journal.JournalReader;
+import io.atomix.storage.journal.JournalSerdes;
+import io.atomix.storage.journal.JournalWriter;
import io.atomix.storage.journal.SegmentedJournal;
-import io.atomix.storage.journal.SegmentedJournalReader;
-import io.atomix.storage.journal.SegmentedJournalWriter;
-import io.atomix.utils.serializer.Namespace;
+import io.atomix.storage.journal.StorageLevel;
import java.io.File;
import java.io.Serializable;
+import java.util.ArrayList;
import java.util.List;
import org.opendaylight.controller.akka.segjournal.DataJournalEntry.FromPersistence;
import org.opendaylight.controller.akka.segjournal.DataJournalEntry.ToPersistence;
import org.opendaylight.controller.akka.segjournal.SegmentedJournalActor.ReplayMessages;
import org.opendaylight.controller.akka.segjournal.SegmentedJournalActor.WriteMessages;
+import org.opendaylight.controller.akka.segjournal.SegmentedJournalActor.WrittenMessages;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import scala.jdk.javaapi.CollectionConverters;
/**
* Version 0 data journal, where every journal entry maps to exactly one segmented file entry.
- *
- * @author Robert Varga
*/
final class DataJournalV0 extends DataJournal {
private static final Logger LOG = LoggerFactory.getLogger(DataJournalV0.class);
super(persistenceId, messageSize);
entries = SegmentedJournal.<DataJournalEntry>builder()
.withStorageLevel(storage).withDirectory(directory).withName("data")
- .withNamespace(Namespace.builder()
- .register(new DataJournalEntrySerializer(system), FromPersistence.class, ToPersistence.class)
+ .withNamespace(JournalSerdes.builder()
+ .register(new DataJournalEntrySerdes(system), FromPersistence.class, ToPersistence.class)
.build())
.withMaxEntrySize(maxEntrySize).withMaxSegmentSize(maxSegmentSize)
.build();
@Override
void close() {
+ flush();
entries.close();
}
+ @Override
+ void flush() {
+ entries.writer().flush();
+ }
+
@Override
@SuppressWarnings("checkstyle:illegalCatch")
void handleReplayMessages(final ReplayMessages message, final long fromSequenceNr) {
- try (SegmentedJournalReader<DataJournalEntry> reader = entries.openReader(fromSequenceNr)) {
- int count = 0;
- while (reader.hasNext() && count < message.max) {
- final Indexed<DataJournalEntry> next = reader.next();
- if (next.index() > message.toSequenceNr) {
- break;
- }
-
- LOG.trace("{}: replay {}", persistenceId, next);
- updateLargestSize(next.size());
- final DataJournalEntry entry = next.entry();
- verify(entry instanceof FromPersistence, "Unexpected entry %s", entry);
-
- final PersistentRepr repr = ((FromPersistence) entry).toRepr(persistenceId, next.index());
- LOG.debug("{}: replaying {}", persistenceId, repr);
- message.replayCallback.accept(repr);
- count++;
- }
- LOG.debug("{}: successfully replayed {} entries", persistenceId, count);
+ try (var reader = entries.openReader(fromSequenceNr)) {
+ handleReplayMessages(reader, message);
} catch (Exception e) {
LOG.warn("{}: failed to replay messages for {}", persistenceId, message, e);
message.promise.failure(e);
}
}
+ private void handleReplayMessages(final JournalReader<DataJournalEntry> reader, final ReplayMessages message) {
+ int count = 0;
+ while (count < message.max && reader.getNextIndex() <= message.toSequenceNr) {
+ final var repr = reader.tryNext((index, entry, size) -> {
+ LOG.trace("{}: replay index={} entry={}", persistenceId, index, entry);
+ updateLargestSize(size);
+ if (entry instanceof FromPersistence fromPersistence) {
+ return fromPersistence.toRepr(persistenceId, index);
+ }
+ throw new VerifyException("Unexpected entry " + entry);
+ });
+
+ if (repr == null) {
+ break;
+ }
+
+ LOG.debug("{}: replaying {}", persistenceId, repr);
+ message.replayCallback.accept(repr);
+ count++;
+ }
+ LOG.debug("{}: successfully replayed {} entries", persistenceId, count);
+ }
+
@Override
@SuppressWarnings("checkstyle:illegalCatch")
- long handleWriteMessages(final WriteMessages message) {
+ WrittenMessages handleWriteMessages(final WriteMessages message) {
final int count = message.size();
- final SegmentedJournalWriter<DataJournalEntry> writer = entries.writer();
- long bytes = 0;
+ final var responses = new ArrayList<>();
+ final var writer = entries.writer();
+ long writtenBytes = 0;
for (int i = 0; i < count; ++i) {
final long mark = writer.getLastIndex();
- final AtomicWrite request = message.getRequest(i);
+ final var request = message.getRequest(i);
- final List<PersistentRepr> reprs = CollectionConverters.asJava(request.payload());
+ final var reprs = CollectionConverters.asJava(request.payload());
LOG.trace("{}: append {}/{}: {} items at mark {}", persistenceId, i, count, reprs.size(), mark);
try {
- bytes += writePayload(writer, reprs);
+ writtenBytes += writePayload(writer, reprs);
} catch (Exception e) {
LOG.warn("{}: failed to write out request {}/{} reverting to {}", persistenceId, i, count, mark, e);
- message.setFailure(i, e);
+ responses.add(e);
writer.truncate(mark);
continue;
}
-
- message.setSuccess(i);
+ responses.add(null);
}
- writer.flush();
- return bytes;
+
+ return new WrittenMessages(message, responses, writtenBytes);
}
- private long writePayload(final SegmentedJournalWriter<DataJournalEntry> writer, final List<PersistentRepr> reprs) {
+ private long writePayload(final JournalWriter<DataJournalEntry> writer, final List<PersistentRepr> reprs) {
long bytes = 0;
- for (PersistentRepr repr : reprs) {
+ for (var repr : reprs) {
final Object payload = repr.payload();
if (!(payload instanceof Serializable)) {
throw new UnsupportedOperationException("Non-serializable payload encountered "
}
LOG.trace("{}: starting append of {}", persistenceId, payload);
- final Indexed<ToPersistence> entry = writer.append(new ToPersistence(repr));
+ final var entry = writer.append(new ToPersistence(repr));
final int size = entry.size();
LOG.trace("{}: finished append of {} with {} bytes at {}", persistenceId, payload, size, entry.index());
recordMessageSize(size);
--- /dev/null
+/*
+ * Copyright (c) 2023 PANTHEON.tech, s.r.o. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.controller.akka.segjournal;
+
+import io.atomix.storage.journal.JournalSerdes.EntryInput;
+import io.atomix.storage.journal.JournalSerdes.EntryOutput;
+import io.atomix.storage.journal.JournalSerdes.EntrySerdes;
+import java.io.IOException;
+
+enum LongEntrySerdes implements EntrySerdes<Long> {
+ LONG_ENTRY_SERDES {
+ @Override
+ public Long read(final EntryInput input) throws IOException {
+ return input.readLong();
+ }
+
+ @Override
+ public void write(final EntryOutput output, final Long entry) throws IOException {
+ output.writeLong(entry);
+ }
+ }
+}
import akka.persistence.PersistentRepr;
import akka.persistence.journal.japi.AsyncWriteJournal;
import com.typesafe.config.Config;
-import com.typesafe.config.ConfigMemorySize;
-import io.atomix.storage.StorageLevel;
import io.atomix.storage.journal.SegmentedJournal;
+import io.atomix.storage.journal.StorageLevel;
import java.io.File;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
-import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.function.Consumer;
* An Akka persistence journal implementation on top of {@link SegmentedJournal}. This actor represents aggregation
* of multiple journals and performs a receptionist job between Akka and invidual per-persistenceId actors. See
* {@link SegmentedJournalActor} for details on how the persistence works.
- *
- * @author Robert Varga
*/
public class SegmentedFileJournal extends AsyncWriteJournal {
public static final String STORAGE_ROOT_DIRECTORY = "root-directory";
public static final int STORAGE_MAX_ENTRY_SIZE_DEFAULT = 16 * 1024 * 1024;
public static final String STORAGE_MAX_SEGMENT_SIZE = "max-segment-size";
public static final int STORAGE_MAX_SEGMENT_SIZE_DEFAULT = STORAGE_MAX_ENTRY_SIZE_DEFAULT * 8;
+ public static final String STORAGE_MAX_UNFLUSHED_BYTES = "max-unflushed-bytes";
public static final String STORAGE_MEMORY_MAPPED = "memory-mapped";
private static final Logger LOG = LoggerFactory.getLogger(SegmentedFileJournal.class);
private final StorageLevel storage;
private final int maxEntrySize;
private final int maxSegmentSize;
+ private final int maxUnflushedBytes;
public SegmentedFileJournal(final Config config) {
rootDir = new File(config.getString(STORAGE_ROOT_DIRECTORY));
maxEntrySize = getBytes(config, STORAGE_MAX_ENTRY_SIZE, STORAGE_MAX_ENTRY_SIZE_DEFAULT);
maxSegmentSize = getBytes(config, STORAGE_MAX_SEGMENT_SIZE, STORAGE_MAX_SEGMENT_SIZE_DEFAULT);
+ maxUnflushedBytes = getBytes(config, STORAGE_MAX_UNFLUSHED_BYTES, maxEntrySize);
if (config.hasPath(STORAGE_MEMORY_MAPPED)) {
storage = config.getBoolean(STORAGE_MEMORY_MAPPED) ? StorageLevel.MAPPED : StorageLevel.DISK;
@Override
public Future<Iterable<Optional<Exception>>> doAsyncWriteMessages(final Iterable<AtomicWrite> messages) {
- final Map<ActorRef, WriteMessages> map = new HashMap<>();
- final List<Future<Optional<Exception>>> result = new ArrayList<>();
+ final var map = new HashMap<ActorRef, WriteMessages>();
+ final var result = new ArrayList<Future<Optional<Exception>>>();
- for (AtomicWrite message : messages) {
- final String persistenceId = message.persistenceId();
- final ActorRef handler = handlers.computeIfAbsent(persistenceId, this::createHandler);
+ for (var message : messages) {
+ final var persistenceId = message.persistenceId();
+ final var handler = handlers.computeIfAbsent(persistenceId, this::createHandler);
result.add(map.computeIfAbsent(handler, key -> new WriteMessages()).add(message));
}
}
private ActorRef createHandler(final String persistenceId) {
- final String directoryName = URLEncoder.encode(persistenceId, StandardCharsets.UTF_8);
- final File directory = new File(rootDir, directoryName);
+ final var directoryName = URLEncoder.encode(persistenceId, StandardCharsets.UTF_8);
+ final var directory = new File(rootDir, directoryName);
LOG.debug("Creating handler for {} in directory {}", persistenceId, directory);
- final ActorRef handler = context().actorOf(SegmentedJournalActor.props(persistenceId, directory, storage,
- maxEntrySize, maxSegmentSize));
+ final var handler = context().actorOf(SegmentedJournalActor.props(persistenceId, directory, storage,
+ maxEntrySize, maxSegmentSize, maxUnflushedBytes));
LOG.debug("Directory {} handled by {}", directory, handler);
return handler;
}
private <T> Future<T> delegateMessage(final String persistenceId, final AsyncMessage<T> message) {
- final ActorRef handler = handlers.get(persistenceId);
+ final var handler = handlers.get(persistenceId);
if (handler == null) {
return Futures.failed(new IllegalStateException("Cannot find handler for " + persistenceId));
}
if (!config.hasPath(path)) {
return defaultValue;
}
- final ConfigMemorySize value = config.getMemorySize(path);
- final long result = value.toBytes();
- checkArgument(result <= Integer.MAX_VALUE, "Size %s exceeds maximum allowed %s", Integer.MAX_VALUE);
- return (int) result;
+ final long value = config.getBytes(path);
+ checkArgument(value <= Integer.MAX_VALUE, "Size %s exceeds maximum allowed %s", Integer.MAX_VALUE);
+ return (int) value;
}
}
*/
package org.opendaylight.controller.akka.segjournal;
+import static com.google.common.base.Verify.verify;
import static com.google.common.base.Verify.verifyNotNull;
import static java.util.Objects.requireNonNull;
import akka.actor.AbstractActor;
+import akka.actor.ActorRef;
import akka.actor.Props;
+import akka.japi.pf.ReceiveBuilder;
import akka.persistence.AtomicWrite;
import akka.persistence.PersistentRepr;
import com.codahale.metrics.Histogram;
import com.codahale.metrics.Timer;
import com.google.common.base.MoreObjects;
import com.google.common.base.Stopwatch;
-import io.atomix.storage.StorageLevel;
import io.atomix.storage.journal.Indexed;
+import io.atomix.storage.journal.JournalSerdes;
import io.atomix.storage.journal.SegmentedJournal;
-import io.atomix.storage.journal.SegmentedJournalWriter;
-import io.atomix.utils.serializer.Namespace;
+import io.atomix.storage.journal.StorageLevel;
import java.io.File;
+import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
* <p>
* Split-file approach allows us to treat sequence numbers and indices as equivalent, without maintaining any explicit
* mapping information. The only additional information we need to maintain is the last deleted sequence number.
- *
- * @author Robert Varga
*/
-final class SegmentedJournalActor extends AbstractActor {
- abstract static class AsyncMessage<T> {
+abstract sealed class SegmentedJournalActor extends AbstractActor {
+ abstract static sealed class AsyncMessage<T> {
final Promise<T> promise = Promise.apply();
}
private final List<Promise<Optional<Exception>>> results = new ArrayList<>();
Future<Optional<Exception>> add(final AtomicWrite write) {
- final Promise<Optional<Exception>> promise = Promise.apply();
+ final var promise = Promise.<Optional<Exception>>apply();
requests.add(write);
results.add(promise);
return promise.future();
void setFailure(final int index, final Exception cause) {
results.get(index).success(Optional.of(cause));
-
}
void setSuccess(final int index) {
}
}
+ // responses == null on success, Exception on failure
+ record WrittenMessages(WriteMessages message, List<Object> responses, long writtenBytes) {
+ WrittenMessages {
+ verify(responses.size() == message.size(), "Mismatched %s and %s", message, responses);
+ verify(writtenBytes >= 0, "Unexpected length %s", writtenBytes);
+ }
+
+ private void complete() {
+ for (int i = 0, size = responses.size(); i < size; ++i) {
+ if (responses.get(i) instanceof Exception ex) {
+ message.setFailure(i, ex);
+ } else {
+ message.setSuccess(i);
+ }
+ }
+ }
+ }
+
+ /**
+ * A {@link SegmentedJournalActor} which delays issuing a flush operation until a watermark is reached or when the
+ * queue is empty.
+ *
+ * <p>
+ * The problem we are addressing is that there is a queue sitting in from of the actor, which we have no direct
+ * access to. Since a flush involves committing data to durable storage, that operation can easily end up dominating
+ * workloads.
+ *
+ * <p>
+ * We solve this by having an additional queue in which we track which messages were written and trigger a flush
+ * only when the number of bytes we have written exceeds specified limit. The other part is that each time this
+ * queue becomes non-empty, we send a dedicated message to self. This acts as a actor queue probe -- when we receive
+ * it, we know we have processed all messages that were in the queue when we first delayed the write.
+ *
+ * <p>
+ * The combination of these mechanisms ensure we use a minimal delay while also ensuring we take advantage of
+ * batching opportunities.
+ */
+ private static final class Delayed extends SegmentedJournalActor {
+ private static final class Flush extends AsyncMessage<Void> {
+ final long batch;
+
+ Flush(final long batch) {
+ this.batch = batch;
+ }
+ }
+
+ private record UnflushedWrite(WrittenMessages message, Stopwatch start, long count) {
+ UnflushedWrite {
+ requireNonNull(message);
+ requireNonNull(start);
+ }
+ }
+
+ private final ArrayDeque<UnflushedWrite> unflushedWrites = new ArrayDeque<>();
+ private final Stopwatch unflushedDuration = Stopwatch.createUnstarted();
+ private final long maxUnflushedBytes;
+
+ private long batch = 0;
+ private long unflushedBytes = 0;
+
+ Delayed(final String persistenceId, final File directory, final StorageLevel storage,
+ final int maxEntrySize, final int maxSegmentSize, final int maxUnflushedBytes) {
+ super(persistenceId, directory, storage, maxEntrySize, maxSegmentSize);
+ this.maxUnflushedBytes = maxUnflushedBytes;
+ }
+
+ @Override
+ ReceiveBuilder addMessages(final ReceiveBuilder builder) {
+ return super.addMessages(builder).match(Flush.class, this::handleFlush);
+ }
+
+ private void handleFlush(final Flush message) {
+ if (message.batch == batch) {
+ flushWrites();
+ } else {
+ LOG.debug("{}: batch {} not flushed by {}", persistenceId(), batch, message.batch);
+ }
+ }
+
+ @Override
+ void onWrittenMessages(final WrittenMessages message, final Stopwatch started, final long count) {
+ boolean first = unflushedWrites.isEmpty();
+ if (first) {
+ unflushedDuration.start();
+ }
+ unflushedWrites.addLast(new UnflushedWrite(message, started, count));
+ unflushedBytes = unflushedBytes + message.writtenBytes;
+ if (unflushedBytes >= maxUnflushedBytes) {
+ LOG.debug("{}: reached {} unflushed journal bytes", persistenceId(), unflushedBytes);
+ flushWrites();
+ } else if (first) {
+ LOG.debug("{}: deferring journal flush", persistenceId());
+ self().tell(new Flush(++batch), ActorRef.noSender());
+ }
+ }
+
+ @Override
+ void flushWrites() {
+ final var unsyncedSize = unflushedWrites.size();
+ if (unsyncedSize == 0) {
+ // Nothing to flush
+ return;
+ }
+
+ LOG.debug("{}: flushing {} journal writes after {}", persistenceId(), unsyncedSize,
+ unflushedDuration.stop());
+ flushJournal(unflushedBytes, unsyncedSize);
+
+ final var sw = Stopwatch.createStarted();
+ unflushedWrites.forEach(write -> completeWriteMessages(write.message, write.start, write.count));
+ unflushedWrites.clear();
+ unflushedBytes = 0;
+ unflushedDuration.reset();
+ LOG.debug("{}: completed {} flushed journal writes in {}", persistenceId(), unsyncedSize, sw);
+ }
+ }
+
+ private static final class Immediate extends SegmentedJournalActor {
+ Immediate(final String persistenceId, final File directory, final StorageLevel storage,
+ final int maxEntrySize, final int maxSegmentSize) {
+ super(persistenceId, directory, storage, maxEntrySize, maxSegmentSize);
+ }
+
+ @Override
+ void onWrittenMessages(final WrittenMessages message, final Stopwatch started, final long count) {
+ flushJournal(message.writtenBytes, 1);
+ completeWriteMessages(message, started, count);
+ }
+
+ @Override
+ void flushWrites() {
+ // No-op
+ }
+ }
+
private static final Logger LOG = LoggerFactory.getLogger(SegmentedJournalActor.class);
- private static final Namespace DELETE_NAMESPACE = Namespace.builder().register(Long.class).build();
+ private static final JournalSerdes DELETE_NAMESPACE = JournalSerdes.builder()
+ .register(LongEntrySerdes.LONG_ENTRY_SERDES, Long.class)
+ .build();
private static final int DELETE_SEGMENT_SIZE = 64 * 1024;
private final String persistenceId;
private Meter messageWriteCount;
// Tracks the size distribution of messages
private Histogram messageSize;
+ // Tracks the number of messages completed for each flush
+ private Histogram flushMessages;
+ // Tracks the number of bytes completed for each flush
+ private Histogram flushBytes;
+ // Tracks the duration of flush operations
+ private Timer flushTime;
private DataJournal dataJournal;
private SegmentedJournal<Long> deleteJournal;
private long lastDelete;
- SegmentedJournalActor(final String persistenceId, final File directory, final StorageLevel storage,
+ private SegmentedJournalActor(final String persistenceId, final File directory, final StorageLevel storage,
final int maxEntrySize, final int maxSegmentSize) {
this.persistenceId = requireNonNull(persistenceId);
this.directory = requireNonNull(directory);
}
static Props props(final String persistenceId, final File directory, final StorageLevel storage,
- final int maxEntrySize, final int maxSegmentSize) {
- return Props.create(SegmentedJournalActor.class, requireNonNull(persistenceId), directory, storage,
- maxEntrySize, maxSegmentSize);
+ final int maxEntrySize, final int maxSegmentSize, final int maxUnflushedBytes) {
+ final var pid = requireNonNull(persistenceId);
+ return maxUnflushedBytes > 0
+ ? Props.create(Delayed.class, pid, directory, storage, maxEntrySize, maxSegmentSize, maxUnflushedBytes)
+ : Props.create(Immediate.class, pid, directory, storage, maxEntrySize, maxSegmentSize);
+ }
+
+ final String persistenceId() {
+ return persistenceId;
+ }
+
+ final void flushJournal(final long bytes, final int messages) {
+ final var sw = Stopwatch.createStarted();
+ dataJournal.flush();
+ LOG.debug("{}: journal flush completed in {}", persistenceId, sw.stop());
+ flushBytes.update(bytes);
+ flushMessages.update(messages);
+ flushTime.update(sw.elapsed(TimeUnit.NANOSECONDS), TimeUnit.NANOSECONDS);
}
@Override
public Receive createReceive() {
- return receiveBuilder()
- .match(DeleteMessagesTo.class, this::handleDeleteMessagesTo)
- .match(ReadHighestSequenceNr.class, this::handleReadHighestSequenceNr)
- .match(ReplayMessages.class, this::handleReplayMessages)
- .match(WriteMessages.class, this::handleWriteMessages)
- .matchAny(this::handleUnknown)
- .build();
+ return addMessages(receiveBuilder())
+ .matchAny(this::handleUnknown)
+ .build();
+ }
+
+ ReceiveBuilder addMessages(final ReceiveBuilder builder) {
+ return builder
+ .match(DeleteMessagesTo.class, this::handleDeleteMessagesTo)
+ .match(ReadHighestSequenceNr.class, this::handleReadHighestSequenceNr)
+ .match(ReplayMessages.class, this::handleReplayMessages)
+ .match(WriteMessages.class, this::handleWriteMessages);
}
@Override
LOG.debug("{}: actor starting", persistenceId);
super.preStart();
- final MetricRegistry registry = MetricsReporter.getInstance(MeteringBehavior.DOMAIN).getMetricsRegistry();
- final String actorName = self().path().parent().toStringWithoutAddress() + '/' + directory.getName();
+ final var registry = MetricsReporter.getInstance(MeteringBehavior.DOMAIN).getMetricsRegistry();
+ final var actorName = self().path().parent().toStringWithoutAddress() + '/' + directory.getName();
batchWriteTime = registry.timer(MetricRegistry.name(actorName, "batchWriteTime"));
messageWriteCount = registry.meter(MetricRegistry.name(actorName, "messageWriteCount"));
messageSize = registry.histogram(MetricRegistry.name(actorName, "messageSize"));
+ flushBytes = registry.histogram(MetricRegistry.name(actorName, "flushBytes"));
+ flushMessages = registry.histogram(MetricRegistry.name(actorName, "flushMessages"));
+ flushTime = registry.timer(MetricRegistry.name(actorName, "flushTime"));
}
@Override
ensureOpen();
LOG.debug("{}: delete messages {}", persistenceId, message);
+ flushWrites();
+
final long to = Long.min(dataJournal.lastWrittenSequenceNr(), message.toSequenceNr);
LOG.debug("{}: adjusted delete to {}", persistenceId, to);
LOG.debug("{}: deleting entries up to {}", persistenceId, to);
lastDelete = to;
- final SegmentedJournalWriter<Long> deleteWriter = deleteJournal.writer();
- final Indexed<Long> entry = deleteWriter.append(lastDelete);
+ final var deleteWriter = deleteJournal.writer();
+ final var entry = deleteWriter.append(lastDelete);
deleteWriter.commit(entry.index());
dataJournal.deleteTo(lastDelete);
final Long sequence;
if (directory.isDirectory()) {
ensureOpen();
+ flushWrites();
sequence = dataJournal.lastWrittenSequenceNr();
} else {
sequence = 0L;
private void handleReplayMessages(final ReplayMessages message) {
LOG.debug("{}: replaying messages {}", persistenceId, message);
ensureOpen();
+ flushWrites();
final long from = Long.max(lastDelete + 1, message.fromSequenceNr);
LOG.debug("{}: adjusted fromSequenceNr to {}", persistenceId, from);
private void handleWriteMessages(final WriteMessages message) {
ensureOpen();
- final Stopwatch sw = Stopwatch.createStarted();
+ final var started = Stopwatch.createStarted();
final long start = dataJournal.lastWrittenSequenceNr();
- final long bytes = dataJournal.handleWriteMessages(message);
- sw.stop();
+ final var writtenMessages = dataJournal.handleWriteMessages(message);
- batchWriteTime.update(sw.elapsed(TimeUnit.NANOSECONDS), TimeUnit.NANOSECONDS);
- messageWriteCount.mark(dataJournal.lastWrittenSequenceNr() - start);
+ onWrittenMessages(writtenMessages, started, dataJournal.lastWrittenSequenceNr() - start);
+ }
+ final void completeWriteMessages(final WrittenMessages message, final Stopwatch started, final long count) {
+ batchWriteTime.update(started.stop().elapsed(TimeUnit.NANOSECONDS), TimeUnit.NANOSECONDS);
+ messageWriteCount.mark(count);
// log message after statistics are updated
- LOG.debug("{}: write of {} bytes completed in {}", persistenceId, bytes, sw);
+ LOG.debug("{}: write of {} bytes completed in {}", persistenceId, message.writtenBytes, started);
+ message.complete();
}
+ /**
+ * Handle a check of written messages.
+ *
+ * @param message Messages which were written
+ * @param started Stopwatch started when the write started
+ * @param count number of writes
+ */
+ abstract void onWrittenMessages(WrittenMessages message, Stopwatch started, long count);
+
private void handleUnknown(final Object message) {
LOG.error("{}: Received unknown message {}", persistenceId, message);
}
return;
}
- final Stopwatch sw = Stopwatch.createStarted();
+ final var sw = Stopwatch.createStarted();
deleteJournal = SegmentedJournal.<Long>builder().withDirectory(directory).withName("delete")
.withNamespace(DELETE_NAMESPACE).withMaxSegmentSize(DELETE_SEGMENT_SIZE).build();
- final Indexed<Long> lastEntry = deleteJournal.writer().getLastEntry();
- lastDelete = lastEntry == null ? 0 : lastEntry.entry();
+ final var lastDeleteRecovered = deleteJournal.openReader(deleteJournal.writer().getLastIndex())
+ .tryNext((index, value, length) -> value);
+ lastDelete = lastDeleteRecovered == null ? 0 : lastDeleteRecovered.longValue();
dataJournal = new DataJournalV0(persistenceId, messageSize, context().system(), storage, directory,
maxEntrySize, maxSegmentSize);
LOG.debug("{}: journal open in {} with last index {}, deleted to {}", persistenceId, sw,
dataJournal.lastWrittenSequenceNr(), lastDelete);
}
+
+ abstract void flushWrites();
+
}
FileUtils.deleteQuietly(JOURNAL_DIR);
super.beforeAll();
}
+
+ @Override
+ public void afterAll() {
+ super.afterAll();
+ FileUtils.deleteQuietly(JOURNAL_DIR);
+ }
}
*/
package org.opendaylight.controller.akka.segjournal;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNull;
-import static org.junit.Assert.assertTrue;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
-import static org.mockito.Mockito.doNothing;
-import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import akka.persistence.PersistentRepr;
import akka.testkit.CallingThreadDispatcher;
import akka.testkit.javadsl.TestKit;
-import io.atomix.storage.StorageLevel;
+import io.atomix.storage.journal.StorageLevel;
import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import org.apache.commons.io.FileUtils;
-import org.junit.After;
-import org.junit.AfterClass;
-import org.junit.Before;
-import org.junit.BeforeClass;
-import org.junit.Test;
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.mockito.Mock;
+import org.mockito.junit.jupiter.MockitoExtension;
import org.opendaylight.controller.akka.segjournal.SegmentedJournalActor.AsyncMessage;
import org.opendaylight.controller.akka.segjournal.SegmentedJournalActor.WriteMessages;
import scala.concurrent.Future;
-public class SegmentedFileJournalTest {
+@ExtendWith(MockitoExtension.class)
+class SegmentedFileJournalTest {
private static final File DIRECTORY = new File("target/sfj-test");
private static final int SEGMENT_SIZE = 1024 * 1024;
private static final int MESSAGE_SIZE = 512 * 1024;
+ private static final int FLUSH_SIZE = 16 * 1024;
private static ActorSystem SYSTEM;
+ @Mock
+ private Consumer<PersistentRepr> firstCallback;
+
private TestKit kit;
private ActorRef actor;
- @BeforeClass
- public static void beforeClass() {
+ @BeforeAll
+ static void beforeClass() {
SYSTEM = ActorSystem.create("test");
}
- @AfterClass
- public static void afterClass() {
+ @AfterAll
+ static void afterClass() {
TestKit.shutdownActorSystem(SYSTEM);
SYSTEM = null;
}
- @Before
- public void before() {
+ @BeforeEach
+ void before() {
kit = new TestKit(SYSTEM);
FileUtils.deleteQuietly(DIRECTORY);
actor = actor();
}
- @After
- public void after() {
+ @AfterEach
+ void after() {
actor.tell(PoisonPill.getInstance(), ActorRef.noSender());
+ FileUtils.deleteQuietly(DIRECTORY);
}
@Test
- public void testDeleteAfterStop() {
+ void testDeleteAfterStop() {
// Preliminary setup
final WriteMessages write = new WriteMessages();
final Future<Optional<Exception>> first = write.add(AtomicWrite.apply(PersistentRepr.apply("first", 1, "foo",
}
@Test
- public void testSegmentation() throws IOException {
+ void testSegmentation() throws IOException {
// We want to have roughly three segments
final LargePayload payload = new LargePayload();
}
@Test
- public void testComplexDeletesAndPartialReplays() throws Exception {
+ void testComplexDeletesAndPartialReplays() throws Exception {
for (int i = 0; i <= 4; i++) {
writeBigPaylod();
}
private ActorRef actor() {
return kit.childActorOf(SegmentedJournalActor.props("foo", DIRECTORY, StorageLevel.DISK, MESSAGE_SIZE,
- SEGMENT_SIZE).withDispatcher(CallingThreadDispatcher.Id()));
+ SEGMENT_SIZE, FLUSH_SIZE).withDispatcher(CallingThreadDispatcher.Id()));
}
private void deleteEntries(final long deleteTo) {
}
private void assertReplayCount(final int expected) {
- Consumer<PersistentRepr> firstCallback = mock(Consumer.class);
- doNothing().when(firstCallback).accept(any(PersistentRepr.class));
+ // Cast fixes an Eclipse warning 'generic array created'
+ reset((Object) firstCallback);
AsyncMessage<Void> replay = SegmentedJournalActor.replayMessages(0, Long.MAX_VALUE, Long.MAX_VALUE,
firstCallback);
actor.tell(replay, ActorRef.noSender());
return future.value().get().get();
}
- private static final class LargePayload implements Serializable {
+ static final class LargePayload implements Serializable {
+ @java.io.Serial
private static final long serialVersionUID = 1L;
final byte[] bytes = new byte[MESSAGE_SIZE / 2];
-
}
}
<parent>
<groupId>org.opendaylight.controller</groupId>
<artifactId>mdsal-it-parent</artifactId>
- <version>7.0.2-SNAPSHOT</version>
+ <version>9.0.3-SNAPSHOT</version>
<relativePath>../mdsal-it-parent</relativePath>
</parent>
<artifactId>sal-binding-it</artifactId>
protected Option[] getAdditionalOptions() {
return new Option[] {
mavenBundle("org.opendaylight.controller", "sal-test-model").versionAsInProject(),
- mavenBundle("net.bytebuddy", "byte-buddy").versionAsInProject(),
};
}
}
import static org.junit.Assert.assertEquals;
import java.util.ArrayList;
-import java.util.List;
import javax.inject.Inject;
import org.junit.Test;
import org.opendaylight.mdsal.binding.api.NotificationPublishService;
import org.opendaylight.mdsal.binding.api.NotificationService;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.bi.ba.notification.rev150205.OpendaylightTestNotificationListener;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.bi.ba.notification.rev150205.OutOfPixieDustNotification;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.bi.ba.notification.rev150205.OutOfPixieDustNotificationBuilder;
-import org.opendaylight.yangtools.concepts.ListenerRegistration;
-import org.opendaylight.yangtools.yang.binding.NotificationListener;
import org.opendaylight.yangtools.yang.common.Uint16;
import org.ops4j.pax.exam.util.Filter;
import org.slf4j.Logger;
*/
@Test
public void notificationTest() throws Exception {
- NotificationTestListener listener1 = new NotificationTestListener();
- ListenerRegistration<NotificationListener> listener1Reg =
- notificationService.registerNotificationListener(listener1);
-
- LOG.info("The notification of type FlowAdded with cookie ID 0 is created. The "
- + "delay 100ms to make sure that the notification was delivered to "
- + "listener.");
- notificationPublishService.putNotification(noDustNotification("rainy day", 42));
- Thread.sleep(100);
-
- /**
- * Check that one notification was delivered and has correct cookie.
- */
- assertEquals(1, listener1.notificationBag.size());
- assertEquals("rainy day", listener1.notificationBag.get(0).getReason());
- assertEquals(42, listener1.notificationBag.get(0).getDaysTillNewDust().intValue());
-
- LOG.info("The registration of the Consumer 2. SalFlowListener is registered "
+ final var bag1 = new ArrayList<OutOfPixieDustNotification>();
+ try (var reg1 = notificationService.registerListener(OutOfPixieDustNotification.class, bag1::add)) {
+ LOG.info("""
+ The notification of type FlowAdded with cookie ID 0 is created. The\s\
+ delay 100ms to make sure that the notification was delivered to\s\
+ listener.""");
+ notificationPublishService.putNotification(noDustNotification("rainy day", 42));
+ Thread.sleep(100);
+
+ // Check that one notification was delivered and has correct cookie.
+ assertEquals(1, bag1.size());
+ assertEquals("rainy day", bag1.get(0).getReason());
+ assertEquals(42, bag1.get(0).getDaysTillNewDust().intValue());
+
+ LOG.info("The registration of the Consumer 2. SalFlowListener is registered "
+ "registered as notification listener.");
- NotificationTestListener listener2 = new NotificationTestListener();
- final ListenerRegistration<NotificationListener> listener2Reg =
- notificationService.registerNotificationListener(listener2);
-
- LOG.info("3 notifications are published");
- notificationPublishService.putNotification(noDustNotification("rainy day", 5));
- notificationPublishService.putNotification(noDustNotification("rainy day", 10));
- notificationPublishService.putNotification(noDustNotification("tax collector", 2));
-
- /**
- * The delay 100ms to make sure that the notifications were delivered to
- * listeners.
- */
- Thread.sleep(100);
-
- /**
- * Check that 3 notification was delivered to both listeners (first one
- * received 4 in total, second 3 in total).
- */
- assertEquals(4, listener1.notificationBag.size());
- assertEquals(3, listener2.notificationBag.size());
-
- /**
- * The second listener is closed (unregistered)
- *
- */
- listener2Reg.close();
-
- LOG.info("The notification 5 is published");
- notificationPublishService.putNotification(noDustNotification("entomologist hunt", 10));
-
- /**
- * The delay 100ms to make sure that the notification was delivered to
- * listener.
- */
- Thread.sleep(100);
-
- /**
- * Check that first consumer received 5 notifications in total, second
- * consumer received only three. Last notification was never received by
- * second consumer because its listener was unregistered.
- *
- */
- assertEquals(5, listener1.notificationBag.size());
- assertEquals(3, listener2.notificationBag.size());
+ final var bag2 = new ArrayList<OutOfPixieDustNotification>();
+ try (var reg2 = notificationService.registerListener(OutOfPixieDustNotification.class, bag2::add)) {
+ LOG.info("3 notifications are published");
+ notificationPublishService.putNotification(noDustNotification("rainy day", 5));
+ notificationPublishService.putNotification(noDustNotification("rainy day", 10));
+ notificationPublishService.putNotification(noDustNotification("tax collector", 2));
+
+ // The delay 100ms to make sure that the notifications were delivered to listeners.
+ Thread.sleep(100);
+
+ // Check that 3 notification was delivered to both listeners (first one received 4 in total, second 3
+ // in total).
+ assertEquals(4, bag1.size());
+ assertEquals(3, bag2.size());
+
+ // The second listener is closed (unregistered)
+ reg2.close();
+
+ LOG.info("The notification 5 is published");
+ notificationPublishService.putNotification(noDustNotification("entomologist hunt", 10));
+
+ // The delay 100ms to make sure that the notification was delivered to listener.
+ Thread.sleep(100);
+
+ // Check that first consumer received 5 notifications in total, second consumer received only three.
+ // Last notification was never received by second consumer because its listener was unregistered.
+ assertEquals(5, bag1.size());
+ assertEquals(3, bag2.size());
+ }
+ }
}
/**
ret.setReason(reason).setDaysTillNewDust(Uint16.valueOf(days));
return ret.build();
}
-
- /**
- * Implements {@link OpendaylightTestNotificationListener} and contains attributes which keep lists of objects of
- * the type {@link OutOfPixieDustNotification}.
- */
- public static class NotificationTestListener implements OpendaylightTestNotificationListener {
- List<OutOfPixieDustNotification> notificationBag = new ArrayList<>();
-
- @Override
- public void onOutOfPixieDustNotification(final OutOfPixieDustNotification arg0) {
- notificationBag.add(arg0);
- }
- }
}
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNotSame;
-import static org.junit.Assert.assertSame;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import javax.inject.Inject;
import org.junit.Before;
import org.junit.Test;
-import org.mockito.Mockito;
-import org.opendaylight.mdsal.binding.api.RpcConsumerRegistry;
import org.opendaylight.mdsal.binding.api.RpcProviderService;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.rpc.routing.rev140701.OpendaylightTestRoutedRpcService;
+import org.opendaylight.mdsal.binding.api.RpcService;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.rpc.routing.rev140701.RoutedSimpleRoute;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.rpc.routing.rev140701.RoutedSimpleRouteInput;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.rpc.routing.rev140701.RoutedSimpleRouteInputBuilder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.rpc.routing.rev140701.RoutedSimpleRouteOutput;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.store.rev140422.lists.UnorderedContainer;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.store.rev140422.lists.unordered.container.UnorderedList;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.test.store.rev140422.lists.unordered.container.UnorderedListKey;
-import org.opendaylight.yangtools.concepts.ObjectRegistration;
+import org.opendaylight.yangtools.concepts.Registration;
import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
import org.opendaylight.yangtools.yang.common.RpcResult;
import org.ops4j.pax.exam.util.Filter;
* Covers routed rpc creation, registration, invocation, unregistration.
*/
public class RoutedServiceIT extends AbstractIT {
+ private static final Logger LOG = LoggerFactory.getLogger(RoutedServiceIT.class);
- private static final Logger LOG = LoggerFactory
- .getLogger(RoutedServiceIT.class);
-
- protected OpendaylightTestRoutedRpcService odlRoutedService1;
- protected OpendaylightTestRoutedRpcService odlRoutedService2;
+ protected RoutedSimpleRoute routedSimpleRouteRpc1;
+ protected RoutedSimpleRoute routedSimpleRouteRpc2;
@Inject
@Filter(timeout = 120 * 1000)
@Inject
@Filter(timeout = 120 * 1000)
- RpcConsumerRegistry rpcConsumerRegistry;
+ RpcService rpcService;
/**
* Prepare mocks.
*/
@Before
public void setUp() {
- odlRoutedService1 = mock(OpendaylightTestRoutedRpcService.class, "First Flow Service");
- odlRoutedService2 = mock(OpendaylightTestRoutedRpcService.class, "Second Flow Service");
- Mockito.when(odlRoutedService1.routedSimpleRoute(Mockito.<RoutedSimpleRouteInput>any()))
- .thenReturn(Futures.<RpcResult<RoutedSimpleRouteOutput>>immediateFuture(null));
- Mockito.when(odlRoutedService2.routedSimpleRoute(Mockito.<RoutedSimpleRouteInput>any()))
- .thenReturn(Futures.<RpcResult<RoutedSimpleRouteOutput>>immediateFuture(null));
+ routedSimpleRouteRpc1 = mock(RoutedSimpleRoute.class, "First Flow Rpc");
+ doReturn(RoutedSimpleRoute.class).when(routedSimpleRouteRpc1).implementedInterface();
+ doReturn(Futures.<RpcResult<RoutedSimpleRouteOutput>>immediateFuture(null)).when(routedSimpleRouteRpc1)
+ .invoke(any());
+
+ routedSimpleRouteRpc2 = mock(RoutedSimpleRoute.class, "Second Flow Rpc");
+ doReturn(RoutedSimpleRoute.class).when(routedSimpleRouteRpc2).implementedInterface();
+ doReturn(Futures.<RpcResult<RoutedSimpleRouteOutput>>immediateFuture(null)).when(routedSimpleRouteRpc2)
+ .invoke(any());
}
@Test
public void testServiceRegistration() {
- LOG.info("Register provider 1 with first implementation of routeSimpleService - service1 of node 1");
+ LOG.info("Register provider 1 with first implementation of routeSimpleService - rpc1 of node 1");
final InstanceIdentifier<UnorderedList> nodeOnePath = createNodeRef("foo:node:1");
final InstanceIdentifier<UnorderedList> nodeTwo = createNodeRef("foo:node:2");
- ObjectRegistration<OpendaylightTestRoutedRpcService> firstReg = rpcProviderService.registerRpcImplementation(
- OpendaylightTestRoutedRpcService.class, odlRoutedService1, Set.of(nodeOnePath));
+ Registration firstReg = rpcProviderService.registerRpcImplementation(routedSimpleRouteRpc1,
+ Set.of(nodeOnePath));
assertNotNull("Registration should not be null", firstReg);
- assertSame(odlRoutedService1, firstReg.getInstance());
- LOG.info("Register provider 2 with second implementation of routeSimpleService - service2 of node 2");
+ LOG.info("Register provider 2 with second implementation of routeSimpleService - rpc2 of node 2");
- ObjectRegistration<OpendaylightTestRoutedRpcService> secondReg = rpcProviderService.registerRpcImplementation(
- OpendaylightTestRoutedRpcService.class, odlRoutedService2, Set.of(nodeTwo));
+ Registration secondReg = rpcProviderService.registerRpcImplementation(routedSimpleRouteRpc2, Set.of(nodeTwo));
assertNotNull("Registration should not be null", firstReg);
- assertSame(odlRoutedService2, secondReg.getInstance());
assertNotSame(secondReg, firstReg);
- OpendaylightTestRoutedRpcService consumerService =
- rpcConsumerRegistry.getRpcService(OpendaylightTestRoutedRpcService.class);
+ RoutedSimpleRoute consumerService = rpcService.getRpc(RoutedSimpleRoute.class);
assertNotNull("MD-SAL instance of test Service should be returned", consumerService);
- assertNotSame("Provider instance and consumer instance should not be same.", odlRoutedService1,
+ assertNotSame("Provider instance and consumer instance should not be same.", routedSimpleRouteRpc1,
consumerService);
/**
* Consumer creates addFlow message for node one and sends it to the MD-SAL.
*/
final RoutedSimpleRouteInput simpleRouteFirstFoo = createSimpleRouteInput(nodeOnePath);
- consumerService.routedSimpleRoute(simpleRouteFirstFoo);
+ consumerService.invoke(simpleRouteFirstFoo);
/**
- * Verifies that implementation of the first provider received the same message from MD-SAL.
+ * Verifies that implementation of the first instance received the same message from MD-SAL.
*/
- verify(odlRoutedService1).routedSimpleRoute(simpleRouteFirstFoo);
+ verify(routedSimpleRouteRpc1).invoke(simpleRouteFirstFoo);
/**
* Verifies that second instance was not invoked with first message
*/
- verify(odlRoutedService2, times(0)).routedSimpleRoute(simpleRouteFirstFoo);
+ verify(routedSimpleRouteRpc2, times(0)).invoke(simpleRouteFirstFoo);
/**
* Consumer sends message to nodeTwo for three times. Should be processed by second instance.
*/
final RoutedSimpleRouteInput simpleRouteSecondFoo = createSimpleRouteInput(nodeTwo);
- consumerService.routedSimpleRoute(simpleRouteSecondFoo);
- consumerService.routedSimpleRoute(simpleRouteSecondFoo);
- consumerService.routedSimpleRoute(simpleRouteSecondFoo);
+ consumerService.invoke(simpleRouteSecondFoo);
+ consumerService.invoke(simpleRouteSecondFoo);
+ consumerService.invoke(simpleRouteSecondFoo);
/**
* Verifies that second instance was invoked 3 times with second message and first instance wasn't invoked.
*/
- verify(odlRoutedService2, times(3)).routedSimpleRoute(simpleRouteSecondFoo);
- verify(odlRoutedService1, times(0)).routedSimpleRoute(simpleRouteSecondFoo);
+ verify(routedSimpleRouteRpc2, times(3)).invoke(simpleRouteSecondFoo);
+ verify(routedSimpleRouteRpc1, times(0)).invoke(simpleRouteSecondFoo);
LOG.info("Unregistration of the path for the node one in the first provider");
firstReg.close();
LOG.info("Provider 2 registers path of node 1");
secondReg.close();
- secondReg = rpcProviderService.registerRpcImplementation(
- OpendaylightTestRoutedRpcService.class, odlRoutedService2, Set.of(nodeOnePath));
+ secondReg = rpcProviderService.registerRpcImplementation(routedSimpleRouteRpc2, Set.of(nodeOnePath));
/**
* A consumer sends third message to node 1.
*/
final RoutedSimpleRouteInput simpleRouteThirdFoo = createSimpleRouteInput(nodeOnePath);
- consumerService.routedSimpleRoute(simpleRouteThirdFoo);
+ consumerService.invoke(simpleRouteThirdFoo);
/**
* Verifies that provider 1 wasn't invoked and provider 2 was invoked 1 time.
* TODO: fix unregister path
*/
- //verify(odlRoutedService1, times(0)).routedSimpleRoute(simpleRouteThirdFoo);
- verify(odlRoutedService2).routedSimpleRoute(simpleRouteThirdFoo);
+ verify(routedSimpleRouteRpc2).invoke(simpleRouteThirdFoo);
}
/**
<parent>
<groupId>org.opendaylight.controller</groupId>
<artifactId>mdsal-parent</artifactId>
- <version>7.0.2-SNAPSHOT</version>
+ <version>9.0.3-SNAPSHOT</version>
<relativePath>../parent</relativePath>
</parent>
<packaging>bundle</packaging>
<dependencies>
+ <dependency>
+ <groupId>com.google.guava</groupId>
+ <artifactId>guava</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.opendaylight.yangtools</groupId>
+ <artifactId>yang-common</artifactId>
+ </dependency>
<dependency>
<groupId>org.opendaylight.controller</groupId>
<artifactId>cds-access-api</artifactId>
<parent>
<groupId>org.opendaylight.controller</groupId>
<artifactId>mdsal-parent</artifactId>
- <version>7.0.2-SNAPSHOT</version>
+ <version>9.0.3-SNAPSHOT</version>
<relativePath>../parent</relativePath>
</parent>
<dependencies>
<dependency>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>sal-cluster-admin-api</artifactId>
+ <groupId>com.github.spotbugs</groupId>
+ <artifactId>spotbugs-annotations</artifactId>
+ <optional>true</optional>
</dependency>
-
- <!-- Tests -->
<dependency>
- <groupId>org.slf4j</groupId>
- <artifactId>slf4j-simple</artifactId>
- <scope>test</scope>
+ <groupId>com.google.guava</groupId>
+ <artifactId>guava</artifactId>
</dependency>
<dependency>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>sal-akka-raft</artifactId>
- <type>test-jar</type>
- <scope>test</scope>
+ <groupId>org.apache.commons</groupId>
+ <artifactId>commons-lang3</artifactId>
</dependency>
<dependency>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>sal-distributed-datastore</artifactId>
- <type>test-jar</type>
- <version>${project.version}</version>
- <scope>test</scope>
+ <groupId>org.eclipse.jdt</groupId>
+ <artifactId>org.eclipse.jdt.annotation</artifactId>
</dependency>
<dependency>
<groupId>org.opendaylight.yangtools</groupId>
- <artifactId>yang-test-util</artifactId>
+ <artifactId>concepts</artifactId>
</dependency>
<dependency>
- <groupId>org.opendaylight.controller.samples</groupId>
- <artifactId>clustering-it-model</artifactId>
- <scope>test</scope>
+ <groupId>org.opendaylight.yangtools</groupId>
+ <artifactId>yang-common</artifactId>
</dependency>
<dependency>
- <groupId>commons-lang</groupId>
- <artifactId>commons-lang</artifactId>
- <scope>test</scope>
+ <groupId>org.opendaylight.mdsal</groupId>
+ <artifactId>mdsal-binding-api</artifactId>
</dependency>
-
- <!-- Akka -->
<dependency>
- <groupId>com.typesafe.akka</groupId>
- <artifactId>akka-testkit_2.13</artifactId>
+ <groupId>org.opendaylight.mdsal</groupId>
+ <artifactId>mdsal-dom-spi</artifactId>
</dependency>
-
- <!-- Scala -->
<dependency>
- <groupId>org.scala-lang</groupId>
- <artifactId>scala-library</artifactId>
+ <groupId>org.opendaylight.mdsal</groupId>
+ <artifactId>yang-binding</artifactId>
</dependency>
-
- <!-- OpenDaylight -->
<dependency>
<groupId>org.opendaylight.controller</groupId>
<artifactId>eos-dom-akka</artifactId>
</dependency>
<dependency>
- <groupId>org.opendaylight.mdsal</groupId>
- <artifactId>mdsal-binding-api</artifactId>
+ <groupId>org.opendaylight.controller</groupId>
+ <artifactId>cds-access-api</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.opendaylight.controller</groupId>
+ <artifactId>repackaged-akka</artifactId>
</dependency>
<dependency>
<groupId>org.opendaylight.controller</groupId>
<artifactId>sal-akka-raft</artifactId>
</dependency>
+ <dependency>
+ <groupId>org.opendaylight.controller</groupId>
+ <artifactId>sal-cluster-admin-api</artifactId>
+ </dependency>
<dependency>
<groupId>org.opendaylight.controller</groupId>
<artifactId>sal-distributed-datastore</artifactId>
</dependency>
<dependency>
- <groupId>org.opendaylight.mdsal</groupId>
- <artifactId>yang-binding</artifactId>
+ <groupId>org.osgi</groupId>
+ <artifactId>org.osgi.service.component.annotations</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.scala-lang</groupId>
+ <artifactId>scala-library</artifactId>
+ </dependency>
+
+ <!-- Tests -->
+ <dependency>
+ <groupId>com.typesafe.akka</groupId>
+ <artifactId>akka-testkit_2.13</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.opendaylight.controller</groupId>
+ <artifactId>sal-akka-raft</artifactId>
+ <type>test-jar</type>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.opendaylight.controller</groupId>
+ <artifactId>sal-distributed-datastore</artifactId>
+ <type>test-jar</type>
+ <version>${project.version}</version>
+ <scope>test</scope>
</dependency>
<dependency>
<groupId>org.opendaylight.yangtools</groupId>
- <artifactId>yang-common</artifactId>
+ <artifactId>yang-data-api</artifactId>
+ <scope>test</scope>
</dependency>
<dependency>
- <groupId>org.apache.commons</groupId>
- <artifactId>commons-lang3</artifactId>
+ <groupId>org.opendaylight.yangtools</groupId>
+ <artifactId>yang-test-util</artifactId>
</dependency>
<dependency>
- <groupId>org.osgi</groupId>
- <artifactId>org.osgi.service.component.annotations</artifactId>
+ <groupId>org.opendaylight.controller.samples</groupId>
+ <artifactId>clustering-it-model</artifactId>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.slf4j</groupId>
+ <artifactId>slf4j-simple</artifactId>
+ <scope>test</scope>
</dependency>
-
</dependencies>
<build>
import akka.dispatch.OnComplete;
import akka.pattern.Patterns;
import akka.util.Timeout;
+import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Strings;
import com.google.common.base.Throwables;
import com.google.common.collect.ImmutableMap;
import org.opendaylight.controller.cluster.datastore.utils.ActorUtils;
import org.opendaylight.controller.cluster.raft.client.messages.GetSnapshot;
import org.opendaylight.controller.eos.akka.DataCenterControl;
-import org.opendaylight.mdsal.binding.dom.codec.api.BindingNormalizedNodeSerializer;
+import org.opendaylight.mdsal.binding.api.RpcProviderService;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.cluster.admin.rev151013.ActivateEosDatacenter;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.cluster.admin.rev151013.ActivateEosDatacenterInput;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.cluster.admin.rev151013.ActivateEosDatacenterOutput;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.cluster.admin.rev151013.AddReplicasForAllShards;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.cluster.admin.rev151013.AddReplicasForAllShardsInput;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.cluster.admin.rev151013.AddReplicasForAllShardsOutput;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.cluster.admin.rev151013.AddReplicasForAllShardsOutputBuilder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.cluster.admin.rev151013.AddShardReplicaInput;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.cluster.admin.rev151013.AddShardReplicaOutput;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.cluster.admin.rev151013.AddShardReplicaOutputBuilder;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.cluster.admin.rev151013.BackupDatastore;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.cluster.admin.rev151013.BackupDatastoreInput;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.cluster.admin.rev151013.BackupDatastoreOutput;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.cluster.admin.rev151013.BackupDatastoreOutputBuilder;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.cluster.admin.rev151013.ChangeMemberVotingStatesForAllShards;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.cluster.admin.rev151013.ChangeMemberVotingStatesForAllShardsInput;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.cluster.admin.rev151013.ChangeMemberVotingStatesForAllShardsOutput;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.cluster.admin.rev151013.ChangeMemberVotingStatesForAllShardsOutputBuilder;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.cluster.admin.rev151013.ChangeMemberVotingStatesForShard;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.cluster.admin.rev151013.ChangeMemberVotingStatesForShardInput;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.cluster.admin.rev151013.ChangeMemberVotingStatesForShardOutput;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.cluster.admin.rev151013.ChangeMemberVotingStatesForShardOutputBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.cluster.admin.rev151013.ClusterAdminService;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.cluster.admin.rev151013.DataStoreType;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.cluster.admin.rev151013.DeactivateEosDatacenter;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.cluster.admin.rev151013.DeactivateEosDatacenterInput;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.cluster.admin.rev151013.DeactivateEosDatacenterOutput;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.cluster.admin.rev151013.FlipMemberVotingStatesForAllShards;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.cluster.admin.rev151013.FlipMemberVotingStatesForAllShardsInput;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.cluster.admin.rev151013.FlipMemberVotingStatesForAllShardsOutput;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.cluster.admin.rev151013.FlipMemberVotingStatesForAllShardsOutputBuilder;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.cluster.admin.rev151013.GetKnownClientsForAllShards;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.cluster.admin.rev151013.GetKnownClientsForAllShardsInput;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.cluster.admin.rev151013.GetKnownClientsForAllShardsOutput;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.cluster.admin.rev151013.GetKnownClientsForAllShardsOutputBuilder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.cluster.admin.rev151013.GetShardRoleInput;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.cluster.admin.rev151013.GetShardRoleOutput;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.cluster.admin.rev151013.GetShardRoleOutputBuilder;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.cluster.admin.rev151013.LocateShard;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.cluster.admin.rev151013.LocateShardInput;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.cluster.admin.rev151013.LocateShardOutput;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.cluster.admin.rev151013.LocateShardOutputBuilder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.cluster.admin.rev151013.MakeLeaderLocalInput;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.cluster.admin.rev151013.MakeLeaderLocalOutput;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.cluster.admin.rev151013.MakeLeaderLocalOutputBuilder;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.cluster.admin.rev151013.RemoveAllShardReplicas;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.cluster.admin.rev151013.RemoveAllShardReplicasInput;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.cluster.admin.rev151013.RemoveAllShardReplicasOutput;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.cluster.admin.rev151013.RemoveAllShardReplicasOutputBuilder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.cluster.admin.rev151013.shard.result.output.ShardResult;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.cluster.admin.rev151013.shard.result.output.ShardResultBuilder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.cluster.admin.rev151013.shard.result.output.ShardResultKey;
+import org.opendaylight.yangtools.concepts.Registration;
import org.opendaylight.yangtools.yang.common.Empty;
import org.opendaylight.yangtools.yang.common.ErrorType;
import org.opendaylight.yangtools.yang.common.RpcResult;
*
* @author Thomas Pantelis
*/
-public class ClusterAdminRpcService implements ClusterAdminService {
+public final class ClusterAdminRpcService {
private static final Timeout SHARD_MGR_TIMEOUT = new Timeout(1, TimeUnit.MINUTES);
private static final Logger LOG = LoggerFactory.getLogger(ClusterAdminRpcService.class);
private final DistributedDataStoreInterface configDataStore;
private final DistributedDataStoreInterface operDataStore;
- private final BindingNormalizedNodeSerializer serializer;
private final Timeout makeLeaderLocalTimeout;
private final DataCenterControl dataCenterControl;
public ClusterAdminRpcService(final DistributedDataStoreInterface configDataStore,
final DistributedDataStoreInterface operDataStore,
- final BindingNormalizedNodeSerializer serializer,
final DataCenterControl dataCenterControl) {
this.configDataStore = configDataStore;
this.operDataStore = operDataStore;
- this.serializer = serializer;
makeLeaderLocalTimeout =
new Timeout(configDataStore.getActorUtils().getDatastoreContext()
this.dataCenterControl = dataCenterControl;
}
- @Override
- public ListenableFuture<RpcResult<AddShardReplicaOutput>> addShardReplica(final AddShardReplicaInput input) {
+ Registration registerWith(final RpcProviderService rpcProviderService) {
+ return rpcProviderService.registerRpcImplementations(
+ (org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.cluster.admin.rev151013
+ .AddShardReplica) this::addShardReplica,
+ (org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.cluster.admin.rev151013
+ .RemoveShardReplica) this::removeShardReplica,
+ (LocateShard) this::locateShard,
+ (org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.cluster.admin.rev151013
+ .MakeLeaderLocal) this::makeLeaderLocal,
+ (AddReplicasForAllShards) this::addReplicasForAllShards,
+ (RemoveAllShardReplicas) this::removeAllShardReplicas,
+ (ChangeMemberVotingStatesForShard) this::changeMemberVotingStatesForShard,
+ (ChangeMemberVotingStatesForAllShards) this::changeMemberVotingStatesForAllShards,
+ (FlipMemberVotingStatesForAllShards) this::flipMemberVotingStatesForAllShards,
+ (org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.cluster.admin.rev151013
+ .GetShardRole) this::getShardRole,
+ (BackupDatastore) this::backupDatastore,
+ (GetKnownClientsForAllShards) this::getKnownClientsForAllShards,
+ (ActivateEosDatacenter) this::activateEosDatacenter,
+ (DeactivateEosDatacenter) this::deactivateEosDatacenter);
+ }
+
+ @VisibleForTesting
+ ListenableFuture<RpcResult<AddShardReplicaOutput>> addShardReplica(final AddShardReplicaInput input) {
final String shardName = input.getShardName();
if (Strings.isNullOrEmpty(shardName)) {
return newFailedRpcResultFuture("A valid shard name must be specified");
LOG.info("Adding replica for shard {}", shardName);
- final SettableFuture<RpcResult<AddShardReplicaOutput>> returnFuture = SettableFuture.create();
- ListenableFuture<Success> future = sendMessageToShardManager(dataStoreType, new AddShardReplica(shardName));
- Futures.addCallback(future, new FutureCallback<Success>() {
- @Override
- public void onSuccess(final Success success) {
- LOG.info("Successfully added replica for shard {}", shardName);
- returnFuture.set(newSuccessfulResult(new AddShardReplicaOutputBuilder().build()));
- }
+ final var returnFuture = SettableFuture.<RpcResult<AddShardReplicaOutput>>create();
+ Futures.addCallback(sendMessageToShardManager(dataStoreType, new AddShardReplica(shardName)),
+ new FutureCallback<Success>() {
+ @Override
+ public void onSuccess(final Success success) {
+ LOG.info("Successfully added replica for shard {}", shardName);
+ returnFuture.set(newSuccessfulResult(new AddShardReplicaOutputBuilder().build()));
+ }
- @Override
- public void onFailure(final Throwable failure) {
- onMessageFailure(String.format("Failed to add replica for shard %s", shardName),
+ @Override
+ public void onFailure(final Throwable failure) {
+ onMessageFailure(String.format("Failed to add replica for shard %s", shardName),
returnFuture, failure);
- }
- }, MoreExecutors.directExecutor());
+ }
+ }, MoreExecutors.directExecutor());
return returnFuture;
}
- @Override
- public ListenableFuture<RpcResult<RemoveShardReplicaOutput>> removeShardReplica(
- final RemoveShardReplicaInput input) {
+ @VisibleForTesting
+ ListenableFuture<RpcResult<RemoveShardReplicaOutput>> removeShardReplica(final RemoveShardReplicaInput input) {
final String shardName = input.getShardName();
if (Strings.isNullOrEmpty(shardName)) {
return newFailedRpcResultFuture("A valid shard name must be specified");
return returnFuture;
}
- @Override
- public ListenableFuture<RpcResult<LocateShardOutput>> locateShard(final LocateShardInput input) {
+ private ListenableFuture<RpcResult<LocateShardOutput>> locateShard(final LocateShardInput input) {
final ActorUtils utils;
switch (input.getDataStoreType()) {
case Config:
return ret;
}
- @Override
- public ListenableFuture<RpcResult<MakeLeaderLocalOutput>> makeLeaderLocal(final MakeLeaderLocalInput input) {
+ @VisibleForTesting
+ ListenableFuture<RpcResult<MakeLeaderLocalOutput>> makeLeaderLocal(final MakeLeaderLocalInput input) {
final String shardName = input.getShardName();
if (Strings.isNullOrEmpty(shardName)) {
return newFailedRpcResultFuture("A valid shard name must be specified");
return future;
}
- @Override
- public ListenableFuture<RpcResult<AddReplicasForAllShardsOutput>> addReplicasForAllShards(
+ @VisibleForTesting ListenableFuture<RpcResult<AddReplicasForAllShardsOutput>> addReplicasForAllShards(
final AddReplicasForAllShardsInput input) {
LOG.info("Adding replicas for all shards");
"Failed to add replica");
}
-
- @Override
- public ListenableFuture<RpcResult<RemoveAllShardReplicasOutput>> removeAllShardReplicas(
+ @VisibleForTesting ListenableFuture<RpcResult<RemoveAllShardReplicasOutput>> removeAllShardReplicas(
final RemoveAllShardReplicasInput input) {
LOG.info("Removing replicas for all shards");
sendMessageToManagerForConfiguredShards(DataStoreType.Config, shardResultData, messageSupplier);
sendMessageToManagerForConfiguredShards(DataStoreType.Operational, shardResultData, messageSupplier);
- return waitForShardResults(shardResultData, shardResults ->
- new RemoveAllShardReplicasOutputBuilder().setShardResult(shardResults).build(),
- " Failed to remove replica");
+ return waitForShardResults(shardResultData,
+ shardResults -> new RemoveAllShardReplicasOutputBuilder().setShardResult(shardResults).build(),
+ " Failed to remove replica");
}
- @Override
- public ListenableFuture<RpcResult<ChangeMemberVotingStatesForShardOutput>> changeMemberVotingStatesForShard(
+ @VisibleForTesting
+ ListenableFuture<RpcResult<ChangeMemberVotingStatesForShardOutput>> changeMemberVotingStatesForShard(
final ChangeMemberVotingStatesForShardInput input) {
final String shardName = input.getShardName();
if (Strings.isNullOrEmpty(shardName)) {
return newFailedRpcResultFuture("A valid shard name must be specified");
}
- DataStoreType dataStoreType = input.getDataStoreType();
+ final var dataStoreType = input.getDataStoreType();
if (dataStoreType == null) {
return newFailedRpcResultFuture("A valid DataStoreType must be specified");
}
- List<MemberVotingState> memberVotingStates = input.getMemberVotingState();
+ final var memberVotingStates = input.getMemberVotingState();
if (memberVotingStates == null || memberVotingStates.isEmpty()) {
return newFailedRpcResultFuture("No member voting state input was specified");
}
- ChangeShardMembersVotingStatus changeVotingStatus = toChangeShardMembersVotingStatus(shardName,
- memberVotingStates);
-
+ final var changeVotingStatus = toChangeShardMembersVotingStatus(shardName, memberVotingStates);
LOG.info("Change member voting states for shard {}: {}", shardName,
changeVotingStatus.getMeberVotingStatusMap());
- final SettableFuture<RpcResult<ChangeMemberVotingStatesForShardOutput>> returnFuture = SettableFuture.create();
- ListenableFuture<Success> future = sendMessageToShardManager(dataStoreType, changeVotingStatus);
- Futures.addCallback(future, new FutureCallback<Success>() {
- @Override
- public void onSuccess(final Success success) {
- LOG.info("Successfully changed member voting states for shard {}", shardName);
- returnFuture.set(newSuccessfulResult(new ChangeMemberVotingStatesForShardOutputBuilder().build()));
- }
+ final var returnFuture = SettableFuture.<RpcResult<ChangeMemberVotingStatesForShardOutput>>create();
+ Futures.addCallback(sendMessageToShardManager(dataStoreType, changeVotingStatus),
+ new FutureCallback<Success>() {
+ @Override
+ public void onSuccess(final Success success) {
+ LOG.info("Successfully changed member voting states for shard {}", shardName);
+ returnFuture.set(newSuccessfulResult(new ChangeMemberVotingStatesForShardOutputBuilder().build()));
+ }
- @Override
- public void onFailure(final Throwable failure) {
- onMessageFailure(String.format("Failed to change member voting states for shard %s", shardName),
+ @Override
+ public void onFailure(final Throwable failure) {
+ onMessageFailure(String.format("Failed to change member voting states for shard %s", shardName),
returnFuture, failure);
- }
- }, MoreExecutors.directExecutor());
+ }
+ }, MoreExecutors.directExecutor());
return returnFuture;
}
- @Override
- public ListenableFuture<RpcResult<ChangeMemberVotingStatesForAllShardsOutput>> changeMemberVotingStatesForAllShards(
+ @VisibleForTesting
+ ListenableFuture<RpcResult<ChangeMemberVotingStatesForAllShardsOutput>> changeMemberVotingStatesForAllShards(
final ChangeMemberVotingStatesForAllShardsInput input) {
List<MemberVotingState> memberVotingStates = input.getMemberVotingState();
if (memberVotingStates == null || memberVotingStates.isEmpty()) {
"Failed to change member voting states");
}
- @Override
- public ListenableFuture<RpcResult<FlipMemberVotingStatesForAllShardsOutput>> flipMemberVotingStatesForAllShards(
+ @VisibleForTesting
+ ListenableFuture<RpcResult<FlipMemberVotingStatesForAllShardsOutput>> flipMemberVotingStatesForAllShards(
final FlipMemberVotingStatesForAllShardsInput input) {
- final List<Entry<ListenableFuture<Success>, ShardResultBuilder>> shardResultData = new ArrayList<>();
- Function<String, Object> messageSupplier = FlipShardMembersVotingStatus::new;
+ final var shardResultData = new ArrayList<Entry<ListenableFuture<Success>, ShardResultBuilder>>();
+ final Function<String, Object> messageSupplier = FlipShardMembersVotingStatus::new;
LOG.info("Flip member voting states for all shards");
"Failed to change member voting states");
}
- @Override
- public ListenableFuture<RpcResult<GetShardRoleOutput>> getShardRole(final GetShardRoleInput input) {
+ private ListenableFuture<RpcResult<GetShardRoleOutput>> getShardRole(final GetShardRoleInput input) {
final String shardName = input.getShardName();
if (Strings.isNullOrEmpty(shardName)) {
return newFailedRpcResultFuture("A valid shard name must be specified");
return returnFuture;
}
- @Override
- public ListenableFuture<RpcResult<BackupDatastoreOutput>> backupDatastore(final BackupDatastoreInput input) {
+ @VisibleForTesting
+ ListenableFuture<RpcResult<BackupDatastoreOutput>> backupDatastore(final BackupDatastoreInput input) {
LOG.debug("backupDatastore: {}", input);
if (Strings.isNullOrEmpty(input.getFilePath())) {
return returnFuture;
}
-
- @Override
- public ListenableFuture<RpcResult<GetKnownClientsForAllShardsOutput>> getKnownClientsForAllShards(
+ private ListenableFuture<RpcResult<GetKnownClientsForAllShardsOutput>> getKnownClientsForAllShards(
final GetKnownClientsForAllShardsInput input) {
final ImmutableMap<ShardIdentifier, ListenableFuture<GetKnownClientsReply>> allShardReplies =
getAllShardLeadersClients();
MoreExecutors.directExecutor());
}
- @Override
- public ListenableFuture<RpcResult<ActivateEosDatacenterOutput>> activateEosDatacenter(
+ private ListenableFuture<RpcResult<ActivateEosDatacenterOutput>> activateEosDatacenter(
final ActivateEosDatacenterInput input) {
LOG.debug("Activating EOS Datacenter");
final SettableFuture<RpcResult<ActivateEosDatacenterOutput>> future = SettableFuture.create();
return future;
}
- @Override
- public ListenableFuture<RpcResult<DeactivateEosDatacenterOutput>> deactivateEosDatacenter(
+ private ListenableFuture<RpcResult<DeactivateEosDatacenterOutput>> deactivateEosDatacenter(
final DeactivateEosDatacenterInput input) {
LOG.debug("Deactivating EOS Datacenter");
final SettableFuture<RpcResult<DeactivateEosDatacenterOutput>> future = SettableFuture.create();
import org.opendaylight.controller.cluster.datastore.DistributedDataStoreInterface;
import org.opendaylight.controller.eos.akka.DataCenterControl;
import org.opendaylight.mdsal.binding.api.RpcProviderService;
-import org.opendaylight.mdsal.binding.dom.codec.api.BindingNormalizedNodeSerializer;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.cluster.admin.rev151013.ClusterAdminService;
import org.opendaylight.yangtools.concepts.Registration;
import org.osgi.service.component.annotations.Activate;
import org.osgi.service.component.annotations.Component;
public OSGiClusterAdmin(
@Reference(target = "(type=distributed-config)") final DistributedDataStoreInterface configDatastore,
@Reference(target = "(type=distributed-operational)") final DistributedDataStoreInterface operDatastore,
- @Reference final BindingNormalizedNodeSerializer serializer,
@Reference final RpcProviderService rpcProviderService,
@Reference final DataCenterControl dataCenterControls,
@Reference final DataCenterControl dataCenterControl) {
- reg = rpcProviderService.registerRpcImplementation(ClusterAdminService.class,
- new ClusterAdminRpcService(configDatastore, operDatastore, serializer, dataCenterControl));
+ reg = new ClusterAdminRpcService(configDatastore, operDatastore, dataCenterControl)
+ .registerWith(rpcProviderService);
LOG.info("Cluster Admin services started");
}
import static java.lang.Boolean.FALSE;
import static java.lang.Boolean.TRUE;
+import static java.util.Objects.requireNonNull;
import static org.hamcrest.CoreMatchers.anyOf;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.MatcherAssert.assertThat;
import akka.actor.PoisonPill;
import akka.actor.Status.Success;
import akka.cluster.Cluster;
-import com.google.common.collect.ImmutableMap;
-import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import java.io.File;
-import java.io.FileInputStream;
-import java.util.AbstractMap.SimpleEntry;
+import java.nio.file.Files;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
-import java.util.Map.Entry;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.junit.Before;
import org.junit.Test;
import org.opendaylight.controller.cluster.access.concepts.MemberName;
+import org.opendaylight.controller.cluster.databroker.ClientBackedDataStore;
import org.opendaylight.controller.cluster.datastore.AbstractDataStore;
import org.opendaylight.controller.cluster.datastore.DatastoreContext;
import org.opendaylight.controller.cluster.datastore.MemberNode;
import org.opendaylight.controller.cluster.raft.utils.InMemoryJournal;
import org.opendaylight.controller.cluster.raft.utils.InMemorySnapshotStore;
import org.opendaylight.controller.md.cluster.datastore.model.CarsModel;
-import org.opendaylight.mdsal.dom.spi.store.DOMStoreThreePhaseCommitCohort;
-import org.opendaylight.mdsal.dom.spi.store.DOMStoreWriteTransaction;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.cluster.admin.rev151013.AddReplicasForAllShardsInputBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.cluster.admin.rev151013.AddReplicasForAllShardsOutput;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.cluster.admin.rev151013.AddShardReplicaInputBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.cluster.admin.rev151013.AddShardReplicaOutput;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.cluster.admin.rev151013.BackupDatastoreInputBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.cluster.admin.rev151013.BackupDatastoreOutput;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.cluster.admin.rev151013.ChangeMemberVotingStatesForAllShardsInputBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.cluster.admin.rev151013.ChangeMemberVotingStatesForAllShardsOutput;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.cluster.admin.rev151013.ChangeMemberVotingStatesForShardInputBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.cluster.admin.rev151013.ChangeMemberVotingStatesForShardOutput;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.cluster.admin.rev151013.DataStoreType;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.cluster.admin.rev151013.FlipMemberVotingStatesForAllShardsInputBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.cluster.admin.rev151013.FlipMemberVotingStatesForAllShardsOutput;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.cluster.admin.rev151013.MakeLeaderLocalInputBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.cluster.admin.rev151013.MakeLeaderLocalOutput;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.cluster.admin.rev151013.RemoveAllShardReplicasInputBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.cluster.admin.rev151013.RemoveAllShardReplicasOutput;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.cluster.admin.rev151013.RemoveShardReplicaInputBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.cluster.admin.rev151013.RemoveShardReplicaOutput;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.cluster.admin.rev151013.member.voting.states.input.MemberVotingStateBuilder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.cluster.admin.rev151013.shard.result.output.ShardResult;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.cluster.admin.rev151013.shard.result.output.ShardResultBuilder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.cluster.admin.rev151013.shard.result.output.ShardResultKey;
-import org.opendaylight.yangtools.yang.common.RpcError;
import org.opendaylight.yangtools.yang.common.RpcResult;
import org.opendaylight.yangtools.yang.common.XMLNamespace;
-import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
+import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
/**
* Unit tests for ClusterAdminRpcService.
* @author Thomas Pantelis
*/
public class ClusterAdminRpcServiceTest {
+ record ExpState(String name, boolean voting) {
+ ExpState {
+ requireNonNull(name);
+ }
+ }
+
private static final MemberName MEMBER_1 = MemberName.forName("member-1");
private static final MemberName MEMBER_2 = MemberName.forName("member-2");
private static final MemberName MEMBER_3 = MemberName.forName("member-3");
@After
public void tearDown() {
- for (MemberNode m : Lists.reverse(memberNodes)) {
- m.cleanup();
+ for (var member : Lists.reverse(memberNodes)) {
+ member.cleanup();
}
memberNodes.clear();
}
@Test
public void testBackupDatastore() throws Exception {
- MemberNode node = MemberNode.builder(memberNodes).akkaConfig("Member1")
- .moduleShardsConfig("module-shards-member1.conf").waitForShardLeader("cars", "people")
- .testName("testBackupDatastore").build();
+ final var node = MemberNode.builder(memberNodes)
+ .akkaConfig("Member1")
+ .moduleShardsConfig("module-shards-member1.conf")
+ .waitForShardLeader("cars", "people")
+ .testName("testBackupDatastore")
+ .build();
- String fileName = "target/testBackupDatastore";
- new File(fileName).delete();
+ final var fileName = "target/testBackupDatastore";
+ final var file = new File(fileName);
+ file.delete();
- final ClusterAdminRpcService service = new ClusterAdminRpcService(node.configDataStore(), node.operDataStore(),
- null, null);
+ final var service = new ClusterAdminRpcService(node.configDataStore(), node.operDataStore(), null);
- RpcResult<BackupDatastoreOutput> rpcResult = service .backupDatastore(new BackupDatastoreInputBuilder()
- .setFilePath(fileName).build()).get(5, TimeUnit.SECONDS);
+ var rpcResult = service.backupDatastore(new BackupDatastoreInputBuilder().setFilePath(fileName).build())
+ .get(5, TimeUnit.SECONDS);
verifySuccessfulRpcResult(rpcResult);
- try (FileInputStream fis = new FileInputStream(fileName)) {
- List<DatastoreSnapshot> snapshots = SerializationUtils.deserialize(fis);
+ try (var fis = Files.newInputStream(file.toPath())) {
+ final List<DatastoreSnapshot> snapshots = SerializationUtils.deserialize(fis);
assertEquals("DatastoreSnapshot size", 2, snapshots.size());
- ImmutableMap<String, DatastoreSnapshot> map = ImmutableMap.of(snapshots.get(0).getType(), snapshots.get(0),
- snapshots.get(1).getType(), snapshots.get(1));
+ final var map = Map.of(
+ snapshots.get(0).getType(), snapshots.get(0),
+ snapshots.get(1).getType(), snapshots.get(1));
verifyDatastoreSnapshot(node.configDataStore().getActorUtils().getDataStoreName(),
map.get(node.configDataStore().getActorUtils().getDataStoreName()), "cars", "people");
} finally {
node.configDataStore().getActorUtils().getShardManager().tell(node.datastoreContextBuilder()
.shardInitializationTimeout(200, TimeUnit.MILLISECONDS).build(), ActorRef.noSender());
- ActorRef carsShardActor = node.configDataStore().getActorUtils().findLocalShard("cars").get();
+ final var carsShardActor = node.configDataStore().getActorUtils().findLocalShard("cars").orElseThrow();
node.kit().watch(carsShardActor);
carsShardActor.tell(PoisonPill.getInstance(), ActorRef.noSender());
node.kit().expectTerminated(carsShardActor);
private static void verifyDatastoreSnapshot(final String type, final DatastoreSnapshot datastoreSnapshot,
final String... expShardNames) {
assertNotNull("Missing DatastoreSnapshot for type " + type, datastoreSnapshot);
- Set<String> shardNames = new HashSet<>();
- for (DatastoreSnapshot.ShardSnapshot s: datastoreSnapshot.getShardSnapshots()) {
- shardNames.add(s.getName());
+ var shardNames = new HashSet<String>();
+ for (var snapshot : datastoreSnapshot.getShardSnapshots()) {
+ shardNames.add(snapshot.getName());
}
assertEquals("DatastoreSnapshot shard names", Set.of(expShardNames), shardNames);
String name = "testGetPrefixShardRole";
String moduleShardsConfig = "module-shards-default-member-1.conf";
- final MemberNode member1 = MemberNode.builder(memberNodes).akkaConfig("Member1").testName(name)
+ final var member1 = MemberNode.builder(memberNodes).akkaConfig("Member1").testName(name)
.moduleShardsConfig(moduleShardsConfig).build();
member1.kit().waitUntilLeader(member1.configDataStore().getActorUtils(), "default");
String name = "testModuleShardLeaderMovement";
String moduleShardsConfig = "module-shards-member1.conf";
- final MemberNode member1 = MemberNode.builder(memberNodes).akkaConfig("Member1").testName(name)
+ final var member1 = MemberNode.builder(memberNodes).akkaConfig("Member1").testName(name)
.waitForShardLeader("cars").moduleShardsConfig(moduleShardsConfig).build();
- final MemberNode replicaNode2 = MemberNode.builder(memberNodes).akkaConfig("Member2").testName(name)
+ final var replicaNode2 = MemberNode.builder(memberNodes).akkaConfig("Member2").testName(name)
.moduleShardsConfig(moduleShardsConfig).build();
- final MemberNode replicaNode3 = MemberNode.builder(memberNodes).akkaConfig("Member3").testName(name)
+ final var replicaNode3 = MemberNode.builder(memberNodes).akkaConfig("Member3").testName(name)
.moduleShardsConfig(moduleShardsConfig).build();
member1.waitForMembersUp("member-2", "member-3");
public void testAddShardReplica() throws Exception {
String name = "testAddShardReplica";
String moduleShardsConfig = "module-shards-cars-member-1.conf";
- MemberNode leaderNode1 = MemberNode.builder(memberNodes).akkaConfig("Member1").testName(name)
+ final var leaderNode1 = MemberNode.builder(memberNodes).akkaConfig("Member1").testName(name)
.moduleShardsConfig(moduleShardsConfig).waitForShardLeader("cars").build();
- MemberNode newReplicaNode2 = MemberNode.builder(memberNodes).akkaConfig("Member2").testName(name)
+ final var newReplicaNode2 = MemberNode.builder(memberNodes).akkaConfig("Member2").testName(name)
.moduleShardsConfig(moduleShardsConfig).build();
leaderNode1.waitForMembersUp("member-2");
doAddShardReplica(newReplicaNode2, "cars", "member-1");
- MemberNode newReplicaNode3 = MemberNode.builder(memberNodes).akkaConfig("Member3").testName(name)
+ var newReplicaNode3 = MemberNode.builder(memberNodes).akkaConfig("Member3").testName(name)
.moduleShardsConfig(moduleShardsConfig).build();
leaderNode1.waitForMembersUp("member-3");
verifyRaftPeersPresent(newReplicaNode2.operDataStore(), "cars", "member-1", "member-3");
// Write data to member-2's config datastore and read/verify via member-3
- final NormalizedNode configCarsNode = writeCarsNodeAndVerify(newReplicaNode2.configDataStore(),
+ final var configCarsNode = writeCarsNodeAndVerify(newReplicaNode2.configDataStore(),
newReplicaNode3.configDataStore());
// Write data to member-3's oper datastore and read/verify via member-2
writeCarsNodeAndVerify(newReplicaNode3.operDataStore(), newReplicaNode2.operDataStore());
// Verify all data has been replicated. We expect 4 log entries and thus last applied index of 3 -
- // 2 ServerConfigurationPayload entries, the transaction payload entry plus a purge payload.
+ // 2 ServerConfigurationPayload entries, the transaction payload entry plus a purge payload.
RaftStateVerifier verifier = raftState -> {
- assertEquals("Commit index", 4, raftState.getCommitIndex());
- assertEquals("Last applied index", 4, raftState.getLastApplied());
+ assertEquals("Commit index", 3, raftState.getCommitIndex());
+ assertEquals("Last applied index", 3, raftState.getLastApplied());
};
verifyRaftState(leaderNode1.configDataStore(), "cars", verifier);
@Test
public void testAddShardReplicaFailures() throws Exception {
String name = "testAddShardReplicaFailures";
- MemberNode memberNode = MemberNode.builder(memberNodes).akkaConfig("Member1").testName(name)
+ final var memberNode = MemberNode.builder(memberNodes).akkaConfig("Member1").testName(name)
.moduleShardsConfig("module-shards-cars-member-1.conf").build();
- final ClusterAdminRpcService service = new ClusterAdminRpcService(memberNode.configDataStore(),
- memberNode.operDataStore(), null, null);
+ final var service = new ClusterAdminRpcService(memberNode.configDataStore(), memberNode.operDataStore(), null);
- RpcResult<AddShardReplicaOutput> rpcResult = service.addShardReplica(new AddShardReplicaInputBuilder()
- .setDataStoreType(DataStoreType.Config).build()).get(10, TimeUnit.SECONDS);
+ var rpcResult = service.addShardReplica(new AddShardReplicaInputBuilder()
+ .setDataStoreType(DataStoreType.Config)
+ .build())
+ .get(10, TimeUnit.SECONDS);
verifyFailedRpcResult(rpcResult);
- rpcResult = service.addShardReplica(new AddShardReplicaInputBuilder().setShardName("cars")
- .build()).get(10, TimeUnit.SECONDS);
+ rpcResult = service.addShardReplica(new AddShardReplicaInputBuilder().setShardName("cars").build())
+ .get(10, TimeUnit.SECONDS);
verifyFailedRpcResult(rpcResult);
rpcResult = service.addShardReplica(new AddShardReplicaInputBuilder().setShardName("people")
- .setDataStoreType(DataStoreType.Config).build()).get(10, TimeUnit.SECONDS);
+ .setDataStoreType(DataStoreType.Config)
+ .build())
+ .get(10, TimeUnit.SECONDS);
verifyFailedRpcResult(rpcResult);
}
- private static NormalizedNode writeCarsNodeAndVerify(final AbstractDataStore writeToStore,
+ private static ContainerNode writeCarsNodeAndVerify(final AbstractDataStore writeToStore,
final AbstractDataStore readFromStore) throws Exception {
- DOMStoreWriteTransaction writeTx = writeToStore.newWriteOnlyTransaction();
- NormalizedNode carsNode = CarsModel.create();
+ final var writeTx = writeToStore.newWriteOnlyTransaction();
+ final var carsNode = CarsModel.create();
writeTx.write(CarsModel.BASE_PATH, carsNode);
- DOMStoreThreePhaseCommitCohort cohort = writeTx.ready();
- Boolean canCommit = cohort.canCommit().get(7, TimeUnit.SECONDS);
- assertEquals("canCommit", TRUE, canCommit);
+ final var cohort = writeTx.ready();
+ assertEquals("canCommit", TRUE, cohort.canCommit().get(7, TimeUnit.SECONDS));
cohort.preCommit().get(5, TimeUnit.SECONDS);
cohort.commit().get(5, TimeUnit.SECONDS);
}
private static void readCarsNodeAndVerify(final AbstractDataStore readFromStore,
- final NormalizedNode expCarsNode) throws Exception {
- Optional<NormalizedNode> optional = readFromStore.newReadOnlyTransaction().read(CarsModel.BASE_PATH)
- .get(15, TimeUnit.SECONDS);
- assertTrue("isPresent", optional.isPresent());
- assertEquals("Data node", expCarsNode, optional.get());
+ final ContainerNode expCarsNode) throws Exception {
+ assertEquals(Optional.of(expCarsNode),
+ readFromStore.newReadOnlyTransaction().read(CarsModel.BASE_PATH).get(15, TimeUnit.SECONDS));
}
private static void doAddShardReplica(final MemberNode memberNode, final String shardName,
final String... peerMemberNames) throws Exception {
memberNode.waitForMembersUp(peerMemberNames);
- final ClusterAdminRpcService service = new ClusterAdminRpcService(memberNode.configDataStore(),
- memberNode.operDataStore(), null, null);
+ final var service = new ClusterAdminRpcService(memberNode.configDataStore(), memberNode.operDataStore(), null);
- RpcResult<AddShardReplicaOutput> rpcResult = service.addShardReplica(new AddShardReplicaInputBuilder()
- .setShardName(shardName).setDataStoreType(DataStoreType.Config).build()).get(10, TimeUnit.SECONDS);
+ var rpcResult = service.addShardReplica(new AddShardReplicaInputBuilder()
+ .setShardName(shardName)
+ .setDataStoreType(DataStoreType.Config)
+ .build()).get(10, TimeUnit.SECONDS);
verifySuccessfulRpcResult(rpcResult);
verifyRaftPeersPresent(memberNode.configDataStore(), shardName, peerMemberNames);
- Optional<ActorRef> optional = memberNode.operDataStore().getActorUtils().findLocalShard(shardName);
- assertFalse("Oper shard present", optional.isPresent());
+ assertEquals(Optional.empty(), memberNode.operDataStore().getActorUtils().findLocalShard(shardName));
- rpcResult = service.addShardReplica(new AddShardReplicaInputBuilder().setShardName(shardName)
- .setDataStoreType(DataStoreType.Operational).build()).get(10, TimeUnit.SECONDS);
+ rpcResult = service.addShardReplica(new AddShardReplicaInputBuilder()
+ .setShardName(shardName)
+ .setDataStoreType(DataStoreType.Operational)
+ .build()).get(10, TimeUnit.SECONDS);
verifySuccessfulRpcResult(rpcResult);
verifyRaftPeersPresent(memberNode.operDataStore(), shardName, peerMemberNames);
private static void doMakeShardLeaderLocal(final MemberNode memberNode, final String shardName,
final String newLeader) throws Exception {
- final ClusterAdminRpcService service = new ClusterAdminRpcService(memberNode.configDataStore(),
- memberNode.operDataStore(), null, null);
+ final var service = new ClusterAdminRpcService(memberNode.configDataStore(), memberNode.operDataStore(), null);
- final RpcResult<MakeLeaderLocalOutput> rpcResult = service.makeLeaderLocal(new MakeLeaderLocalInputBuilder()
- .setDataStoreType(DataStoreType.Config).setShardName(shardName).build())
- .get(10, TimeUnit.SECONDS);
+ final var rpcResult = service.makeLeaderLocal(new MakeLeaderLocalInputBuilder()
+ .setDataStoreType(DataStoreType.Config)
+ .setShardName(shardName)
+ .build()).get(10, TimeUnit.SECONDS);
verifySuccessfulRpcResult(rpcResult);
private static <T> T verifySuccessfulRpcResult(final RpcResult<T> rpcResult) {
if (!rpcResult.isSuccessful()) {
- if (rpcResult.getErrors().size() > 0) {
- RpcError error = Iterables.getFirst(rpcResult.getErrors(), null);
+ final var errors = rpcResult.getErrors();
+ if (errors.size() > 0) {
+ final var error = errors.get(0);
throw new AssertionError("Rpc failed with error: " + error, error.getCause());
}
private static void verifyFailedRpcResult(final RpcResult<?> rpcResult) {
assertFalse("RpcResult", rpcResult.isSuccessful());
- assertEquals("RpcResult errors size", 1, rpcResult.getErrors().size());
- RpcError error = Iterables.getFirst(rpcResult.getErrors(), null);
+ final var errors = rpcResult.getErrors();
+ assertEquals("RpcResult errors size", 1, errors.size());
+ final var error = errors.get(0);
assertNotNull("RpcResult error message null", error.getMessage());
}
public void testRemoveShardReplica() throws Exception {
String name = "testRemoveShardReplica";
String moduleShardsConfig = "module-shards-member1-and-2-and-3.conf";
- final MemberNode leaderNode1 = MemberNode.builder(memberNodes).akkaConfig("Member1").testName(name)
+ final var leaderNode1 = MemberNode.builder(memberNodes).akkaConfig("Member1").testName(name)
.moduleShardsConfig(moduleShardsConfig).datastoreContextBuilder(
DatastoreContext.newBuilder().shardHeartbeatIntervalInMillis(300).shardElectionTimeoutFactor(1))
.build();
- final MemberNode replicaNode2 = MemberNode.builder(memberNodes).akkaConfig("Member2").testName(name)
+ final var replicaNode2 = MemberNode.builder(memberNodes).akkaConfig("Member2").testName(name)
.moduleShardsConfig(moduleShardsConfig).build();
- final MemberNode replicaNode3 = MemberNode.builder(memberNodes).akkaConfig("Member3").testName(name)
+ final var replicaNode3 = MemberNode.builder(memberNodes).akkaConfig("Member3").testName(name)
.moduleShardsConfig(moduleShardsConfig).build();
leaderNode1.configDataStore().waitTillReady();
// Invoke RPC service on member-3 to remove it's local shard
- final ClusterAdminRpcService service3 = new ClusterAdminRpcService(replicaNode3.configDataStore(),
- replicaNode3.operDataStore(), null, null);
+ final var service3 = new ClusterAdminRpcService(replicaNode3.configDataStore(), replicaNode3.operDataStore(),
+ null);
- RpcResult<RemoveShardReplicaOutput> rpcResult = service3.removeShardReplica(new RemoveShardReplicaInputBuilder()
- .setShardName("cars").setMemberName("member-3").setDataStoreType(DataStoreType.Config).build())
- .get(10, TimeUnit.SECONDS);
+ var rpcResult = service3.removeShardReplica(new RemoveShardReplicaInputBuilder()
+ .setShardName("cars").setMemberName("member-3")
+ .setDataStoreType(DataStoreType.Config)
+ .build()).get(10, TimeUnit.SECONDS);
verifySuccessfulRpcResult(rpcResult);
verifyRaftPeersPresent(leaderNode1.configDataStore(), "cars", "member-2");
Cluster.get(leaderNode1.kit().getSystem()).down(Cluster.get(replicaNode2.kit().getSystem()).selfAddress());
replicaNode2.cleanup();
- MemberNode newPeplicaNode2 = MemberNode.builder(memberNodes).akkaConfig("Member2").testName(name)
+ final var newPeplicaNode2 = MemberNode.builder(memberNodes).akkaConfig("Member2").testName(name)
.moduleShardsConfig(moduleShardsConfig).build();
newPeplicaNode2.configDataStore().waitTillReady();
// Invoke RPC service on member-1 to remove member-2
- final ClusterAdminRpcService service1 = new ClusterAdminRpcService(leaderNode1.configDataStore(),
- leaderNode1.operDataStore(), null, null);
+ final var service1 = new ClusterAdminRpcService(leaderNode1.configDataStore(), leaderNode1.operDataStore(),
+ null);
- rpcResult = service1.removeShardReplica(new RemoveShardReplicaInputBuilder().setShardName("cars")
- .setMemberName("member-2").setDataStoreType(DataStoreType.Config).build()).get(10, TimeUnit.SECONDS);
+ rpcResult = service1.removeShardReplica(new RemoveShardReplicaInputBuilder()
+ .setShardName("cars")
+ .setMemberName("member-2")
+ .setDataStoreType(DataStoreType.Config)
+ .build()).get(10, TimeUnit.SECONDS);
verifySuccessfulRpcResult(rpcResult);
verifyRaftPeersPresent(leaderNode1.configDataStore(), "cars");
public void testRemoveShardLeaderReplica() throws Exception {
String name = "testRemoveShardLeaderReplica";
String moduleShardsConfig = "module-shards-member1-and-2-and-3.conf";
- final MemberNode leaderNode1 = MemberNode.builder(memberNodes).akkaConfig("Member1").testName(name)
+ final var leaderNode1 = MemberNode.builder(memberNodes).akkaConfig("Member1").testName(name)
.moduleShardsConfig(moduleShardsConfig).datastoreContextBuilder(
DatastoreContext.newBuilder().shardHeartbeatIntervalInMillis(300).shardElectionTimeoutFactor(1))
.build();
- final MemberNode replicaNode2 = MemberNode.builder(memberNodes).akkaConfig("Member2").testName(name)
+ final var replicaNode2 = MemberNode.builder(memberNodes).akkaConfig("Member2").testName(name)
.moduleShardsConfig(moduleShardsConfig).build();
- final MemberNode replicaNode3 = MemberNode.builder(memberNodes).akkaConfig("Member3").testName(name)
+ final var replicaNode3 = MemberNode.builder(memberNodes).akkaConfig("Member3").testName(name)
.moduleShardsConfig(moduleShardsConfig).build();
leaderNode1.configDataStore().waitTillReady();
// Invoke RPC service on leader member-1 to remove it's local shard
- final ClusterAdminRpcService service1 = new ClusterAdminRpcService(leaderNode1.configDataStore(),
- leaderNode1.operDataStore(), null, null);
+ final var service1 = new ClusterAdminRpcService(leaderNode1.configDataStore(), leaderNode1.operDataStore(),
+ null);
- RpcResult<RemoveShardReplicaOutput> rpcResult = service1.removeShardReplica(new RemoveShardReplicaInputBuilder()
- .setShardName("cars").setMemberName("member-1").setDataStoreType(DataStoreType.Config).build())
- .get(10, TimeUnit.SECONDS);
+ final var rpcResult = service1.removeShardReplica(new RemoveShardReplicaInputBuilder()
+ .setShardName("cars")
+ .setMemberName("member-1")
+ .setDataStoreType(DataStoreType.Config)
+ .build()).get(10, TimeUnit.SECONDS);
verifySuccessfulRpcResult(rpcResult);
verifyRaftState(replicaNode2.configDataStore(), "cars", raftState ->
public void testAddReplicasForAllShards() throws Exception {
String name = "testAddReplicasForAllShards";
String moduleShardsConfig = "module-shards-member1.conf";
- MemberNode leaderNode1 = MemberNode.builder(memberNodes).akkaConfig("Member1").testName(name)
+ final var leaderNode1 = MemberNode.builder(memberNodes).akkaConfig("Member1").testName(name)
.moduleShardsConfig(moduleShardsConfig).waitForShardLeader("cars", "people").build();
- ModuleShardConfiguration petsModuleConfig = new ModuleShardConfiguration(
- XMLNamespace.of("pets-ns"), "pets-module", "pets", null, List.of(MEMBER_1));
+ final var petsModuleConfig = new ModuleShardConfiguration(XMLNamespace.of("pets-ns"), "pets-module", "pets",
+ null, List.of(MEMBER_1));
leaderNode1.configDataStore().getActorUtils().getShardManager().tell(
new CreateShard(petsModuleConfig, Shard.builder(), null), leaderNode1.kit().getRef());
leaderNode1.kit().expectMsgClass(Success.class);
leaderNode1.kit().waitUntilLeader(leaderNode1.configDataStore().getActorUtils(), "pets");
- MemberNode newReplicaNode2 = MemberNode.builder(memberNodes).akkaConfig("Member2").testName(name)
+ final var newReplicaNode2 = MemberNode.builder(memberNodes).akkaConfig("Member2").testName(name)
.moduleShardsConfig(moduleShardsConfig).build();
leaderNode1.waitForMembersUp("member-2");
new CreateShard(petsModuleConfig, Shard.builder(), null), newReplicaNode2.kit().getRef());
newReplicaNode2.kit().expectMsgClass(Success.class);
- newReplicaNode2.operDataStore().getActorUtils().getShardManager().tell(
- new CreateShard(new ModuleShardConfiguration(XMLNamespace.of("no-leader-ns"), "no-leader-module",
- "no-leader", null, List.of(MEMBER_1)),
- Shard.builder(), null),
- newReplicaNode2.kit().getRef());
+ newReplicaNode2.operDataStore().getActorUtils().getShardManager()
+ .tell(new CreateShard(new ModuleShardConfiguration(XMLNamespace.of("no-leader-ns"), "no-leader-module",
+ "no-leader", null, List.of(MEMBER_1)),
+ Shard.builder(), null), newReplicaNode2.kit().getRef());
newReplicaNode2.kit().expectMsgClass(Success.class);
- final ClusterAdminRpcService service = new ClusterAdminRpcService(newReplicaNode2.configDataStore(),
- newReplicaNode2.operDataStore(), null, null);
+ final var service = new ClusterAdminRpcService(newReplicaNode2.configDataStore(),
+ newReplicaNode2.operDataStore(), null);
- RpcResult<AddReplicasForAllShardsOutput> rpcResult = service.addReplicasForAllShards(
- new AddReplicasForAllShardsInputBuilder().build()).get(10, TimeUnit.SECONDS);
- AddReplicasForAllShardsOutput result = verifySuccessfulRpcResult(rpcResult);
+ var rpcResult = service.addReplicasForAllShards(new AddReplicasForAllShardsInputBuilder().build())
+ .get(10, TimeUnit.SECONDS);
+ final var result = verifySuccessfulRpcResult(rpcResult);
verifyShardResults(result.getShardResult(), successShardResult("cars", DataStoreType.Config),
successShardResult("people", DataStoreType.Config),
successShardResult("pets", DataStoreType.Config),
public void testRemoveAllShardReplicas() throws Exception {
String name = "testRemoveAllShardReplicas";
String moduleShardsConfig = "module-shards-member1-and-2-and-3.conf";
- final MemberNode leaderNode1 = MemberNode.builder(memberNodes).akkaConfig("Member1").testName(name)
+ final var leaderNode1 = MemberNode.builder(memberNodes).akkaConfig("Member1").testName(name)
.moduleShardsConfig(moduleShardsConfig).datastoreContextBuilder(
DatastoreContext.newBuilder().shardHeartbeatIntervalInMillis(300).shardElectionTimeoutFactor(1))
.build();
- final MemberNode replicaNode2 = MemberNode.builder(memberNodes).akkaConfig("Member2").testName(name)
+ final var replicaNode2 = MemberNode.builder(memberNodes).akkaConfig("Member2").testName(name)
.moduleShardsConfig(moduleShardsConfig).build();
- final MemberNode replicaNode3 = MemberNode.builder(memberNodes).akkaConfig("Member3").testName(name)
+ final var replicaNode3 = MemberNode.builder(memberNodes).akkaConfig("Member3").testName(name)
.moduleShardsConfig(moduleShardsConfig).build();
leaderNode1.configDataStore().waitTillReady();
verifyRaftPeersPresent(replicaNode2.configDataStore(), "cars", "member-1", "member-3");
verifyRaftPeersPresent(replicaNode3.configDataStore(), "cars", "member-1", "member-2");
- ModuleShardConfiguration petsModuleConfig = new ModuleShardConfiguration(XMLNamespace.of("pets-ns"),
- "pets-module", "pets", null, List.of(MEMBER_1, MEMBER_2, MEMBER_3));
+ final var petsModuleConfig = new ModuleShardConfiguration(XMLNamespace.of("pets-ns"), "pets-module", "pets",
+ null, List.of(MEMBER_1, MEMBER_2, MEMBER_3));
leaderNode1.configDataStore().getActorUtils().getShardManager().tell(
new CreateShard(petsModuleConfig, Shard.builder(), null), leaderNode1.kit().getRef());
leaderNode1.kit().expectMsgClass(Success.class);
verifyRaftPeersPresent(replicaNode2.configDataStore(), "pets", "member-1", "member-3");
verifyRaftPeersPresent(replicaNode3.configDataStore(), "pets", "member-1", "member-2");
- final ClusterAdminRpcService service3 = new ClusterAdminRpcService(replicaNode3.configDataStore(),
- replicaNode3.operDataStore(), null, null);
+ final var service3 = new ClusterAdminRpcService(replicaNode3.configDataStore(), replicaNode3.operDataStore(),
+ null);
- RpcResult<RemoveAllShardReplicasOutput> rpcResult = service3.removeAllShardReplicas(
- new RemoveAllShardReplicasInputBuilder().setMemberName("member-3").build()).get(10, TimeUnit.SECONDS);
- RemoveAllShardReplicasOutput result = verifySuccessfulRpcResult(rpcResult);
+ var rpcResult = service3.removeAllShardReplicas(
+ new RemoveAllShardReplicasInputBuilder().setMemberName("member-3").build())
+ .get(10, TimeUnit.SECONDS);
+ final var result = verifySuccessfulRpcResult(rpcResult);
verifyShardResults(result.getShardResult(), successShardResult("cars", DataStoreType.Config),
successShardResult("people", DataStoreType.Config),
successShardResult("pets", DataStoreType.Config),
public void testChangeMemberVotingStatesForShard() throws Exception {
String name = "testChangeMemberVotingStatusForShard";
String moduleShardsConfig = "module-shards-member1-and-2-and-3.conf";
- final MemberNode leaderNode1 = MemberNode.builder(memberNodes).akkaConfig("Member1").testName(name)
+ final var leaderNode1 = MemberNode.builder(memberNodes).akkaConfig("Member1").testName(name)
.moduleShardsConfig(moduleShardsConfig).datastoreContextBuilder(
DatastoreContext.newBuilder().shardHeartbeatIntervalInMillis(300).shardElectionTimeoutFactor(1))
.build();
- final MemberNode replicaNode2 = MemberNode.builder(memberNodes).akkaConfig("Member2").testName(name)
+ final var replicaNode2 = MemberNode.builder(memberNodes).akkaConfig("Member2").testName(name)
.moduleShardsConfig(moduleShardsConfig).build();
- final MemberNode replicaNode3 = MemberNode.builder(memberNodes).akkaConfig("Member3").testName(name)
+ final var replicaNode3 = MemberNode.builder(memberNodes).akkaConfig("Member3").testName(name)
.moduleShardsConfig(moduleShardsConfig).build();
leaderNode1.configDataStore().waitTillReady();
// Invoke RPC service on member-3 to change voting status
- final ClusterAdminRpcService service3 = new ClusterAdminRpcService(replicaNode3.configDataStore(),
- replicaNode3.operDataStore(), null, null);
+ final var service3 = new ClusterAdminRpcService(replicaNode3.configDataStore(), replicaNode3.operDataStore(),
+ null);
- RpcResult<ChangeMemberVotingStatesForShardOutput> rpcResult = service3
- .changeMemberVotingStatesForShard(new ChangeMemberVotingStatesForShardInputBuilder()
- .setShardName("cars").setDataStoreType(DataStoreType.Config)
- .setMemberVotingState(List.of(
- new MemberVotingStateBuilder().setMemberName("member-2").setVoting(FALSE).build(),
- new MemberVotingStateBuilder().setMemberName("member-3").setVoting(FALSE).build()))
- .build())
- .get(10, TimeUnit.SECONDS);
+ var rpcResult = service3.changeMemberVotingStatesForShard(new ChangeMemberVotingStatesForShardInputBuilder()
+ .setShardName("cars").setDataStoreType(DataStoreType.Config)
+ .setMemberVotingState(List.of(
+ new MemberVotingStateBuilder().setMemberName("member-2").setVoting(FALSE).build(),
+ new MemberVotingStateBuilder().setMemberName("member-3").setVoting(FALSE).build()))
+ .build())
+ .get(10, TimeUnit.SECONDS);
verifySuccessfulRpcResult(rpcResult);
- verifyVotingStates(leaderNode1.configDataStore(), "cars", new SimpleEntry<>("member-1", TRUE),
- new SimpleEntry<>("member-2", FALSE), new SimpleEntry<>("member-3", FALSE));
- verifyVotingStates(replicaNode2.configDataStore(), "cars", new SimpleEntry<>("member-1", TRUE),
- new SimpleEntry<>("member-2", FALSE), new SimpleEntry<>("member-3", FALSE));
- verifyVotingStates(replicaNode3.configDataStore(), "cars", new SimpleEntry<>("member-1", TRUE),
- new SimpleEntry<>("member-2", FALSE), new SimpleEntry<>("member-3", FALSE));
+ verifyVotingStates(leaderNode1.configDataStore(), "cars",
+ new ExpState("member-1", true), new ExpState("member-2", false), new ExpState("member-3", false));
+ verifyVotingStates(replicaNode2.configDataStore(), "cars",
+ new ExpState("member-1", true), new ExpState("member-2", false), new ExpState("member-3", false));
+ verifyVotingStates(replicaNode3.configDataStore(), "cars",
+ new ExpState("member-1", true), new ExpState("member-2", false), new ExpState("member-3", false));
}
@Test
public void testChangeMemberVotingStatesForSingleNodeShard() throws Exception {
String name = "testChangeMemberVotingStatesForSingleNodeShard";
String moduleShardsConfig = "module-shards-member1.conf";
- MemberNode leaderNode = MemberNode.builder(memberNodes).akkaConfig("Member1").testName(name)
+ final var leaderNode = MemberNode.builder(memberNodes).akkaConfig("Member1").testName(name)
.moduleShardsConfig(moduleShardsConfig).datastoreContextBuilder(
DatastoreContext.newBuilder().shardHeartbeatIntervalInMillis(300).shardElectionTimeoutFactor(1))
.build();
// Invoke RPC service on member-3 to change voting status
- final ClusterAdminRpcService service = new ClusterAdminRpcService(leaderNode.configDataStore(),
- leaderNode.operDataStore(), null, null);
-
- RpcResult<ChangeMemberVotingStatesForShardOutput> rpcResult = service
- .changeMemberVotingStatesForShard(new ChangeMemberVotingStatesForShardInputBuilder()
- .setShardName("cars").setDataStoreType(DataStoreType.Config)
- .setMemberVotingState(List.of(new MemberVotingStateBuilder()
- .setMemberName("member-1")
- .setVoting(FALSE)
- .build()))
- .build())
- .get(10, TimeUnit.SECONDS);
+ final var service = new ClusterAdminRpcService(leaderNode.configDataStore(), leaderNode.operDataStore(), null);
+
+ final var rpcResult = service.changeMemberVotingStatesForShard(
+ new ChangeMemberVotingStatesForShardInputBuilder()
+ .setShardName("cars").setDataStoreType(DataStoreType.Config)
+ .setMemberVotingState(List.of(new MemberVotingStateBuilder()
+ .setMemberName("member-1")
+ .setVoting(FALSE)
+ .build()))
+ .build())
+ .get(10, TimeUnit.SECONDS);
verifyFailedRpcResult(rpcResult);
- verifyVotingStates(leaderNode.configDataStore(), "cars", new SimpleEntry<>("member-1", TRUE));
+ verifyVotingStates(leaderNode.configDataStore(), "cars", new ExpState("member-1", true));
}
@Test
public void testChangeMemberVotingStatesForAllShards() throws Exception {
String name = "testChangeMemberVotingStatesForAllShards";
String moduleShardsConfig = "module-shards-member1-and-2-and-3.conf";
- final MemberNode leaderNode1 = MemberNode.builder(memberNodes).akkaConfig("Member1").testName(name)
- .moduleShardsConfig(moduleShardsConfig).datastoreContextBuilder(
- DatastoreContext.newBuilder().shardHeartbeatIntervalInMillis(300).shardElectionTimeoutFactor(1))
- .build();
-
- final MemberNode replicaNode2 = MemberNode.builder(memberNodes).akkaConfig("Member2").testName(name)
+ final var leaderNode1 = MemberNode.builder(memberNodes)
+ .akkaConfig("Member1")
+ .testName(name)
+ .moduleShardsConfig(moduleShardsConfig)
+ .datastoreContextBuilder(DatastoreContext.newBuilder()
+ .shardHeartbeatIntervalInMillis(300)
+ .shardElectionTimeoutFactor(1))
+ .build();
+
+ final var replicaNode2 = MemberNode.builder(memberNodes).akkaConfig("Member2").testName(name)
.moduleShardsConfig(moduleShardsConfig).build();
- final MemberNode replicaNode3 = MemberNode.builder(memberNodes).akkaConfig("Member3").testName(name)
+ final var replicaNode3 = MemberNode.builder(memberNodes).akkaConfig("Member3").testName(name)
.moduleShardsConfig(moduleShardsConfig).build();
leaderNode1.configDataStore().waitTillReady();
// Invoke RPC service on member-3 to change voting status
- final ClusterAdminRpcService service3 = new ClusterAdminRpcService(replicaNode3.configDataStore(),
- replicaNode3.operDataStore(), null, null);
+ final var service3 = new ClusterAdminRpcService(replicaNode3.configDataStore(),
+ replicaNode3.operDataStore(), null);
- RpcResult<ChangeMemberVotingStatesForAllShardsOutput> rpcResult = service3.changeMemberVotingStatesForAllShards(
- new ChangeMemberVotingStatesForAllShardsInputBuilder().setMemberVotingState(List.of(
+ final var rpcResult = service3.changeMemberVotingStatesForAllShards(
+ new ChangeMemberVotingStatesForAllShardsInputBuilder()
+ .setMemberVotingState(List.of(
new MemberVotingStateBuilder().setMemberName("member-2").setVoting(FALSE).build(),
- new MemberVotingStateBuilder().setMemberName("member-3").setVoting(FALSE).build())).build())
+ new MemberVotingStateBuilder().setMemberName("member-3").setVoting(FALSE).build()))
+ .build())
.get(10, TimeUnit.SECONDS);
- ChangeMemberVotingStatesForAllShardsOutput result = verifySuccessfulRpcResult(rpcResult);
+ final var result = verifySuccessfulRpcResult(rpcResult);
verifyShardResults(result.getShardResult(), successShardResult("cars", DataStoreType.Config),
successShardResult("people", DataStoreType.Config),
successShardResult("cars", DataStoreType.Operational),
successShardResult("people", DataStoreType.Operational));
- verifyVotingStates(new AbstractDataStore[]{leaderNode1.configDataStore(), leaderNode1.operDataStore(),
- replicaNode2.configDataStore(), replicaNode2.operDataStore(),
- replicaNode3.configDataStore(), replicaNode3.operDataStore()},
- new String[]{"cars", "people"}, new SimpleEntry<>("member-1", TRUE),
- new SimpleEntry<>("member-2", FALSE), new SimpleEntry<>("member-3", FALSE));
+ verifyVotingStates(new ClientBackedDataStore[] {
+ leaderNode1.configDataStore(), leaderNode1.operDataStore(),
+ replicaNode2.configDataStore(), replicaNode2.operDataStore(),
+ replicaNode3.configDataStore(), replicaNode3.operDataStore()
+ }, new String[] { "cars", "people" },
+ new ExpState("member-1", true), new ExpState("member-2", false), new ExpState("member-3", false));
}
@Test
public void testFlipMemberVotingStates() throws Exception {
String name = "testFlipMemberVotingStates";
- ServerConfigurationPayload persistedServerConfig = new ServerConfigurationPayload(List.of(
- new ServerInfo("member-1", true), new ServerInfo("member-2", true),
- new ServerInfo("member-3", false)));
+ final var persistedServerConfig = new ServerConfigurationPayload(List.of(
+ new ServerInfo("member-1", true), new ServerInfo("member-2", true), new ServerInfo("member-3", false)));
setupPersistedServerConfigPayload(persistedServerConfig, "member-1", name, "cars", "people");
setupPersistedServerConfigPayload(persistedServerConfig, "member-2", name, "cars", "people");
setupPersistedServerConfigPayload(persistedServerConfig, "member-3", name, "cars", "people");
String moduleShardsConfig = "module-shards-member1-and-2-and-3.conf";
- final MemberNode leaderNode1 = MemberNode.builder(memberNodes).akkaConfig("Member1").testName(name)
+ final var leaderNode1 = MemberNode.builder(memberNodes).akkaConfig("Member1").testName(name)
.moduleShardsConfig(moduleShardsConfig).datastoreContextBuilder(DatastoreContext.newBuilder()
.shardHeartbeatIntervalInMillis(100).shardElectionTimeoutFactor(10))
.build();
- final MemberNode replicaNode2 = MemberNode.builder(memberNodes).akkaConfig("Member2").testName(name)
+ final var replicaNode2 = MemberNode.builder(memberNodes).akkaConfig("Member2").testName(name)
.moduleShardsConfig(moduleShardsConfig).build();
- final MemberNode replicaNode3 = MemberNode.builder(memberNodes).akkaConfig("Member3").testName(name)
+ final var replicaNode3 = MemberNode.builder(memberNodes).akkaConfig("Member3").testName(name)
.moduleShardsConfig(moduleShardsConfig).build();
leaderNode1.configDataStore().waitTillReady();
leaderNode1.operDataStore().waitTillReady();
replicaNode3.configDataStore().waitTillReady();
replicaNode3.operDataStore().waitTillReady();
- verifyVotingStates(leaderNode1.configDataStore(), "cars", new SimpleEntry<>("member-1", TRUE),
- new SimpleEntry<>("member-2", TRUE), new SimpleEntry<>("member-3", FALSE));
+ verifyVotingStates(leaderNode1.configDataStore(), "cars",
+ new ExpState("member-1", true), new ExpState("member-2", true), new ExpState("member-3", false));
- final ClusterAdminRpcService service3 = new ClusterAdminRpcService(replicaNode3.configDataStore(),
- replicaNode3.operDataStore(), null, null);
+ final var service3 = new ClusterAdminRpcService(replicaNode3.configDataStore(), replicaNode3.operDataStore(),
+ null);
- RpcResult<FlipMemberVotingStatesForAllShardsOutput> rpcResult = service3.flipMemberVotingStatesForAllShards(
- new FlipMemberVotingStatesForAllShardsInputBuilder().build()).get(10, TimeUnit.SECONDS);
- FlipMemberVotingStatesForAllShardsOutput result = verifySuccessfulRpcResult(rpcResult);
+ var rpcResult = service3.flipMemberVotingStatesForAllShards(
+ new FlipMemberVotingStatesForAllShardsInputBuilder().build())
+ .get(10, TimeUnit.SECONDS);
+ var result = verifySuccessfulRpcResult(rpcResult);
verifyShardResults(result.getShardResult(), successShardResult("cars", DataStoreType.Config),
successShardResult("people", DataStoreType.Config),
successShardResult("cars", DataStoreType.Operational),
successShardResult("people", DataStoreType.Operational));
- verifyVotingStates(new AbstractDataStore[]{leaderNode1.configDataStore(), leaderNode1.operDataStore(),
- replicaNode2.configDataStore(), replicaNode2.operDataStore(),
- replicaNode3.configDataStore(), replicaNode3.operDataStore()},
- new String[]{"cars", "people"},
- new SimpleEntry<>("member-1", FALSE), new SimpleEntry<>("member-2", FALSE),
- new SimpleEntry<>("member-3", TRUE));
+ verifyVotingStates(new ClientBackedDataStore[] {
+ leaderNode1.configDataStore(), leaderNode1.operDataStore(),
+ replicaNode2.configDataStore(), replicaNode2.operDataStore(),
+ replicaNode3.configDataStore(), replicaNode3.operDataStore()
+ }, new String[] { "cars", "people" },
+ new ExpState("member-1", false), new ExpState("member-2", false), new ExpState("member-3", true));
// Leadership should have transferred to member 3 since it is the only remaining voting member.
verifyRaftState(leaderNode1.configDataStore(), "cars", raftState -> {
// Flip the voting states back to the original states.
rpcResult = service3.flipMemberVotingStatesForAllShards(
- new FlipMemberVotingStatesForAllShardsInputBuilder().build()).get(10, TimeUnit.SECONDS);
+ new FlipMemberVotingStatesForAllShardsInputBuilder().build())
+ .get(10, TimeUnit.SECONDS);
result = verifySuccessfulRpcResult(rpcResult);
verifyShardResults(result.getShardResult(), successShardResult("cars", DataStoreType.Config),
successShardResult("people", DataStoreType.Config),
successShardResult("cars", DataStoreType.Operational),
successShardResult("people", DataStoreType.Operational));
- verifyVotingStates(new AbstractDataStore[]{leaderNode1.configDataStore(), leaderNode1.operDataStore(),
- replicaNode2.configDataStore(), replicaNode2.operDataStore(),
- replicaNode3.configDataStore(), replicaNode3.operDataStore()},
- new String[]{"cars", "people"},
- new SimpleEntry<>("member-1", TRUE), new SimpleEntry<>("member-2", TRUE),
- new SimpleEntry<>("member-3", FALSE));
+ verifyVotingStates(new ClientBackedDataStore[] {
+ leaderNode1.configDataStore(), leaderNode1.operDataStore(),
+ replicaNode2.configDataStore(), replicaNode2.operDataStore(),
+ replicaNode3.configDataStore(), replicaNode3.operDataStore()
+ }, new String[] { "cars", "people" },
+ new ExpState("member-1", true), new ExpState("member-2", true), new ExpState("member-3", false));
// Leadership should have transferred to member 1 or 2.
verifyRaftState(leaderNode1.configDataStore(), "cars", raftState -> {
// Members 1, 2, and 3 are initially started up as non-voting. Members 4, 5, and 6 are initially
// non-voting and simulated as down by not starting them up.
- ServerConfigurationPayload persistedServerConfig = new ServerConfigurationPayload(List.of(
+ final var persistedServerConfig = new ServerConfigurationPayload(List.of(
new ServerInfo("member-1", false), new ServerInfo("member-2", false),
new ServerInfo("member-3", false), new ServerInfo("member-4", true),
new ServerInfo("member-5", true), new ServerInfo("member-6", true)));
setupPersistedServerConfigPayload(persistedServerConfig, "member-3", name, "cars", "people");
String moduleShardsConfig = "module-shards-member1-and-2-and-3.conf";
- final MemberNode replicaNode1 = MemberNode.builder(memberNodes).akkaConfig("Member1").testName(name)
+ final var replicaNode1 = MemberNode.builder(memberNodes).akkaConfig("Member1").testName(name)
.moduleShardsConfig(moduleShardsConfig).datastoreContextBuilder(
DatastoreContext.newBuilder().shardHeartbeatIntervalInMillis(300).shardElectionTimeoutFactor(1))
.build();
- final MemberNode replicaNode2 = MemberNode.builder(memberNodes).akkaConfig("Member2").testName(name)
+ final var replicaNode2 = MemberNode.builder(memberNodes).akkaConfig("Member2").testName(name)
.moduleShardsConfig(moduleShardsConfig).build();
- final MemberNode replicaNode3 = MemberNode.builder(memberNodes).akkaConfig("Member3").testName(name)
+ final var replicaNode3 = MemberNode.builder(memberNodes).akkaConfig("Member3").testName(name)
.moduleShardsConfig(moduleShardsConfig).build();
// Initially there won't be a leader b/c all the up nodes are non-voting.
replicaNode1.waitForMembersUp("member-2", "member-3");
- verifyVotingStates(replicaNode1.configDataStore(), "cars", new SimpleEntry<>("member-1", FALSE),
- new SimpleEntry<>("member-2", FALSE), new SimpleEntry<>("member-3", FALSE),
- new SimpleEntry<>("member-4", TRUE), new SimpleEntry<>("member-5", TRUE),
- new SimpleEntry<>("member-6", TRUE));
+ verifyVotingStates(replicaNode1.configDataStore(), "cars",
+ new ExpState("member-1", false), new ExpState("member-2", false), new ExpState("member-3", false),
+ new ExpState("member-4", true), new ExpState("member-5", true), new ExpState("member-6", true));
verifyRaftState(replicaNode1.configDataStore(), "cars", raftState ->
assertEquals("Expected raft state", RaftState.Follower.toString(), raftState.getRaftState()));
- final ClusterAdminRpcService service1 = new ClusterAdminRpcService(replicaNode1.configDataStore(),
- replicaNode1.operDataStore(), null, null);
+ final var service1 = new ClusterAdminRpcService(replicaNode1.configDataStore(), replicaNode1.operDataStore(),
+ null);
- RpcResult<FlipMemberVotingStatesForAllShardsOutput> rpcResult = service1.flipMemberVotingStatesForAllShards(
- new FlipMemberVotingStatesForAllShardsInputBuilder().build()).get(10, TimeUnit.SECONDS);
- FlipMemberVotingStatesForAllShardsOutput result = verifySuccessfulRpcResult(rpcResult);
+ final var rpcResult = service1.flipMemberVotingStatesForAllShards(
+ new FlipMemberVotingStatesForAllShardsInputBuilder().build())
+ .get(10, TimeUnit.SECONDS);
+ final var result = verifySuccessfulRpcResult(rpcResult);
verifyShardResults(result.getShardResult(), successShardResult("cars", DataStoreType.Config),
successShardResult("people", DataStoreType.Config),
successShardResult("cars", DataStoreType.Operational),
successShardResult("people", DataStoreType.Operational));
- verifyVotingStates(new AbstractDataStore[]{replicaNode1.configDataStore(), replicaNode1.operDataStore(),
- replicaNode2.configDataStore(), replicaNode2.operDataStore(),
- replicaNode3.configDataStore(), replicaNode3.operDataStore()},
- new String[]{"cars", "people"},
- new SimpleEntry<>("member-1", TRUE), new SimpleEntry<>("member-2", TRUE),
- new SimpleEntry<>("member-3", TRUE), new SimpleEntry<>("member-4", FALSE),
- new SimpleEntry<>("member-5", FALSE), new SimpleEntry<>("member-6", FALSE));
+ verifyVotingStates(new ClientBackedDataStore[] {
+ replicaNode1.configDataStore(), replicaNode1.operDataStore(),
+ replicaNode2.configDataStore(), replicaNode2.operDataStore(),
+ replicaNode3.configDataStore(), replicaNode3.operDataStore()
+ }, new String[] { "cars", "people" },
+ new ExpState("member-1", true), new ExpState("member-2", true), new ExpState("member-3", true),
+ new ExpState("member-4", false), new ExpState("member-5", false), new ExpState("member-6", false));
// Since member 1 was changed to voting and there was no leader, it should've started and election
// and become leader
String name = "testFlipMemberVotingStatesWithVotingMembersDown";
// Members 4, 5, and 6 are initially non-voting and simulated as down by not starting them up.
- ServerConfigurationPayload persistedServerConfig = new ServerConfigurationPayload(List.of(
+ final var persistedServerConfig = new ServerConfigurationPayload(List.of(
new ServerInfo("member-1", true), new ServerInfo("member-2", true),
new ServerInfo("member-3", true), new ServerInfo("member-4", false),
new ServerInfo("member-5", false), new ServerInfo("member-6", false)));
setupPersistedServerConfigPayload(persistedServerConfig, "member-3", name, "cars", "people");
String moduleShardsConfig = "module-shards-member1-and-2-and-3.conf";
- final MemberNode leaderNode1 = MemberNode.builder(memberNodes).akkaConfig("Member1").testName(name)
+ final var leaderNode1 = MemberNode.builder(memberNodes).akkaConfig("Member1").testName(name)
.moduleShardsConfig(moduleShardsConfig).datastoreContextBuilder(
DatastoreContext.newBuilder().shardHeartbeatIntervalInMillis(300).shardElectionTimeoutFactor(1))
.build();
- final MemberNode replicaNode2 = MemberNode.builder(memberNodes).akkaConfig("Member2").testName(name)
+ final var replicaNode2 = MemberNode.builder(memberNodes).akkaConfig("Member2").testName(name)
.moduleShardsConfig(moduleShardsConfig).build();
- final MemberNode replicaNode3 = MemberNode.builder(memberNodes).akkaConfig("Member3").testName(name)
+ final var replicaNode3 = MemberNode.builder(memberNodes).akkaConfig("Member3").testName(name)
.moduleShardsConfig(moduleShardsConfig).build();
leaderNode1.configDataStore().waitTillReady();
leaderNode1.operDataStore().waitTillReady();
- verifyVotingStates(leaderNode1.configDataStore(), "cars", new SimpleEntry<>("member-1", TRUE),
- new SimpleEntry<>("member-2", TRUE), new SimpleEntry<>("member-3", TRUE),
- new SimpleEntry<>("member-4", FALSE), new SimpleEntry<>("member-5", FALSE),
- new SimpleEntry<>("member-6", FALSE));
+ verifyVotingStates(leaderNode1.configDataStore(), "cars",
+ new ExpState("member-1", true), new ExpState("member-2", true), new ExpState("member-3", true),
+ new ExpState("member-4", false), new ExpState("member-5", false), new ExpState("member-6", false));
- final ClusterAdminRpcService service1 = new ClusterAdminRpcService(leaderNode1.configDataStore(),
- leaderNode1.operDataStore(), null, null);
+ final var service1 = new ClusterAdminRpcService(leaderNode1.configDataStore(), leaderNode1.operDataStore(),
+ null);
- RpcResult<FlipMemberVotingStatesForAllShardsOutput> rpcResult = service1.flipMemberVotingStatesForAllShards(
- new FlipMemberVotingStatesForAllShardsInputBuilder().build()).get(10, TimeUnit.SECONDS);
- FlipMemberVotingStatesForAllShardsOutput result = verifySuccessfulRpcResult(rpcResult);
+ final var rpcResult = service1.flipMemberVotingStatesForAllShards(
+ new FlipMemberVotingStatesForAllShardsInputBuilder().build())
+ .get(10, TimeUnit.SECONDS);
+ final var result = verifySuccessfulRpcResult(rpcResult);
verifyShardResults(result.getShardResult(), successShardResult("cars", DataStoreType.Config),
successShardResult("people", DataStoreType.Config),
successShardResult("cars", DataStoreType.Operational),
successShardResult("people", DataStoreType.Operational));
// Members 2 and 3 are now non-voting but should get replicated with the new new server config.
- verifyVotingStates(new AbstractDataStore[]{leaderNode1.configDataStore(), leaderNode1.operDataStore(),
- replicaNode2.configDataStore(), replicaNode2.operDataStore(),
- replicaNode3.configDataStore(), replicaNode3.operDataStore()},
- new String[]{"cars", "people"},
- new SimpleEntry<>("member-1", FALSE), new SimpleEntry<>("member-2", FALSE),
- new SimpleEntry<>("member-3", FALSE), new SimpleEntry<>("member-4", TRUE),
- new SimpleEntry<>("member-5", TRUE), new SimpleEntry<>("member-6", TRUE));
+ verifyVotingStates(new ClientBackedDataStore[] {
+ leaderNode1.configDataStore(), leaderNode1.operDataStore(),
+ replicaNode2.configDataStore(), replicaNode2.operDataStore(),
+ replicaNode3.configDataStore(), replicaNode3.operDataStore()
+ }, new String[] { "cars", "people" },
+ new ExpState("member-1", false), new ExpState("member-2", false), new ExpState("member-3", false),
+ new ExpState("member-4", true), new ExpState("member-5", true), new ExpState("member-6", true));
// The leader (member 1) was changed to non-voting but it shouldn't be able to step down as leader yet
// b/c it can't get a majority consensus with all voting members down. So verify it remains the leader.
private static void setupPersistedServerConfigPayload(final ServerConfigurationPayload serverConfig,
final String member, final String datastoreTypeSuffix, final String... shards) {
- String[] datastoreTypes = {"config_", "oper_"};
+ String[] datastoreTypes = { "config_", "oper_" };
for (String type : datastoreTypes) {
for (String shard : shards) {
- List<ServerInfo> newServerInfo = new ArrayList<>(serverConfig.getServerConfig().size());
- for (ServerInfo info : serverConfig.getServerConfig()) {
- newServerInfo.add(new ServerInfo(ShardIdentifier.create(shard, MemberName.forName(info.getId()),
+ final var newServerInfo = new ArrayList<ServerInfo>(serverConfig.getServerConfig().size());
+ for (var info : serverConfig.getServerConfig()) {
+ newServerInfo.add(new ServerInfo(ShardIdentifier.create(shard, MemberName.forName(info.peerId()),
type + datastoreTypeSuffix).toString(), info.isVoting()));
}
}
}
- @SafeVarargs
- private static void verifyVotingStates(final AbstractDataStore[] datastores, final String[] shards,
- final SimpleEntry<String, Boolean>... expStates) throws Exception {
- for (AbstractDataStore datastore: datastores) {
- for (String shard: shards) {
+ private static void verifyVotingStates(final ClientBackedDataStore[] datastores, final String[] shards,
+ final ExpState... expStates) throws Exception {
+ for (var datastore : datastores) {
+ for (String shard : shards) {
verifyVotingStates(datastore, shard, expStates);
}
}
}
- @SafeVarargs
- private static void verifyVotingStates(final AbstractDataStore datastore, final String shardName,
- final SimpleEntry<String, Boolean>... expStates) throws Exception {
+ private static void verifyVotingStates(final ClientBackedDataStore datastore, final String shardName,
+ final ExpState... expStates) throws Exception {
String localMemberName = datastore.getActorUtils().getCurrentMemberName().getName();
- Map<String, Boolean> expStateMap = new HashMap<>();
- for (Entry<String, Boolean> e: expStates) {
- expStateMap.put(ShardIdentifier.create(shardName, MemberName.forName(e.getKey()),
- datastore.getActorUtils().getDataStoreName()).toString(), e.getValue());
+ var expStateMap = new HashMap<String, Boolean>();
+ for (var expState : expStates) {
+ expStateMap.put(ShardIdentifier.create(shardName, MemberName.forName(expState.name),
+ datastore.getActorUtils().getDataStoreName()).toString(), expState.voting);
}
verifyRaftState(datastore, shardName, raftState -> {
String localPeerId = ShardIdentifier.create(shardName, MemberName.forName(localMemberName),
datastore.getActorUtils().getDataStoreName()).toString();
assertEquals("Voting state for " + localPeerId, expStateMap.get(localPeerId), raftState.isVoting());
- for (Entry<String, Boolean> e: raftState.getPeerVotingStates().entrySet()) {
- assertEquals("Voting state for " + e.getKey(), expStateMap.get(e.getKey()), e.getValue());
+ for (var entry : raftState.getPeerVotingStates().entrySet()) {
+ assertEquals("Voting state for " + entry.getKey(), expStateMap.get(entry.getKey()), entry.getValue());
}
});
}
private static void verifyShardResults(final Map<ShardResultKey, ShardResult> shardResults,
final ShardResult... expShardResults) {
- Map<String, ShardResult> expResultsMap = new HashMap<>();
- for (ShardResult r: expShardResults) {
+ var expResultsMap = new HashMap<String, ShardResult>();
+ for (var r : expShardResults) {
expResultsMap.put(r.getShardName() + "-" + r.getDataStoreType(), r);
}
- for (ShardResult result: shardResults.values()) {
- ShardResult exp = expResultsMap.remove(result.getShardName() + "-" + result.getDataStoreType());
+ for (var result : shardResults.values()) {
+ var exp = expResultsMap.remove(result.getShardName() + "-" + result.getDataStoreType());
assertNotNull(String.format("Unexpected result for shard %s, type %s", result.getShardName(),
result.getDataStoreType()), exp);
assertEquals("isSucceeded", exp.getSucceeded(), result.getSucceeded());
<parent>
<artifactId>mdsal-parent</artifactId>
<groupId>org.opendaylight.controller</groupId>
- <version>7.0.2-SNAPSHOT</version>
+ <version>9.0.3-SNAPSHOT</version>
<relativePath>../parent/pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
import org.apache.karaf.shell.api.action.Command;
import org.apache.karaf.shell.api.action.lifecycle.Reference;
import org.apache.karaf.shell.api.action.lifecycle.Service;
-import org.opendaylight.mdsal.binding.api.RpcConsumerRegistry;
+import org.opendaylight.mdsal.binding.api.RpcService;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.cluster.admin.rev151013.ActivateEosDatacenter;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.cluster.admin.rev151013.ActivateEosDatacenterInputBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.cluster.admin.rev151013.ClusterAdminService;
import org.opendaylight.yangtools.yang.common.RpcResult;
@Service
@Command(scope = "cluster-admin", name = "activate-eos-datacenter", description = "Run an activate-eos-datacenter test")
public class ActivateEosDatacenterCommand extends AbstractRpcAction {
@Reference
- private RpcConsumerRegistry rpcConsumerRegistry;
+ private RpcService rpcService;
@Override
protected ListenableFuture<? extends RpcResult<?>> invokeRpc() {
- return rpcConsumerRegistry.getRpcService(ClusterAdminService.class)
- .activateEosDatacenter(new ActivateEosDatacenterInputBuilder().build());
+ return rpcService.getRpc(ActivateEosDatacenter.class)
+ .invoke(new ActivateEosDatacenterInputBuilder().build());
}
}
import org.apache.karaf.shell.api.action.Command;
import org.apache.karaf.shell.api.action.lifecycle.Reference;
import org.apache.karaf.shell.api.action.lifecycle.Service;
-import org.opendaylight.mdsal.binding.api.RpcConsumerRegistry;
+import org.opendaylight.mdsal.binding.api.RpcService;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.cluster.admin.rev151013.AddReplicasForAllShards;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.cluster.admin.rev151013.AddReplicasForAllShardsInputBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.cluster.admin.rev151013.ClusterAdminService;
import org.opendaylight.yangtools.yang.common.RpcResult;
@Service
description = "Run an add-replicas-for-all-shards test")
public class AddReplicasForAllShardsCommand extends AbstractRpcAction {
@Reference
- private RpcConsumerRegistry rpcConsumerRegistry;
+ private RpcService rpcService;
@Override
protected ListenableFuture<? extends RpcResult<?>> invokeRpc() {
- return rpcConsumerRegistry.getRpcService(ClusterAdminService.class)
- .addReplicasForAllShards(new AddReplicasForAllShardsInputBuilder().build());
+ return rpcService.getRpc(AddReplicasForAllShards.class)
+ .invoke(new AddReplicasForAllShardsInputBuilder().build());
}
}
import org.apache.karaf.shell.api.action.Command;
import org.apache.karaf.shell.api.action.lifecycle.Reference;
import org.apache.karaf.shell.api.action.lifecycle.Service;
-import org.opendaylight.mdsal.binding.api.RpcConsumerRegistry;
+import org.opendaylight.mdsal.binding.api.RpcService;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.cluster.admin.rev151013.AddShardReplica;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.cluster.admin.rev151013.AddShardReplicaInputBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.cluster.admin.rev151013.ClusterAdminService;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.cluster.admin.rev151013.DataStoreType;
import org.opendaylight.yangtools.yang.common.RpcResult;
@Command(scope = "cluster-admin", name = "add-shard-replica", description = "Run an add-shard-replica test")
public class AddShardReplicaCommand extends AbstractRpcAction {
@Reference
- private RpcConsumerRegistry rpcConsumerRegistry;
+ private RpcService rpcService;
@Argument(index = 0, name = "shard-name", required = true)
private String shardName;
@Argument(index = 1, name = "data-store-type", required = true, description = "config / operational")
@Override
protected ListenableFuture<? extends RpcResult<?>> invokeRpc() {
- return rpcConsumerRegistry.getRpcService(ClusterAdminService.class)
- .addShardReplica(new AddShardReplicaInputBuilder()
+ return rpcService.getRpc(AddShardReplica.class)
+ .invoke(new AddShardReplicaInputBuilder()
.setShardName(shardName)
.setDataStoreType(DataStoreType.forName(dataStoreType))
.build());
import org.apache.karaf.shell.api.action.Command;
import org.apache.karaf.shell.api.action.lifecycle.Reference;
import org.apache.karaf.shell.api.action.lifecycle.Service;
-import org.opendaylight.mdsal.binding.api.RpcConsumerRegistry;
+import org.opendaylight.mdsal.binding.api.RpcService;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.cluster.admin.rev151013.BackupDatastore;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.cluster.admin.rev151013.BackupDatastoreInputBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.cluster.admin.rev151013.ClusterAdminService;
import org.opendaylight.yangtools.yang.common.RpcResult;
import org.opendaylight.yangtools.yang.common.Uint32;
@Command(scope = "cluster-admin", name = "backup-datastore", description = "Run a backup-datastore test")
public class BackupDatastoreCommand extends AbstractRpcAction {
@Reference
- private RpcConsumerRegistry rpcConsumerRegistry;
+ private RpcService rpcService;
@Argument(index = 0, name = "file-path", required = true)
private String filePath;
@Argument(index = 1, name = "timeout", required = true)
@Override
protected ListenableFuture<? extends RpcResult<?>> invokeRpc() {
- return rpcConsumerRegistry.getRpcService(ClusterAdminService.class)
- .backupDatastore(new BackupDatastoreInputBuilder()
+ return rpcService.getRpc(BackupDatastore.class)
+ .invoke(new BackupDatastoreInputBuilder()
.setFilePath(filePath)
.setTimeout(Uint32.valueOf(timeout))
.build());
import org.apache.karaf.shell.api.action.Command;
import org.apache.karaf.shell.api.action.lifecycle.Reference;
import org.apache.karaf.shell.api.action.lifecycle.Service;
-import org.opendaylight.mdsal.binding.api.RpcConsumerRegistry;
+import org.opendaylight.mdsal.binding.api.RpcService;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.cluster.admin.rev151013.ChangeMemberVotingStatesForAllShards;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.cluster.admin.rev151013.ChangeMemberVotingStatesForAllShardsInputBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.cluster.admin.rev151013.ClusterAdminService;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.cluster.admin.rev151013.member.voting.states.input.MemberVotingState;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.cluster.admin.rev151013.member.voting.states.input.MemberVotingStateBuilder;
import org.opendaylight.yangtools.yang.common.RpcResult;
description = "Run a change-member-voting-states-for-all-shards test")
public class ChangeMemberVotingStatesForAllShardsCommand extends AbstractRpcAction {
@Reference
- private RpcConsumerRegistry rpcConsumerRegistry;
+ private RpcService rpcService;
@Argument(index = 0, name = "member-name", required = true)
private String memberName;
@Argument(index = 1, name = "voting", required = true)
.setVoting(voting)
.build();
- return rpcConsumerRegistry.getRpcService(ClusterAdminService.class)
- .changeMemberVotingStatesForAllShards(new ChangeMemberVotingStatesForAllShardsInputBuilder()
+ return rpcService.getRpc(ChangeMemberVotingStatesForAllShards.class)
+ .invoke(new ChangeMemberVotingStatesForAllShardsInputBuilder()
.setMemberVotingState(List.of(memberVotingState))
.build());
}
import org.apache.karaf.shell.api.action.Command;
import org.apache.karaf.shell.api.action.lifecycle.Reference;
import org.apache.karaf.shell.api.action.lifecycle.Service;
-import org.opendaylight.mdsal.binding.api.RpcConsumerRegistry;
+import org.opendaylight.mdsal.binding.api.RpcService;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.cluster.admin.rev151013.ChangeMemberVotingStatesForShard;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.cluster.admin.rev151013.ChangeMemberVotingStatesForShardInputBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.cluster.admin.rev151013.ClusterAdminService;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.cluster.admin.rev151013.DataStoreType;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.cluster.admin.rev151013.member.voting.states.input.MemberVotingState;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.cluster.admin.rev151013.member.voting.states.input.MemberVotingStateBuilder;
description = "Run a change-member-voting-states-for-shard test")
public class ChangeMemberVotingStatesForShardCommand extends AbstractRpcAction {
@Reference
- private RpcConsumerRegistry rpcConsumerRegistry;
+ private RpcService rpcService;
@Argument(index = 0, name = "shard-name", required = true)
private String shardName;
@Argument(index = 1, name = "data-store-type", required = true, description = "config / operational")
.setVoting(voting)
.build();
- return rpcConsumerRegistry.getRpcService(ClusterAdminService.class)
- .changeMemberVotingStatesForShard(new ChangeMemberVotingStatesForShardInputBuilder()
+ return rpcService.getRpc(ChangeMemberVotingStatesForShard.class)
+ .invoke(new ChangeMemberVotingStatesForShardInputBuilder()
.setShardName(shardName)
.setDataStoreType(DataStoreType.forName(dataStoreType))
.setMemberVotingState(List.of(memberVotingState))
import org.apache.karaf.shell.api.action.Command;
import org.apache.karaf.shell.api.action.lifecycle.Reference;
import org.apache.karaf.shell.api.action.lifecycle.Service;
-import org.opendaylight.mdsal.binding.api.RpcConsumerRegistry;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.cluster.admin.rev151013.ClusterAdminService;
+import org.opendaylight.mdsal.binding.api.RpcService;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.cluster.admin.rev151013.DeactivateEosDatacenter;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.cluster.admin.rev151013.DeactivateEosDatacenterInputBuilder;
import org.opendaylight.yangtools.yang.common.RpcResult;
description = "Run a deactivate-eos-datacenter test")
public class DeactivateEosDatacenterCommand extends AbstractRpcAction {
@Reference
- private RpcConsumerRegistry rpcConsumerRegistry;
+ private RpcService rpcService;
@Override
protected ListenableFuture<? extends RpcResult<?>> invokeRpc() {
- return rpcConsumerRegistry.getRpcService(ClusterAdminService.class)
- .deactivateEosDatacenter(new DeactivateEosDatacenterInputBuilder().build());
+ return rpcService.getRpc(DeactivateEosDatacenter.class)
+ .invoke(new DeactivateEosDatacenterInputBuilder().build());
}
}
import org.apache.karaf.shell.api.action.Command;
import org.apache.karaf.shell.api.action.lifecycle.Reference;
import org.apache.karaf.shell.api.action.lifecycle.Service;
-import org.opendaylight.mdsal.binding.api.RpcConsumerRegistry;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.cluster.admin.rev151013.ClusterAdminService;
+import org.opendaylight.mdsal.binding.api.RpcService;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.cluster.admin.rev151013.FlipMemberVotingStatesForAllShards;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.cluster.admin.rev151013.FlipMemberVotingStatesForAllShardsInputBuilder;
import org.opendaylight.yangtools.yang.common.RpcResult;
description = "Run a flip-member-voting-states-for-all-shards test")
public class FlipMemberVotingStatesForAllShardsCommand extends AbstractRpcAction {
@Reference
- private RpcConsumerRegistry rpcConsumerRegistry;
+ private RpcService rpcService;
@Override
protected ListenableFuture<? extends RpcResult<?>> invokeRpc() {
- return rpcConsumerRegistry.getRpcService(ClusterAdminService.class)
- .flipMemberVotingStatesForAllShards(new FlipMemberVotingStatesForAllShardsInputBuilder().build());
+ return rpcService.getRpc(FlipMemberVotingStatesForAllShards.class)
+ .invoke(new FlipMemberVotingStatesForAllShardsInputBuilder().build());
}
}
import org.apache.karaf.shell.api.action.Command;
import org.apache.karaf.shell.api.action.lifecycle.Reference;
import org.apache.karaf.shell.api.action.lifecycle.Service;
-import org.opendaylight.mdsal.binding.api.RpcConsumerRegistry;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.cluster.admin.rev151013.ClusterAdminService;
+import org.opendaylight.mdsal.binding.api.RpcService;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.cluster.admin.rev151013.GetKnownClientsForAllShards;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.cluster.admin.rev151013.GetKnownClientsForAllShardsInputBuilder;
import org.opendaylight.yangtools.yang.common.RpcResult;
description = "Run a get-known-clients-for-all-shards test")
public class GetKnownClientsForAllShardsCommand extends AbstractRpcAction {
@Reference
- private RpcConsumerRegistry rpcConsumerRegistry;
+ private RpcService rpcService;
@Override
protected ListenableFuture<? extends RpcResult<?>> invokeRpc() {
- return rpcConsumerRegistry.getRpcService(ClusterAdminService.class)
- .getKnownClientsForAllShards(new GetKnownClientsForAllShardsInputBuilder().build());
+ return rpcService.getRpc(GetKnownClientsForAllShards.class)
+ .invoke(new GetKnownClientsForAllShardsInputBuilder().build());
}
}
import org.apache.karaf.shell.api.action.Command;
import org.apache.karaf.shell.api.action.lifecycle.Reference;
import org.apache.karaf.shell.api.action.lifecycle.Service;
-import org.opendaylight.mdsal.binding.api.RpcConsumerRegistry;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.cluster.admin.rev151013.ClusterAdminService;
+import org.opendaylight.mdsal.binding.api.RpcService;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.cluster.admin.rev151013.DataStoreType;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.cluster.admin.rev151013.GetShardRole;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.cluster.admin.rev151013.GetShardRoleInputBuilder;
import org.opendaylight.yangtools.yang.common.RpcResult;
@Command(scope = "cluster-admin", name = "get-shard-role", description = "Run a get-shard-role test")
public class GetShardRoleCommand extends AbstractRpcAction {
@Reference
- private RpcConsumerRegistry rpcConsumerRegistry;
+ private RpcService rpcService;
@Argument(index = 0, name = "shard-name", required = true)
private String shardName;
@Argument(index = 1, name = "data-store-type", required = true, description = "config / operational")
@Override
protected ListenableFuture<? extends RpcResult<?>> invokeRpc() {
- return rpcConsumerRegistry.getRpcService(ClusterAdminService.class)
- .getShardRole(new GetShardRoleInputBuilder()
+ return rpcService.getRpc(GetShardRole.class)
+ .invoke(new GetShardRoleInputBuilder()
.setShardName(shardName)
.setDataStoreType(DataStoreType.forName(dataStoreType))
.build());
import org.apache.karaf.shell.api.action.Command;
import org.apache.karaf.shell.api.action.lifecycle.Reference;
import org.apache.karaf.shell.api.action.lifecycle.Service;
-import org.opendaylight.mdsal.binding.api.RpcConsumerRegistry;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.cluster.admin.rev151013.ClusterAdminService;
+import org.opendaylight.mdsal.binding.api.RpcService;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.cluster.admin.rev151013.DataStoreType;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.cluster.admin.rev151013.LocateShard;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.cluster.admin.rev151013.LocateShardInputBuilder;
import org.opendaylight.yangtools.yang.common.RpcResult;
@Command(scope = "cluster-admin", name = "locate-shard", description = "Run a locate-shard test")
public class LocateShardCommand extends AbstractRpcAction {
@Reference
- private RpcConsumerRegistry rpcConsumerRegistry;
+ private RpcService rpcService;
@Argument(index = 0, name = "shard-name", required = true)
private String shardName;
@Argument(index = 1, name = "data-store-type", required = true, description = "config / operational")
@Override
protected ListenableFuture<? extends RpcResult<?>> invokeRpc() {
- return rpcConsumerRegistry.getRpcService(ClusterAdminService.class)
- .locateShard(new LocateShardInputBuilder()
+ return rpcService.getRpc(LocateShard.class)
+ .invoke(new LocateShardInputBuilder()
.setShardName(shardName)
.setDataStoreType(DataStoreType.forName(dataStoreType))
.build());
import org.apache.karaf.shell.api.action.Command;
import org.apache.karaf.shell.api.action.lifecycle.Reference;
import org.apache.karaf.shell.api.action.lifecycle.Service;
-import org.opendaylight.mdsal.binding.api.RpcConsumerRegistry;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.cluster.admin.rev151013.ClusterAdminService;
+import org.opendaylight.mdsal.binding.api.RpcService;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.cluster.admin.rev151013.DataStoreType;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.cluster.admin.rev151013.MakeLeaderLocal;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.cluster.admin.rev151013.MakeLeaderLocalInputBuilder;
import org.opendaylight.yangtools.yang.common.RpcResult;
@Command(scope = "cluster-admin", name = "make-leader-local", description = "Run a make-leader-local test")
public class MakeLeaderLocalCommand extends AbstractRpcAction {
@Reference
- private RpcConsumerRegistry rpcConsumerRegistry;
+ private RpcService rpcService;
@Argument(index = 0, name = "shard-name", required = true)
private String shardName;
@Argument(index = 1, name = "data-store-type", required = true, description = "config / operational")
@Override
protected ListenableFuture<? extends RpcResult<?>> invokeRpc() {
- return rpcConsumerRegistry.getRpcService(ClusterAdminService.class)
- .makeLeaderLocal(new MakeLeaderLocalInputBuilder()
+ return rpcService.getRpc(MakeLeaderLocal.class)
+ .invoke(new MakeLeaderLocalInputBuilder()
.setShardName(shardName)
.setDataStoreType(DataStoreType.forName(dataStoreType))
.build());
import org.apache.karaf.shell.api.action.Command;
import org.apache.karaf.shell.api.action.lifecycle.Reference;
import org.apache.karaf.shell.api.action.lifecycle.Service;
-import org.opendaylight.mdsal.binding.api.RpcConsumerRegistry;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.cluster.admin.rev151013.ClusterAdminService;
+import org.opendaylight.mdsal.binding.api.RpcService;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.cluster.admin.rev151013.RemoveAllShardReplicas;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.cluster.admin.rev151013.RemoveAllShardReplicasInputBuilder;
import org.opendaylight.yangtools.yang.common.RpcResult;
description = "Run a remove-all-shard-replicas test")
public class RemoveAllShardReplicasCommand extends AbstractRpcAction {
@Reference
- private RpcConsumerRegistry rpcConsumerRegistry;
+ private RpcService rpcService;
@Argument(index = 0, name = "member-name",required = true)
private String memberName;
@Override
protected ListenableFuture<? extends RpcResult<?>> invokeRpc() {
- return rpcConsumerRegistry.getRpcService(ClusterAdminService.class)
- .removeAllShardReplicas(new RemoveAllShardReplicasInputBuilder()
+ return rpcService.getRpc(RemoveAllShardReplicas.class)
+ .invoke(new RemoveAllShardReplicasInputBuilder()
.setMemberName(memberName)
.build());
}
import org.apache.karaf.shell.api.action.Command;
import org.apache.karaf.shell.api.action.lifecycle.Reference;
import org.apache.karaf.shell.api.action.lifecycle.Service;
-import org.opendaylight.mdsal.binding.api.RpcConsumerRegistry;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.cluster.admin.rev151013.ClusterAdminService;
+import org.opendaylight.mdsal.binding.api.RpcService;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.cluster.admin.rev151013.DataStoreType;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.cluster.admin.rev151013.RemoveShardReplica;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.md.sal.cluster.admin.rev151013.RemoveShardReplicaInputBuilder;
import org.opendaylight.yangtools.yang.common.RpcResult;
@Command(scope = "cluster-admin", name = "remove-shard-replica", description = "Run a remove-shard-replica")
public class RemoveShardReplicaCommand extends AbstractRpcAction {
@Reference
- private RpcConsumerRegistry rpcConsumerRegistry;
+ private RpcService rpcService;
@Argument(index = 0, name = "shard-name", required = true)
private String shardName;
@Argument(index = 1, name = "data-store-type", required = true, description = "config / operational")
@Override
protected ListenableFuture<? extends RpcResult<?>> invokeRpc() {
- return rpcConsumerRegistry.getRpcService(ClusterAdminService.class)
- .removeShardReplica(new RemoveShardReplicaInputBuilder()
+ return rpcService.getRpc(RemoveShardReplica.class)
+ .invoke(new RemoveShardReplicaInputBuilder()
.setShardName(shardName)
.setDataStoreType(DataStoreType.forName(dataStoreType))
.setMemberName(memberName)
<parent>
<groupId>org.opendaylight.controller</groupId>
<artifactId>mdsal-parent</artifactId>
- <version>7.0.2-SNAPSHOT</version>
+ <version>9.0.3-SNAPSHOT</version>
<relativePath>../parent</relativePath>
</parent>
<packaging>bundle</packaging>
<dependencies>
- <!-- Java -->
<dependency>
- <groupId>org.xmlunit</groupId>
- <artifactId>xmlunit-legacy</artifactId>
- </dependency>
-
- <dependency>
- <groupId>org.slf4j</groupId>
- <artifactId>slf4j-simple</artifactId>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>org.opendaylight.yangtools</groupId>
- <artifactId>yang-test-util</artifactId>
- </dependency>
-
- <!-- Apache -->
- <dependency>
- <groupId>commons-lang</groupId>
- <artifactId>commons-lang</artifactId>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>commons-io</groupId>
- <artifactId>commons-io</artifactId>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>org.apache.commons</groupId>
- <artifactId>commons-lang3</artifactId>
- <scope>test</scope>
+ <!-- Enforce Netty’s optional dependency on servlet API -->
+ <!-- FIXME: is this really needed ? -->
+ <groupId>javax.servlet</groupId>
+ <artifactId>javax.servlet-api</artifactId>
</dependency>
- <!-- Akka -->
- <dependency>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>repackaged-akka</artifactId>
- </dependency>
<dependency>
- <groupId>com.typesafe.akka</groupId>
- <artifactId>akka-testkit_2.13</artifactId>
+ <groupId>com.github.spotbugs</groupId>
+ <artifactId>spotbugs-annotations</artifactId>
+ <optional>true</optional>
</dependency>
<dependency>
- <groupId>com.typesafe.akka</groupId>
- <artifactId>akka-persistence-tck_2.13</artifactId>
+ <groupId>com.google.guava</groupId>
+ <artifactId>guava</artifactId>
</dependency>
<dependency>
- <groupId>org.scalatestplus</groupId>
- <artifactId>junit-4-13_2.13</artifactId>
- <scope>test</scope>
+ <groupId>com.guicedee.services</groupId>
+ <artifactId>javax.inject</artifactId>
+ <scope>provided</scope>
+ <optional>true</optional>
</dependency>
-
<dependency>
- <!-- Enforce Netty’s optional dependency on servlet API -->
- <!-- FIXME: is this really needed ? -->
- <groupId>javax.servlet</groupId>
- <artifactId>javax.servlet-api</artifactId>
+ <groupId>com.typesafe</groupId>
+ <artifactId>config</artifactId>
</dependency>
-
- <!-- Codahale -->
<dependency>
<groupId>io.dropwizard.metrics</groupId>
<artifactId>metrics-core</artifactId>
<artifactId>metrics-jmx</artifactId>
</dependency>
<dependency>
- <groupId>com.guicedee.services</groupId>
- <artifactId>javax.inject</artifactId>
- <scope>provided</scope>
+ <groupId>org.checkerframework</groupId>
+ <artifactId>checker-qual</artifactId>
<optional>true</optional>
</dependency>
+ <dependency>
+ <groupId>org.eclipse.jdt</groupId>
+ <artifactId>org.eclipse.jdt.annotation</artifactId>
+ </dependency>
<dependency>
<groupId>org.kohsuke.metainf-services</groupId>
<artifactId>metainf-services</artifactId>
</dependency>
<dependency>
- <groupId>org.osgi</groupId>
- <artifactId>org.osgi.service.component.annotations</artifactId>
+ <groupId>org.lz4</groupId>
+ <artifactId>lz4-java</artifactId>
+ <version>1.8.0</version>
</dependency>
-
- <!-- Google -->
<dependency>
- <groupId>com.google.guava</groupId>
- <artifactId>guava-testlib</artifactId>
+ <groupId>org.opendaylight.yangtools</groupId>
+ <artifactId>concepts</artifactId>
</dependency>
-
- <!-- Scala -->
<dependency>
- <groupId>org.scala-lang</groupId>
- <artifactId>scala-library</artifactId>
+ <groupId>org.opendaylight.yangtools</groupId>
+ <artifactId>util</artifactId>
</dependency>
-
- <!-- OpenDaylight -->
<dependency>
<groupId>org.opendaylight.yangtools</groupId>
- <artifactId>util</artifactId>
+ <artifactId>yang-common</artifactId>
</dependency>
<dependency>
<groupId>org.opendaylight.yangtools</groupId>
<artifactId>yang-data-api</artifactId>
</dependency>
+ <dependency>
+ <groupId>org.opendaylight.yangtools</groupId>
+ <artifactId>yang-data-codec-binfmt</artifactId>
+ </dependency>
<dependency>
<groupId>org.opendaylight.yangtools</groupId>
<artifactId>yang-data-impl</artifactId>
</dependency>
+ <dependency>
+ <groupId>org.opendaylight.yangtools</groupId>
+ <artifactId>yang-data-tree-api</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.opendaylight.yangtools</groupId>
+ <artifactId>yang-data-util</artifactId>
+ </dependency>
<dependency>
<groupId>org.opendaylight.yangtools</groupId>
<artifactId>yang-model-api</artifactId>
</dependency>
<dependency>
<groupId>org.opendaylight.yangtools</groupId>
- <artifactId>yang-data-codec-binfmt</artifactId>
+ <artifactId>yang-repo-api</artifactId>
</dependency>
<dependency>
<groupId>org.opendaylight.yangtools</groupId>
<artifactId>yang-repo-spi</artifactId>
</dependency>
+ <dependency>
+ <groupId>org.opendaylight.controller</groupId>
+ <artifactId>repackaged-akka</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.osgi</groupId>
+ <artifactId>org.osgi.service.component.annotations</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.scala-lang</groupId>
+ <artifactId>scala-library</artifactId>
+ </dependency>
- <!-- Compression -->
<dependency>
- <groupId>org.lz4</groupId>
- <artifactId>lz4-java</artifactId>
- <version>1.8.0</version>
+ <groupId>com.google.guava</groupId>
+ <artifactId>guava-testlib</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>com.typesafe.akka</groupId>
+ <artifactId>akka-persistence-tck_2.13</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>com.typesafe.akka</groupId>
+ <artifactId>akka-testkit_2.13</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>commons-io</groupId>
+ <artifactId>commons-io</artifactId>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.commons</groupId>
+ <artifactId>commons-lang3</artifactId>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.opendaylight.yangtools</groupId>
+ <artifactId>yang-test-util</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.scalatestplus</groupId>
+ <artifactId>junit-4-13_2.13</artifactId>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.slf4j</groupId>
+ <artifactId>slf4j-simple</artifactId>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.xmlunit</groupId>
+ <artifactId>xmlunit-core</artifactId>
</dependency>
</dependencies>
final DataContainerNode dataContainerNode) {
visitor.visitNode(level, parentPath, dataContainerNode);
- String newParentPath = parentPath + "/" + dataContainerNode.getIdentifier().toString();
+ String newParentPath = parentPath + "/" + dataContainerNode.name().toString();
for (var node : dataContainerNode.body()) {
if (node instanceof MixinNode && node instanceof NormalizedNodeContainer<?> container) {
final NormalizedNodeContainer<?> node) {
visitor.visitNode(level, parentPath, node);
- String newParentPath = parentPath + "/" + node.getIdentifier().toString();
+ String newParentPath = parentPath + "/" + node.name().toString();
for (var normalizedNode : node.body()) {
if (normalizedNode instanceof MixinNode && normalizedNode instanceof NormalizedNodeContainer<?> container) {
*/
package org.opendaylight.controller.cluster.datastore.node.utils.stream;
-import static org.opendaylight.yangtools.yang.data.codec.binfmt.NormalizedNodeStreamVersion.MAGNESIUM;
-
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
public static void writeNormalizedNode(final DataOutput out, final @Nullable NormalizedNode node)
throws IOException {
- writeNormalizedNode(out, MAGNESIUM, node);
+ writeNormalizedNode(out, NormalizedNodeStreamVersion.POTASSIUM, node);
}
public static void writeNormalizedNode(final DataOutput out, final NormalizedNodeStreamVersion version,
public static void writePath(final DataOutput out, final @NonNull YangInstanceIdentifier path)
throws IOException {
- writePath(out, MAGNESIUM, path);
+ writePath(out, NormalizedNodeStreamVersion.POTASSIUM, path);
}
public static void writePath(final DataOutput out, final NormalizedNodeStreamVersion version,
public static void writeNodeAndPath(final DataOutput out, final YangInstanceIdentifier path,
final NormalizedNode node) throws IOException {
- writeNodeAndPath(out, MAGNESIUM, path, node);
+ writeNodeAndPath(out, NormalizedNodeStreamVersion.POTASSIUM, path, node);
}
public static <T> void readPathAndNode(final DataInput in, final T instance, final Applier<T> applier)
public static void writePathAndNode(final DataOutput out, final YangInstanceIdentifier path,
final NormalizedNode node) throws IOException {
- writePathAndNode(out, MAGNESIUM, path, node);
+ writePathAndNode(out, NormalizedNodeStreamVersion.POTASSIUM, path, node);
}
}
import java.util.Optional;
import javax.xml.transform.dom.DOMSource;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
-import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeWithValue;
import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
import org.opendaylight.yangtools.yang.data.impl.schema.ReusableImmutableNormalizedNodeStreamWriter;
-import org.opendaylight.yangtools.yang.data.util.DataSchemaContextNode;
+import org.opendaylight.yangtools.yang.data.util.DataSchemaContext;
import org.opendaylight.yangtools.yang.data.util.DataSchemaContextTree;
import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
private static final Logger LOG = LoggerFactory.getLogger(AbstractNormalizedNodePruner.class);
- private final Deque<DataSchemaContextNode<?>> stack = new ArrayDeque<>();
+ private final Deque<DataSchemaContext> stack = new ArrayDeque<>();
private final ReusableImmutableNormalizedNodeStreamWriter delegate =
ReusableImmutableNormalizedNodeStreamWriter.create();
private final DataSchemaContextTree tree;
- private DataSchemaContextNode<?> nodePathSchemaNode;
+ private DataSchemaContext nodePathSchemaNode;
private NormalizedNode normalizedNode;
private State state = State.UNITIALIZED;
private int unknown;
enter(ReusableImmutableNormalizedNodeStreamWriter::startChoiceNode, name, childSizeHint);
}
- @Override
- public final void startAugmentationNode(final AugmentationIdentifier identifier) throws IOException {
- enter(ReusableImmutableNormalizedNodeStreamWriter::startAugmentationNode, identifier);
- }
-
@Override
public final boolean startAnyxmlNode(final NodeIdentifier name, final Class<?> objectModel) throws IOException {
if (enter(name)) {
}
}
- Object translateScalar(final DataSchemaContextNode<?> context, final Object value) {
+ Object translateScalar(final DataSchemaContext context, final Object value) {
// Default is pass-through
return value;
}
}
if (stack.isEmpty()) {
- normalizedNode = delegate.getResult();
+ final var result = delegate.result();
+ normalizedNode = result != null ? result.data() : null;
state = State.CLOSED;
}
}
return false;
}
- final DataSchemaContextNode<?> schema;
- final DataSchemaContextNode<?> parent = currentSchema();
+ final DataSchemaContext schema;
+ final DataSchemaContext parent = currentSchema();
if (parent != null) {
- schema = parent.getChild(name);
+ schema = parent instanceof DataSchemaContext.Composite compositeParent ? compositeParent.childByArg(name)
+ : null;
} else {
schema = nodePathSchemaNode;
}
}
stack.push(schema);
- final DataSchemaNode dataSchema = schema.getDataSchemaNode();
+ final DataSchemaNode dataSchema = schema.dataSchemaNode();
if (dataSchema != null) {
delegate.nextDataSchemaNode(dataSchema);
}
}
}
- final DataSchemaContextNode<?> currentSchema() {
+ final DataSchemaContext currentSchema() {
return stack.peek();
}
}
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeWithValue;
import org.opendaylight.yangtools.yang.data.impl.schema.ReusableImmutableNormalizedNodeStreamWriter;
-import org.opendaylight.yangtools.yang.data.util.DataSchemaContextNode;
+import org.opendaylight.yangtools.yang.data.util.DataSchemaContext;
import org.opendaylight.yangtools.yang.data.util.DataSchemaContextTree;
import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
}
@Override
- Object translateScalar(final DataSchemaContextNode<?> context, final Object value) {
- final DataSchemaNode schema = context.getDataSchemaNode();
- return schema instanceof TypedDataSchemaNode ? adaptValue(((TypedDataSchemaNode) schema).getType(), value)
- : value;
+ Object translateScalar(final DataSchemaContext context, final Object value) {
+ final DataSchemaNode schema = context.dataSchemaNode();
+ return schema instanceof TypedDataSchemaNode typed ? adaptValue(typed.getType(), value) : value;
}
private void adaptEntry(final ReusableImmutableNormalizedNodeStreamWriter writer, final NodeWithValue<?> name) {
final NodeWithValue<?> adapted;
- final DataSchemaNode schema = currentSchema().getDataSchemaNode();
+ final DataSchemaNode schema = currentSchema().dataSchemaNode();
if (schema instanceof TypedDataSchemaNode typed) {
final Object oldValue = name.getValue();
final Object newValue = adaptValue(typed.getType(), oldValue);
private void adaptEntry(final ReusableImmutableNormalizedNodeStreamWriter writer,
final NodeIdentifierWithPredicates name, final int size) {
final NodeIdentifierWithPredicates adapted;
- final DataSchemaNode schema = currentSchema().getDataSchemaNode();
+ final DataSchemaNode schema = currentSchema().dataSchemaNode();
if (schema instanceof ListSchemaNode list) {
adapted = NIP_ADAPTERS.getUnchecked(list).apply(name);
} else {
*/
@Beta
public abstract class AbstractDataTreeModificationCursor implements DataTreeModificationCursor {
- private YangInstanceIdentifier current = YangInstanceIdentifier.empty();
+ private YangInstanceIdentifier current = YangInstanceIdentifier.of();
protected final YangInstanceIdentifier current() {
return current;
if (file != null) {
return Files.newInputStream(file.toPath());
} else {
- return new ByteArrayInputStream(memory.getBuffer(), 0, memory.getCount());
+ return new ByteArrayInputStream(memory.buf(), 0, memory.count());
}
}
}
throw new IOException("Stream already closed");
}
- if (file == null && memory.getCount() + len > fileThreshold) {
+ if (file == null && memory.count() + len > fileThreshold) {
final File temp = File.createTempFile("FileBackedOutputStream", null,
fileDirectory == null ? null : new File(fileDirectory));
temp.deleteOnExit();
final Cleaner.Cleanable cleanup = FILE_CLEANER.register(this, () -> deleteFile(temp));
- LOG.debug("Byte count {} has exceeded threshold {} - switching to file: {}", memory.getCount() + len,
+ LOG.debug("Byte count {} has exceeded threshold {} - switching to file: {}", memory.count() + len,
fileThreshold, temp);
final OutputStream transfer;
try {
transfer = Files.newOutputStream(temp.toPath());
try {
- transfer.write(memory.getBuffer(), 0, memory.getCount());
+ transfer.write(memory.buf(), 0, memory.count());
transfer.flush();
} catch (IOException e) {
try {
/**
* ByteArrayOutputStream that exposes its internals for efficiency.
*/
- private static class MemoryOutputStream extends ByteArrayOutputStream {
- byte[] getBuffer() {
+ private static final class MemoryOutputStream extends ByteArrayOutputStream {
+ byte[] buf() {
return buf;
}
- int getCount() {
+ int count() {
return count;
}
}
final Optional<MessageSliceException> failure = reply.getFailure();
if (failure.isPresent()) {
LOG.warn("{}: Received failed {}", logContext, reply);
- processMessageSliceException(failure.get(), state, reply.getSendTo());
+ processMessageSliceException(failure.orElseThrow(), state, reply.getSendTo());
return true;
}
* @author Thomas Pantelis
*/
public class LeaderStateChanged {
- private final String memberId;
- private final String leaderId;
+ private final @NonNull String memberId;
+ private final @Nullable String leaderId;
private final short leaderPayloadVersion;
- public LeaderStateChanged(@NonNull String memberId, @Nullable String leaderId, short leaderPayloadVersion) {
+ public LeaderStateChanged(final @NonNull String memberId, final @Nullable String leaderId,
+ final short leaderPayloadVersion) {
this.memberId = requireNonNull(memberId);
this.leaderId = leaderId;
this.leaderPayloadVersion = leaderPayloadVersion;
new RoleChangeNotification(roleChanged.getMemberId(),
roleChanged.getOldRole(), roleChanged.getNewRole());
- for (ActorRef listener: registeredListeners.values()) {
+ for (ActorRef listener : registeredListeners.values()) {
listener.tell(latestRoleChangeNotification, getSelf());
}
} else if (message instanceof LeaderStateChanged leaderStateChanged) {
import com.google.common.annotations.VisibleForTesting;
import com.google.common.io.ByteStreams;
import com.typesafe.config.Config;
-import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
*
* @author Thomas Pantelis
*/
-public class LocalSnapshotStore extends SnapshotStore {
+public final class LocalSnapshotStore extends SnapshotStore {
private static final Logger LOG = LoggerFactory.getLogger(LocalSnapshotStore.class);
private static final int PERSISTENCE_ID_START_INDEX = "snapshot-".length();
private final int maxLoadAttempts;
private final File snapshotDir;
- @SuppressFBWarnings(value = "MC_OVERRIDABLE_METHOD_CALL_IN_CONSTRUCTOR", justification = "Akka class design")
public LocalSnapshotStore(final Config config) {
executionContext = context().system().dispatchers().lookup(config.getString("stream-dispatcher"));
snapshotDir = new File(config.getString("dir"));
import java.util.Set;
import org.eclipse.jdt.annotation.NonNull;
import org.opendaylight.controller.cluster.schema.provider.impl.YangTextSchemaSourceSerializationProxy;
-import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
+import org.opendaylight.yangtools.yang.model.api.source.SourceIdentifier;
import scala.concurrent.Future;
/**
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.SettableFuture;
import org.opendaylight.controller.cluster.schema.provider.RemoteYangTextSourceProvider;
-import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
-import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
+import org.opendaylight.yangtools.yang.model.api.source.SourceIdentifier;
+import org.opendaylight.yangtools.yang.model.api.source.YangTextSource;
import org.opendaylight.yangtools.yang.model.repo.spi.SchemaSourceProvider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import scala.concurrent.ExecutionContext;
-import scala.concurrent.Future;
/**
* Provides schema sources from {@link RemoteYangTextSourceProvider}.
*/
@Beta
-public class RemoteSchemaProvider implements SchemaSourceProvider<YangTextSchemaSource> {
+public class RemoteSchemaProvider implements SchemaSourceProvider<YangTextSource> {
private static final Logger LOG = LoggerFactory.getLogger(RemoteSchemaProvider.class);
private final RemoteYangTextSourceProvider remoteRepo;
}
@Override
- public ListenableFuture<YangTextSchemaSource> getSource(final SourceIdentifier sourceIdentifier) {
+ public ListenableFuture<YangTextSource> getSource(final SourceIdentifier sourceIdentifier) {
LOG.trace("Getting yang schema source for {}", sourceIdentifier.name().getLocalName());
- Future<YangTextSchemaSourceSerializationProxy> result = remoteRepo.getYangTextSchemaSource(sourceIdentifier);
-
- final SettableFuture<YangTextSchemaSource> res = SettableFuture.create();
- result.onComplete(new OnComplete<YangTextSchemaSourceSerializationProxy>() {
+ final var res = SettableFuture.<YangTextSource>create();
+ remoteRepo.getYangTextSchemaSource(sourceIdentifier).onComplete(new OnComplete<>() {
@Override
- public void onComplete(final Throwable throwable,
- final YangTextSchemaSourceSerializationProxy yangTextSchemaSourceSerializationProxy) {
- if (yangTextSchemaSourceSerializationProxy != null) {
- res.set(yangTextSchemaSourceSerializationProxy.getRepresentation());
+ public void onComplete(final Throwable failure, final YangTextSchemaSourceSerializationProxy success) {
+ if (success != null) {
+ res.set(success.getRepresentation());
}
- if (throwable != null) {
- res.setException(throwable);
+ if (failure != null) {
+ res.setException(failure);
}
}
}, executionContext);
import java.io.IOException;
import java.util.Set;
import org.opendaylight.controller.cluster.schema.provider.RemoteYangTextSourceProvider;
+import org.opendaylight.yangtools.yang.model.api.source.SourceIdentifier;
+import org.opendaylight.yangtools.yang.model.api.source.YangTextSource;
import org.opendaylight.yangtools.yang.model.repo.api.SchemaRepository;
-import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
-import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import scala.concurrent.Future;
LOG.trace("Sending yang schema source for {}", identifier);
final Promise<YangTextSchemaSourceSerializationProxy> promise = akka.dispatch.Futures.promise();
- ListenableFuture<YangTextSchemaSource> future =
- repository.getSchemaSource(identifier, YangTextSchemaSource.class);
+ ListenableFuture<YangTextSource> future =
+ repository.getSchemaSource(identifier, YangTextSource.class);
- Futures.addCallback(future, new FutureCallback<YangTextSchemaSource>() {
+ Futures.addCallback(future, new FutureCallback<YangTextSource>() {
@Override
- public void onSuccess(final YangTextSchemaSource result) {
+ public void onSuccess(final YangTextSource result) {
try {
promise.success(new YangTextSchemaSourceSerializationProxy(result));
} catch (IOException e) {
- LOG.warn("Unable to read schema source for {}", result.getIdentifier(), e);
+ LOG.warn("Unable to read schema source for {}", result.sourceId(), e);
promise.failure(e);
}
}
package org.opendaylight.controller.cluster.schema.provider.impl;
import com.google.common.annotations.Beta;
-import com.google.common.io.ByteSource;
+import com.google.common.io.CharSource;
import java.io.IOException;
import java.io.Serializable;
import org.opendaylight.yangtools.yang.common.Revision;
import org.opendaylight.yangtools.yang.common.UnresolvedQName.Unqualified;
-import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
-import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
+import org.opendaylight.yangtools.yang.model.api.source.SourceIdentifier;
+import org.opendaylight.yangtools.yang.model.api.source.YangTextSource;
+import org.opendaylight.yangtools.yang.model.spi.source.DelegatedYangTextSource;
/**
- * {@link org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource} serialization proxy.
+ * {@link YangTextSource} serialization proxy.
*/
@Beta
public class YangTextSchemaSourceSerializationProxy implements Serializable {
private static final long serialVersionUID = -6361268518176019477L;
- private final byte[] schemaSource;
+ private final String schemaSource;
private final Revision revision;
private final String name;
- public YangTextSchemaSourceSerializationProxy(final YangTextSchemaSource source) throws IOException {
- final var id = source.getIdentifier();
- revision = id.revision();
- name = id.name().getLocalName();
+ public YangTextSchemaSourceSerializationProxy(final YangTextSource source) throws IOException {
+ final var sourceId = source.sourceId();
+ revision = sourceId.revision();
+ name = sourceId.name().getLocalName();
schemaSource = source.read();
}
- public YangTextSchemaSource getRepresentation() {
- return YangTextSchemaSource.delegateForByteSource(new SourceIdentifier(Unqualified.of(name), revision),
- ByteSource.wrap(schemaSource));
+ public YangTextSource getRepresentation() {
+ return new DelegatedYangTextSource(new SourceIdentifier(Unqualified.of(name), revision),
+ CharSource.wrap(schemaSource));
}
}
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.fail;
+import static org.junit.Assert.assertThrows;
+import static org.junit.Assert.assertTrue;
import com.google.common.testing.FakeTicker;
import java.util.List;
-import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
ticker.advance(20, MILLISECONDS);
MessageTracker.Context context2 = messageTracker.received(new Foo());
- Assert.assertEquals(true, context2.error().isPresent());
- Assert.assertEquals(0, context2.error().get().getMessageProcessingTimesSinceLastExpectedMessage().size());
-
+ assertEquals(true, context2.error().isPresent());
+ assertEquals(0, context2.error().orElseThrow().getMessageProcessingTimesSinceLastExpectedMessage().size());
}
@Test
MessageTracker.Context context2 = messageTracker.received(new Foo());
- Assert.assertEquals(true, context2.error().isPresent());
+ assertEquals(true, context2.error().isPresent());
- MessageTracker.Error error = context2.error().get();
+ MessageTracker.Error error = context2.error().orElseThrow();
List<MessageTracker.MessageProcessingTime> messageProcessingTimes =
error.getMessageProcessingTimesSinceLastExpectedMessage();
- Assert.assertEquals(3, messageProcessingTimes.size());
+ assertEquals(3, messageProcessingTimes.size());
- Assert.assertEquals(String.class, messageProcessingTimes.get(0).getMessageClass());
- Assert.assertEquals(Long.class, messageProcessingTimes.get(1).getMessageClass());
- Assert.assertEquals(Integer.class, messageProcessingTimes.get(2).getMessageClass());
- Assert.assertTrue(messageProcessingTimes.get(2).getElapsedTimeInNanos() > MILLISECONDS.toNanos(10));
- Assert.assertEquals(Foo.class, error.getLastExpectedMessage().getClass());
- Assert.assertEquals(Foo.class, error.getCurrentExpectedMessage().getClass());
+ assertEquals(String.class, messageProcessingTimes.get(0).getMessageClass());
+ assertEquals(Long.class, messageProcessingTimes.get(1).getMessageClass());
+ assertEquals(Integer.class, messageProcessingTimes.get(2).getMessageClass());
+ assertTrue(messageProcessingTimes.get(2).getElapsedTimeInNanos() > MILLISECONDS.toNanos(10));
+ assertEquals(Foo.class, error.getLastExpectedMessage().getClass());
+ assertEquals(Foo.class, error.getCurrentExpectedMessage().getClass());
LOG.error("An error occurred : {}" , error);
}
ticker.advance(1, MILLISECONDS);
MessageTracker.Context context2 = messageTracker.received(new Foo());
- Assert.assertEquals(false, context2.error().isPresent());
-
+ assertEquals(false, context2.error().isPresent());
}
@Test
messageTracker.received(new Foo());
- try {
- messageTracker.received(new Foo());
- fail("Expected an IllegalStateException");
- } catch (IllegalStateException e) {
- // expected
- }
+ assertThrows(IllegalStateException.class, () -> messageTracker.received(new Foo()));
}
@Test
MessageTracker.Context context = messageTracker.received(new Foo());
- Assert.assertEquals(true, context.error().isPresent());
+ assertEquals(true, context.error().isPresent());
- MessageTracker.Error error = context.error().get();
+ MessageTracker.Error error = context.error().orElseThrow();
- Assert.assertEquals(null, error.getLastExpectedMessage());
- Assert.assertEquals(Foo.class, error.getCurrentExpectedMessage().getClass());
+ assertEquals(null, error.getLastExpectedMessage());
+ assertEquals(Foo.class, error.getCurrentExpectedMessage().getClass());
String errorString = error.toString();
- Assert.assertTrue(errorString.contains("Last Expected Message = null"));
+ assertTrue(errorString.contains("Last Expected Message = null"));
LOG.error("An error occurred : {}", error);
}
MessageTracker.Context context = messageTracker.received(new Foo());
- Assert.assertEquals(true, context.error().isPresent());
-
+ assertEquals(true, context.error().isPresent());
}
@Test
messageTracker.begin();
try (MessageTracker.Context ctx = messageTracker.received(45)) {
- Assert.assertEquals(false, ctx.error().isPresent());
+ assertEquals(false, ctx.error().isPresent());
}
try (MessageTracker.Context ctx = messageTracker.received(45L)) {
- Assert.assertEquals(false, ctx.error().isPresent());
+ assertEquals(false, ctx.error().isPresent());
}
List<MessageTracker.MessageProcessingTime> processingTimeList =
messageTracker.getMessagesSinceLastExpectedMessage();
- Assert.assertEquals(2, processingTimeList.size());
+ assertEquals(2, processingTimeList.size());
assertEquals(Integer.class, processingTimeList.get(0).getMessageClass());
assertEquals(Long.class, processingTimeList.get(1).getMessageClass());
-
}
-
}
package org.opendaylight.controller.cluster.datastore.node.utils.stream;
import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
-import com.google.common.collect.ImmutableSet;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
-import java.io.DataOutput;
import java.io.DataOutputStream;
import java.io.IOException;
-import java.nio.charset.Charset;
-import java.util.Arrays;
-import java.util.Set;
+import java.nio.charset.StandardCharsets;
import java.util.concurrent.atomic.AtomicBoolean;
-import java.util.stream.Collectors;
import javax.xml.transform.dom.DOMSource;
-import org.custommonkey.xmlunit.Diff;
-import org.custommonkey.xmlunit.XMLUnit;
import org.junit.Test;
import org.opendaylight.yangtools.util.xml.UntrustedXML;
import org.opendaylight.yangtools.yang.common.QName;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
-import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
-import org.opendaylight.yangtools.yang.data.api.schema.AugmentationNode;
-import org.opendaylight.yangtools.yang.data.api.schema.ChoiceNode;
-import org.opendaylight.yangtools.yang.data.api.schema.DOMSourceAnyxmlNode;
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeWithValue;
+import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
import org.opendaylight.yangtools.yang.data.api.schema.LeafNode;
import org.opendaylight.yangtools.yang.data.api.schema.LeafSetEntryNode;
-import org.opendaylight.yangtools.yang.data.api.schema.LeafSetNode;
-import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
-import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
-import org.opendaylight.yangtools.yang.data.api.schema.UnkeyedListEntryNode;
-import org.opendaylight.yangtools.yang.data.api.schema.UnkeyedListNode;
-import org.opendaylight.yangtools.yang.data.api.schema.UserMapNode;
-import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
-import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
-import org.w3c.dom.Document;
+import org.opendaylight.yangtools.yang.data.spi.node.ImmutableNodes;
+import org.xmlunit.builder.DiffBuilder;
public class SerializationUtilsTest {
-
- private static final QName CONTAINER_Q_NAME = QName.create("ns-1", "2017-03-17", "container1");
+ private static final QName CONTAINER1 = QName.create("ns-1", "2017-03-17", "container1");
@Test
- public void testSerializeDeserializeNodes() throws IOException {
- final NormalizedNode normalizedNode = createNormalizedNode();
- final byte[] bytes = serializeNormalizedNode(normalizedNode);
- assertEquals(10564, bytes.length);
- assertEquals(normalizedNode, deserializeNormalizedNode(bytes));
+ public void testSerializeDeserializeNodes() throws Exception {
+ final var normalizedNode = createNormalizedNode();
+ final var bytes = serialize(normalizedNode);
+ assertEquals(10567, bytes.length);
+ assertEquals(normalizedNode, deserialize(bytes));
}
@Test
public void testSerializeDeserializeAnyXmlNode() throws Exception {
- final ByteArrayInputStream is =
- new ByteArrayInputStream("<xml><data/></xml>".getBytes(Charset.defaultCharset()));
- final Document parse = UntrustedXML.newDocumentBuilder().parse(is);
- final DOMSourceAnyxmlNode anyXmlNode = Builders.anyXmlBuilder()
- .withNodeIdentifier(id("anyXmlNode"))
- .withValue(new DOMSource(parse))
- .build();
- final byte[] bytes = serializeNormalizedNode(anyXmlNode);
+ final var parse = UntrustedXML.newDocumentBuilder().parse(
+ new ByteArrayInputStream("<xml><data/></xml>".getBytes(StandardCharsets.UTF_8)));
+ final var anyXmlNode = ImmutableNodes.newAnyxmlBuilder(DOMSource.class)
+ .withNodeIdentifier(id("anyXmlNode"))
+ .withValue(new DOMSource(parse))
+ .build();
+ final byte[] bytes = serialize(anyXmlNode);
assertEquals(113, bytes.length);
- final NormalizedNode deserialized = deserializeNormalizedNode(bytes);
- final DOMSource value = (DOMSource) deserialized.body();
- final Diff diff = XMLUnit.compareXML((Document) anyXmlNode.body().getNode(),
- value.getNode().getOwnerDocument());
- assertTrue(diff.toString(), diff.similar());
+
+ final var diff = DiffBuilder.compare(anyXmlNode.body().getNode())
+ // FIXME: why all this magic?
+ .withTest(((DOMSource) deserialize(bytes).body()).getNode().getOwnerDocument())
+ .checkForSimilar()
+ .build();
+ assertFalse(diff.toString(), diff.hasDifferences());
}
@Test
public void testSerializeDeserializePath() throws IOException {
- final ByteArrayOutputStream bos = new ByteArrayOutputStream();
- final DataOutput out = new DataOutputStream(bos);
- final YangInstanceIdentifier path = YangInstanceIdentifier.builder()
- .node(id("container1"))
- .node(autmentationId("list1", "list2"))
- .node(listId("list1", "keyName1", "keyValue1"))
- .node(leafSetId("leafSer1", "leafSetValue1"))
- .build();
- SerializationUtils.writePath(out, path);
+ final var path = YangInstanceIdentifier.builder()
+ .node(id("container1"))
+ .node(listId("list1", "keyName1", "keyValue1"))
+ .node(leafSetId("leafSer1", "leafSetValue1"))
+ .build();
+
+ final var bos = new ByteArrayOutputStream();
+ try (var out = new DataOutputStream(bos)) {
+ SerializationUtils.writePath(out, path);
+ }
- final byte[] bytes = bos.toByteArray();
- assertEquals(119, bytes.length);
+ final var bytes = bos.toByteArray();
+ assertEquals(105, bytes.length);
- final YangInstanceIdentifier deserialized =
- SerializationUtils.readPath(new DataInputStream(new ByteArrayInputStream(bytes)));
- assertEquals(path, deserialized);
+ assertEquals(path, SerializationUtils.readPath(new DataInputStream(new ByteArrayInputStream(bytes))));
}
@Test
public void testSerializeDeserializePathAndNode() throws IOException {
- final ByteArrayOutputStream bos = new ByteArrayOutputStream();
- final DataOutput out = new DataOutputStream(bos);
- final NormalizedNode node = createNormalizedNode();
- final YangInstanceIdentifier path = YangInstanceIdentifier.create(id("container1"));
- SerializationUtils.writeNodeAndPath(out, path, node);
-
- final byte[] bytes = bos.toByteArray();
- assertEquals(10566, bytes.length);
+ final var path = YangInstanceIdentifier.of(id("container1"));
+ final var node = createNormalizedNode();
- final DataInputStream in = new DataInputStream(new ByteArrayInputStream(bytes));
- final AtomicBoolean applierCalled = new AtomicBoolean(false);
- SerializationUtils.readNodeAndPath(in, applierCalled, (instance, deserializedPath, deserializedNode) -> {
- assertEquals(path, deserializedPath);
- assertEquals(node, deserializedNode);
- applierCalled.set(true);
- });
- assertTrue(applierCalled.get());
- }
-
- @Test
- public void testSerializeDeserializeAugmentNoref() throws IOException {
- final YangInstanceIdentifier expected = YangInstanceIdentifier.create(
- AugmentationIdentifier.create(ImmutableSet.of(
- QName.create("foo", "leaf1"),
- QName.create("bar", "leaf2"))));
-
- final ByteArrayOutputStream bos = new ByteArrayOutputStream();
- final DataOutput out = new DataOutputStream(bos);
- SerializationUtils.writePath(out, expected);
+ final var bos = new ByteArrayOutputStream();
+ try (var out = new DataOutputStream(bos)) {
+ SerializationUtils.writeNodeAndPath(out, path, node);
+ }
final byte[] bytes = bos.toByteArray();
- assertEquals(37, bytes.length);
-
- final DataInputStream in = new DataInputStream(new ByteArrayInputStream(bytes));
- final YangInstanceIdentifier read = SerializationUtils.readPath(in);
- assertEquals(expected, read);
+ assertEquals(10569, bytes.length);
+
+ final var applierCalled = new AtomicBoolean(false);
+ try (var in = new DataInputStream(new ByteArrayInputStream(bytes))) {
+ SerializationUtils.readNodeAndPath(in, applierCalled, (instance, deserializedPath, deserializedNode) -> {
+ assertEquals(path, deserializedPath);
+ assertEquals(node, deserializedNode);
+ applierCalled.set(true);
+ });
+ }
+ assertTrue(applierCalled.get());
}
- private static NormalizedNode deserializeNormalizedNode(final byte[] bytes) throws IOException {
- return SerializationUtils.readNormalizedNode(new DataInputStream(new ByteArrayInputStream(bytes))).get();
+ private static NormalizedNode deserialize(final byte[] bytes) throws Exception {
+ return SerializationUtils.readNormalizedNode(new DataInputStream(new ByteArrayInputStream(bytes)))
+ .orElseThrow();
}
- private static byte[] serializeNormalizedNode(final NormalizedNode node) throws IOException {
- ByteArrayOutputStream bos = new ByteArrayOutputStream();
+ private static byte[] serialize(final NormalizedNode node) throws Exception {
+ final var bos = new ByteArrayOutputStream();
SerializationUtils.writeNormalizedNode(new DataOutputStream(bos), node);
return bos.toByteArray();
}
- private static NormalizedNode createNormalizedNode() {
- final LeafSetNode<Object> leafSetNode = Builders.leafSetBuilder()
- .withNodeIdentifier(id("leafSetNode"))
- .withChild(createLeafSetEntry("leafSetNode", "leafSetValue1"))
- .withChild(createLeafSetEntry("leafSetNode", "leafSetValue2"))
- .build();
- final LeafSetNode<Object> orderedLeafSetNode = Builders.orderedLeafSetBuilder()
- .withNodeIdentifier(id("orderedLeafSetNode"))
- .withChild(createLeafSetEntry("orderedLeafSetNode", "value1"))
- .withChild(createLeafSetEntry("orderedLeafSetNode", "value2"))
- .build();
- final LeafNode<Boolean> booleanLeaf = createLeaf("booleanLeaf", true);
- final LeafNode<Byte> byteLeaf = createLeaf("byteLeaf", (byte) 0);
- final LeafNode<Short> shortLeaf = createLeaf("shortLeaf", (short) 55);
- final LeafNode<Integer> intLeaf = createLeaf("intLeaf", 11);
- final LeafNode<Long> longLeaf = createLeaf("longLeaf", 151515L);
- final LeafNode<String> stringLeaf = createLeaf("stringLeaf", "stringValue");
- final LeafNode<String> longStringLeaf = createLeaf("longStringLeaf", getLongString());
- final LeafNode<QName> qNameLeaf = createLeaf("stringLeaf", QName.create("base", "qName"));
- final LeafNode<YangInstanceIdentifier> idLeaf = createLeaf("stringLeaf", YangInstanceIdentifier.empty());
- final MapEntryNode entry1 = Builders.mapEntryBuilder()
- .withNodeIdentifier(listId("mapNode", "key", "key1"))
+ private static ContainerNode createNormalizedNode() {
+ final var stringLeaf = createLeaf("stringLeaf", "stringValue");
+ final var entry1 = ImmutableNodes.newMapEntryBuilder()
+ .withNodeIdentifier(listId("mapNode", "key", "key1"))
+ .withChild(stringLeaf)
+ .build();
+ final var entry2 = ImmutableNodes.newMapEntryBuilder()
+ .withNodeIdentifier(listId("mapNode", "key", "key2"))
+ .withChild(stringLeaf)
+ .build();
+
+ return ImmutableNodes.newContainerBuilder()
+ .withNodeIdentifier(new NodeIdentifier(CONTAINER1))
+ .withChild(createLeaf("booleanLeaf", true))
+ .withChild(createLeaf("byteLeaf", (byte) 0))
+ .withChild(createLeaf("shortLeaf", (short) 55))
+ .withChild(createLeaf("intLeaf", 11))
+ .withChild(createLeaf("longLeaf", 151515L))
.withChild(stringLeaf)
- .build();
- final MapEntryNode entry2 = Builders.mapEntryBuilder()
- .withNodeIdentifier(listId("mapNode", "key", "key2"))
- .withChild(stringLeaf)
- .build();
- final MapNode mapNode = Builders.mapBuilder()
- .withNodeIdentifier(id("mapNode"))
- .withChild(entry1)
- .withChild(entry2)
- .build();
- final UserMapNode orderedMapNode = Builders.orderedMapBuilder()
- .withNodeIdentifier(id("orderedMapNode"))
- .withChild(entry2)
- .withChild(entry1)
- .build();
- final UnkeyedListEntryNode unkeyedListEntry1 = Builders.unkeyedListEntryBuilder()
- .withNodeIdentifier(id("unkeyedList"))
- .withChild(stringLeaf)
- .build();
- final UnkeyedListEntryNode unkeyedListEntry2 = Builders.unkeyedListEntryBuilder()
- .withNodeIdentifier(id("unkeyedList"))
- .withChild(stringLeaf)
- .build();
- final UnkeyedListNode unkeyedListNode = Builders.unkeyedListBuilder()
- .withNodeIdentifier(id("unkeyedList"))
- .withChild(unkeyedListEntry1)
- .withChild(unkeyedListEntry2)
- .build();
- final ImmutableSet<QName> childNames =
- ImmutableSet.of(QName.create(CONTAINER_Q_NAME, "aug1"), QName.create(CONTAINER_Q_NAME, "aug1"));
- final AugmentationNode augmentationNode = Builders.augmentationBuilder()
- .withNodeIdentifier(new YangInstanceIdentifier.AugmentationIdentifier(childNames))
+ .withChild(createLeaf("longStringLeaf", "0123456789".repeat(1000)))
+ .withChild(createLeaf("stringLeaf", QName.create("base", "qName")))
+ .withChild(createLeaf("stringLeaf", YangInstanceIdentifier.of(QName.create("test", "test"))))
+ .withChild(ImmutableNodes.newSystemMapBuilder()
+ .withNodeIdentifier(id("mapNode"))
+ .withChild(entry1)
+ .withChild(entry2)
+ .build())
+ .withChild(ImmutableNodes.newUserMapBuilder()
+ .withNodeIdentifier(id("orderedMapNode"))
+ .withChild(entry2)
+ .withChild(entry1)
+ .build())
+ .withChild(ImmutableNodes.newUnkeyedListBuilder()
+ .withNodeIdentifier(id("unkeyedList"))
+ .withChild(ImmutableNodes.newUnkeyedListEntryBuilder()
+ .withNodeIdentifier(id("unkeyedList"))
+ .withChild(stringLeaf)
+ .build())
+ .withChild(ImmutableNodes.newUnkeyedListEntryBuilder()
+ .withNodeIdentifier(id("unkeyedList"))
+ .withChild(stringLeaf)
+ .build())
+ .build())
+ .withChild(ImmutableNodes.newSystemLeafSetBuilder()
+ .withNodeIdentifier(id("leafSetNode"))
+ .withChild(createLeafSetEntry("leafSetNode", "leafSetValue1"))
+ .withChild(createLeafSetEntry("leafSetNode", "leafSetValue2"))
+ .build())
+ .withChild(ImmutableNodes.newUserLeafSetBuilder()
+ .withNodeIdentifier(id("orderedLeafSetNode"))
+ .withChild(createLeafSetEntry("orderedLeafSetNode", "value1"))
+ .withChild(createLeafSetEntry("orderedLeafSetNode", "value2"))
+ .build())
.withChild(createLeaf("aug1", "aug1Value"))
.withChild(createLeaf("aug2", "aug2Value"))
- .build();
- final ChoiceNode choiceNode = Builders.choiceBuilder()
- .withNodeIdentifier(id("choiceNode"))
- .withChild(createLeaf("choiceLeaf", 12))
- .build();
- return Builders.containerBuilder()
- .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(CONTAINER_Q_NAME))
- .withChild(booleanLeaf)
- .withChild(byteLeaf)
- .withChild(shortLeaf)
- .withChild(intLeaf)
- .withChild(longLeaf)
- .withChild(stringLeaf)
- .withChild(longStringLeaf)
- .withChild(qNameLeaf)
- .withChild(idLeaf)
- .withChild(mapNode)
- .withChild(orderedMapNode)
- .withChild(unkeyedListNode)
- .withChild(leafSetNode)
- .withChild(orderedLeafSetNode)
- .withChild(augmentationNode)
- .withChild(choiceNode)
+ .withChild(ImmutableNodes.newChoiceBuilder()
+ .withNodeIdentifier(id("choiceNode"))
+ .withChild(createLeaf("choiceLeaf", 12))
+ .build())
.build();
}
}
private static LeafSetEntryNode<Object> createLeafSetEntry(final String leafSet, final String value) {
- return Builders.leafSetEntryBuilder()
- .withNodeIdentifier(leafSetId(leafSet, value))
- .withValue(value)
- .build();
+ return ImmutableNodes.leafSetEntry(leafSetId(leafSet, value));
}
- private static YangInstanceIdentifier.NodeIdentifier id(final String name) {
- return new YangInstanceIdentifier.NodeIdentifier(QName.create(CONTAINER_Q_NAME, name));
+ private static NodeIdentifier id(final String name) {
+ return new NodeIdentifier(QName.create(CONTAINER1, name));
}
- private static YangInstanceIdentifier.NodeIdentifierWithPredicates listId(final String listName,
- final String keyName,
- final Object keyValue) {
- return YangInstanceIdentifier.NodeIdentifierWithPredicates.of(QName.create(CONTAINER_Q_NAME, listName),
- QName.create(CONTAINER_Q_NAME, keyName), keyValue);
+ private static NodeIdentifierWithPredicates listId(final String listName, final String keyName,
+ final Object keyValue) {
+ return NodeIdentifierWithPredicates.of(QName.create(CONTAINER1, listName), QName.create(CONTAINER1, keyName),
+ keyValue);
}
- private static <T> YangInstanceIdentifier.NodeWithValue<T> leafSetId(final String node, final T value) {
- return new YangInstanceIdentifier.NodeWithValue<>(QName.create(CONTAINER_Q_NAME, node), value);
- }
-
- private static YangInstanceIdentifier.AugmentationIdentifier autmentationId(final String... nodes) {
- final Set<QName> qNames = Arrays.stream(nodes)
- .map(node -> QName.create(CONTAINER_Q_NAME, node))
- .collect(Collectors.toSet());
- return new YangInstanceIdentifier.AugmentationIdentifier(qNames);
- }
-
- private static String getLongString() {
- final StringBuilder builder = new StringBuilder(10000);
- for (int i = 0; i < 1000; i++) {
- builder.append("0123456789");
- }
- return builder.toString();
+ private static <T> NodeWithValue<T> leafSetId(final String node, final T value) {
+ return new NodeWithValue<>(QName.create(CONTAINER1, node), value);
}
}
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;
+import static org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes.containerNode;
import static org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes.mapEntry;
import static org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes.mapEntryBuilder;
import static org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes.mapNodeBuilder;
-import com.google.common.collect.Sets;
import java.io.IOException;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicInteger;
import org.opendaylight.controller.cluster.datastore.node.utils.NormalizedNodeNavigator;
import org.opendaylight.controller.cluster.datastore.util.TestModel;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
-import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
-import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeWithValue;
-import org.opendaylight.yangtools.yang.data.api.schema.DOMSourceAnyxmlNode;
+import org.opendaylight.yangtools.yang.data.api.schema.AnyxmlNode;
+import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
import org.opendaylight.yangtools.yang.data.api.schema.LeafNode;
import org.opendaylight.yangtools.yang.data.api.schema.LeafSetEntryNode;
-import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
+import org.opendaylight.yangtools.yang.data.api.schema.SystemLeafSetNode;
+import org.opendaylight.yangtools.yang.data.api.schema.SystemMapNode;
import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeWriter;
-import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
-import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
+import org.opendaylight.yangtools.yang.data.spi.node.ImmutableNodes;
import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
@RunWith(MockitoJUnitRunner.StrictStubs.class)
NormalizedNode actual = pruner.getResult().orElseThrow();
assertEquals(expected, actual);
-
}
@Test(expected = IllegalStateException.class)
assertEquals(expected, actual);
NormalizedNodeWriter.forStreamWriter(pruner).write(expected);
-
}
-
@Test
public void testNodesPrunedWhenAugmentationSchemaMissing() throws IOException {
AbstractNormalizedNodePruner pruner = prunerNoAugSchema(TestModel.TEST_PATH);
// Asserting true here instead of checking actual value because I don't want this assertion to be fragile
assertTrue(countNodes(expected, "urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:test") > 0);
-
}
private static int countNodes(final NormalizedNode normalizedNode, final String namespaceFilter) {
}
final AtomicInteger count = new AtomicInteger();
new NormalizedNodeNavigator((level, parentPath, normalizedNode1) -> {
- if (!(normalizedNode1.getIdentifier() instanceof AugmentationIdentifier)) {
- if (normalizedNode1.getIdentifier().getNodeType().getNamespace().toString().contains(namespaceFilter)) {
- count.incrementAndGet();
- }
+ if (normalizedNode1.name().getNodeType().getNamespace().toString().contains(namespaceFilter)) {
+ count.incrementAndGet();
}
- }).navigate(YangInstanceIdentifier.empty().toString(), normalizedNode);
+ }).navigate(YangInstanceIdentifier.of().toString(), normalizedNode);
return count.get();
}
@Test
public void testLeafNodeNotPrunedWhenHasNoParent() throws IOException {
AbstractNormalizedNodePruner pruner = prunerFullSchema(TestModel.TEST_PATH.node(TestModel.DESC_QNAME));
- NormalizedNode input = Builders.leafBuilder().withNodeIdentifier(
- new NodeIdentifier(TestModel.DESC_QNAME)).withValue("test").build();
+ NormalizedNode input = ImmutableNodes.leafNode(TestModel.DESC_QNAME, "test");
NormalizedNodeWriter.forStreamWriter(pruner).write(input);
assertEquals("normalizedNode", input, pruner.getResult().orElseThrow());
}
- @Test
- public void testLeafNodePrunedWhenHasAugmentationParentAndSchemaMissing() throws IOException {
- AugmentationIdentifier augId = new AugmentationIdentifier(Sets.newHashSet(TestModel.AUG_CONT_QNAME));
- AbstractNormalizedNodePruner pruner = prunerFullSchema(YangInstanceIdentifier.builder()
- .node(TestModel.TEST_QNAME).node(TestModel.AUGMENTED_LIST_QNAME)
- .node(TestModel.AUGMENTED_LIST_QNAME).node(augId).build());
- LeafNode<Object> child = Builders.leafBuilder().withNodeIdentifier(
- new NodeIdentifier(TestModel.INVALID_QNAME)).withValue("test").build();
- NormalizedNode input = Builders.augmentationBuilder().withNodeIdentifier(augId).withChild(child).build();
- NormalizedNodeWriter.forStreamWriter(pruner).write(input);
-
- NormalizedNode actual = pruner.getResult().orElseThrow();
- assertEquals("normalizedNode", Builders.augmentationBuilder().withNodeIdentifier(augId).build(), actual);
- }
-
@Test
public void testLeafNodePrunedWhenHasNoParentAndSchemaMissing() throws IOException {
AbstractNormalizedNodePruner pruner = prunerFullSchema(TestModel.TEST_PATH.node(TestModel.INVALID_QNAME));
- NormalizedNode input = Builders.leafBuilder().withNodeIdentifier(
- new NodeIdentifier(TestModel.INVALID_QNAME)).withValue("test").build();
+ LeafNode<String> input = ImmutableNodes.leafNode(TestModel.INVALID_QNAME, "test");
NormalizedNodeWriter.forStreamWriter(pruner).write(input);
assertEquals(Optional.empty(), pruner.getResult());
@Test
public void testLeafSetEntryNodeNotPrunedWhenHasNoParent() throws IOException {
AbstractNormalizedNodePruner pruner = prunerFullSchema(TestModel.TEST_PATH.node(TestModel.SHOE_QNAME));
- NormalizedNode input = Builders.leafSetEntryBuilder().withValue("puma").withNodeIdentifier(
- new NodeWithValue<>(TestModel.SHOE_QNAME, "puma")).build();
+ LeafSetEntryNode<?> input = ImmutableNodes.leafSetEntry(TestModel.SHOE_QNAME, "puma");
NormalizedNodeWriter.forStreamWriter(pruner).write(input);
NormalizedNode actual = pruner.getResult().orElseThrow();
@Test
public void testLeafSetEntryNodeNotPrunedWhenHasParent() throws IOException {
AbstractNormalizedNodePruner pruner = prunerFullSchema(TestModel.TEST_PATH.node(TestModel.SHOE_QNAME));
- LeafSetEntryNode<Object> child = Builders.leafSetEntryBuilder().withValue("puma").withNodeIdentifier(
- new NodeWithValue<>(TestModel.SHOE_QNAME, "puma")).build();
- NormalizedNode input = Builders.leafSetBuilder().withNodeIdentifier(
- new NodeIdentifier(TestModel.SHOE_QNAME)).withChild(child).build();
+ SystemLeafSetNode<?> input = ImmutableNodes.<String>newSystemLeafSetBuilder()
+ .withNodeIdentifier(new NodeIdentifier(TestModel.SHOE_QNAME))
+ .withChildValue("puma")
+ .build();
NormalizedNodeWriter.forStreamWriter(pruner).write(input);
NormalizedNode actual = pruner.getResult().orElseThrow();
@Test
public void testLeafSetEntryNodePrunedWhenHasNoParentAndSchemaMissing() throws IOException {
AbstractNormalizedNodePruner pruner = prunerFullSchema(TestModel.TEST_PATH.node(TestModel.INVALID_QNAME));
- NormalizedNode input = Builders.leafSetEntryBuilder().withValue("test").withNodeIdentifier(
- new NodeWithValue<>(TestModel.INVALID_QNAME, "test")).build();
+ LeafSetEntryNode<?> input = ImmutableNodes.leafSetEntry(TestModel.INVALID_QNAME, "test");
NormalizedNodeWriter.forStreamWriter(pruner).write(input);
assertEquals(Optional.empty(), pruner.getResult());
@Test
public void testLeafSetEntryNodePrunedWhenHasParentAndSchemaMissing() throws IOException {
AbstractNormalizedNodePruner pruner = prunerFullSchema(TestModel.TEST_PATH.node(TestModel.INVALID_QNAME));
- LeafSetEntryNode<Object> child = Builders.leafSetEntryBuilder().withValue("test").withNodeIdentifier(
- new NodeWithValue<>(TestModel.INVALID_QNAME, "test")).build();
- NormalizedNode input = Builders.leafSetBuilder().withNodeIdentifier(
- new NodeIdentifier(TestModel.INVALID_QNAME)).withChild(child).build();
- NormalizedNodeWriter.forStreamWriter(pruner).write(input);
+ NormalizedNodeWriter.forStreamWriter(pruner).write(ImmutableNodes.<String>newSystemLeafSetBuilder()
+ .withNodeIdentifier(new NodeIdentifier(TestModel.INVALID_QNAME))
+ .withChildValue("test")
+ .build());
assertEquals(Optional.empty(), pruner.getResult());
}
@Test
public void testAnyXMLNodeNotPrunedWhenHasNoParent() throws IOException {
AbstractNormalizedNodePruner pruner = prunerFullSchema(TestModel.TEST_PATH.node(TestModel.ANY_XML_QNAME));
- NormalizedNode input = Builders.anyXmlBuilder().withNodeIdentifier(
- new NodeIdentifier(TestModel.ANY_XML_QNAME)).withValue(mock(DOMSource.class)).build();
+ AnyxmlNode<DOMSource> input = ImmutableNodes.newAnyxmlBuilder(DOMSource.class)
+ .withNodeIdentifier(new NodeIdentifier(TestModel.ANY_XML_QNAME))
+ .withValue(mock(DOMSource.class))
+ .build();
NormalizedNodeWriter.forStreamWriter(pruner).write(input);
- NormalizedNode actual = pruner.getResult().orElseThrow();
- assertEquals("normalizedNode", input, actual);
+ assertEquals(input, pruner.getResult().orElseThrow());
}
@Test
public void testAnyXMLNodeNotPrunedWhenHasParent() throws IOException {
- AbstractNormalizedNodePruner pruner = prunerFullSchema(TestModel.TEST_PATH);
- DOMSourceAnyxmlNode child = Builders.anyXmlBuilder().withNodeIdentifier(
- new NodeIdentifier(TestModel.ANY_XML_QNAME)).withValue(mock(DOMSource.class)).build();
- NormalizedNode input = Builders.containerBuilder().withNodeIdentifier(
- new NodeIdentifier(TestModel.TEST_QNAME)).withChild(child).build();
+ final var pruner = prunerFullSchema(TestModel.TEST_PATH);
+ final var input = ImmutableNodes.newContainerBuilder()
+ .withNodeIdentifier(new NodeIdentifier(TestModel.TEST_QNAME))
+ .withChild(ImmutableNodes.newAnyxmlBuilder(DOMSource.class)
+ .withNodeIdentifier(new NodeIdentifier(TestModel.ANY_XML_QNAME))
+ .withValue(mock(DOMSource.class))
+ .build())
+ .build();
NormalizedNodeWriter.forStreamWriter(pruner).write(input);
- NormalizedNode actual = pruner.getResult().orElseThrow();
- assertEquals("normalizedNode", input, actual);
+ assertEquals(input, pruner.getResult().orElseThrow());
}
@Test
public void testAnyXmlNodePrunedWhenHasNoParentAndSchemaMissing() throws IOException {
AbstractNormalizedNodePruner pruner = prunerNoTestSchema(TestModel.TEST_PATH.node(TestModel.ANY_XML_QNAME));
- NormalizedNode input = Builders.anyXmlBuilder().withNodeIdentifier(
- new NodeIdentifier(TestModel.ANY_XML_QNAME)).withValue(mock(DOMSource.class)).build();
- NormalizedNodeWriter.forStreamWriter(pruner).write(input);
+ NormalizedNodeWriter.forStreamWriter(pruner).write(ImmutableNodes.newAnyxmlBuilder(DOMSource.class)
+ .withNodeIdentifier(new NodeIdentifier(TestModel.ANY_XML_QNAME))
+ .withValue(mock(DOMSource.class))
+ .build());
assertEquals(Optional.empty(), pruner.getResult());
}
.node(TestModel.INNER_CONTAINER_QNAME).build();
AbstractNormalizedNodePruner pruner = prunerFullSchema(path);
- NormalizedNode input = ImmutableNodes.containerNode(TestModel.INNER_CONTAINER_QNAME);
+ ContainerNode input = containerNode(TestModel.INNER_CONTAINER_QNAME);
NormalizedNodeWriter.forStreamWriter(pruner).write(input);
- NormalizedNode actual = pruner.getResult().orElseThrow();
- assertEquals("normalizedNode", input, actual);
+ assertEquals(input, pruner.getResult().orElseThrow());
}
@Test
.node(TestModel.INVALID_QNAME).build();
AbstractNormalizedNodePruner pruner = prunerFullSchema(path);
- NormalizedNode input = ImmutableNodes.containerNode(TestModel.INVALID_QNAME);
- NormalizedNodeWriter.forStreamWriter(pruner).write(input);
+ NormalizedNodeWriter.forStreamWriter(pruner).write(containerNode(TestModel.INVALID_QNAME));
assertEquals(Optional.empty(), pruner.getResult());
}
.build();
AbstractNormalizedNodePruner pruner = prunerFullSchema(path);
- MapNode innerList = mapNodeBuilder(TestModel.INNER_LIST_QNAME).withChild(mapEntryBuilder(
- TestModel.INNER_LIST_QNAME, TestModel.NAME_QNAME, "one").withChild(
- ImmutableNodes.containerNode(TestModel.INVALID_QNAME)).build()).build();
- NormalizedNode input = mapEntryBuilder(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1)
- .withChild(innerList).build();
- NormalizedNodeWriter.forStreamWriter(pruner).write(input);
+ NormalizedNodeWriter.forStreamWriter(pruner)
+ .write(mapEntryBuilder(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1)
+ .withChild(mapNodeBuilder(TestModel.INNER_LIST_QNAME)
+ .withChild(mapEntryBuilder(TestModel.INNER_LIST_QNAME, TestModel.NAME_QNAME, "one")
+ .withChild(containerNode(TestModel.INVALID_QNAME))
+ .build())
+ .build())
+ .build());
- NormalizedNode expected = mapEntryBuilder(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1)
- .withChild(mapNodeBuilder(TestModel.INNER_LIST_QNAME).withChild(mapEntryBuilder(
- TestModel.INNER_LIST_QNAME, TestModel.NAME_QNAME, "one").build()).build()).build();
- NormalizedNode actual = pruner.getResult().orElseThrow();
- assertEquals("normalizedNode", expected, actual);
+ assertEquals(mapEntryBuilder(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1)
+ .withChild(mapNodeBuilder(TestModel.INNER_LIST_QNAME)
+ .withChild(mapEntryBuilder(TestModel.INNER_LIST_QNAME, TestModel.NAME_QNAME, "one").build())
+ .build())
+ .build(), pruner.getResult().orElseThrow());
}
@Test
.node(TestModel.INNER_LIST_QNAME).build();
AbstractNormalizedNodePruner pruner = prunerFullSchema(path);
- MapNode input = mapNodeBuilder(TestModel.INNER_LIST_QNAME).withChild(mapEntryBuilder(
- TestModel.INNER_LIST_QNAME, TestModel.NAME_QNAME, "one").withChild(
- ImmutableNodes.containerNode(TestModel.INNER_CONTAINER_QNAME)).build()).build();
+ SystemMapNode input = mapNodeBuilder(TestModel.INNER_LIST_QNAME)
+ .withChild(mapEntryBuilder(TestModel.INNER_LIST_QNAME, TestModel.NAME_QNAME, "one")
+ .withChild(containerNode(TestModel.INNER_CONTAINER_QNAME))
+ .build())
+ .build();
NormalizedNodeWriter.forStreamWriter(pruner).write(input);
- NormalizedNode actual = pruner.getResult().orElseThrow();
- assertEquals("normalizedNode", input, actual);
+ assertEquals(input, pruner.getResult().orElseThrow());
}
@Test
.node(TestModel.INVALID_QNAME).build();
AbstractNormalizedNodePruner pruner = prunerFullSchema(path);
- MapNode input = mapNodeBuilder(TestModel.INVALID_QNAME).withChild(mapEntryBuilder(
- TestModel.INVALID_QNAME, TestModel.NAME_QNAME, "one").withChild(
- ImmutableNodes.containerNode(TestModel.INNER_CONTAINER_QNAME)).build()).build();
- NormalizedNodeWriter.forStreamWriter(pruner).write(input);
+ NormalizedNodeWriter.forStreamWriter(pruner).write(mapNodeBuilder(TestModel.INVALID_QNAME)
+ .withChild(mapEntryBuilder(TestModel.INVALID_QNAME, TestModel.NAME_QNAME, "one")
+ .withChild(containerNode(TestModel.INNER_CONTAINER_QNAME))
+ .build())
+ .build());
assertEquals(Optional.empty(), pruner.getResult());
}
.build();
AbstractNormalizedNodePruner pruner = prunerFullSchema(path);
- MapNode innerList = mapNodeBuilder(TestModel.INVALID_QNAME).withChild(mapEntryBuilder(
- TestModel.INVALID_QNAME, TestModel.NAME_QNAME, "one").withChild(
- ImmutableNodes.containerNode(TestModel.INNER_CONTAINER_QNAME)).build()).build();
- NormalizedNode input = mapEntryBuilder(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1)
- .withChild(innerList).build();
- NormalizedNodeWriter.forStreamWriter(pruner).write(input);
+ NormalizedNodeWriter.forStreamWriter(pruner)
+ .write(mapEntryBuilder(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1)
+ .withChild(mapNodeBuilder(TestModel.INVALID_QNAME)
+ .withChild(mapEntryBuilder(TestModel.INVALID_QNAME, TestModel.NAME_QNAME, "one")
+ .withChild(containerNode(TestModel.INNER_CONTAINER_QNAME))
+ .build())
+ .build())
+ .build());
- NormalizedNode expected = mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1);
- NormalizedNode actual = pruner.getResult().orElseThrow();
- assertEquals("normalizedNode", expected, actual);
+ assertEquals(mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 1),
+ pruner.getResult().orElseThrow());
}
- private static NormalizedNode createTestContainer() {
- byte[] bytes1 = {1, 2, 3};
- LeafSetEntryNode<Object> entry1 = Builders.leafSetEntryBuilder()
- .withNodeIdentifier(new NodeWithValue<>(TestModel.BINARY_LEAF_LIST_QNAME, bytes1))
- .withValue(bytes1)
- .build();
-
- byte[] bytes2 = {};
- LeafSetEntryNode<Object> entry2 = Builders.leafSetEntryBuilder()
- .withNodeIdentifier(new NodeWithValue<>(TestModel.BINARY_LEAF_LIST_QNAME, bytes2))
- .withValue(bytes2).build();
-
+ private static ContainerNode createTestContainer() {
return TestModel.createBaseTestContainerBuilder()
- .withChild(Builders.leafSetBuilder()
- .withNodeIdentifier(new NodeIdentifier(TestModel.BINARY_LEAF_LIST_QNAME))
- .withChild(entry1)
- .withChild(entry2)
- .build())
- .withChild(ImmutableNodes.leafNode(TestModel.SOME_BINARY_DATA_QNAME, new byte[]{1, 2, 3, 4}))
- .build();
+ .withChild(ImmutableNodes.newSystemLeafSetBuilder()
+ .withNodeIdentifier(new NodeIdentifier(TestModel.BINARY_LEAF_LIST_QNAME))
+ .withChildValue(new byte[] {1, 2, 3})
+ .withChildValue(new byte[0])
+ .build())
+ .withChild(ImmutableNodes.leafNode(TestModel.SOME_BINARY_DATA_QNAME, new byte[] {1, 2, 3, 4}))
+ .build();
}
}
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
-import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeWithValue;
import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeWriter;
-import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
-import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
+import org.opendaylight.yangtools.yang.data.spi.node.ImmutableNodes;
import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
import org.opendaylight.yangtools.yang.test.util.YangParserTestUtils;
@Test
public void testListTranslation() throws IOException {
- assertEquals(Builders.mapBuilder()
+ assertEquals(ImmutableNodes.newSystemMapBuilder()
.withNodeIdentifier(new NodeIdentifier(LST))
- .withChild(Builders.mapEntryBuilder()
+ .withChild(ImmutableNodes.newMapEntryBuilder()
.withNodeIdentifier(NodeIdentifierWithPredicates.of(LST, ImmutableMap.<QName, Object>builder()
.put(A, (byte) 1)
.put(B, (short) 1)
.withChild(ImmutableNodes.leafNode(H, Uint64.ONE))
.build())
.build(),
- prune(Builders.mapBuilder()
+ prune(ImmutableNodes.newSystemMapBuilder()
.withNodeIdentifier(new NodeIdentifier(LST))
- .withChild(Builders.mapEntryBuilder()
+ .withChild(ImmutableNodes.newMapEntryBuilder()
.withNodeIdentifier(NodeIdentifierWithPredicates.of(LST, ImmutableMap.<QName, Object>builder()
.put(A, (byte) 1)
.put(B, (short) 1)
@Test
public void testContainerTranslation() throws IOException {
- assertEquals(Builders.containerBuilder()
+ assertEquals(ImmutableNodes.newContainerBuilder()
.withNodeIdentifier(new NodeIdentifier(CONT))
.withChild(ImmutableNodes.leafNode(A, (byte) 1))
.withChild(ImmutableNodes.leafNode(B, (short) 1))
.withChild(ImmutableNodes.leafNode(G, Uint32.ONE))
.withChild(ImmutableNodes.leafNode(H, Uint64.ONE))
.build(),
- prune(Builders.containerBuilder()
+ prune(ImmutableNodes.newContainerBuilder()
.withNodeIdentifier(new NodeIdentifier(CONT))
.withChild(ImmutableNodes.leafNode(A, (byte) 1))
.withChild(ImmutableNodes.leafNode(B, (short) 1))
@Test
public void testLeafList8() throws IOException {
- assertEquals(Builders.leafSetBuilder()
+ assertEquals(ImmutableNodes.newSystemLeafSetBuilder()
.withNodeIdentifier(new NodeIdentifier(LFLST8))
- .withChild(Builders.leafSetEntryBuilder()
- .withNodeIdentifier(new NodeWithValue<>(LFLST8, Uint8.ONE))
- .withValue(Uint8.ONE)
- .build())
+ .withChildValue(Uint8.ONE)
.build(),
- prune(Builders.leafSetBuilder()
+ prune(ImmutableNodes.newSystemLeafSetBuilder()
.withNodeIdentifier(new NodeIdentifier(LFLST8))
- .withChild(Builders.leafSetEntryBuilder()
- .withNodeIdentifier(new NodeWithValue<>(LFLST8, (short) 1))
- .withValue((short) 1)
- .build())
+ .withChildValue((short) 1)
.build()));
}
@Test
public void testLeafList16() throws IOException {
- assertEquals(Builders.leafSetBuilder()
+ assertEquals(ImmutableNodes.newSystemLeafSetBuilder()
.withNodeIdentifier(new NodeIdentifier(LFLST16))
- .withChild(Builders.leafSetEntryBuilder()
- .withNodeIdentifier(new NodeWithValue<>(LFLST16, Uint16.ONE))
- .withValue(Uint16.ONE)
- .build())
+ .withChildValue(Uint16.ONE)
.build(),
- prune(Builders.leafSetBuilder()
+ prune(ImmutableNodes.newSystemLeafSetBuilder()
.withNodeIdentifier(new NodeIdentifier(LFLST16))
- .withChild(Builders.leafSetEntryBuilder()
- .withNodeIdentifier(new NodeWithValue<>(LFLST16, 1))
- .withValue(1)
- .build())
+ .withChildValue(1)
.build()));
}
@Test
public void testLeafList32() throws IOException {
- assertEquals(Builders.leafSetBuilder()
+ assertEquals(ImmutableNodes.newSystemLeafSetBuilder()
.withNodeIdentifier(new NodeIdentifier(LFLST32))
- .withChild(Builders.leafSetEntryBuilder()
- .withNodeIdentifier(new NodeWithValue<>(LFLST32, Uint32.ONE))
- .withValue(Uint32.ONE)
- .build())
+ .withChildValue(Uint32.ONE)
.build(),
- prune(Builders.leafSetBuilder()
+ prune(ImmutableNodes.newSystemLeafSetBuilder()
.withNodeIdentifier(new NodeIdentifier(LFLST32))
- .withChild(Builders.leafSetEntryBuilder()
- .withNodeIdentifier(new NodeWithValue<>(LFLST32, 1L))
- .withValue(1L)
- .build())
+ .withChildValue(1L)
.build()));
}
@Test
public void testLeafList64() throws IOException {
- assertEquals(Builders.leafSetBuilder()
+ assertEquals(ImmutableNodes.newSystemLeafSetBuilder()
.withNodeIdentifier(new NodeIdentifier(LFLST64))
- .withChild(Builders.leafSetEntryBuilder()
- .withNodeIdentifier(new NodeWithValue<>(LFLST64, Uint64.ONE))
- .withValue(Uint64.ONE)
- .build())
+ .withChildValue(Uint64.ONE)
.build(),
- prune(Builders.leafSetBuilder()
+ prune(ImmutableNodes.newSystemLeafSetBuilder()
.withNodeIdentifier(new NodeIdentifier(LFLST64))
- .withChild(Builders.leafSetEntryBuilder()
- .withNodeIdentifier(new NodeWithValue<>(LFLST64, BigInteger.ONE))
- .withValue(BigInteger.ONE)
- .build())
+ .withChildValue(BigInteger.ONE)
.build()));
}
private static NormalizedNode prune(final NormalizedNode node) throws IOException {
- final ReusableNormalizedNodePruner pruner = ReusableNormalizedNodePruner.forSchemaContext(CONTEXT)
- .withUintAdaption();
- pruner.initializeForPath(YangInstanceIdentifier.create(node.getIdentifier()));
+ final var pruner = ReusableNormalizedNodePruner.forSchemaContext(CONTEXT).withUintAdaption();
+ pruner.initializeForPath(YangInstanceIdentifier.of(node.name()));
try (NormalizedNodeWriter writer = NormalizedNodeWriter.forStreamWriter(pruner)) {
writer.write(node);
}
pruner.close();
- return pruner.getResult().get();
+ return pruner.getResult().orElseThrow();
}
}
*/
package org.opendaylight.controller.cluster.datastore.util;
-import static org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes.leafNode;
import static org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes.mapEntry;
import static org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes.mapEntryBuilder;
import static org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes.mapNodeBuilder;
+import static org.opendaylight.yangtools.yang.data.spi.node.ImmutableNodes.leafNode;
import com.google.common.collect.ImmutableSet;
import java.io.InputStream;
import java.util.List;
-import java.util.Set;
import org.opendaylight.yangtools.yang.common.Decimal64;
import org.opendaylight.yangtools.yang.common.QName;
import org.opendaylight.yangtools.yang.common.Uint64;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
-import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeWithValue;
import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
import org.opendaylight.yangtools.yang.data.api.schema.builder.DataContainerNodeBuilder;
-import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
+import org.opendaylight.yangtools.yang.data.spi.node.ImmutableNodes;
import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
import org.opendaylight.yangtools.yang.test.util.YangParserTestUtils;
public static DataContainerNodeBuilder<NodeIdentifier, ContainerNode> createBaseTestContainerBuilder() {
// Create YangInstanceIdentifier with all path arg types.
- YangInstanceIdentifier instanceID = YangInstanceIdentifier.create(
- new NodeIdentifier(QName.create(TEST_QNAME, "qname")),
- NodeIdentifierWithPredicates.of(QName.create(TEST_QNAME, "list-entry"),
- QName.create(TEST_QNAME, "key"), 10),
- new AugmentationIdentifier(ImmutableSet.of(
- QName.create(TEST_QNAME, "aug1"), QName.create(TEST_QNAME, "aug2"))),
- new NodeWithValue<>(QName.create(TEST_QNAME, "leaf-list-entry"), "foo"));
+ YangInstanceIdentifier instanceID = YangInstanceIdentifier.of(
+ new NodeIdentifier(QName.create(TEST_QNAME, "qname")),
+ NodeIdentifierWithPredicates.of(QName.create(TEST_QNAME, "list-entry"),
+ QName.create(TEST_QNAME, "key"), 10),
+ new NodeWithValue<>(QName.create(TEST_QNAME, "leaf-list-entry"), "foo"));
// Create the document
- return Builders.containerBuilder()
+ return ImmutableNodes.newContainerBuilder()
.withNodeIdentifier(new NodeIdentifier(TEST_QNAME))
// Create a bits leaf
.withChild(leafNode(QName.create(TEST_QNAME, "my-bits"), ImmutableSet.of("foo", "bar")))
.withChild(leafNode(TestModel.BIGDECIMAL_LEAF_QNAME, Decimal64.valueOf("1.2").scaleTo(2)))
.withChild(leafNode(SOME_REF_QNAME, instanceID))
.withChild(leafNode(MYIDENTITY_QNAME, DESC_QNAME))
- .withChild(Builders.unkeyedListBuilder()
+ .withChild(ImmutableNodes.newUnkeyedListBuilder()
.withNodeIdentifier(new NodeIdentifier(UNKEYED_LIST_QNAME))
// Create unkeyed list entry
- .withChild(Builders.unkeyedListEntryBuilder()
+ .withChild(ImmutableNodes.newUnkeyedListEntryBuilder()
.withNodeIdentifier(new NodeIdentifier(UNKEYED_LIST_QNAME))
.withChild(leafNode(NAME_QNAME, "unkeyed-entry-name"))
.build())
.build())
- .withChild(Builders.choiceBuilder()
+ .withChild(ImmutableNodes.newChoiceBuilder()
.withNodeIdentifier(new NodeIdentifier(TWO_THREE_QNAME))
.withChild(leafNode(TWO_QNAME, "two")).build())
- .withChild(Builders.orderedMapBuilder()
+ .withChild(ImmutableNodes.newUserMapBuilder()
.withNodeIdentifier(new NodeIdentifier(ORDERED_LIST_QNAME))
.withValue(List.of(
mapEntryBuilder(ORDERED_LIST_QNAME, ORDERED_LIST_ENTRY_QNAME, "1").build(),
mapEntryBuilder(ORDERED_LIST_QNAME, ORDERED_LIST_ENTRY_QNAME, "2").build()))
.build())
- .withChild(Builders.leafSetBuilder()
+ .withChild(ImmutableNodes.newSystemLeafSetBuilder()
.withNodeIdentifier(new NodeIdentifier(SHOE_QNAME))
- .withChild(Builders.leafSetEntryBuilder()
- .withNodeIdentifier(new NodeWithValue<>(SHOE_QNAME, "nike"))
- .withValue("nike")
- .build())
- .withChild(Builders.leafSetEntryBuilder()
- .withNodeIdentifier(new NodeWithValue<>(SHOE_QNAME, "puma"))
- .withValue("puma")
- .build())
+ .withChildValue("nike")
+ .withChildValue("puma")
.build())
- .withChild(Builders.leafSetBuilder()
+ .withChild(ImmutableNodes.newSystemLeafSetBuilder()
.withNodeIdentifier(new NodeIdentifier(QName.create(TEST_QNAME, "number")))
- .withChild(Builders.leafSetEntryBuilder()
- .withNodeIdentifier(new NodeWithValue<>(QName.create(TEST_QNAME, "number"), 5))
- .withValue(5)
- .build())
- .withChild(Builders.leafSetEntryBuilder()
- .withNodeIdentifier(new NodeWithValue<>(QName.create(TEST_QNAME, "number"), 15))
- .withValue(15)
- .build())
+ .withChildValue(5)
+ .withChildValue(15)
.build())
- .withChild(Builders.containerBuilder()
+ .withChild(ImmutableNodes.newContainerBuilder()
.withNodeIdentifier(new NodeIdentifier(SWITCH_FEATURES_QNAME))
// Test a leaf-list where each entry contains an identity
- .withChild(Builders.leafSetBuilder()
+ .withChild(ImmutableNodes.newSystemLeafSetBuilder()
.withNodeIdentifier(new NodeIdentifier(QName.create(TEST_QNAME, "capability")))
- .withChild(Builders.leafSetEntryBuilder()
- .withNodeIdentifier(new NodeWithValue<>(QName.create(TEST_QNAME, "capability"), DESC_QNAME))
- .withValue(DESC_QNAME)
- .build())
+ .withChildValue(DESC_QNAME)
.build())
.build())
.withChild(mapNodeBuilder(AUGMENTED_LIST_QNAME)
}
public static MapEntryNode createAugmentedListEntry(final int id, final String name) {
- return Builders.mapEntryBuilder()
+ return ImmutableNodes.newMapEntryBuilder()
.withNodeIdentifier(NodeIdentifierWithPredicates.of(AUGMENTED_LIST_QNAME, ID_QNAME, id))
.withChild(leafNode(ID_QNAME, id))
- .withChild(Builders.augmentationBuilder()
- .withNodeIdentifier(new AugmentationIdentifier(Set.of(AUG_CONT_QNAME)))
- .withChild(Builders.containerBuilder()
- .withNodeIdentifier(new NodeIdentifier(AUG_CONT_QNAME))
- .withChild(leafNode(AUG_NAME_QNAME, name))
- .build())
+ .withChild(ImmutableNodes.newContainerBuilder()
+ .withNodeIdentifier(new NodeIdentifier(AUG_CONT_QNAME))
+ .withChild(leafNode(AUG_NAME_QNAME, name))
.build())
.build();
}
.withChild(leafNode(GRAND_CHILD_NUMBER_QNAME,FIRST_GRAND_CHILD_ID))
.withChild(leafNode(GRAND_CHILD_NAME_QNAME, FIRST_GRAND_CHILD_NAME));
- return Builders.containerBuilder()
+ return ImmutableNodes.newContainerBuilder()
.withNodeIdentifier(new NodeIdentifier(FAMILY_QNAME))
- .withChild(mapNodeBuilder()
+ .withChild(ImmutableNodes.newSystemMapBuilder()
.withNodeIdentifier(new NodeIdentifier(CHILDREN_QNAME))
.withChild(mapEntryBuilder(CHILDREN_QNAME, CHILD_NUMBER_QNAME, FIRST_CHILD_ID)
.withChild(leafNode(CHILD_NUMBER_QNAME, FIRST_CHILD_ID))
}
int counter = 0;
- for (byte[] chunk: assertFinishedStream(size, 2)) {
- for (byte actual: chunk) {
+ for (byte[] chunk : assertFinishedStream(size, 2)) {
+ for (byte actual : chunk) {
assertEquals((byte) counter++, actual);
}
}
import com.google.common.util.concurrent.Uninterruptibles;
import java.io.File;
import java.io.IOException;
-import java.io.InputStream;
import java.util.Arrays;
import java.util.concurrent.TimeUnit;
import org.junit.After;
assertEquals("Temp file", tempFileName, findTempFileName(TEMP_DIR));
assertEquals("Size", bytes.length, fbos.asByteSource().size());
- InputStream inputStream = fbos.asByteSource().openStream();
+ try (var inputStream = fbos.asByteSource().openStream()) {
+ assertArrayEquals("Read bytes", bytes, fbos.asByteSource().read());
- assertArrayEquals("Read bytes", bytes, fbos.asByteSource().read());
-
- byte[] inBytes = new byte[bytes.length];
- assertEquals("# bytes read", bytes.length, inputStream.read(inBytes));
- assertArrayEquals("Read InputStream", bytes, inBytes);
- assertEquals("End of stream", -1, inputStream.read());
-
- inputStream.close();
+ byte[] inBytes = new byte[bytes.length];
+ assertEquals("# bytes read", bytes.length, inputStream.read(inBytes));
+ assertArrayEquals("Read InputStream", bytes, inBytes);
+ assertEquals("End of stream", -1, inputStream.read());
+ }
fbos.cleanup();
fail("Temp file was not deleted");
}
- static String findTempFileName(String dirPath) {
+ static String findTempFileName(final String dirPath) {
String[] files = new File(dirPath).list();
assertNotNull(files);
assertTrue("Found more than one temp file: " + Arrays.toString(files), files.length < 2);
return files.length == 1 ? files[0] : null;
}
- static boolean deleteFile(String file) {
+ static boolean deleteFile(final String file) {
return new File(file).delete();
}
- static void deleteTempFiles(String path) {
+ static void deleteTempFiles(final String path) {
String[] files = new File(path).list();
if (files != null) {
- for (String file: files) {
+ for (String file : files) {
deleteFile(path + File.separator + file);
}
}
}
- static void createDir(String path) {
+ static void createDir(final String path) {
File dir = new File(path);
if (!dir.exists() && !dir.mkdirs()) {
throw new RuntimeException("Failed to create temp dir " + path);
import static org.junit.Assert.assertEquals;
-import org.apache.commons.lang.SerializationUtils;
+import org.apache.commons.lang3.SerializationUtils;
import org.junit.Test;
/**
@Test
public void testSerialization() {
AbortSlicing expected = new AbortSlicing(new StringIdentifier("test"));
- AbortSlicing cloned = (AbortSlicing) SerializationUtils.clone(expected);
+ AbortSlicing cloned = SerializationUtils.clone(expected);
assertEquals("getIdentifier", expected.getIdentifier(), cloned.getIdentifier());
}
}
final MessageSliceReply reply = testProbe.expectMsgClass(MessageSliceReply.class);
assertFailedMessageSliceReply(reply, IDENTIFIER, false);
- assertEquals("Failure cause", mockFailure, reply.getFailure().get().getCause());
+ assertEquals("Failure cause", mockFailure, reply.getFailure().orElseThrow().getCause());
assertFalse("MessageAssembler did not remove state for " + identifier, assembler.hasState(identifier));
verify(mockFiledBackedStream).cleanup();
final MessageSliceReply reply = testProbe.expectMsgClass(MessageSliceReply.class);
assertFailedMessageSliceReply(reply, IDENTIFIER, false);
- assertEquals("Failure cause", mockFailure, reply.getFailure().get().getCause());
+ assertEquals("Failure cause", mockFailure, reply.getFailure().orElseThrow().getCause());
assertFalse("MessageAssembler did not remove state for " + identifier, assembler.hasState(identifier));
verify(mockFiledBackedStream).cleanup();
}
}
- private MessageAssembler newMessageAssembler(String logContext) {
+ private MessageAssembler newMessageAssembler(final String logContext) {
return newMessageAssemblerBuilder(logContext).build();
}
- private Builder newMessageAssemblerBuilder(String logContext) {
+ private Builder newMessageAssemblerBuilder(final String logContext) {
return MessageAssembler.builder().fileBackedStreamFactory(mockFiledBackedStreamFactory)
.assembledMessageCallback(mockAssembledMessageCallback).logContext(logContext);
}
import static org.junit.Assert.assertEquals;
-import org.apache.commons.lang.SerializationUtils;
+import org.apache.commons.lang3.SerializationUtils;
import org.junit.Test;
/**
@Test
public void testSerialization() {
MessageSliceIdentifier expected = new MessageSliceIdentifier(new StringIdentifier("test"), 123L);
- MessageSliceIdentifier cloned = (MessageSliceIdentifier) SerializationUtils.clone(expected);
+ MessageSliceIdentifier cloned = SerializationUtils.clone(expected);
assertEquals("cloned", expected, cloned);
assertEquals("getClientIdentifier", expected.getClientIdentifier(), cloned.getClientIdentifier());
assertEquals("getSlicerId", expected.getSlicerId(), cloned.getSlicerId());
import akka.serialization.JavaSerializer;
import akka.testkit.TestProbe;
import akka.testkit.javadsl.TestKit;
-import org.apache.commons.lang.SerializationUtils;
+import org.apache.commons.lang3.SerializationUtils;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
private void testSuccess() {
MessageSliceReply expected = MessageSliceReply.success(new StringIdentifier("test"), 3,
TestProbe.apply(actorSystem).ref());
- MessageSliceReply cloned = (MessageSliceReply) SerializationUtils.clone(expected);
+ MessageSliceReply cloned = SerializationUtils.clone(expected);
assertEquals("getIdentifier", expected.getIdentifier(), cloned.getIdentifier());
assertEquals("getSliceIndex", expected.getSliceIndex(), cloned.getSliceIndex());
private void testFailure() {
MessageSliceReply expected = MessageSliceReply.failed(new StringIdentifier("test"),
new MessageSliceException("mock", true), TestProbe.apply(actorSystem).ref());
- MessageSliceReply cloned = (MessageSliceReply) SerializationUtils.clone(expected);
+ MessageSliceReply cloned = SerializationUtils.clone(expected);
assertEquals("getIdentifier", expected.getIdentifier(), cloned.getIdentifier());
assertEquals("getSliceIndex", expected.getSliceIndex(), cloned.getSliceIndex());
assertEquals("getSendTo", expected.getSendTo(), cloned.getSendTo());
assertTrue("getFailure present", cloned.getFailure().isPresent());
- assertEquals("getFailure message", expected.getFailure().get().getMessage(),
- cloned.getFailure().get().getMessage());
- assertEquals("getFailure isRetriable", expected.getFailure().get().isRetriable(),
- cloned.getFailure().get().isRetriable());
+ assertEquals("getFailure message", expected.getFailure().orElseThrow().getMessage(),
+ cloned.getFailure().orElseThrow().getMessage());
+ assertEquals("getFailure isRetriable", expected.getFailure().orElseThrow().isRetriable(),
+ cloned.getFailure().orElseThrow().isRetriable());
}
}
import akka.serialization.JavaSerializer;
import akka.testkit.TestProbe;
import akka.testkit.javadsl.TestKit;
-import org.apache.commons.lang.SerializationUtils;
+import org.apache.commons.lang3.SerializationUtils;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
@After
public void tearDown() {
- TestKit.shutdownActorSystem(actorSystem, Boolean.TRUE);
+ TestKit.shutdownActorSystem(actorSystem, true);
}
@Test
MessageSlice expected = new MessageSlice(new StringIdentifier("test"), data, 2, 3, 54321,
TestProbe.apply(actorSystem).ref());
- MessageSlice cloned = (MessageSlice) SerializationUtils.clone(expected);
+ MessageSlice cloned = SerializationUtils.clone(expected);
assertEquals("getIdentifier", expected.getIdentifier(), cloned.getIdentifier());
assertEquals("getSliceIndex", expected.getSliceIndex(), cloned.getSliceIndex());
assertEquals("Identifier", identifier, ((MessageSliceIdentifier)reply.getIdentifier())
.getClientIdentifier());
assertEquals("Failure present", Boolean.TRUE, reply.getFailure().isPresent());
- assertEquals("isRetriable", isRetriable, reply.getFailure().get().isRetriable());
+ assertEquals("isRetriable", isRetriable, reply.getFailure().orElseThrow().isRetriable());
}
static void assertMessageSlice(final MessageSlice sliceMessage, final Identifier identifier, final int sliceIndex,
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import org.apache.commons.io.FileUtils;
-import org.apache.commons.lang.SerializationUtils;
+import org.apache.commons.lang3.SerializationUtils;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
*/
package org.opendaylight.controller.cluster.schema.provider.impl;
-import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertThrows;
import akka.dispatch.ExecutionContexts;
import akka.dispatch.Futures;
import com.google.common.io.CharSource;
-import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.MoreExecutors;
import java.io.IOException;
-import java.nio.charset.StandardCharsets;
import java.util.concurrent.ExecutionException;
import org.junit.Before;
import org.junit.Test;
import org.opendaylight.controller.cluster.schema.provider.RemoteYangTextSourceProvider;
+import org.opendaylight.yangtools.yang.model.api.source.SourceIdentifier;
import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceException;
-import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
-import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
+import org.opendaylight.yangtools.yang.model.spi.source.DelegatedYangTextSource;
public class RemoteSchemaProviderTest {
private static final SourceIdentifier ID = new SourceIdentifier("Test", "2015-10-30");
@Test
public void getExistingYangTextSchemaSource() throws IOException, InterruptedException, ExecutionException {
- YangTextSchemaSource schemaSource = YangTextSchemaSource.delegateForByteSource(ID,
- CharSource.wrap("Test").asByteSource(StandardCharsets.UTF_8));
+ final var schemaSource = new DelegatedYangTextSource(ID, CharSource.wrap("Test"));
doReturn(Futures.successful(new YangTextSchemaSourceSerializationProxy(schemaSource)))
.when(mockedRemoteSchemaRepository).getYangTextSchemaSource(ID);
- YangTextSchemaSource providedSource = remoteSchemaProvider.getSource(ID).get();
- assertEquals(ID, providedSource.getIdentifier());
- assertArrayEquals(schemaSource.read(), providedSource.read());
+ final var providedSource = remoteSchemaProvider.getSource(ID).get();
+ assertEquals(ID, providedSource.sourceId());
+ assertEquals(schemaSource.read(), providedSource.read());
}
@Test
public void getNonExistingSchemaSource() throws InterruptedException {
- final var exception = new SchemaSourceException("Source not provided");
+ final var exception = new SchemaSourceException(ID, "Source not provided");
doReturn(Futures.failed(exception)).when(mockedRemoteSchemaRepository).getYangTextSchemaSource(ID);
- ListenableFuture<YangTextSchemaSource> sourceFuture = remoteSchemaProvider.getSource(ID);
+ final var sourceFuture = remoteSchemaProvider.getSource(ID);
assertTrue(sourceFuture.isDone());
final var cause = assertThrows(ExecutionException.class, sourceFuture::get).getCause();
*/
package org.opendaylight.controller.cluster.schema.provider.impl;
-import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertThrows;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.doReturn;
-import com.google.common.io.ByteSource;
+import com.google.common.io.CharSource;
import com.google.common.util.concurrent.Futures;
import java.util.Collections;
import java.util.Set;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
+import org.opendaylight.yangtools.yang.model.api.source.SourceIdentifier;
+import org.opendaylight.yangtools.yang.model.api.source.YangTextSource;
import org.opendaylight.yangtools.yang.model.repo.api.SchemaRepository;
import org.opendaylight.yangtools.yang.model.repo.api.SchemaSourceException;
-import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
-import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
+import org.opendaylight.yangtools.yang.model.spi.source.DelegatedYangTextSource;
import scala.concurrent.Await;
import scala.concurrent.duration.FiniteDuration;
@Test
public void testGetExistingYangTextSchemaSource() throws Exception {
- var schemaSource = YangTextSchemaSource.delegateForByteSource(ID, ByteSource.wrap("Test source.".getBytes()));
+ var schemaSource = new DelegatedYangTextSource(ID, CharSource.wrap("Test source."));
doReturn(Futures.immediateFuture(schemaSource)).when(mockedLocalRepository)
- .getSchemaSource(ID, YangTextSchemaSource.class);
+ .getSchemaSource(ID, YangTextSource.class);
var retrievedSourceFuture = remoteRepository.getYangTextSchemaSource(ID);
assertTrue(retrievedSourceFuture.isCompleted());
var resultSchemaSource = Await.result(retrievedSourceFuture, FiniteDuration.Zero()).getRepresentation();
- assertEquals(resultSchemaSource.getIdentifier(), schemaSource.getIdentifier());
- assertArrayEquals(resultSchemaSource.read(), schemaSource.read());
+ assertEquals(resultSchemaSource.sourceId(), schemaSource.sourceId());
+ assertEquals(resultSchemaSource.read(), schemaSource.read());
}
@Test
public void testGetNonExistentYangTextSchemaSource() throws Exception {
- final var exception = new SchemaSourceException("Source is not provided");
+ final var exception = new SchemaSourceException(ID, "Source is not provided");
doReturn(Futures.immediateFailedFuture(exception)).when(mockedLocalRepository)
- .getSchemaSource(ID, YangTextSchemaSource.class);
+ .getSchemaSource(ID, YangTextSource.class);
var retrievedSourceFuture = remoteRepository.getYangTextSchemaSource(ID);
assertTrue(retrievedSourceFuture.isCompleted());
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
-
package org.opendaylight.controller.cluster.schema.provider.impl;
-import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
-import com.google.common.io.ByteSource;
+import com.google.common.io.CharSource;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
-import java.nio.charset.StandardCharsets;
import org.junit.Before;
import org.junit.Test;
-import org.opendaylight.yangtools.yang.model.repo.api.SourceIdentifier;
-import org.opendaylight.yangtools.yang.model.repo.api.YangTextSchemaSource;
+import org.opendaylight.yangtools.yang.model.api.source.SourceIdentifier;
+import org.opendaylight.yangtools.yang.model.api.source.YangTextSource;
+import org.opendaylight.yangtools.yang.model.spi.source.DelegatedYangTextSource;
public class YangTextSourceSerializationProxyTest {
- private YangTextSchemaSource schemaSource;
+ private YangTextSource schemaSource;
@Before
public void setUp() {
- String source = "Test source.";
- schemaSource = YangTextSchemaSource.delegateForByteSource(new SourceIdentifier("test", "2015-10-30"),
- ByteSource.wrap(source.getBytes(StandardCharsets.UTF_8)));
+ schemaSource = new DelegatedYangTextSource(new SourceIdentifier("test", "2015-10-30"),
+ CharSource.wrap("Test source."));
}
-
@Test
public void serializeAndDeserializeProxy() throws ClassNotFoundException, IOException {
- YangTextSchemaSourceSerializationProxy proxy = new YangTextSchemaSourceSerializationProxy(schemaSource);
+ final var proxy = new YangTextSchemaSourceSerializationProxy(schemaSource);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(proxy);
final byte[] bytes = bos.toByteArray();
- assertEquals(353, bytes.length);
+ assertEquals(323, bytes.length);
ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(bytes));
- YangTextSchemaSourceSerializationProxy deserializedProxy =
- (YangTextSchemaSourceSerializationProxy) ois.readObject();
+ final var deserializedProxy = (YangTextSchemaSourceSerializationProxy) ois.readObject();
- assertEquals(deserializedProxy.getRepresentation().getIdentifier(), proxy.getRepresentation().getIdentifier());
- assertArrayEquals(deserializedProxy.getRepresentation().read(), proxy.getRepresentation().read());
+ assertEquals(deserializedProxy.getRepresentation().sourceId(), proxy.getRepresentation().sourceId());
+ assertEquals(deserializedProxy.getRepresentation().read(), proxy.getRepresentation().read());
}
@Test
public void testProxyEqualsBackingYangTextSource() throws IOException {
- YangTextSchemaSourceSerializationProxy serializationProxy =
- new YangTextSchemaSourceSerializationProxy(schemaSource);
+ final var serializationProxy = new YangTextSchemaSourceSerializationProxy(schemaSource);
- assertEquals(serializationProxy.getRepresentation().getIdentifier(), schemaSource.getIdentifier());
- assertArrayEquals(serializationProxy.getRepresentation().read(), schemaSource.read());
+ assertEquals(serializationProxy.getRepresentation().sourceId(), schemaSource.sourceId());
+ assertEquals(serializationProxy.getRepresentation().read(), schemaSource.read());
}
}
<parent>
<groupId>org.opendaylight.odlparent</groupId>
<artifactId>odlparent-lite</artifactId>
- <version>12.0.1</version>
+ <version>13.0.11</version>
<relativePath/>
</parent>
<groupId>org.opendaylight.controller</groupId>
<artifactId>sal-clustering-config</artifactId>
- <version>7.0.2-SNAPSHOT</version>
+ <version>9.0.3-SNAPSHOT</version>
<packaging>jar</packaging>
<description>Configuration files for md-sal clustering</description>
# for a message slice. This needs to be below Akka's maximum-frame-size and defaults to 480KiB.
maximum-message-slice-size=491520
-# Enable tell-based protocol between frontend (applications) and backend (shards). Using this protocol
-# should avoid AskTimeoutExceptions seen under heavy load. Defaults to false (use tell-based protocol).
-# Set to false to enable ask-based protocol.
-# This option is obsolete and will be removed in the next major release.
-use-tell-based-protocol=true
-
# Tune the maximum number of entries a follower is allowed to lag behind the leader before it is
# considered out-of-sync. This flag may require tuning in face of a large number of small transactions.
#sync-index-threshold=10
max-entry-size = 16M
# Maximum size of a segment
max-segment-size = 128M
+ # Maximum number of bytes that are written without synchronizing storage. Defaults to max-entry-size.
+ # Set to <= 0 to flush immediately.
+ #max-unflushed-bytes = 1M
# Map each segment into memory. Defaults to true, use false to keep a heap-based
# buffer instead.
memory-mapped = true
max-entry-size = 512K
# Maximum size of a segment
max-segment-size = 1M
+ # Maximum number of bytes that are written without synchronizing storage. Defaults to max-entry-size.
+ # Set to <= 0 to flush immediately.
+ #max-unflushed-bytes = 128K
# Map each segment into memory. Note that while this can improve performance,
# it will also place additional burden on system resources.
memory-mapped = false
<parent>
<groupId>org.opendaylight.controller</groupId>
<artifactId>mdsal-parent</artifactId>
- <version>7.0.2-SNAPSHOT</version>
+ <version>9.0.3-SNAPSHOT</version>
<relativePath>../parent</relativePath>
</parent>
<dependencies>
<dependency>
- <groupId>com.google.guava</groupId>
- <artifactId>guava</artifactId>
+ <groupId>org.eclipse.jdt</groupId>
+ <artifactId>org.eclipse.jdt.annotation</artifactId>
</dependency>
<dependency>
<groupId>org.opendaylight.yangtools</groupId>
<parent>
<groupId>org.opendaylight.controller</groupId>
<artifactId>mdsal-parent</artifactId>
- <version>7.0.2-SNAPSHOT</version>
+ <version>9.0.3-SNAPSHOT</version>
<relativePath>../parent</relativePath>
</parent>
<packaging>bundle</packaging>
<dependencies>
+ <dependency>
+ <groupId>com.github.spotbugs</groupId>
+ <artifactId>spotbugs-annotations</artifactId>
+ <optional>true</optional>
+ </dependency>
+
<!-- Java -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>commons-text</artifactId>
</dependency>
- <dependency>
- <groupId>io.atomix</groupId>
- <artifactId>atomix-storage</artifactId>
- <version>3.1.12</version>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>io.atomix</groupId>
- <artifactId>atomix-utils</artifactId>
- <version>3.1.12</version>
- <scope>test</scope>
- </dependency>
<dependency>
<groupId>org.awaitility</groupId>
<artifactId>awaitility</artifactId>
<artifactId>commons-io</artifactId>
<scope>test</scope>
</dependency>
- <dependency>
- <groupId>commons-lang</groupId>
- <artifactId>commons-lang</artifactId>
- <scope>test</scope>
- </dependency>
<dependency>
<groupId>org.opendaylight.yangtools</groupId>
<artifactId>yang-test-util</artifactId>
</dependency>
+ <dependency>
+ <groupId>org.opendaylight.mdsal</groupId>
+ <artifactId>mdsal-binding-dom-codec</artifactId>
+ <scope>test</scope>
+ </dependency>
<dependency>
<groupId>org.opendaylight.mdsal</groupId>
<artifactId>mdsal-binding-test-utils</artifactId>
<instructions>
<Bundle-Name>${project.groupId}.${project.artifactId}</Bundle-Name>
- <!-- Karaf cannot handle Factory Component requirements, see https://issues.apache.org/jira/browse/KARAF-6625 -->
- <_dsannotations-options>norequirements</_dsannotations-options>
-
<Export-Package>
org.opendaylight.controller.cluster.datastore;
org.opendaylight.controller.cluster.datastore.config;
package org.opendaylight.controller.cluster.akka.osgi.impl;
import akka.actor.ActorSystem;
-import com.typesafe.config.Config;
import java.util.concurrent.TimeoutException;
import org.opendaylight.controller.cluster.ActorSystemProvider;
import org.opendaylight.controller.cluster.ActorSystemProviderListener;
public final class OSGiActorSystemProvider implements ActorSystemProvider {
private static final Logger LOG = LoggerFactory.getLogger(OSGiActorSystemProvider.class);
- @Reference
- AkkaConfigurationReader reader = null;
-
private ActorSystemProviderImpl delegate;
- @Override
- public ActorSystem getActorSystem() {
- return delegate.getActorSystem();
- }
-
- @Override
- public ListenerRegistration<ActorSystemProviderListener> registerActorSystemProviderListener(
- final ActorSystemProviderListener listener) {
- return delegate.registerActorSystemProviderListener(listener);
- }
-
@Activate
- void activate(final BundleContext bundleContext) {
+ public OSGiActorSystemProvider(@Reference final AkkaConfigurationReader reader, final BundleContext bundleContext) {
LOG.info("Actor System provider starting");
- final Config akkaConfig = AkkaConfigFactory.createAkkaConfig(reader);
+ final var akkaConfig = AkkaConfigFactory.createAkkaConfig(reader);
delegate = new ActorSystemProviderImpl(BundleClassLoaderFactory.createClassLoader(bundleContext),
QuarantinedMonitorActorPropsFactory.createProps(bundleContext, akkaConfig), akkaConfig);
LOG.info("Actor System provider started");
delegate = null;
LOG.info("Actor System provider stopped");
}
+
+ @Override
+ public ActorSystem getActorSystem() {
+ return delegate.getActorSystem();
+ }
+
+ @Override
+ public ListenerRegistration<ActorSystemProviderListener> registerActorSystemProviderListener(
+ final ActorSystemProviderListener listener) {
+ return delegate.registerActorSystemProviderListener(listener);
+ }
}
+++ /dev/null
-/*
- * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.cluster.databroker;
-
-import static com.google.common.base.Preconditions.checkState;
-
-import com.google.common.collect.ClassToInstanceMap;
-import com.google.common.collect.ImmutableClassToInstanceMap;
-import com.google.common.collect.ImmutableClassToInstanceMap.Builder;
-import java.util.EnumMap;
-import java.util.Map;
-import java.util.concurrent.atomic.AtomicLong;
-import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
-import org.opendaylight.mdsal.dom.api.DOMDataBrokerExtension;
-import org.opendaylight.mdsal.dom.api.DOMDataTreeChangeListener;
-import org.opendaylight.mdsal.dom.api.DOMDataTreeChangeService;
-import org.opendaylight.mdsal.dom.api.DOMDataTreeCommitCohort;
-import org.opendaylight.mdsal.dom.api.DOMDataTreeCommitCohortRegistration;
-import org.opendaylight.mdsal.dom.api.DOMDataTreeCommitCohortRegistry;
-import org.opendaylight.mdsal.dom.api.DOMDataTreeIdentifier;
-import org.opendaylight.mdsal.dom.api.DOMTransactionChain;
-import org.opendaylight.mdsal.dom.api.DOMTransactionChainListener;
-import org.opendaylight.mdsal.dom.spi.PingPongMergingDOMDataBroker;
-import org.opendaylight.mdsal.dom.spi.store.DOMStore;
-import org.opendaylight.mdsal.dom.spi.store.DOMStoreTransactionChain;
-import org.opendaylight.mdsal.dom.spi.store.DOMStoreTreeChangePublisher;
-import org.opendaylight.yangtools.concepts.ListenerRegistration;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public abstract class AbstractDOMBroker extends AbstractDOMTransactionFactory<DOMStore>
- implements PingPongMergingDOMDataBroker {
-
- private static final Logger LOG = LoggerFactory.getLogger(AbstractDOMBroker.class);
-
- private final AtomicLong txNum = new AtomicLong();
- private final AtomicLong chainNum = new AtomicLong();
- private final ClassToInstanceMap<DOMDataBrokerExtension> extensions;
-
- private volatile AutoCloseable closeable;
-
- protected AbstractDOMBroker(final Map<LogicalDatastoreType, DOMStore> datastores) {
- super(datastores);
-
- Builder<DOMDataBrokerExtension> extBuilder = ImmutableClassToInstanceMap.builder();
- if (isSupported(datastores, DOMStoreTreeChangePublisher.class)) {
- extBuilder.put(DOMDataTreeChangeService.class, new DOMDataTreeChangeService() {
- @Override
- public <L extends DOMDataTreeChangeListener> ListenerRegistration<L> registerDataTreeChangeListener(
- final DOMDataTreeIdentifier treeId, final L listener) {
- DOMStore store = getDOMStore(treeId.getDatastoreType());
- return ((DOMStoreTreeChangePublisher) store).registerTreeChangeListener(
- treeId.getRootIdentifier(), listener);
- }
- });
- }
-
- if (isSupported(datastores, DOMDataTreeCommitCohortRegistry.class)) {
- extBuilder.put(DOMDataTreeCommitCohortRegistry.class, new DOMDataTreeCommitCohortRegistry() {
- @Override
- public <T extends DOMDataTreeCommitCohort> DOMDataTreeCommitCohortRegistration<T> registerCommitCohort(
- final DOMDataTreeIdentifier path, final T cohort) {
- DOMStore store = getDOMStore(path.getDatastoreType());
- return ((DOMDataTreeCommitCohortRegistry) store).registerCommitCohort(path, cohort);
- }
- });
- }
-
- extensions = extBuilder.build();
- }
-
- private static boolean isSupported(final Map<LogicalDatastoreType, DOMStore> datastores,
- final Class<?> expDOMStoreInterface) {
- return datastores.values().stream().allMatch(expDOMStoreInterface::isInstance);
- }
-
- public void setCloseable(final AutoCloseable closeable) {
- this.closeable = closeable;
- }
-
- @Override
- @SuppressWarnings("checkstyle:IllegalCatch")
- public void close() {
- super.close();
-
- if (closeable != null) {
- try {
- closeable.close();
- } catch (Exception e) {
- LOG.debug("Error closing instance", e);
- }
- }
- }
-
- @Override
- protected Object newTransactionIdentifier() {
- return "DOM-" + txNum.getAndIncrement();
- }
-
- @Override
- public ClassToInstanceMap<DOMDataBrokerExtension> getExtensions() {
- return extensions;
- }
-
- @Override
- public DOMTransactionChain createTransactionChain(final DOMTransactionChainListener listener) {
- checkNotClosed();
-
- final Map<LogicalDatastoreType, DOMStoreTransactionChain> backingChains =
- new EnumMap<>(LogicalDatastoreType.class);
- for (Map.Entry<LogicalDatastoreType, DOMStore> entry : getTxFactories().entrySet()) {
- backingChains.put(entry.getKey(), entry.getValue().createTransactionChain());
- }
-
- final long chainId = chainNum.getAndIncrement();
- LOG.debug("Transaction chain {} created with listener {}, backing store chains {}", chainId, listener,
- backingChains);
- return new DOMBrokerTransactionChain(chainId, backingChains, this, listener);
- }
-
- private DOMStore getDOMStore(final LogicalDatastoreType type) {
- DOMStore store = getTxFactories().get(type);
- checkState(store != null, "Requested logical data store is not available.");
- return store;
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.cluster.databroker;
-
-import static com.google.common.base.Preconditions.checkArgument;
-import static java.util.Objects.requireNonNull;
-
-import com.google.common.base.MoreObjects;
-import com.google.common.base.MoreObjects.ToStringHelper;
-import java.lang.invoke.MethodHandles;
-import java.lang.invoke.VarHandle;
-import java.util.Map;
-import java.util.Map.Entry;
-import org.eclipse.jdt.annotation.NonNull;
-import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
-import org.opendaylight.mdsal.common.api.TransactionDatastoreMismatchException;
-import org.opendaylight.mdsal.dom.api.DOMDataTreeTransaction;
-import org.opendaylight.mdsal.dom.spi.store.DOMStoreTransaction;
-import org.opendaylight.mdsal.dom.spi.store.DOMStoreTransactionFactory;
-
-public abstract class AbstractDOMBrokerTransaction<T extends DOMStoreTransaction> implements DOMDataTreeTransaction {
-
- private static final VarHandle BACKING_TX;
-
- static {
- try {
- BACKING_TX = MethodHandles.lookup()
- .findVarHandle(AbstractDOMBrokerTransaction.class, "backingTx", Entry.class);
- } catch (NoSuchFieldException | IllegalAccessException e) {
- throw new ExceptionInInitializerError(e);
- }
- }
-
- private final @NonNull Object identifier;
- private final Map<LogicalDatastoreType, ? extends DOMStoreTransactionFactory> storeTxFactories;
-
- private volatile Entry<LogicalDatastoreType, T> backingTx;
-
- /**
- * Creates new transaction.
- *
- * @param identifier Identifier of transaction.
- */
- protected AbstractDOMBrokerTransaction(final Object identifier,
- Map<LogicalDatastoreType, ? extends DOMStoreTransactionFactory> storeTxFactories) {
- this.identifier = requireNonNull(identifier, "Identifier should not be null");
- this.storeTxFactories = requireNonNull(storeTxFactories, "Store Transaction Factories should not be null");
- checkArgument(!storeTxFactories.isEmpty(), "Store Transaction Factories should not be empty");
- }
-
- /**
- * Returns sub-transaction associated with supplied key.
- *
- * @param datastoreType the data store type
- * @return the sub-transaction
- * @throws NullPointerException if datastoreType is null
- * @throws IllegalArgumentException if no sub-transaction is associated with datastoreType.
- * @throws TransactionDatastoreMismatchException if datastoreType mismatches the one used at first access
- */
- protected final T getSubtransaction(final LogicalDatastoreType datastoreType) {
- requireNonNull(datastoreType, "datastoreType must not be null.");
-
- var entry = backingTx;
- if (entry == null) {
- if (!storeTxFactories.containsKey(datastoreType)) {
- throw new IllegalArgumentException(datastoreType + " is not supported");
- }
- final var tx = createTransaction(datastoreType);
- final var newEntry = Map.entry(datastoreType, tx);
- final var witness = (Entry<LogicalDatastoreType, T>) BACKING_TX.compareAndExchange(this, null, newEntry);
- if (witness != null) {
- tx.close();
- entry = witness;
- } else {
- entry = newEntry;
- }
- }
-
- final var expected = entry.getKey();
- if (expected != datastoreType) {
- throw new TransactionDatastoreMismatchException(expected, datastoreType);
- }
- return entry.getValue();
- }
-
- /**
- * Returns sub-transaction if initialized.
- */
- protected T getSubtransaction() {
- final Entry<LogicalDatastoreType, T> entry;
- return (entry = backingTx) == null ? null : entry.getValue();
- }
-
- protected abstract T createTransaction(LogicalDatastoreType datastoreType);
-
- @Override
- public Object getIdentifier() {
- return identifier;
- }
-
- @SuppressWarnings("checkstyle:IllegalCatch")
- protected void closeSubtransaction() {
- if (backingTx != null) {
- try {
- backingTx.getValue().close();
- } catch (Exception e) {
- throw new IllegalStateException("Uncaught exception occurred during closing transaction", e);
- }
- }
- }
-
- protected DOMStoreTransactionFactory getTxFactory(LogicalDatastoreType type) {
- return storeTxFactories.get(type);
- }
-
- @Override
- public final String toString() {
- return addToStringAttributes(MoreObjects.toStringHelper(this).omitNullValues()).toString();
- }
-
- protected ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
- return toStringHelper.add("identifier", identifier);
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.cluster.databroker;
-
-import static com.google.common.base.Preconditions.checkArgument;
-import static com.google.common.base.Preconditions.checkState;
-import static java.util.Objects.requireNonNull;
-import static org.opendaylight.yangtools.util.concurrent.FluentFutures.immediateFailedFluentFuture;
-
-import com.google.common.base.MoreObjects.ToStringHelper;
-import com.google.common.util.concurrent.FluentFuture;
-import com.google.common.util.concurrent.Futures;
-import java.util.Map;
-import java.util.concurrent.Future;
-import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
-import org.opendaylight.mdsal.common.api.CommitInfo;
-import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
-import org.opendaylight.mdsal.dom.api.DOMDataTreeWriteTransaction;
-import org.opendaylight.mdsal.dom.broker.TransactionCommitFailedExceptionMapper;
-import org.opendaylight.mdsal.dom.spi.store.DOMStoreTransactionFactory;
-import org.opendaylight.mdsal.dom.spi.store.DOMStoreWriteTransaction;
-import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
-import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
-import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public abstract class AbstractDOMBrokerWriteTransaction<T extends DOMStoreWriteTransaction>
- extends AbstractDOMBrokerTransaction<T> implements DOMDataTreeWriteTransaction {
-
- @SuppressWarnings("rawtypes")
- private static final AtomicReferenceFieldUpdater<AbstractDOMBrokerWriteTransaction, AbstractDOMTransactionFactory>
- IMPL_UPDATER = AtomicReferenceFieldUpdater.newUpdater(AbstractDOMBrokerWriteTransaction.class,
- AbstractDOMTransactionFactory.class, "commitImpl");
- @SuppressWarnings("rawtypes")
- private static final AtomicReferenceFieldUpdater<AbstractDOMBrokerWriteTransaction, Future> FUTURE_UPDATER =
- AtomicReferenceFieldUpdater.newUpdater(AbstractDOMBrokerWriteTransaction.class, Future.class,
- "commitFuture");
- private static final Logger LOG = LoggerFactory.getLogger(AbstractDOMBrokerWriteTransaction.class);
- private static final Future<?> CANCELLED_FUTURE = Futures.immediateCancelledFuture();
-
- /**
- * Implementation of real commit. It also acts as an indication that
- * the transaction is running -- which we flip atomically using
- * {@link #IMPL_UPDATER}.
- */
- private volatile AbstractDOMTransactionFactory<?> commitImpl;
-
- /**
- * Future task of transaction commit. It starts off as null, but is
- * set appropriately on {@link #submit()} and {@link #cancel()} via
- * {@link AtomicReferenceFieldUpdater#lazySet(Object, Object)}.
- * <p/>
- * Lazy set is safe for use because it is only referenced to in the
- * {@link #cancel()} slow path, where we will busy-wait for it. The
- * fast path gets the benefit of a store-store barrier instead of the
- * usual store-load barrier.
- */
- private volatile Future<?> commitFuture;
-
- protected AbstractDOMBrokerWriteTransaction(final Object identifier,
- final Map<LogicalDatastoreType, ? extends DOMStoreTransactionFactory> storeTxFactories,
- final AbstractDOMTransactionFactory<?> commitImpl) {
- super(identifier, storeTxFactories);
- this.commitImpl = requireNonNull(commitImpl, "commitImpl must not be null.");
- }
-
- @Override
- public void put(final LogicalDatastoreType store, final YangInstanceIdentifier path, final NormalizedNode data) {
- checkRunning(commitImpl);
- checkInstanceIdentifierReferencesData(path,data);
- getSubtransaction(store).write(path, data);
- }
-
- private static void checkInstanceIdentifierReferencesData(final YangInstanceIdentifier path,
- final NormalizedNode data) {
- checkArgument(data != null, "Attempted to store null data at %s", path);
- final PathArgument lastArg = path.getLastPathArgument();
- if (lastArg != null) {
- checkArgument(lastArg.equals(data.getIdentifier()),
- "Instance identifier references %s but data identifier is %s", lastArg, data);
- }
- }
-
- @Override
- public void delete(final LogicalDatastoreType store, final YangInstanceIdentifier path) {
- checkRunning(commitImpl);
- getSubtransaction(store).delete(path);
- }
-
- @Override
- public void merge(final LogicalDatastoreType store, final YangInstanceIdentifier path, final NormalizedNode data) {
- checkRunning(commitImpl);
- checkInstanceIdentifierReferencesData(path, data);
- getSubtransaction(store).merge(path, data);
- }
-
- @Override
- public boolean cancel() {
- final AbstractDOMTransactionFactory<?> impl = IMPL_UPDATER.getAndSet(this, null);
- if (impl != null) {
- LOG.trace("Transaction {} cancelled before submit", getIdentifier());
- FUTURE_UPDATER.lazySet(this, CANCELLED_FUTURE);
- closeSubtransaction();
- return true;
- }
-
- // The transaction is in process of being submitted or cancelled. Busy-wait
- // for the corresponding future.
- Future<?> future;
- do {
- future = commitFuture;
- }
- while (future == null);
-
- return future.cancel(false);
- }
-
- @Override
- @SuppressWarnings("checkstyle:IllegalCatch")
- public FluentFuture<? extends CommitInfo> commit() {
- final AbstractDOMTransactionFactory<?> impl = IMPL_UPDATER.getAndSet(this, null);
- checkRunning(impl);
-
- FluentFuture<? extends CommitInfo> ret;
- final var tx = getSubtransaction();
- if (tx == null) {
- ret = CommitInfo.emptyFluentFuture();
- } else {
- try {
- ret = impl.commit(this, tx.ready());
- } catch (RuntimeException e) {
- ret = immediateFailedFluentFuture(TransactionCommitFailedExceptionMapper.COMMIT_ERROR_MAPPER.apply(e));
- }
- }
-
- FUTURE_UPDATER.lazySet(this, ret);
- return ret;
- }
-
- private void checkRunning(final AbstractDOMTransactionFactory<?> impl) {
- checkState(impl != null, "Transaction %s is no longer running", getIdentifier());
- }
-
- @Override
- protected ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
- return super.addToStringAttributes(toStringHelper).add("running", commitImpl == null);
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.cluster.databroker;
-
-import com.google.common.base.Preconditions;
-import com.google.common.util.concurrent.FluentFuture;
-import java.lang.invoke.MethodHandles;
-import java.lang.invoke.VarHandle;
-import java.util.EnumMap;
-import java.util.Map;
-import org.opendaylight.mdsal.common.api.CommitInfo;
-import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
-import org.opendaylight.mdsal.dom.api.DOMDataTreeReadTransaction;
-import org.opendaylight.mdsal.dom.api.DOMDataTreeReadWriteTransaction;
-import org.opendaylight.mdsal.dom.api.DOMDataTreeWriteTransaction;
-import org.opendaylight.mdsal.dom.spi.store.DOMStoreThreePhaseCommitCohort;
-import org.opendaylight.mdsal.dom.spi.store.DOMStoreTransactionFactory;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-public abstract class AbstractDOMTransactionFactory<T extends DOMStoreTransactionFactory> implements AutoCloseable {
- private static final Logger LOG = LoggerFactory.getLogger(AbstractDOMTransactionFactory.class);
- private static final VarHandle CLOSED;
-
- static {
- try {
- CLOSED = MethodHandles.lookup().findVarHandle(AbstractDOMTransactionFactory.class, "closed", boolean.class);
- } catch (NoSuchFieldException | IllegalAccessException e) {
- throw new ExceptionInInitializerError(e);
- }
- }
-
- private final Map<LogicalDatastoreType, T> storeTxFactories;
-
- private volatile boolean closed;
-
- protected AbstractDOMTransactionFactory(final Map<LogicalDatastoreType, T> txFactories) {
- this.storeTxFactories = new EnumMap<>(txFactories);
- }
-
- /**
- * Implementations must return unique identifier for each and every call of
- * this method.
- *
- * @return new Unique transaction identifier.
- */
- protected abstract Object newTransactionIdentifier();
-
- /**
- * Submits a transaction asynchronously for commit.
- *
- * @param transaction the transaction to submit
- * @param cohort the associated cohort
- * @return a resulting Future
- */
- protected abstract FluentFuture<? extends CommitInfo> commit(DOMDataTreeWriteTransaction transaction,
- DOMStoreThreePhaseCommitCohort cohort);
-
- /**
- * Creates a new read-only transaction.
- *
- * @return the transaction instance
- */
- public final DOMDataTreeReadTransaction newReadOnlyTransaction() {
- checkNotClosed();
-
- return new DOMBrokerReadOnlyTransaction(newTransactionIdentifier(), storeTxFactories);
- }
-
-
- /**
- * Creates a new write-only transaction.
- *
- * @return the transaction instance
- */
- public final DOMDataTreeWriteTransaction newWriteOnlyTransaction() {
- checkNotClosed();
-
- return new DOMBrokerWriteOnlyTransaction(newTransactionIdentifier(), storeTxFactories, this);
- }
-
-
- /**
- * Creates a new read-write transaction.
- *
- * @return the transaction instance
- */
- public final DOMDataTreeReadWriteTransaction newReadWriteTransaction() {
- checkNotClosed();
-
- return new DOMBrokerReadWriteTransaction(newTransactionIdentifier(), storeTxFactories, this);
- }
-
- /**
- * Convenience accessor of backing factories intended to be used only by
- * finalization of this class.
- *
- * <b>Note:</b>
- * Finalization of this class may want to access other functionality of
- * supplied Transaction factories.
- *
- * @return Map of backing transaction factories.
- */
- public final Map<LogicalDatastoreType, T> getTxFactories() {
- return storeTxFactories;
- }
-
- /**
- * Checks if instance is not closed.
- *
- * @throws IllegalStateException If instance of this class was closed.
- *
- */
- protected final void checkNotClosed() {
- Preconditions.checkState(!closed, "Transaction factory was closed. No further operations allowed.");
- }
-
- @Override
- public void close() {
- if (!CLOSED.compareAndSet(this, false, true)) {
- LOG.warn("Transaction factory was already closed", new Throwable());
- }
- }
-}
import static com.google.common.base.Preconditions.checkArgument;
import static java.util.Objects.requireNonNull;
-import static org.opendaylight.mdsal.dom.broker.TransactionCommitFailedExceptionMapper.CAN_COMMIT_ERROR_MAPPER;
-import static org.opendaylight.mdsal.dom.broker.TransactionCommitFailedExceptionMapper.COMMIT_ERROR_MAPPER;
-import static org.opendaylight.mdsal.dom.broker.TransactionCommitFailedExceptionMapper.PRE_COMMIT_MAPPER;
+import static org.opendaylight.mdsal.dom.spi.TransactionCommitFailedExceptionMapper.CAN_COMMIT_ERROR_MAPPER;
+import static org.opendaylight.mdsal.dom.spi.TransactionCommitFailedExceptionMapper.COMMIT_ERROR_MAPPER;
+import static org.opendaylight.mdsal.dom.spi.TransactionCommitFailedExceptionMapper.PRE_COMMIT_MAPPER;
import com.google.common.annotations.Beta;
import com.google.common.util.concurrent.AbstractFuture;
import org.opendaylight.mdsal.common.api.DataStoreUnavailableException;
import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
import org.opendaylight.mdsal.common.api.TransactionCommitFailedException;
+import org.opendaylight.mdsal.dom.api.DOMDataBroker;
import org.opendaylight.mdsal.dom.api.DOMDataTreeWriteTransaction;
-import org.opendaylight.mdsal.dom.broker.TransactionCommitFailedExceptionMapper;
+import org.opendaylight.mdsal.dom.spi.AbstractDOMDataBroker;
+import org.opendaylight.mdsal.dom.spi.TransactionCommitFailedExceptionMapper;
import org.opendaylight.mdsal.dom.spi.store.DOMStore;
import org.opendaylight.mdsal.dom.spi.store.DOMStoreThreePhaseCommitCohort;
import org.opendaylight.yangtools.util.DurationStatisticsTracker;
import org.opendaylight.yangtools.yang.common.Empty;
+import org.osgi.service.component.annotations.Activate;
+import org.osgi.service.component.annotations.Component;
+import org.osgi.service.component.annotations.Deactivate;
+import org.osgi.service.component.annotations.Reference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
* @author Thomas Pantelis
*/
@Beta
-public class ConcurrentDOMDataBroker extends AbstractDOMBroker {
+@Component(service = DOMDataBroker.class, property = "type=default")
+public class ConcurrentDOMDataBroker extends AbstractDOMDataBroker {
private static final Logger LOG = LoggerFactory.getLogger(ConcurrentDOMDataBroker.class);
private static final String CAN_COMMIT = "CAN_COMMIT";
private static final String PRE_COMMIT = "PRE_COMMIT";
this.commitStatsTracker = requireNonNull(commitStatsTracker);
}
- public DurationStatisticsTracker getCommitStatsTracker() {
- return commitStatsTracker;
+ @Activate
+ public ConcurrentDOMDataBroker(@Reference final DataBrokerCommitExecutor commitExecutor,
+ @Reference(target = "(type=distributed-config)") final DOMStore configDatastore,
+ @Reference(target = "(type=distributed-operational)") final DOMStore operDatastore) {
+ this(Map.of(
+ LogicalDatastoreType.CONFIGURATION, configDatastore, LogicalDatastoreType.OPERATIONAL, operDatastore),
+ commitExecutor.executor(), commitExecutor.commitStatsTracker());
+ LOG.info("DOM Data Broker started");
+ }
+
+ @Override
+ @Deactivate
+ public void close() {
+ LOG.info("DOM Data Broker stopping");
+ super.close();
+ LOG.info("DOM Data Broker stopped");
}
@Override
checkArgument(cohort != null, "Cohorts must not be null.");
LOG.debug("Tx: {} is submitted for execution.", transaction.getIdentifier());
- final AsyncNotifyingSettableFuture clientSubmitFuture =
- new AsyncNotifyingSettableFuture(clientFutureCallbackExecutor);
-
+ final var clientSubmitFuture = new AsyncNotifyingSettableFuture(clientFutureCallbackExecutor);
doCanCommit(clientSubmitFuture, transaction, cohort);
return FluentFuture.from(clientSubmitFuture);
}
final Exception e;
if (throwable instanceof NoShardLeaderException || throwable instanceof ShardLeaderNotRespondingException) {
e = new DataStoreUnavailableException(throwable.getMessage(), throwable);
- } else if (throwable instanceof Exception) {
- e = (Exception) throwable;
+ } else if (throwable instanceof Exception ex) {
+ e = ex;
} else {
e = new RuntimeException("Unexpected error occurred", throwable);
}
+++ /dev/null
-/*
- * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.cluster.databroker;
-
-import com.google.common.util.concurrent.FluentFuture;
-import java.util.Map;
-import java.util.Optional;
-import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
-import org.opendaylight.mdsal.dom.api.DOMDataTreeReadTransaction;
-import org.opendaylight.mdsal.dom.spi.store.DOMStoreReadTransaction;
-import org.opendaylight.mdsal.dom.spi.store.DOMStoreTransactionFactory;
-import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
-import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
-
-public class DOMBrokerReadOnlyTransaction
- extends AbstractDOMBrokerTransaction<DOMStoreReadTransaction> implements DOMDataTreeReadTransaction {
-
- /**
- * Creates new composite Transactions.
- *
- * @param identifier Identifier of transaction.
- */
- protected DOMBrokerReadOnlyTransaction(final Object identifier,
- final Map<LogicalDatastoreType, ? extends DOMStoreTransactionFactory> storeTxFactories) {
- super(identifier, storeTxFactories);
- }
-
- @Override
- public FluentFuture<Optional<NormalizedNode>> read(final LogicalDatastoreType store,
- final YangInstanceIdentifier path) {
- return getSubtransaction(store).read(path);
- }
-
- @Override
- public FluentFuture<Boolean> exists(final LogicalDatastoreType store, final YangInstanceIdentifier path) {
- return getSubtransaction(store).exists(path);
- }
-
- @Override
- public void close() {
- closeSubtransaction();
- }
-
- @Override
- protected DOMStoreReadTransaction createTransaction(final LogicalDatastoreType key) {
- return getTxFactory(key).newReadOnlyTransaction();
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.cluster.databroker;
-
-import com.google.common.util.concurrent.FluentFuture;
-import java.util.Map;
-import java.util.Optional;
-import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
-import org.opendaylight.mdsal.dom.api.DOMDataTreeReadWriteTransaction;
-import org.opendaylight.mdsal.dom.spi.store.DOMStoreReadWriteTransaction;
-import org.opendaylight.mdsal.dom.spi.store.DOMStoreTransactionFactory;
-import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
-import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
-
-public class DOMBrokerReadWriteTransaction extends AbstractDOMBrokerWriteTransaction<DOMStoreReadWriteTransaction>
- implements DOMDataTreeReadWriteTransaction {
-
- /**
- * Constructs an instance.
- *
- * @param identifier identifier of transaction.
- * @param storeTxFactories the backing transaction store factories
- */
- protected DOMBrokerReadWriteTransaction(final Object identifier,
- final Map<LogicalDatastoreType, ? extends DOMStoreTransactionFactory> storeTxFactories,
- final AbstractDOMTransactionFactory<?> commitImpl) {
- super(identifier, storeTxFactories, commitImpl);
- }
-
- @Override
- public FluentFuture<Optional<NormalizedNode>> read(final LogicalDatastoreType store,
- final YangInstanceIdentifier path) {
- return getSubtransaction(store).read(path);
- }
-
- @Override
- public FluentFuture<Boolean> exists(final LogicalDatastoreType store, final YangInstanceIdentifier path) {
- return getSubtransaction(store).exists(path);
- }
-
- @Override
- protected DOMStoreReadWriteTransaction createTransaction(final LogicalDatastoreType key) {
- return getTxFactory(key).newReadWriteTransaction();
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.cluster.databroker;
-
-import static com.google.common.base.Preconditions.checkState;
-import static java.util.Objects.requireNonNull;
-
-import com.google.common.util.concurrent.FluentFuture;
-import com.google.common.util.concurrent.FutureCallback;
-import com.google.common.util.concurrent.MoreExecutors;
-import java.util.Map;
-import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;
-import java.util.concurrent.atomic.AtomicLong;
-import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
-import org.opendaylight.mdsal.common.api.CommitInfo;
-import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
-import org.opendaylight.mdsal.dom.api.DOMDataTreeWriteTransaction;
-import org.opendaylight.mdsal.dom.api.DOMTransactionChain;
-import org.opendaylight.mdsal.dom.api.DOMTransactionChainListener;
-import org.opendaylight.mdsal.dom.spi.store.DOMStoreThreePhaseCommitCohort;
-import org.opendaylight.mdsal.dom.spi.store.DOMStoreTransactionChain;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-final class DOMBrokerTransactionChain extends AbstractDOMTransactionFactory<DOMStoreTransactionChain>
- implements DOMTransactionChain {
- private enum State {
- RUNNING,
- CLOSING,
- CLOSED,
- FAILED,
- }
-
- private static final AtomicIntegerFieldUpdater<DOMBrokerTransactionChain> COUNTER_UPDATER =
- AtomicIntegerFieldUpdater.newUpdater(DOMBrokerTransactionChain.class, "counter");
- private static final AtomicReferenceFieldUpdater<DOMBrokerTransactionChain, State> STATE_UPDATER =
- AtomicReferenceFieldUpdater.newUpdater(DOMBrokerTransactionChain.class, State.class, "state");
- private static final Logger LOG = LoggerFactory.getLogger(DOMBrokerTransactionChain.class);
- private final AtomicLong txNum = new AtomicLong();
- private final AbstractDOMBroker broker;
- private final DOMTransactionChainListener listener;
- private final long chainId;
-
- private volatile State state = State.RUNNING;
- private volatile int counter = 0;
-
- /**
- * Constructs an instance.
- *
- * @param chainId
- * ID of transaction chain
- * @param chains
- * Backing {@link DOMStoreTransactionChain}s.
- * @param listener
- * Listener, which listens on transaction chain events.
- * @throws NullPointerException
- * If any of arguments is null.
- */
- DOMBrokerTransactionChain(final long chainId, final Map<LogicalDatastoreType, DOMStoreTransactionChain> chains,
- final AbstractDOMBroker broker, final DOMTransactionChainListener listener) {
- super(chains);
- this.chainId = chainId;
- this.broker = requireNonNull(broker);
- this.listener = requireNonNull(listener);
- }
-
- private void checkNotFailed() {
- checkState(state != State.FAILED, "Transaction chain has failed");
- }
-
- @Override
- protected Object newTransactionIdentifier() {
- return "DOM-CHAIN-" + chainId + "-" + txNum.getAndIncrement();
- }
-
- @Override
- public FluentFuture<? extends CommitInfo> commit(
- final DOMDataTreeWriteTransaction transaction, final DOMStoreThreePhaseCommitCohort cohort) {
- checkNotFailed();
- checkNotClosed();
-
- final FluentFuture<? extends CommitInfo> ret = broker.commit(transaction, cohort);
-
- COUNTER_UPDATER.incrementAndGet(this);
- ret.addCallback(new FutureCallback<CommitInfo>() {
- @Override
- public void onSuccess(final CommitInfo result) {
- transactionCompleted();
- }
-
- @Override
- public void onFailure(final Throwable failure) {
- transactionFailed(transaction, failure);
- }
- }, MoreExecutors.directExecutor());
-
- return ret;
- }
-
- @Override
- public void close() {
- final boolean success = STATE_UPDATER.compareAndSet(this, State.RUNNING, State.CLOSING);
- if (!success) {
- LOG.debug("Chain {} is no longer running", this);
- return;
- }
-
- super.close();
- for (DOMStoreTransactionChain subChain : getTxFactories().values()) {
- subChain.close();
- }
-
- if (counter == 0) {
- finishClose();
- }
- }
-
- private void finishClose() {
- state = State.CLOSED;
- listener.onTransactionChainSuccessful(this);
- }
-
- private void transactionCompleted() {
- if (COUNTER_UPDATER.decrementAndGet(this) == 0 && state == State.CLOSING) {
- finishClose();
- }
- }
-
- private void transactionFailed(final DOMDataTreeWriteTransaction tx, final Throwable cause) {
- state = State.FAILED;
- LOG.debug("Transaction chain {} failed.", this, cause);
- listener.onTransactionChainFailed(this, tx, cause);
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2015 Huawei Technologies Co. Ltd. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.cluster.databroker;
-
-import java.util.Map;
-import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
-import org.opendaylight.mdsal.dom.spi.store.DOMStoreTransactionFactory;
-import org.opendaylight.mdsal.dom.spi.store.DOMStoreWriteTransaction;
-
-public class DOMBrokerWriteOnlyTransaction extends AbstractDOMBrokerWriteTransaction<DOMStoreWriteTransaction> {
-
- /**
- * Constructs an instance.
- *
- * @param identifier identifier of transaction.
- * @param storeTxFactories the backing transaction store factories
- */
- public DOMBrokerWriteOnlyTransaction(Object identifier,
- Map<LogicalDatastoreType, ? extends DOMStoreTransactionFactory> storeTxFactories,
- AbstractDOMTransactionFactory<?> commitImpl) {
- super(identifier, storeTxFactories, commitImpl);
- }
-
- @Override
- protected DOMStoreWriteTransaction createTransaction(LogicalDatastoreType key) {
- return getTxFactory(key).newWriteOnlyTransaction();
- }
-
-}
--- /dev/null
+/*
+ * Copyright (c) 2024 PANTHEON.tech, s.r.o. and others. All rights reserved.
+ *
+ * This program and the accompanying materials are made available under the
+ * terms of the Eclipse Public License v1.0 which accompanies this distribution,
+ * and is available at http://www.eclipse.org/legal/epl-v10.html
+ */
+package org.opendaylight.controller.cluster.databroker;
+
+import java.util.concurrent.Executor;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.TimeUnit;
+import org.opendaylight.controller.md.sal.common.util.jmx.ThreadExecutorStatsMXBeanImpl;
+import org.opendaylight.yangtools.util.DurationStatisticsTracker;
+import org.opendaylight.yangtools.util.concurrent.SpecialExecutors;
+import org.osgi.service.component.annotations.Activate;
+import org.osgi.service.component.annotations.Component;
+import org.osgi.service.component.annotations.Deactivate;
+import org.osgi.service.metatype.annotations.AttributeDefinition;
+import org.osgi.service.metatype.annotations.Designate;
+import org.osgi.service.metatype.annotations.ObjectClassDefinition;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+@Component(
+ service = DataBrokerCommitExecutor.class,
+ configurationPid = "org.opendaylight.controller.cluster.datastore.broker")
+@Designate(ocd = DataBrokerCommitExecutor.Config.class)
+public final class DataBrokerCommitExecutor {
+ @ObjectClassDefinition
+ public @interface Config {
+ @AttributeDefinition(name = "max-data-broker-future-callback-queue-size")
+ int callbackQueueSize() default 1000;
+ @AttributeDefinition(name = "max-data-broker-future-callback-pool-size")
+ int callbackPoolSize() default 20;
+ }
+
+ private static final Logger LOG = LoggerFactory.getLogger(DataBrokerCommitExecutor.class);
+
+ private final DurationStatisticsTracker commitStatsTracker = DurationStatisticsTracker.createConcurrent();
+ private final ThreadExecutorStatsMXBeanImpl threadStats;
+ private final CommitStatsMXBeanImpl commitStats;
+ private final ExecutorService executorService;
+
+ @Activate
+ public DataBrokerCommitExecutor(final Config config) {
+ executorService = SpecialExecutors.newBlockingBoundedCachedThreadPool(config.callbackPoolSize(),
+ config.callbackQueueSize(), "CommitFutures", ConcurrentDOMDataBroker.class);
+ threadStats = ThreadExecutorStatsMXBeanImpl.create(executorService, "CommitFutureExecutorStats",
+ "DOMDataBroker");
+ commitStats = new CommitStatsMXBeanImpl(commitStatsTracker, "DOMDataBroker");
+ commitStats.register();
+ LOG.info("DOM Data Broker commit exector started");
+ }
+
+ @Deactivate
+ void deactivate() {
+ LOG.info("DOM Data Broker commit exector stopping");
+ commitStats.unregister();
+ threadStats.unregister();
+ executorService.shutdown();
+ try {
+ executorService.awaitTermination(1, TimeUnit.MINUTES);
+ } catch (InterruptedException e) {
+ LOG.warn("Future executor failed to finish in time, giving up", e);
+ }
+ LOG.info("DOM Data Broker commit exector stopped");
+ }
+
+ Executor executor() {
+ return executorService;
+ }
+
+ DurationStatisticsTracker commitStatsTracker() {
+ return commitStatsTracker;
+ }
+}
+++ /dev/null
-/*
- * Copyright (c) 2020 PANTHEON.tech, s.r.o. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.cluster.databroker;
-
-import com.google.common.annotations.Beta;
-import com.google.common.collect.ClassToInstanceMap;
-import com.google.common.collect.ImmutableMap;
-import java.util.concurrent.ExecutorService;
-import java.util.concurrent.TimeUnit;
-import org.opendaylight.controller.md.sal.common.util.jmx.ThreadExecutorStatsMXBeanImpl;
-import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
-import org.opendaylight.mdsal.dom.api.DOMDataBroker;
-import org.opendaylight.mdsal.dom.api.DOMDataBrokerExtension;
-import org.opendaylight.mdsal.dom.api.DOMDataTreeReadTransaction;
-import org.opendaylight.mdsal.dom.api.DOMDataTreeReadWriteTransaction;
-import org.opendaylight.mdsal.dom.api.DOMDataTreeWriteTransaction;
-import org.opendaylight.mdsal.dom.api.DOMTransactionChain;
-import org.opendaylight.mdsal.dom.api.DOMTransactionChainListener;
-import org.opendaylight.mdsal.dom.spi.store.DOMStore;
-import org.opendaylight.yangtools.util.DurationStatisticsTracker;
-import org.opendaylight.yangtools.util.concurrent.SpecialExecutors;
-import org.osgi.service.component.annotations.Activate;
-import org.osgi.service.component.annotations.Component;
-import org.osgi.service.component.annotations.Deactivate;
-import org.osgi.service.component.annotations.Reference;
-import org.osgi.service.metatype.annotations.AttributeDefinition;
-import org.osgi.service.metatype.annotations.Designate;
-import org.osgi.service.metatype.annotations.ObjectClassDefinition;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-@Beta
-@Component(immediate = true, configurationPid = "org.opendaylight.controller.cluster.datastore.broker",
- property = "type=default")
-@Designate(ocd = OSGiDOMDataBroker.Config.class)
-public final class OSGiDOMDataBroker implements DOMDataBroker {
- @ObjectClassDefinition
- public @interface Config {
- @AttributeDefinition(name = "max-data-broker-future-callback-queue-size")
- int callbackQueueSize() default 1000;
- @AttributeDefinition(name = "max-data-broker-future-callback-pool-size")
- int callbackPoolSize() default 20;
- }
-
- private static final Logger LOG = LoggerFactory.getLogger(OSGiDOMDataBroker.class);
-
- @Reference(target = "(type=distributed-config)")
- DOMStore configDatastore = null;
- @Reference(target = "(type=distributed-operational)")
- DOMStore operDatastore = null;
-
- private ExecutorService executorService;
- private ConcurrentDOMDataBroker delegate;
- private CommitStatsMXBeanImpl commitStats;
- private ThreadExecutorStatsMXBeanImpl threadStats;
-
- @Override
- public DOMDataTreeReadTransaction newReadOnlyTransaction() {
- return delegate.newReadOnlyTransaction();
- }
-
- @Override
- public DOMDataTreeWriteTransaction newWriteOnlyTransaction() {
- return delegate.newWriteOnlyTransaction();
- }
-
- @Override
- public DOMDataTreeReadWriteTransaction newReadWriteTransaction() {
- return delegate.newReadWriteTransaction();
- }
-
- @Override
- public ClassToInstanceMap<DOMDataBrokerExtension> getExtensions() {
- return delegate.getExtensions();
- }
-
- @Override
- public DOMTransactionChain createTransactionChain(final DOMTransactionChainListener listener) {
- return delegate.createTransactionChain(listener);
- }
-
- @Override
- public DOMTransactionChain createMergingTransactionChain(final DOMTransactionChainListener listener) {
- return delegate.createMergingTransactionChain(listener);
- }
-
- @Activate
- void activate(final Config config) {
- LOG.info("DOM Data Broker starting");
- final DurationStatisticsTracker commitStatsTracker = DurationStatisticsTracker.createConcurrent();
-
- executorService = SpecialExecutors.newBlockingBoundedCachedThreadPool(config.callbackPoolSize(),
- config.callbackQueueSize(), "CommitFutures", ConcurrentDOMDataBroker.class);
- delegate = new ConcurrentDOMDataBroker(ImmutableMap.of(
- LogicalDatastoreType.CONFIGURATION, configDatastore, LogicalDatastoreType.OPERATIONAL, operDatastore),
- executorService, commitStatsTracker);
-
- commitStats = new CommitStatsMXBeanImpl(commitStatsTracker, "DOMDataBroker");
- commitStats.register();
- threadStats = ThreadExecutorStatsMXBeanImpl.create(executorService, "CommitFutureExecutorStats",
- "DOMDataBroker");
-
- LOG.info("DOM Data Broker started");
- }
-
- @Deactivate
- void deactivate() {
- LOG.info("DOM Data Broker stopping");
- commitStats.unregister();
- if (threadStats != null) {
- threadStats.unregister();
- }
-
- delegate.close();
- executorService.shutdown();
- try {
- executorService.awaitTermination(1, TimeUnit.MINUTES);
- } catch (InterruptedException e) {
- LOG.warn("Future executor failed to finish in time, giving up", e);
- }
- LOG.info("DOM Data Broker stopped");
- }
-}
* <p>
* This class interacts with the queueing mechanism in ClientActorBehavior, hence once we arrive at a decision
* to use either a local or remote implementation, we are stuck with it. We can re-evaluate on the next transaction.
- *
- * @author Robert Varga
*/
-// FIXME: sealed when we have JDK17+
-abstract class AbstractProxyTransaction implements Identifiable<TransactionIdentifier> {
+abstract sealed class AbstractProxyTransaction implements Identifiable<TransactionIdentifier>
+ permits LocalProxyTransaction, RemoteProxyTransaction {
/**
* Marker object used instead of read-type of requests, which are satisfied only once. This has a lower footprint
* and allows compressing multiple requests into a single entry. This class is not thread-safe.
// Propagate state and seal the successor.
final Optional<ModifyTransactionRequest> optState = flushState();
if (optState.isPresent()) {
- forwardToSuccessor(successor, optState.get(), null);
+ forwardToSuccessor(successor, optState.orElseThrow(), null);
}
successor.predecessorSealed();
}
final long enqueuedTicks = parent.currentTime();
final Optional<ModifyTransactionRequest> optState = flushState();
if (optState.isPresent()) {
- successor.handleReplayedRemoteRequest(optState.get(), null, enqueuedTicks);
+ successor.handleReplayedRemoteRequest(optState.orElseThrow(), null, enqueuedTicks);
}
if (successor.markSealed()) {
successor.sealAndSend(OptionalLong.of(enqueuedTicks));
// FIXME: we really need just ActorContext.findPrimaryShardAsync()
AbstractShardBackendResolver(final ClientIdentifier clientId, final ActorUtils actorUtils) {
this.actorUtils = requireNonNull(actorUtils);
- connectFunction = ExplicitAsk.toScala(t -> new ConnectClientRequest(clientId, t, ABIVersion.MAGNESIUM,
+ connectFunction = ExplicitAsk.toScala(t -> new ConnectClientRequest(clientId, t, ABIVersion.POTASSIUM,
ABIVersion.current()));
}
return () -> staleBackendInfoCallbacks.remove(callback);
}
- protected void notifyStaleBackendInfoCallbacks(Long cookie) {
+ protected void notifyStaleBackendInfoCallbacks(final Long cookie) {
staleBackendInfoCallbacks.forEach(callback -> callback.accept(cookie));
}
private FluentFuture<Optional<NormalizedNode>> readRoot() {
return RootScatterGather.gather(parent().actorUtils(), ensureAllProxies()
- .map(proxy -> proxy.read(YangInstanceIdentifier.empty())));
+ .map(proxy -> proxy.read(YangInstanceIdentifier.of())));
}
@Override
private FluentFuture<Optional<NormalizedNode>> readRoot() {
return RootScatterGather.gather(parent().actorUtils(), ensureAllProxies()
- .map(proxy -> proxy.read(YangInstanceIdentifier.empty())));
+ .map(proxy -> proxy.read(YangInstanceIdentifier.of())));
}
public void delete(final YangInstanceIdentifier path) {
if (path.isEmpty()) {
- ensureAllProxies().forEach(proxy -> proxy.delete(YangInstanceIdentifier.empty()));
+ ensureAllProxies().forEach(proxy -> proxy.delete(YangInstanceIdentifier.of()));
} else {
ensureProxy(path).delete(path);
}
private void mergeRoot(final @NonNull ContainerNode rootData) {
if (!rootData.isEmpty()) {
RootScatterGather.scatterTouched(rootData, this::ensureProxy).forEach(
- scattered -> scattered.shard().merge(YangInstanceIdentifier.empty(), scattered.container()));
+ scattered -> scattered.shard().merge(YangInstanceIdentifier.of(), scattered.container()));
}
}
private void writeRoot(final @NonNull ContainerNode rootData) {
RootScatterGather.scatterAll(rootData, this::ensureProxy, ensureAllProxies()).forEach(
- scattered -> scattered.shard().write(YangInstanceIdentifier.empty(), scattered.container()));
+ scattered -> scattered.shard().write(YangInstanceIdentifier.of(), scattered.container()));
}
private AbstractProxyTransaction ensureProxy(final PathArgument childId) {
- return ensureProxy(YangInstanceIdentifier.create(childId));
+ return ensureProxy(YangInstanceIdentifier.of(childId));
}
public DOMStoreThreePhaseCommitCohort ready() {
final AbstractClientHistory parent = parent();
parent.onTransactionShardsBound(txId, participants.keySet());
- final AbstractTransactionCommitCohort cohort;
- switch (toReady.size()) {
- case 0:
- cohort = new EmptyTransactionCommitCohort(parent, txId);
- break;
- case 1:
- cohort = new DirectTransactionCommitCohort(parent, txId, toReady.iterator().next());
- break;
- default:
- cohort = new ClientTransactionCommitCohort(parent, txId, toReady);
- break;
- }
-
+ final AbstractTransactionCommitCohort cohort = switch (toReady.size()) {
+ case 0 -> new EmptyTransactionCommitCohort(parent, txId);
+ case 1 -> new DirectTransactionCommitCohort(parent, txId, toReady.iterator().next());
+ default -> new ClientTransactionCommitCohort(parent, txId, toReady);
+ };
return parent.onTransactionReady(this, cohort);
}
import org.opendaylight.yangtools.yang.data.tree.api.DataTreeModificationCursor;
import org.opendaylight.yangtools.yang.data.tree.api.DataTreeSnapshot;
import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
-import org.opendaylight.yangtools.yang.model.spi.AbstractEffectiveModelContextProvider;
/**
* A {@link CursorAwareDataTreeModification} which does not really do anything and throws an
* {@link DataTreeSnapshot#newModification()} fails, see {@link LocalReadWriteProxyTransaction} for details. Surrounding
* code should guard against invocation of most of these methods.
*/
-final class FailedDataTreeModification extends AbstractEffectiveModelContextProvider
- implements CursorAwareDataTreeModification {
- private final @NonNull Exception cause;
+record FailedDataTreeModification(
+ @NonNull EffectiveModelContext modelContext,
+ @NonNull Exception cause) implements CursorAwareDataTreeModification {
- FailedDataTreeModification(final EffectiveModelContext context, final Exception cause) {
- super(context);
- this.cause = requireNonNull(cause);
- }
-
- @NonNull Exception cause() {
- return cause;
+ FailedDataTreeModification {
+ requireNonNull(modelContext);
+ requireNonNull(cause);
}
@Override
* <p>
* This class is not thread-safe as usual with transactions. Since it does not interact with the backend until the
* transaction is submitted, at which point this class gets out of the picture, this is not a cause for concern.
- *
- * @author Robert Varga
*/
-// FIXME: sealed when we have JDK17+
-abstract class LocalProxyTransaction extends AbstractProxyTransaction {
+abstract sealed class LocalProxyTransaction extends AbstractProxyTransaction
+ permits LocalReadOnlyProxyTransaction, LocalReadWriteProxyTransaction {
private static final Logger LOG = LoggerFactory.getLogger(LocalProxyTransaction.class);
private final @NonNull TransactionIdentifier identifier;
@Override
final void forwardToRemote(final RemoteProxyTransaction successor, final TransactionRequest<?> request,
final Consumer<Response<?, ?>> callback) {
- if (request instanceof CommitLocalTransactionRequest) {
- final CommitLocalTransactionRequest req = (CommitLocalTransactionRequest) request;
+ if (request instanceof final CommitLocalTransactionRequest req) {
final DataTreeModification mod = req.getModification();
LOG.debug("Applying modification {} to successor {}", mod, successor);
private static void commonModifyTransactionRequest(final ModifyTransactionRequest request) {
verify(request.getModifications().isEmpty());
- final PersistenceProtocol protocol = request.getPersistenceProtocol().get();
+ final PersistenceProtocol protocol = request.getPersistenceProtocol().orElseThrow();
verify(protocol == PersistenceProtocol.ABORT);
}
}
} catch (Exception e) {
LOG.debug("Failed to instantiate modification for {}", identifier, e);
recordedFailure = e;
- mod = new FailedDataTreeModification(snapshot.getEffectiveModelContext(), e);
+ mod = new FailedDataTreeModification(snapshot.modelContext(), e);
}
modification = mod;
}
sealOnly();
}
- switch (maybeProtocol.get()) {
+ switch (maybeProtocol.orElseThrow()) {
case ABORT:
sendMethod.accept(new AbortLocalTransactionRequest(getIdentifier(), localActor()), cb);
break;
sendMethod.accept(commitRequest(true), cb);
break;
default:
- throw new IllegalArgumentException("Unhandled protocol " + maybeProtocol.get());
+ throw new IllegalArgumentException("Unhandled protocol " + maybeProtocol.orElseThrow());
}
}
}
*/
package org.opendaylight.controller.cluster.databroker.actors.dds;
-import static akka.pattern.Patterns.ask;
import static com.google.common.base.Verify.verifyNotNull;
import akka.dispatch.ExecutionContexts;
import akka.dispatch.OnComplete;
+import akka.pattern.Patterns;
import akka.util.Timeout;
import com.google.common.collect.ImmutableBiMap;
import java.util.concurrent.CompletionStage;
ModuleShardBackendResolver(final ClientIdentifier clientId, final ActorUtils actorUtils) {
super(clientId, actorUtils);
- shardAvailabilityChangesRegFuture = ask(actorUtils.getShardManager(), new RegisterForShardAvailabilityChanges(
- this::onShardAvailabilityChange), Timeout.apply(60, TimeUnit.MINUTES))
+ shardAvailabilityChangesRegFuture = Patterns.ask(actorUtils.getShardManager(),
+ new RegisterForShardAvailabilityChanges(this::onShardAvailabilityChange),
+ Timeout.apply(60, TimeUnit.MINUTES))
.map(reply -> (Registration)reply, ExecutionContexts.global());
shardAvailabilityChangesRegFuture.onComplete(new OnComplete<Registration>() {
static ProxyHistory createClient(final AbstractClientHistory parent,
final AbstractClientConnection<ShardBackendInfo> connection, final LocalHistoryIdentifier identifier) {
final Optional<ReadOnlyDataTree> dataTree = connection.getBackendInfo().flatMap(ShardBackendInfo::getDataTree);
- return dataTree.isPresent() ? new Local(parent, connection, identifier, dataTree.get())
+ return dataTree.isPresent() ? new Local(parent, connection, identifier, dataTree.orElseThrow())
: new Remote(parent, connection, identifier);
}
final AbstractClientConnection<ShardBackendInfo> connection,
final LocalHistoryIdentifier identifier) {
final Optional<ReadOnlyDataTree> dataTree = connection.getBackendInfo().flatMap(ShardBackendInfo::getDataTree);
- return dataTree.isPresent() ? new LocalSingle(parent, connection, identifier, dataTree.get())
+ return dataTree.isPresent() ? new LocalSingle(parent, connection, identifier, dataTree.orElseThrow())
: new RemoteSingle(parent, connection, identifier);
}
* <p>
* This class is not safe to access from multiple application threads, as is usual for transactions. Its internal state
* transitions based on backend responses are thread-safe.
- *
- * @author Robert Varga
*/
final class RemoteProxyTransaction extends AbstractProxyTransaction {
private static final Logger LOG = LoggerFactory.getLogger(RemoteProxyTransaction.class);
- // FIXME: make this tuneable
- private static final int REQUEST_MAX_MODIFICATIONS = 1000;
-
private final ModifyTransactionRequestBuilder builder;
private final boolean sendReadyOnSeal;
private final boolean snapshotOnly;
+ private final int maxModifications;
private boolean builderBusy;
this.snapshotOnly = snapshotOnly;
this.sendReadyOnSeal = sendReadyOnSeal;
builder = new ModifyTransactionRequestBuilder(identifier, localActor());
+ maxModifications = parent.parent().actorUtils().getDatastoreContext().getShardBatchedModificationCount();
}
@Override
private void sendModification(final TransactionRequest<?> request, final OptionalLong enqueuedTicks) {
if (enqueuedTicks.isPresent()) {
- enqueueRequest(request, response -> completeModify(request, response), enqueuedTicks.getAsLong());
+ enqueueRequest(request, response -> completeModify(request, response), enqueuedTicks.orElseThrow());
} else {
sendRequest(request, response -> completeModify(request, response));
}
ensureInitializedBuilder();
builder.addModification(modification);
- if (builder.size() >= REQUEST_MAX_MODIFICATIONS) {
+ if (builder.size() >= maxModifications) {
flushBuilder(enqueuedTicks);
}
} else {
private Exception recordFailedResponse(final Response<?, ?> response) {
final Exception failure;
- if (response instanceof RequestFailure) {
- final RequestException cause = ((RequestFailure<?, ?>) response).getCause();
+ if (response instanceof RequestFailure<?, ?> requestFailure) {
+ final RequestException cause = requestFailure.getCause();
failure = cause instanceof RequestTimeoutException
? new DataStoreUnavailableException(cause.getMessage(), cause) : cause;
} else {
final Response<?, ?> response) {
LOG.debug("Exists request for {} completed with {}", path, response);
- if (response instanceof ExistsTransactionSuccess) {
- future.set(((ExistsTransactionSuccess) response).getExists());
+ if (response instanceof ExistsTransactionSuccess success) {
+ future.set(success.getExists());
} else {
failReadFuture(future, "Error executing exists request for path " + path, response);
}
final Response<?, ?> response) {
LOG.debug("Read request for {} completed with {}", path, response);
- if (response instanceof ReadTransactionSuccess) {
- future.set(((ReadTransactionSuccess) response).getData());
+ if (response instanceof ReadTransactionSuccess success) {
+ future.set(success.getData());
} else {
failReadFuture(future, "Error reading data for path " + path, response);
}
}
void handleForwardedRequest(final TransactionRequest<?> request, final Consumer<Response<?, ?>> callback) {
- if (request instanceof ModifyTransactionRequest) {
- handleForwardedModifyTransactionRequest(callback, (ModifyTransactionRequest) request);
- } else if (request instanceof ReadTransactionRequest) {
+ if (request instanceof ModifyTransactionRequest modifyRequest) {
+ handleForwardedModifyTransactionRequest(callback, modifyRequest);
+ } else if (request instanceof ReadTransactionRequest readRequest) {
ensureFlushedBuider();
sendRequest(new ReadTransactionRequest(getIdentifier(), nextSequence(), localActor(),
- ((ReadTransactionRequest) request).getPath(), isSnapshotOnly()), resp -> {
+ readRequest.getPath(), isSnapshotOnly()), resp -> {
recordFinishedRequest(resp);
callback.accept(resp);
});
- } else if (request instanceof ExistsTransactionRequest) {
+ } else if (request instanceof ExistsTransactionRequest existsRequest) {
ensureFlushedBuider();
sendRequest(new ExistsTransactionRequest(getIdentifier(), nextSequence(), localActor(),
- ((ExistsTransactionRequest) request).getPath(), isSnapshotOnly()), resp -> {
+ existsRequest.getPath(), isSnapshotOnly()), resp -> {
recordFinishedRequest(resp);
callback.accept(resp);
});
}
final TransactionRequest<?> tmp;
- switch (maybeProto.get()) {
+ switch (maybeProto.orElseThrow()) {
case ABORT:
tmp = abortRequest();
sendRequest(tmp, resp -> {
});
break;
default:
- throw new IllegalArgumentException("Unhandled protocol " + maybeProto.get());
+ throw new IllegalArgumentException("Unhandled protocol " + maybeProto.orElseThrow());
}
}
}
@Override
void handleReplayedLocalRequest(final AbstractLocalTransactionRequest<?> request,
final Consumer<Response<?, ?>> callback, final long enqueuedTicks) {
- if (request instanceof CommitLocalTransactionRequest) {
- replayLocalCommitRequest((CommitLocalTransactionRequest) request, callback, enqueuedTicks);
+ if (request instanceof CommitLocalTransactionRequest commitRequest) {
+ replayLocalCommitRequest(commitRequest, callback, enqueuedTicks);
} else if (request instanceof AbortLocalTransactionRequest) {
enqueueRequest(abortRequest(), callback, enqueuedTicks);
} else {
final Consumer<Response<?, ?>> cb = callback != null ? callback : resp -> { /* NOOP */ };
final OptionalLong optTicks = OptionalLong.of(enqueuedTicks);
- if (request instanceof ModifyTransactionRequest) {
- handleReplayedModifyTransactionRequest(enqueuedTicks, cb, (ModifyTransactionRequest) request);
- } else if (request instanceof ReadTransactionRequest) {
+ if (request instanceof ModifyTransactionRequest modifyRequest) {
+ handleReplayedModifyTransactionRequest(enqueuedTicks, cb, modifyRequest);
+ } else if (request instanceof ReadTransactionRequest readRequest) {
ensureFlushedBuider(optTicks);
enqueueRequest(new ReadTransactionRequest(getIdentifier(), nextSequence(), localActor(),
- ((ReadTransactionRequest) request).getPath(), isSnapshotOnly()), resp -> {
+ readRequest.getPath(), isSnapshotOnly()), resp -> {
recordFinishedRequest(resp);
cb.accept(resp);
}, enqueuedTicks);
- } else if (request instanceof ExistsTransactionRequest) {
+ } else if (request instanceof ExistsTransactionRequest existsRequest) {
ensureFlushedBuider(optTicks);
enqueueRequest(new ExistsTransactionRequest(getIdentifier(), nextSequence(), localActor(),
- ((ExistsTransactionRequest) request).getPath(), isSnapshotOnly()), resp -> {
+ existsRequest.getPath(), isSnapshotOnly()), resp -> {
recordFinishedRequest(resp);
cb.accept(resp);
}, enqueuedTicks);
enqueueDoAbort(callback, enqueuedTicks);
} else if (request instanceof TransactionPurgeRequest) {
enqueuePurge(callback, enqueuedTicks);
- } else if (request instanceof IncrementTransactionSequenceRequest) {
- final IncrementTransactionSequenceRequest req = (IncrementTransactionSequenceRequest) request;
+ } else if (request instanceof IncrementTransactionSequenceRequest req) {
ensureFlushedBuider(optTicks);
enqueueRequest(new IncrementTransactionSequenceRequest(getIdentifier(), nextSequence(), localActor(),
snapshotOnly, req.getIncrement()), callback, enqueuedTicks);
}
final TransactionRequest<?> tmp;
- switch (maybeProto.get()) {
+ switch (maybeProto.orElseThrow()) {
case ABORT:
tmp = abortRequest();
enqueueRequest(tmp, resp -> {
}, enqueuedTicks);
break;
default:
- throw new IllegalArgumentException("Unhandled protocol " + maybeProto.get());
+ throw new IllegalArgumentException("Unhandled protocol " + maybeProto.orElseThrow());
}
}
}
*/
package org.opendaylight.controller.cluster.datastore;
-import static com.google.common.base.Preconditions.checkArgument;
import static java.util.Objects.requireNonNull;
import akka.actor.ActorRef;
import com.google.common.util.concurrent.Uninterruptibles;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import java.util.List;
-import java.util.Set;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
+import org.eclipse.jdt.annotation.NonNull;
import org.opendaylight.controller.cluster.access.concepts.ClientIdentifier;
import org.opendaylight.controller.cluster.common.actor.Dispatchers;
import org.opendaylight.controller.cluster.databroker.actors.dds.DataStoreClient;
import org.opendaylight.controller.cluster.datastore.shardmanager.ShardManagerCreator;
import org.opendaylight.controller.cluster.datastore.utils.ActorUtils;
import org.opendaylight.controller.cluster.datastore.utils.PrimaryShardInfoFutureCache;
-import org.opendaylight.mdsal.dom.api.ClusteredDOMDataTreeChangeListener;
+import org.opendaylight.mdsal.dom.api.DOMDataBroker.CommitCohortExtension;
import org.opendaylight.mdsal.dom.api.DOMDataTreeChangeListener;
import org.opendaylight.mdsal.dom.api.DOMDataTreeCommitCohort;
-import org.opendaylight.mdsal.dom.api.DOMDataTreeCommitCohortRegistration;
-import org.opendaylight.mdsal.dom.api.DOMDataTreeCommitCohortRegistry;
import org.opendaylight.mdsal.dom.api.DOMDataTreeIdentifier;
import org.opendaylight.mdsal.dom.spi.store.DOMStoreTreeChangePublisher;
-import org.opendaylight.yangtools.concepts.ListenerRegistration;
+import org.opendaylight.yangtools.concepts.Registration;
import org.opendaylight.yangtools.yang.common.Empty;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
import org.opendaylight.yangtools.yang.data.tree.api.DataTreeCandidate;
import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
-import org.opendaylight.yangtools.yang.model.api.EffectiveModelContextListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import scala.concurrent.duration.Duration;
/**
* Base implementation of a distributed DOMStore.
*/
-public abstract class AbstractDataStore implements DistributedDataStoreInterface, EffectiveModelContextListener,
- DatastoreContextPropertiesUpdater.Listener, DOMStoreTreeChangePublisher,
- DOMDataTreeCommitCohortRegistry, AutoCloseable {
-
+public abstract class AbstractDataStore implements DistributedDataStoreInterface,
+ DatastoreContextPropertiesUpdater.Listener, DOMStoreTreeChangePublisher, CommitCohortExtension,
+ AutoCloseable {
private static final Logger LOG = LoggerFactory.getLogger(AbstractDataStore.class);
private final SettableFuture<Empty> readinessFuture = SettableFuture.create();
datastoreInfoMXBean.registerMBean();
}
- @VisibleForTesting
- protected AbstractDataStore(final ActorUtils actorUtils, final ClientIdentifier identifier) {
- this.actorUtils = requireNonNull(actorUtils, "actorContext should not be null");
- client = null;
- this.identifier = requireNonNull(identifier);
- }
-
@VisibleForTesting
protected AbstractDataStore(final ActorUtils actorUtils, final ClientIdentifier identifier,
final DataStoreClient clientActor) {
this.identifier = requireNonNull(identifier);
}
+ @VisibleForTesting
protected AbstractShardManagerCreator<?> getShardManagerCreator() {
return new ShardManagerCreator();
}
return client;
}
- final ClientIdentifier getIdentifier() {
- return identifier;
- }
-
public void setCloseable(final AutoCloseable closeable) {
this.closeable = closeable;
}
@Override
- public <L extends DOMDataTreeChangeListener> ListenerRegistration<L> registerTreeChangeListener(
- final YangInstanceIdentifier treeId, final L listener) {
+ public final Registration registerTreeChangeListener(final YangInstanceIdentifier treeId,
+ final DOMDataTreeChangeListener listener) {
+ return registerTreeChangeListener(treeId, listener, true);
+ }
+
+ private @NonNull Registration registerTreeChangeListener(final YangInstanceIdentifier treeId,
+ final DOMDataTreeChangeListener listener, final boolean clustered) {
requireNonNull(treeId, "treeId should not be null");
requireNonNull(listener, "listener should not be null");
if (treeId.isEmpty()) {
// User is targeting root of the datastore. If there is more than one shard, we have to register with them
// all and perform data composition.
- final Set<String> shardNames = actorUtils.getConfiguration().getAllShardNames();
+ final var shardNames = actorUtils.getConfiguration().getAllShardNames();
if (shardNames.size() > 1) {
- checkArgument(listener instanceof ClusteredDOMDataTreeChangeListener,
- "Cannot listen on root without non-clustered listener %s", listener);
+ if (!clustered) {
+ throw new IllegalArgumentException(
+ "Cannot listen on root without non-clustered listener " + listener);
+ }
return new RootDataTreeChangeListenerProxy<>(actorUtils, listener, shardNames);
}
}
- final String shardName = actorUtils.getShardStrategyFactory().getStrategy(treeId).findShard(treeId);
+ final var shardName = actorUtils.getShardStrategyFactory().getStrategy(treeId).findShard(treeId);
LOG.debug("Registering tree listener: {} for tree: {} shard: {}", listener, treeId, shardName);
- final DataTreeChangeListenerProxy<L> listenerRegistrationProxy =
- new DataTreeChangeListenerProxy<>(actorUtils, listener, treeId);
- listenerRegistrationProxy.init(shardName);
+ return DataTreeChangeListenerProxy.of(actorUtils, listener, treeId, clustered, shardName);
+ }
- return listenerRegistrationProxy;
+ @Override
+ @Deprecated(since = "9.0.0", forRemoval = true)
+ public final Registration registerLegacyTreeChangeListener(final YangInstanceIdentifier treeId,
+ final DOMDataTreeChangeListener listener) {
+ return registerTreeChangeListener(treeId, listener, false);
}
@Override
- public <C extends DOMDataTreeCommitCohort> DOMDataTreeCommitCohortRegistration<C> registerCommitCohort(
- final DOMDataTreeIdentifier subtree, final C cohort) {
- YangInstanceIdentifier treeId = requireNonNull(subtree, "subtree should not be null").getRootIdentifier();
+ // Non-final for testing
+ public Registration registerCommitCohort(final DOMDataTreeIdentifier subtree,
+ final DOMDataTreeCommitCohort cohort) {
+ YangInstanceIdentifier treeId = requireNonNull(subtree, "subtree should not be null").path();
requireNonNull(cohort, "listener should not be null");
final String shardName = actorUtils.getShardStrategyFactory().getStrategy(treeId).findShard(treeId);
LOG.debug("Registering cohort: {} for tree: {} shard: {}", cohort, treeId, shardName);
- DataTreeCohortRegistrationProxy<C> cohortProxy =
- new DataTreeCohortRegistrationProxy<>(actorUtils, subtree, cohort);
+ final var cohortProxy = new DataTreeCohortRegistrationProxy<>(actorUtils, subtree, cohort);
cohortProxy.init(shardName);
return cohortProxy;
}
- @Override
public void onModelContextUpdated(final EffectiveModelContext newModelContext) {
actorUtils.setSchemaContext(newModelContext);
}
@Override
- public void onDatastoreContextUpdated(final DatastoreContextFactory contextFactory) {
+ public final void onDatastoreContextUpdated(final DatastoreContextFactory contextFactory) {
LOG.info("DatastoreContext updated for data store {}", actorUtils.getDataStoreName());
actorUtils.setDatastoreContext(contextFactory);
@Override
@SuppressWarnings("checkstyle:IllegalCatch")
- public void close() {
+ public final void close() {
LOG.info("Closing data store {}", identifier);
if (datastoreConfigMXBean != null) {
// TODO: consider removing this in favor of awaitReadiness()
@Deprecated
- public void waitTillReady() {
+ public final void waitTillReady() {
LOG.info("Beginning to wait for data store to become ready : {}", identifier);
final Duration toWait = initialSettleTime();
@Beta
@Deprecated
- public boolean awaitReadiness() throws InterruptedException {
+ public final boolean awaitReadiness() throws InterruptedException {
return awaitReadiness(initialSettleTime());
}
@Beta
@Deprecated
- public boolean awaitReadiness(final Duration toWait) throws InterruptedException {
+ public final boolean awaitReadiness(final Duration toWait) throws InterruptedException {
try {
if (toWait.isFinite()) {
try {
@Beta
@Deprecated
- public void awaitReadiness(final long timeout, final TimeUnit unit) throws InterruptedException, TimeoutException {
+ public final void awaitReadiness(final long timeout, final TimeUnit unit)
+ throws InterruptedException, TimeoutException {
if (!awaitReadiness(Duration.create(timeout, unit))) {
throw new TimeoutException("Shard leaders failed to settle");
}
}
@VisibleForTesting
- SettableFuture<Empty> readinessFuture() {
+ public final SettableFuture<Empty> readinessFuture() {
return readinessFuture;
}
@Override
- @SuppressWarnings("unchecked")
- public <L extends DOMDataTreeChangeListener> ListenerRegistration<L> registerProxyListener(
- final YangInstanceIdentifier shardLookup, final YangInstanceIdentifier insideShard,
- final DOMDataTreeChangeListener delegate) {
-
+ public final Registration registerProxyListener(final YangInstanceIdentifier shardLookup,
+ final YangInstanceIdentifier insideShard, final DOMDataTreeChangeListener delegate) {
requireNonNull(shardLookup, "shardLookup should not be null");
requireNonNull(insideShard, "insideShard should not be null");
requireNonNull(delegate, "delegate should not be null");
- final String shardName = actorUtils.getShardStrategyFactory().getStrategy(shardLookup).findShard(shardLookup);
- LOG.debug("Registering tree listener: {} for tree: {} shard: {}, path inside shard: {}",
- delegate,shardLookup, shardName, insideShard);
-
- // wrap this in the ClusteredDOMDataTreeChangeLister interface
- // since we always want clustered registration
- final DataTreeChangeListenerProxy<DOMDataTreeChangeListener> listenerRegistrationProxy =
- new DataTreeChangeListenerProxy<>(actorUtils, new ClusteredDOMDataTreeChangeListener() {
- @Override
- public void onDataTreeChanged(final List<DataTreeCandidate> changes) {
- delegate.onDataTreeChanged(changes);
- }
-
- @Override
- public void onInitialData() {
- delegate.onInitialData();
- }
- }, insideShard);
- listenerRegistrationProxy.init(shardName);
-
- return (ListenerRegistration<L>) listenerRegistrationProxy;
+ final var shardName = actorUtils.getShardStrategyFactory().getStrategy(shardLookup).findShard(shardLookup);
+ LOG.debug("Registering tree listener: {} for tree: {} shard: {}, path inside shard: {}", delegate, shardLookup,
+ shardName, insideShard);
+
+ return DataTreeChangeListenerProxy.of(actorUtils, new DOMDataTreeChangeListener() {
+ @Override
+ public void onDataTreeChanged(final List<DataTreeCandidate> changes) {
+ delegate.onDataTreeChanged(changes);
+ }
+
+ @Override
+ public void onInitialData() {
+ delegate.onInitialData();
+ }
+ }, insideShard, true, shardName);
}
private Duration initialSettleTime() {
import org.eclipse.jdt.annotation.NonNull;
import org.opendaylight.mdsal.binding.dom.codec.api.BindingNormalizedNodeSerializer;
import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.distributed.datastore.provider.rev140612.DataStorePropertiesContainer;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.distributed.datastore.provider.rev231229.DataStorePropertiesContainer;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
-import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
+import org.opendaylight.yangtools.yang.data.spi.node.ImmutableNodes;
abstract class AbstractDatastoreContextIntrospectorFactory implements DatastoreContextIntrospectorFactory {
@Override
@VisibleForTesting
final @NonNull DatastoreContextIntrospector newInstance(final DatastoreContext context) {
- final DataStorePropertiesContainer defaultPropsContainer = (DataStorePropertiesContainer)
- serializer().fromNormalizedNode(YangInstanceIdentifier.of(DataStorePropertiesContainer.QNAME),
- ImmutableNodes.containerNode(DataStorePropertiesContainer.QNAME)).getValue();
-
- return new DatastoreContextIntrospector(context, defaultPropsContainer);
+ return new DatastoreContextIntrospector(context, (DataStorePropertiesContainer) serializer()
+ .fromNormalizedNode(YangInstanceIdentifier.of(DataStorePropertiesContainer.QNAME),
+ ImmutableNodes.newContainerBuilder()
+ .withNodeIdentifier(new NodeIdentifier(DataStorePropertiesContainer.QNAME))
+ .build())
+ .getValue());
}
abstract BindingNormalizedNodeSerializer serializer();
final @Nullable TransactionSuccess<?> handleTransactionRequest(final TransactionRequest<?> request,
final RequestEnvelope envelope, final long now) throws RequestException {
- if (request instanceof TransactionPurgeRequest) {
- return handleTransactionPurgeRequest((TransactionPurgeRequest) request, envelope, now);
- } else if (request instanceof SkipTransactionsRequest) {
- return handleSkipTransactionsRequest((SkipTransactionsRequest) request, envelope, now);
+ if (request instanceof TransactionPurgeRequest purgeRequest) {
+ return handleTransactionPurgeRequest(purgeRequest, envelope, now);
+ } else if (request instanceof SkipTransactionsRequest skipRequest) {
+ return handleSkipTransactionsRequest(skipRequest, envelope, now);
}
final TransactionIdentifier id = request.getTarget();
} else if (!(request instanceof IncrementTransactionSequenceRequest)) {
final Optional<TransactionSuccess<?>> maybeReplay = tx.replaySequence(request.getSequence());
if (maybeReplay.isPresent()) {
- final TransactionSuccess<?> replay = maybeReplay.get();
+ final TransactionSuccess<?> replay = maybeReplay.orElseThrow();
LOG.debug("{}: envelope {} replaying response {}", persistenceId(), envelope, replay);
return replay;
}
}
private FrontendTransaction createTransaction(final TransactionRequest<?> request, final TransactionIdentifier id) {
- if (request instanceof CommitLocalTransactionRequest) {
+ if (request instanceof CommitLocalTransactionRequest commitLocalRequest) {
LOG.debug("{}: allocating new ready transaction {}", persistenceId(), id);
tree.getStats().incrementReadWriteTransactionCount();
- return createReadyTransaction(id, ((CommitLocalTransactionRequest) request).getModification());
+ return createReadyTransaction(id, commitLocalRequest.getModification());
}
- if (request instanceof AbstractReadTransactionRequest
- && ((AbstractReadTransactionRequest<?>) request).isSnapshotOnly()) {
+ if (request instanceof AbstractReadTransactionRequest<?> readTxRequest && readTxRequest.isSnapshotOnly()) {
LOG.debug("{}: allocating new open snapshot {}", persistenceId(), id);
tree.getStats().incrementReadOnlyTransactionCount();
return createOpenSnapshot(id);
+++ /dev/null
-/*
- * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.cluster.datastore;
-
-import com.google.common.util.concurrent.Futures;
-import com.google.common.util.concurrent.ListenableFuture;
-import java.util.List;
-import org.eclipse.jdt.annotation.NonNull;
-import org.opendaylight.mdsal.dom.spi.store.DOMStoreThreePhaseCommitCohort;
-import org.opendaylight.yangtools.yang.common.Empty;
-import scala.concurrent.Future;
-
-/**
- * Abstract base class for {@link DOMStoreThreePhaseCommitCohort} instances returned by this
- * implementation. In addition to the usual set of methods it also contains the list of actor
- * futures.
- */
-public abstract class AbstractThreePhaseCommitCohort<T> implements DOMStoreThreePhaseCommitCohort {
- protected static final @NonNull ListenableFuture<Empty> IMMEDIATE_EMPTY_SUCCESS =
- Futures.immediateFuture(Empty.value());
- protected static final @NonNull ListenableFuture<Boolean> IMMEDIATE_BOOLEAN_SUCCESS =
- Futures.immediateFuture(Boolean.TRUE);
-
- abstract List<Future<T>> getCohortFutures();
-}
+++ /dev/null
-/*
- * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.cluster.datastore;
-
-import static java.util.Objects.requireNonNull;
-
-import akka.actor.ActorSelection;
-import java.util.Collection;
-import java.util.Optional;
-import java.util.concurrent.ConcurrentHashMap;
-import java.util.concurrent.ConcurrentMap;
-import java.util.concurrent.atomic.AtomicLongFieldUpdater;
-import org.eclipse.jdt.annotation.NonNull;
-import org.opendaylight.controller.cluster.access.concepts.LocalHistoryIdentifier;
-import org.opendaylight.controller.cluster.access.concepts.MemberName;
-import org.opendaylight.controller.cluster.access.concepts.TransactionIdentifier;
-import org.opendaylight.controller.cluster.datastore.messages.PrimaryShardInfo;
-import org.opendaylight.controller.cluster.datastore.utils.ActorUtils;
-import org.opendaylight.mdsal.dom.spi.store.DOMStoreReadTransaction;
-import org.opendaylight.mdsal.dom.spi.store.DOMStoreReadWriteTransaction;
-import org.opendaylight.mdsal.dom.spi.store.DOMStoreWriteTransaction;
-import org.opendaylight.yangtools.yang.data.tree.api.ReadOnlyDataTree;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import scala.concurrent.Future;
-import scala.util.Try;
-
-/**
- * Factory for creating local and remote TransactionContext instances. Maintains a cache of known local
- * transaction factories.
- */
-abstract class AbstractTransactionContextFactory<F extends LocalTransactionFactory> implements AutoCloseable {
- private static final Logger LOG = LoggerFactory.getLogger(AbstractTransactionContextFactory.class);
- @SuppressWarnings("rawtypes")
- private static final AtomicLongFieldUpdater<AbstractTransactionContextFactory> TX_COUNTER_UPDATER =
- AtomicLongFieldUpdater.newUpdater(AbstractTransactionContextFactory.class, "nextTx");
-
- private final ConcurrentMap<String, F> knownLocal = new ConcurrentHashMap<>();
- private final @NonNull LocalHistoryIdentifier historyId;
- private final @NonNull ActorUtils actorUtils;
-
- // Used via TX_COUNTER_UPDATER
- @SuppressWarnings("unused")
- private volatile long nextTx;
-
- protected AbstractTransactionContextFactory(final ActorUtils actorUtils, final LocalHistoryIdentifier historyId) {
- this.actorUtils = requireNonNull(actorUtils);
- this.historyId = requireNonNull(historyId);
- }
-
- final ActorUtils getActorUtils() {
- return actorUtils;
- }
-
- final LocalHistoryIdentifier getHistoryId() {
- return historyId;
- }
-
- @SuppressWarnings("checkstyle:IllegalCatch")
- private TransactionContext maybeCreateLocalTransactionContext(final TransactionProxy parent,
- final String shardName) {
- final LocalTransactionFactory local = knownLocal.get(shardName);
- if (local != null) {
- LOG.debug("Tx {} - Creating local component for shard {} using factory {}", parent.getIdentifier(),
- shardName, local);
-
- try {
- return createLocalTransactionContext(local, parent);
- } catch (Exception e) {
- return new NoOpTransactionContext(e, parent.getIdentifier());
- }
- }
-
- return null;
- }
-
- private AbstractTransactionContextWrapper maybeCreateDirectTransactionContextWrapper(
- final PrimaryShardInfo primaryShardInfo, final TransactionProxy parent,
- final String shardName, final DelayedTransactionContextWrapper transactionContextWrapper) {
- LOG.debug("Tx {}: Found primary {} for shard {}, trying to use DirectTransactionContextWrapper",
- parent.getIdentifier(), primaryShardInfo.getPrimaryShardActor(), shardName);
-
- updateShardInfo(shardName, primaryShardInfo);
-
- final TransactionContext localContext = maybeCreateLocalTransactionContext(parent, shardName);
- try {
- if (localContext != null) {
- LOG.debug("Tx {}: Local transaction context created successfully, using DirectTransactionWrapper",
- parent.getIdentifier());
- return new DirectTransactionContextWrapper(parent.getIdentifier(), actorUtils, shardName,
- localContext);
- }
-
- LOG.debug("Tx {}: Local transaction context creation failed, using DelayedTransactionWrapper",
- parent.getIdentifier());
- final RemoteTransactionContextSupport remote = new RemoteTransactionContextSupport(
- transactionContextWrapper, parent, shardName);
- remote.setPrimaryShard(primaryShardInfo);
- return transactionContextWrapper;
- } finally {
- onTransactionContextCreated(parent.getIdentifier());
- }
- }
-
- private void onFindPrimaryShardSuccess(final PrimaryShardInfo primaryShardInfo, final TransactionProxy parent,
- final String shardName, final DelayedTransactionContextWrapper transactionContextWrapper) {
- LOG.debug("Tx {}: Found primary {} for shard {}", parent.getIdentifier(),
- primaryShardInfo.getPrimaryShardActor(), shardName);
-
- updateShardInfo(shardName, primaryShardInfo);
-
- final TransactionContext localContext = maybeCreateLocalTransactionContext(parent, shardName);
- try {
- if (localContext != null) {
- transactionContextWrapper.executePriorTransactionOperations(localContext);
- } else {
- final RemoteTransactionContextSupport remote = new RemoteTransactionContextSupport(
- transactionContextWrapper, parent, shardName);
- remote.setPrimaryShard(primaryShardInfo);
- }
- } finally {
- onTransactionContextCreated(parent.getIdentifier());
- }
- }
-
- private void onFindPrimaryShardFailure(final Throwable failure, final TransactionProxy parent,
- final String shardName, final DelayedTransactionContextWrapper transactionContextWrapper) {
- LOG.debug("Tx {}: Find primary for shard {} failed", parent.getIdentifier(), shardName, failure);
-
- try {
- transactionContextWrapper.executePriorTransactionOperations(
- new NoOpTransactionContext(failure, parent.getIdentifier()));
- } finally {
- onTransactionContextCreated(parent.getIdentifier());
- }
- }
-
- final AbstractTransactionContextWrapper newTransactionContextWrapper(final TransactionProxy parent,
- final String shardName) {
- final DelayedTransactionContextWrapper contextWrapper = new DelayedTransactionContextWrapper(
- parent.getIdentifier(), actorUtils, shardName);
- final Future<PrimaryShardInfo> findPrimaryFuture = findPrimaryShard(shardName, parent.getIdentifier());
- if (findPrimaryFuture.isCompleted()) {
- final Try<PrimaryShardInfo> maybe = findPrimaryFuture.value().get();
- if (maybe.isSuccess()) {
- return maybeCreateDirectTransactionContextWrapper(maybe.get(), parent, shardName, contextWrapper);
- }
-
- onFindPrimaryShardFailure(maybe.failed().get(), parent, shardName, contextWrapper);
- } else {
- findPrimaryFuture.onComplete(result -> {
- if (result.isSuccess()) {
- onFindPrimaryShardSuccess(result.get(), parent, shardName, contextWrapper);
- } else {
- onFindPrimaryShardFailure(result.failed().get(), parent, shardName, contextWrapper);
- }
- return null;
- }, actorUtils.getClientDispatcher());
- }
- return contextWrapper;
- }
-
- private void updateShardInfo(final String shardName, final PrimaryShardInfo primaryShardInfo) {
- final Optional<ReadOnlyDataTree> maybeDataTree = primaryShardInfo.getLocalShardDataTree();
- if (maybeDataTree.isPresent()) {
- if (!knownLocal.containsKey(shardName)) {
- LOG.debug("Shard {} resolved to local data tree - adding local factory", shardName);
-
- F factory = factoryForShard(shardName, primaryShardInfo.getPrimaryShardActor(), maybeDataTree.get());
- knownLocal.putIfAbsent(shardName, factory);
- }
- } else if (knownLocal.containsKey(shardName)) {
- LOG.debug("Shard {} invalidating local data tree", shardName);
-
- knownLocal.remove(shardName);
- }
- }
-
- protected final MemberName getMemberName() {
- return historyId.getClientId().getFrontendId().getMemberName();
- }
-
- /**
- * Create an identifier for the next TransactionProxy attached to this component
- * factory.
- * @return Transaction identifier, may not be null.
- */
- protected final TransactionIdentifier nextIdentifier() {
- return new TransactionIdentifier(historyId, TX_COUNTER_UPDATER.getAndIncrement(this));
- }
-
- /**
- * Find the primary shard actor.
- *
- * @param shardName Shard name
- * @return Future containing shard information.
- */
- protected abstract Future<PrimaryShardInfo> findPrimaryShard(@NonNull String shardName,
- @NonNull TransactionIdentifier txId);
-
- /**
- * Create local transaction factory for specified shard, backed by specified shard leader
- * and data tree instance.
- *
- * @param shardName the shard name
- * @param shardLeader the shard leader
- * @param dataTree Backing data tree instance. The data tree may only be accessed in
- * read-only manner.
- * @return Transaction factory for local use.
- */
- protected abstract F factoryForShard(String shardName, ActorSelection shardLeader, ReadOnlyDataTree dataTree);
-
- /**
- * Callback invoked from child transactions to push any futures, which need to
- * be waited for before the next transaction is allocated.
- * @param cohortFutures Collection of futures
- */
- protected abstract <T> void onTransactionReady(@NonNull TransactionIdentifier transaction,
- @NonNull Collection<Future<T>> cohortFutures);
-
- /**
- * Callback invoked when the internal TransactionContext has been created for a transaction.
- *
- * @param transactionId the ID of the transaction.
- */
- protected abstract void onTransactionContextCreated(@NonNull TransactionIdentifier transactionId);
-
- private static TransactionContext createLocalTransactionContext(final LocalTransactionFactory factory,
- final TransactionProxy parent) {
-
- switch (parent.getType()) {
- case READ_ONLY:
- final DOMStoreReadTransaction readOnly = factory.newReadOnlyTransaction(parent.getIdentifier());
- return new LocalTransactionContext(readOnly, parent.getIdentifier(), factory) {
- @Override
- DOMStoreWriteTransaction getWriteDelegate() {
- throw new UnsupportedOperationException();
- }
-
- @Override
- DOMStoreReadTransaction getReadDelegate() {
- return readOnly;
- }
- };
- case READ_WRITE:
- final DOMStoreReadWriteTransaction readWrite = factory.newReadWriteTransaction(parent.getIdentifier());
- return new LocalTransactionContext(readWrite, parent.getIdentifier(), factory) {
- @Override
- DOMStoreWriteTransaction getWriteDelegate() {
- return readWrite;
- }
-
- @Override
- DOMStoreReadTransaction getReadDelegate() {
- return readWrite;
- }
- };
- case WRITE_ONLY:
- final DOMStoreWriteTransaction writeOnly = factory.newWriteOnlyTransaction(parent.getIdentifier());
- return new LocalTransactionContext(writeOnly, parent.getIdentifier(), factory) {
- @Override
- DOMStoreWriteTransaction getWriteDelegate() {
- return writeOnly;
- }
-
- @Override
- DOMStoreReadTransaction getReadDelegate() {
- throw new UnsupportedOperationException();
- }
- };
- default:
- throw new IllegalArgumentException("Invalid transaction type: " + parent.getType());
- }
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2021 PANTHEON.tech, s.r.o. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.cluster.datastore;
-
-import static java.util.Objects.requireNonNull;
-
-import akka.actor.ActorSelection;
-import java.util.Optional;
-import java.util.SortedSet;
-import java.util.concurrent.TimeUnit;
-import org.eclipse.jdt.annotation.NonNull;
-import org.eclipse.jdt.annotation.Nullable;
-import org.opendaylight.controller.cluster.access.concepts.TransactionIdentifier;
-import org.opendaylight.controller.cluster.datastore.utils.ActorUtils;
-import scala.concurrent.Future;
-
-/**
- * A helper class that wraps an eventual TransactionContext instance. We have two specializations:
- * <ul>
- * <li>{@link DelayedTransactionContextWrapper}, which enqueues operations towards the backend</li>
- * <li>{@link DirectTransactionContextWrapper}, which sends operations to the backend</li>
- * </ul>
- */
-abstract class AbstractTransactionContextWrapper {
- private final TransactionIdentifier identifier;
- private final OperationLimiter limiter;
- private final String shardName;
-
- AbstractTransactionContextWrapper(@NonNull final TransactionIdentifier identifier,
- @NonNull final ActorUtils actorUtils, @NonNull final String shardName) {
- this.identifier = requireNonNull(identifier);
- this.shardName = requireNonNull(shardName);
- limiter = new OperationLimiter(identifier,
- // 1 extra permit for the ready operation
- actorUtils.getDatastoreContext().getShardBatchedModificationCount() + 1,
- TimeUnit.MILLISECONDS.toSeconds(actorUtils.getDatastoreContext().getOperationTimeoutInMillis()));
- }
-
- final TransactionIdentifier getIdentifier() {
- return identifier;
- }
-
- final OperationLimiter getLimiter() {
- return limiter;
- }
-
- final String getShardName() {
- return shardName;
- }
-
- abstract @Nullable TransactionContext getTransactionContext();
-
- /**
- * Either enqueue or execute specified operation.
- *
- * @param op Operation to (eventually) execute
- */
- abstract void maybeExecuteTransactionOperation(TransactionOperation op);
-
- /**
- * Mark the transaction as ready.
- *
- * @param participatingShardNames Shards which participate on the transaction
- * @return Future indicating the transaction has been readied on the backend
- */
- abstract @NonNull Future<ActorSelection> readyTransaction(Optional<SortedSet<String>> participatingShardNames);
-}
}
@Override
- public TransactionIdentifier getIdentifier() {
- return delegate.getIdentifier();
+ TransactionIdentifier transactionId() {
+ return delegate.transactionId();
}
@Override
import org.opendaylight.yangtools.yang.data.tree.api.DataTreeCandidate;
import org.opendaylight.yangtools.yang.data.tree.api.DataTreeModification;
+@Deprecated(since = "9.0.0", forRemoval = true)
final class CohortEntry {
private final ReadWriteShardDataTreeTransaction transaction;
private final TransactionIdentifier transactionId;
private CohortEntry(final ShardDataTreeCohort cohort, final short clientVersion) {
this.cohort = requireNonNull(cohort);
- transactionId = cohort.getIdentifier();
+ transactionId = cohort.transactionId();
transaction = null;
this.clientVersion = clientVersion;
}
import org.opendaylight.controller.cluster.datastore.DataTreeCohortActor.Success;
import org.opendaylight.yangtools.yang.common.Empty;
import org.opendaylight.yangtools.yang.data.tree.api.DataTreeCandidate;
-import org.opendaylight.yangtools.yang.model.api.SchemaContext;
+import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import scala.compat.java8.FutureConverters;
private final DataTreeCohortActorRegistry registry;
private final TransactionIdentifier txId;
- private final SchemaContext schema;
+ private final EffectiveModelContext schema;
private final Executor callbackExecutor;
private final Timeout timeout;
private State state = State.IDLE;
CompositeDataTreeCohort(final DataTreeCohortActorRegistry registry, final TransactionIdentifier transactionID,
- final SchemaContext schema, final Executor callbackExecutor, final Timeout timeout) {
+ final EffectiveModelContext schema, final Executor callbackExecutor, final Timeout timeout) {
this.registry = requireNonNull(registry);
txId = requireNonNull(transactionID);
this.schema = requireNonNull(schema);
public static final short FLUORINE_VERSION = 9;
@Deprecated
public static final short NEON_SR2_VERSION = 10;
+ @Deprecated
public static final short SODIUM_SR1_VERSION = 11;
+ @Deprecated
public static final short PHOSPHORUS_VERSION = 12;
- public static final short CURRENT_VERSION = PHOSPHORUS_VERSION;
+ public static final short POTASSIUM_VERSION = 13;
+ public static final short CURRENT_VERSION = POTASSIUM_VERSION;
private DataStoreVersions() {
LOG.debug("{}: Notifying onInitialData to listener {}", logContext, listener);
try {
- this.listener.onInitialData();
+ listener.onInitialData();
} catch (Exception e) {
- LOG.error("{}: Error notifying listener {}", logContext, this.listener, e);
+ LOG.error("{}: Error notifying listener {}", logContext, listener, e);
}
}
return;
}
- LOG.debug("{}: Sending {} change notification(s) {} to listener {}", logContext, message.getChanges().size(),
- message.getChanges(), listener);
+ final var changes = message.getChanges();
+ LOG.debug("{}: Sending {} change notification(s) to listener {}", logContext, changes.size(), listener);
+ if (LOG.isTraceEnabled() && !changes.isEmpty()) {
+ LOG.trace("{}: detailed change follow", logContext);
+ for (int i = 0, size = changes.size(); i < size; ++i) {
+ LOG.trace("{}: change {}: {}", logContext, i, changes.get(i));
+ }
+ }
notificationCount++;
try {
- this.listener.onDataTreeChanged(message.getChanges());
+ listener.onDataTreeChanged(changes);
} catch (Exception e) {
- LOG.error("{}: Error notifying listener {}", logContext, this.listener, e);
+ LOG.error("{}: Error notifying listener {}", logContext, listener, e);
}
// TODO: do we really need this?
import akka.actor.PoisonPill;
import akka.dispatch.OnComplete;
import com.google.common.annotations.VisibleForTesting;
+import com.google.common.util.concurrent.MoreExecutors;
+import java.util.concurrent.Executor;
import org.checkerframework.checker.lock.qual.GuardedBy;
+import org.eclipse.jdt.annotation.NonNull;
import org.opendaylight.controller.cluster.datastore.exceptions.LocalShardNotFoundException;
import org.opendaylight.controller.cluster.datastore.messages.CloseDataTreeNotificationListenerRegistration;
import org.opendaylight.controller.cluster.datastore.messages.RegisterDataTreeChangeListener;
import org.opendaylight.controller.cluster.datastore.messages.RegisterDataTreeNotificationListenerReply;
import org.opendaylight.controller.cluster.datastore.utils.ActorUtils;
-import org.opendaylight.mdsal.dom.api.ClusteredDOMDataTreeChangeListener;
import org.opendaylight.mdsal.dom.api.DOMDataTreeChangeListener;
-import org.opendaylight.yangtools.concepts.AbstractListenerRegistration;
+import org.opendaylight.yangtools.concepts.AbstractObjectRegistration;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import scala.concurrent.Future;
/**
* Proxy class for holding required state to lazily instantiate a listener registration with an
*
* @param <T> listener type
*/
-final class DataTreeChangeListenerProxy<T extends DOMDataTreeChangeListener> extends AbstractListenerRegistration<T> {
+final class DataTreeChangeListenerProxy extends AbstractObjectRegistration<DOMDataTreeChangeListener> {
private static final Logger LOG = LoggerFactory.getLogger(DataTreeChangeListenerProxy.class);
private final ActorRef dataChangeListenerActor;
private final ActorUtils actorUtils;
private final YangInstanceIdentifier registeredPath;
+ private final boolean clustered;
@GuardedBy("this")
private ActorSelection listenerRegistrationActor;
- DataTreeChangeListenerProxy(final ActorUtils actorUtils, final T listener,
- final YangInstanceIdentifier registeredPath) {
+ @VisibleForTesting
+ private DataTreeChangeListenerProxy(final ActorUtils actorUtils, final DOMDataTreeChangeListener listener,
+ final YangInstanceIdentifier registeredPath, final boolean clustered, final String shardName) {
super(listener);
this.actorUtils = requireNonNull(actorUtils);
this.registeredPath = requireNonNull(registeredPath);
- this.dataChangeListenerActor = actorUtils.getActorSystem().actorOf(
+ this.clustered = clustered;
+ dataChangeListenerActor = actorUtils.getActorSystem().actorOf(
DataTreeChangeListenerActor.props(getInstance(), registeredPath)
.withDispatcher(actorUtils.getNotificationDispatcherPath()));
-
LOG.debug("{}: Created actor {} for DTCL {}", actorUtils.getDatastoreContext().getLogicalStoreType(),
dataChangeListenerActor, listener);
}
+ static @NonNull DataTreeChangeListenerProxy of(final ActorUtils actorUtils,
+ final DOMDataTreeChangeListener listener, final YangInstanceIdentifier registeredPath,
+ final boolean clustered, final String shardName) {
+ return ofTesting(actorUtils, listener, registeredPath, clustered, shardName, MoreExecutors.directExecutor());
+ }
+
+ @VisibleForTesting
+ static @NonNull DataTreeChangeListenerProxy ofTesting(final ActorUtils actorUtils,
+ final DOMDataTreeChangeListener listener, final YangInstanceIdentifier registeredPath,
+ final boolean clustered, final String shardName, final Executor executor) {
+ final var ret = new DataTreeChangeListenerProxy(actorUtils, listener, registeredPath, clustered, shardName);
+ executor.execute(() -> {
+ LOG.debug("{}: Starting discovery of shard {}", ret.logContext(), shardName);
+ actorUtils.findLocalShardAsync(shardName).onComplete(new OnComplete<>() {
+ @Override
+ public void onComplete(final Throwable failure, final ActorRef shard) {
+ if (failure instanceof LocalShardNotFoundException) {
+ LOG.debug("{}: No local shard found for {} - DataTreeChangeListener {} at path {} cannot be "
+ + "registered", ret.logContext(), shardName, listener, registeredPath);
+ } else if (failure != null) {
+ LOG.error("{}: Failed to find local shard {} - DataTreeChangeListener {} at path {} cannot be "
+ + "registered", ret.logContext(), shardName, listener, registeredPath, failure);
+ } else {
+ ret.doRegistration(shard);
+ }
+ }
+ }, actorUtils.getClientDispatcher());
+ });
+ return ret;
+ }
+
@Override
protected synchronized void removeRegistration() {
if (listenerRegistrationActor != null) {
dataChangeListenerActor.tell(PoisonPill.getInstance(), ActorRef.noSender());
}
- void init(final String shardName) {
- Future<ActorRef> findFuture = actorUtils.findLocalShardAsync(shardName);
- findFuture.onComplete(new OnComplete<ActorRef>() {
- @Override
- public void onComplete(final Throwable failure, final ActorRef shard) {
- if (failure instanceof LocalShardNotFoundException) {
- LOG.debug("{}: No local shard found for {} - DataTreeChangeListener {} at path {} "
- + "cannot be registered", logContext(), shardName, getInstance(), registeredPath);
- } else if (failure != null) {
- LOG.error("{}: Failed to find local shard {} - DataTreeChangeListener {} at path {} "
- + "cannot be registered", logContext(), shardName, getInstance(), registeredPath,
- failure);
- } else {
- doRegistration(shard);
- }
- }
- }, actorUtils.getClientDispatcher());
- }
-
private void setListenerRegistrationActor(final ActorSelection actor) {
if (actor == null) {
LOG.debug("{}: Ignoring null actor on {}", logContext(), this);
synchronized (this) {
if (!isClosed()) {
- this.listenerRegistrationActor = actor;
+ listenerRegistrationActor = actor;
return;
}
}
}
private void doRegistration(final ActorRef shard) {
-
- Future<Object> future = actorUtils.executeOperationAsync(shard,
- new RegisterDataTreeChangeListener(registeredPath, dataChangeListenerActor,
- getInstance() instanceof ClusteredDOMDataTreeChangeListener),
- actorUtils.getDatastoreContext().getShardInitializationTimeout());
-
- future.onComplete(new OnComplete<>() {
- @Override
- public void onComplete(final Throwable failure, final Object result) {
- if (failure != null) {
- LOG.error("{}: Failed to register DataTreeChangeListener {} at path {}", logContext(),
+ actorUtils.executeOperationAsync(shard,
+ new RegisterDataTreeChangeListener(registeredPath, dataChangeListenerActor, clustered),
+ actorUtils.getDatastoreContext().getShardInitializationTimeout()).onComplete(new OnComplete<>() {
+ @Override
+ public void onComplete(final Throwable failure, final Object result) {
+ if (failure != null) {
+ LOG.error("{}: Failed to register DataTreeChangeListener {} at path {}", logContext(),
getInstance(), registeredPath, failure);
- } else {
- RegisterDataTreeNotificationListenerReply reply = (RegisterDataTreeNotificationListenerReply)result;
- setListenerRegistrationActor(actorUtils.actorSelection(
- reply.getListenerRegistrationPath()));
+ } else {
+ setListenerRegistrationActor(actorUtils.actorSelection(
+ ((RegisterDataTreeNotificationListenerReply) result).getListenerRegistrationPath()));
+ }
}
- }
- }, actorUtils.getClientDispatcher());
+ }, actorUtils.getClientDispatcher());
}
@VisibleForTesting
final class DataTreeChangeListenerSupport extends LeaderLocalDelegateFactory<RegisterDataTreeChangeListener> {
private static final Logger LOG = LoggerFactory.getLogger(DataTreeChangeListenerSupport.class);
- private final Collection<DelayedDataTreeChangeListenerRegistration<DOMDataTreeChangeListener>>
+ private final Collection<DelayedDataTreeChangeListenerRegistration>
delayedDataTreeChangeListenerRegistrations = ConcurrentHashMap.newKeySet();
- private final Collection<DelayedDataTreeChangeListenerRegistration<DOMDataTreeChangeListener>>
+ private final Collection<DelayedDataTreeChangeListenerRegistration>
delayedListenerOnAllRegistrations = ConcurrentHashMap.newKeySet();
private final Collection<ActorSelection> leaderOnlyListenerActors = ConcurrentHashMap.newKeySet();
private final Collection<ActorSelection> allListenerActors = ConcurrentHashMap.newKeySet();
}
if (hasLeader) {
- for (DelayedDataTreeChangeListenerRegistration<DOMDataTreeChangeListener> reg :
- delayedListenerOnAllRegistrations) {
+ for (var reg : delayedListenerOnAllRegistrations) {
reg.doRegistration(this);
}
}
if (isLeader) {
- for (DelayedDataTreeChangeListenerRegistration<DOMDataTreeChangeListener> reg :
- delayedDataTreeChangeListenerRegistrations) {
+ for (var reg : delayedDataTreeChangeListenerRegistrations) {
reg.doRegistration(this);
}
} else {
LOG.debug("{}: Shard does not have a leader - delaying registration", persistenceId());
- final DelayedDataTreeChangeListenerRegistration<DOMDataTreeChangeListener> delayedReg =
- new DelayedDataTreeChangeListenerRegistration<>(message, registrationActor);
- final Collection<DelayedDataTreeChangeListenerRegistration<DOMDataTreeChangeListener>> delayedRegList;
+ final var delayedReg = new DelayedDataTreeChangeListenerRegistration(message, registrationActor);
+ final Collection<DelayedDataTreeChangeListenerRegistration> delayedRegList;
if (message.isRegisterOnAllInstances()) {
delayedRegList = delayedListenerOnAllRegistrations;
} else {
import org.opendaylight.mdsal.dom.api.DOMDataTreeCandidate;
import org.opendaylight.mdsal.dom.api.DOMDataTreeCommitCohort;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
-import org.opendaylight.yangtools.yang.model.api.SchemaContext;
+import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
/**
* Proxy actor which acts as a facade to the user-provided commit cohort. Responsible for
private final Collection<DOMDataTreeCandidate> candidates;
private final ActorRef cohort;
- private final SchemaContext schema;
+ private final EffectiveModelContext schema;
CanCommit(final TransactionIdentifier txId, final Collection<DOMDataTreeCandidate> candidates,
- final SchemaContext schema, final ActorRef cohort) {
+ final EffectiveModelContext schema, final ActorRef cohort) {
super(txId);
this.cohort = Objects.requireNonNull(cohort);
this.candidates = Objects.requireNonNull(candidates);
return candidates;
}
- SchemaContext getSchema() {
+ EffectiveModelContext getSchema() {
return schema;
}
import org.opendaylight.mdsal.dom.api.DOMDataTreeCandidate;
import org.opendaylight.mdsal.dom.api.DOMDataTreeIdentifier;
import org.opendaylight.mdsal.dom.spi.AbstractRegistrationTree;
-import org.opendaylight.mdsal.dom.spi.RegistrationTreeNode;
-import org.opendaylight.mdsal.dom.spi.RegistrationTreeSnapshot;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
import org.opendaylight.yangtools.yang.data.tree.api.DataTreeCandidate;
import org.opendaylight.yangtools.yang.data.tree.api.DataTreeCandidateNode;
import org.opendaylight.yangtools.yang.data.tree.api.ModificationType;
-import org.opendaylight.yangtools.yang.model.api.SchemaContext;
+import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Registry of user commit cohorts, which is responsible for handling registration and calculation
* of affected cohorts based on {@link DataTreeCandidate}. This class is NOT thread-safe.
- *
*/
class DataTreeCohortActorRegistry extends AbstractRegistrationTree<ActorRef> {
private static final Logger LOG = LoggerFactory.getLogger(DataTreeCohortActorRegistry.class);
- private final Map<ActorRef, RegistrationTreeNode<ActorRef>> cohortToNode = new HashMap<>();
+ private final Map<ActorRef, Node<ActorRef>> cohortToNode = new HashMap<>();
Collection<ActorRef> getCohortActors() {
return new ArrayList<>(cohortToNode.keySet());
takeLock();
try {
final ActorRef cohortRef = cohort.getCohort();
- final RegistrationTreeNode<ActorRef> node =
- findNodeFor(cohort.getPath().getRootIdentifier().getPathArguments());
+ final Node<ActorRef> node = findNodeFor(cohort.getPath().path().getPathArguments());
addRegistration(node, cohort.getCohort());
cohortToNode.put(cohortRef, node);
} catch (final Exception e) {
void removeCommitCohort(final ActorRef sender, final RemoveCohort message) {
final ActorRef cohort = message.getCohort();
- final RegistrationTreeNode<ActorRef> node = cohortToNode.get(cohort);
+ final Node<ActorRef> node = cohortToNode.get(cohort);
if (node != null) {
removeRegistration(node, cohort);
cohortToNode.remove(cohort);
}
List<DataTreeCohortActor.CanCommit> createCanCommitMessages(final TransactionIdentifier txId,
- final DataTreeCandidate candidate, final SchemaContext schema) {
- try (RegistrationTreeSnapshot<ActorRef> cohorts = takeSnapshot()) {
+ final DataTreeCandidate candidate, final EffectiveModelContext schema) {
+ try (var cohorts = takeSnapshot()) {
return new CanCommitMessageBuilder(txId, candidate, schema).perform(cohorts.getRootNode());
}
}
private final Multimap<ActorRef, DOMDataTreeCandidate> actorToCandidates = ArrayListMultimap.create();
private final TransactionIdentifier txId;
private final DataTreeCandidate candidate;
- private final SchemaContext schema;
+ private final EffectiveModelContext schema;
CanCommitMessageBuilder(final TransactionIdentifier txId, final DataTreeCandidate candidate,
- final SchemaContext schema) {
+ final EffectiveModelContext schema) {
this.txId = requireNonNull(txId);
this.candidate = requireNonNull(candidate);
this.schema = schema;
}
private void lookupAndCreateCanCommits(final List<PathArgument> args, final int offset,
- final RegistrationTreeNode<ActorRef> node) {
+ final Node<ActorRef> node) {
if (args.size() != offset) {
final PathArgument arg = args.get(offset);
- final RegistrationTreeNode<ActorRef> exactChild = node.getExactChild(arg);
+ final var exactChild = node.getExactChild(arg);
if (exactChild != null) {
lookupAndCreateCanCommits(args, offset + 1, exactChild);
}
- for (final RegistrationTreeNode<ActorRef> c : node.getInexactChildren(arg)) {
- lookupAndCreateCanCommits(args, offset + 1, c);
+ for (var inexact : node.getInexactChildren(arg)) {
+ lookupAndCreateCanCommits(args, offset + 1, inexact);
}
} else {
lookupAndCreateCanCommits(candidate.getRootPath(), node, candidate.getRootNode());
}
}
- private void lookupAndCreateCanCommits(final YangInstanceIdentifier path,
- final RegistrationTreeNode<ActorRef> regNode, final DataTreeCandidateNode candNode) {
- if (candNode.getModificationType() == ModificationType.UNMODIFIED) {
+ private void lookupAndCreateCanCommits(final YangInstanceIdentifier path, final Node<ActorRef> regNode,
+ final DataTreeCandidateNode candNode) {
+ if (candNode.modificationType() == ModificationType.UNMODIFIED) {
LOG.debug("Skipping unmodified candidate {}", path);
return;
}
- final Collection<ActorRef> regs = regNode.getRegistrations();
+ final var regs = regNode.getRegistrations();
if (!regs.isEmpty()) {
createCanCommits(regs, path, candNode);
}
- for (final DataTreeCandidateNode candChild : candNode.getChildNodes()) {
- if (candChild.getModificationType() != ModificationType.UNMODIFIED) {
- final RegistrationTreeNode<ActorRef> regChild =
- regNode.getExactChild(candChild.getIdentifier());
+ for (var candChild : candNode.childNodes()) {
+ if (candChild.modificationType() != ModificationType.UNMODIFIED) {
+ final var regChild = regNode.getExactChild(candChild.name());
if (regChild != null) {
- lookupAndCreateCanCommits(path.node(candChild.getIdentifier()), regChild, candChild);
+ lookupAndCreateCanCommits(path.node(candChild.name()), regChild, candChild);
}
- for (final RegistrationTreeNode<ActorRef> rc : regNode
- .getInexactChildren(candChild.getIdentifier())) {
- lookupAndCreateCanCommits(path.node(candChild.getIdentifier()), rc, candChild);
+ for (var rc : regNode.getInexactChildren(candChild.name())) {
+ lookupAndCreateCanCommits(path.node(candChild.name()), rc, candChild);
}
}
}
}
private static DOMDataTreeIdentifier treeIdentifier(final YangInstanceIdentifier path) {
- return new DOMDataTreeIdentifier(LogicalDatastoreType.CONFIGURATION, path);
+ return DOMDataTreeIdentifier.of(LogicalDatastoreType.CONFIGURATION, path);
}
- List<DataTreeCohortActor.CanCommit> perform(final RegistrationTreeNode<ActorRef> rootNode) {
- final List<PathArgument> toLookup = candidate.getRootPath().getPathArguments();
+ List<DataTreeCohortActor.CanCommit> perform(final Node<ActorRef> rootNode) {
+ final var toLookup = candidate.getRootPath().getPathArguments();
lookupAndCreateCanCommits(toLookup, 0, rootNode);
final Map<ActorRef, Collection<DOMDataTreeCandidate>> mapView = actorToCandidates.asMap();
}
}
- CompositeDataTreeCohort createCohort(final SchemaContext schemaContext, final TransactionIdentifier txId,
+ CompositeDataTreeCohort createCohort(final EffectiveModelContext schemaContext, final TransactionIdentifier txId,
final Executor callbackExecutor, final Timeout commitStepTimeout) {
return new CompositeDataTreeCohort(this, txId, schemaContext, callbackExecutor, commitStepTimeout);
}
import org.opendaylight.controller.cluster.datastore.exceptions.LocalShardNotFoundException;
import org.opendaylight.controller.cluster.datastore.utils.ActorUtils;
import org.opendaylight.mdsal.dom.api.DOMDataTreeCommitCohort;
-import org.opendaylight.mdsal.dom.api.DOMDataTreeCommitCohortRegistration;
import org.opendaylight.mdsal.dom.api.DOMDataTreeIdentifier;
import org.opendaylight.yangtools.concepts.AbstractObjectRegistration;
import org.slf4j.Logger;
import scala.concurrent.Future;
import scala.concurrent.duration.FiniteDuration;
-public class DataTreeCohortRegistrationProxy<C extends DOMDataTreeCommitCohort> extends AbstractObjectRegistration<C>
- implements DOMDataTreeCommitCohortRegistration<C> {
-
+public class DataTreeCohortRegistrationProxy<C extends DOMDataTreeCommitCohort> extends AbstractObjectRegistration<C> {
private static final Logger LOG = LoggerFactory.getLogger(DataTreeCohortRegistrationProxy.class);
private static final Timeout TIMEOUT = new Timeout(new FiniteDuration(5, TimeUnit.SECONDS));
+
private final DOMDataTreeIdentifier subtree;
private final ActorRef actor;
private final ActorUtils actorUtils;
super(cohort);
this.subtree = requireNonNull(subtree);
this.actorUtils = requireNonNull(actorUtils);
- this.actor = actorUtils.getActorSystem().actorOf(DataTreeCohortActor.props(getInstance(),
- subtree.getRootIdentifier()).withDispatcher(actorUtils.getNotificationDispatcherPath()));
+ actor = actorUtils.getActorSystem().actorOf(DataTreeCohortActor.props(getInstance(),
+ subtree.path()).withDispatcher(actorUtils.getNotificationDispatcherPath()));
}
public void init(final String shardName) {
import org.opendaylight.controller.cluster.raft.DefaultConfigParamsImpl;
import org.opendaylight.controller.cluster.raft.PeerAddressResolver;
import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.distributed.datastore.provider.rev140612.DataStoreProperties.ExportOnRecovery;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.distributed.datastore.provider.rev231229.DataStoreProperties.ExportOnRecovery;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
private long transactionCreationInitialRateLimit = DEFAULT_TX_CREATION_INITIAL_RATE_LIMIT;
private String dataStoreName = UNKNOWN_DATA_STORE_TYPE;
private LogicalDatastoreType logicalStoreType = LogicalDatastoreType.OPERATIONAL;
- private YangInstanceIdentifier storeRoot = YangInstanceIdentifier.empty();
+ private YangInstanceIdentifier storeRoot = YangInstanceIdentifier.of();
private int shardBatchedModificationCount = DEFAULT_SHARD_BATCHED_MODIFICATION_COUNT;
private boolean writeOnlyTransactionOptimizationsEnabled = true;
private long shardCommitQueueExpiryTimeoutInMillis = DEFAULT_SHARD_COMMIT_QUEUE_EXPIRY_TIMEOUT_IN_MS;
- @Deprecated(since = "7.0.0", forRemoval = true)
- private boolean useTellBasedProtocol = true;
private boolean transactionDebugContextEnabled = false;
private String shardManagerPersistenceId;
private int maximumMessageSliceSize = DEFAULT_MAX_MESSAGE_SLICE_SIZE;
shardCommitQueueExpiryTimeoutInMillis = other.shardCommitQueueExpiryTimeoutInMillis;
transactionDebugContextEnabled = other.transactionDebugContextEnabled;
shardManagerPersistenceId = other.shardManagerPersistenceId;
- useTellBasedProtocol = other.useTellBasedProtocol;
backendAlivenessTimerInterval = other.backendAlivenessTimerInterval;
requestTimeout = other.requestTimeout;
noProgressTimeout = other.noProgressTimeout;
setCandidateElectionTimeoutDivisor(other.raftConfig.getCandidateElectionTimeoutDivisor());
setCustomRaftPolicyImplementation(other.raftConfig.getCustomRaftPolicyImplementationClass());
setMaximumMessageSliceSize(other.getMaximumMessageSliceSize());
- setShardSnapshotChunkSize(other.raftConfig.getSnapshotChunkSize());
setPeerAddressResolver(other.raftConfig.getPeerAddressResolver());
setTempFileDirectory(other.getTempFileDirectory());
setFileBackedStreamingThreshold(other.getFileBackedStreamingThreshold());
raftConfig.setRecoverySnapshotIntervalSeconds(recoverySnapshotInterval);
}
- @Deprecated
- private void setShardSnapshotChunkSize(final int shardSnapshotChunkSize) {
- // We'll honor the shardSnapshotChunkSize setting for backwards compatibility but only if it doesn't exceed
- // maximumMessageSliceSize.
- if (shardSnapshotChunkSize < maximumMessageSliceSize) {
- raftConfig.setSnapshotChunkSize(shardSnapshotChunkSize);
- }
- }
-
private void setMaximumMessageSliceSize(final int maximumMessageSliceSize) {
- raftConfig.setSnapshotChunkSize(maximumMessageSliceSize);
+ raftConfig.setMaximumMessageSliceSize(maximumMessageSliceSize);
this.maximumMessageSliceSize = maximumMessageSliceSize;
}
return transactionDebugContextEnabled;
}
- @Deprecated(since = "7.0.0", forRemoval = true)
- public boolean isUseTellBasedProtocol() {
- return useTellBasedProtocol;
- }
-
public boolean isUseLz4Compression() {
return useLz4Compression;
}
return this;
}
- @Deprecated(since = "7.0.0", forRemoval = true)
- public Builder useTellBasedProtocol(final boolean value) {
- datastoreContext.useTellBasedProtocol = value;
- return this;
- }
-
public Builder useLz4Compression(final boolean value) {
datastoreContext.useLz4Compression = value;
return this;
return this;
}
- @Deprecated
- public Builder shardSnapshotChunkSize(final int shardSnapshotChunkSize) {
- LOG.warn("The shard-snapshot-chunk-size configuration parameter is deprecated - "
- + "use maximum-message-slice-size instead");
- datastoreContext.setShardSnapshotChunkSize(shardSnapshotChunkSize);
- return this;
- }
-
public Builder maximumMessageSliceSize(final int maximumMessageSliceSize) {
datastoreContext.setMaximumMessageSliceSize(maximumMessageSliceSize);
return this;
import org.apache.commons.text.WordUtils;
import org.checkerframework.checker.lock.qual.GuardedBy;
import org.opendaylight.controller.cluster.datastore.DatastoreContext.Builder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.distributed.datastore.provider.rev140612.DataStoreProperties;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.distributed.datastore.provider.rev140612.DataStorePropertiesContainer;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.distributed.datastore.provider.rev231229.DataStoreProperties;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.distributed.datastore.provider.rev231229.DataStorePropertiesContainer;
import org.opendaylight.yangtools.yang.common.Uint16;
import org.opendaylight.yangtools.yang.common.Uint32;
import org.opendaylight.yangtools.yang.common.Uint64;
+++ /dev/null
-/*
- * Copyright (c) 2015 Brocade Communications Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.cluster.datastore;
-
-import static java.util.Objects.requireNonNull;
-
-import com.google.common.annotations.VisibleForTesting;
-import com.google.common.util.concurrent.FutureCallback;
-import com.google.common.util.concurrent.Futures;
-import com.google.common.util.concurrent.ListenableFuture;
-import com.google.common.util.concurrent.MoreExecutors;
-import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
-import java.util.List;
-import org.opendaylight.controller.cluster.access.concepts.TransactionIdentifier;
-import org.opendaylight.mdsal.common.api.CommitInfo;
-import org.opendaylight.yangtools.yang.common.Empty;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import scala.concurrent.Future;
-
-/**
- * An AbstractThreePhaseCommitCohort implementation used for debugging. If a failure occurs, the transaction
- * call site is printed.
- *
- * @author Thomas Pantelis
- */
-class DebugThreePhaseCommitCohort extends AbstractThreePhaseCommitCohort<Object> {
- private static final Logger LOG = LoggerFactory.getLogger(DebugThreePhaseCommitCohort.class);
-
- private final AbstractThreePhaseCommitCohort<?> delegate;
- private final Throwable debugContext;
- private final TransactionIdentifier transactionId;
-
- @SuppressFBWarnings("SLF4J_LOGGER_SHOULD_BE_FINAL")
- private Logger log = LOG;
-
- DebugThreePhaseCommitCohort(final TransactionIdentifier transactionId,
- final AbstractThreePhaseCommitCohort<?> delegate, final Throwable debugContext) {
- this.delegate = requireNonNull(delegate);
- this.debugContext = requireNonNull(debugContext);
- this.transactionId = requireNonNull(transactionId);
- }
-
- private <V> ListenableFuture<V> addFutureCallback(final ListenableFuture<V> future) {
- Futures.addCallback(future, new FutureCallback<V>() {
- @Override
- public void onSuccess(final V result) {
- // no-op
- }
-
- @Override
- public void onFailure(final Throwable failure) {
- log.warn("Transaction {} failed with error \"{}\" - was allocated in the following context",
- transactionId, failure, debugContext);
- }
- }, MoreExecutors.directExecutor());
-
- return future;
- }
-
- @Override
- public ListenableFuture<Boolean> canCommit() {
- return addFutureCallback(delegate.canCommit());
- }
-
- @Override
- public ListenableFuture<Empty> preCommit() {
- return addFutureCallback(delegate.preCommit());
- }
-
- @Override
- public ListenableFuture<? extends CommitInfo> commit() {
- return addFutureCallback(delegate.commit());
- }
-
- @Override
- public ListenableFuture<Empty> abort() {
- return delegate.abort();
- }
-
- @SuppressWarnings({ "rawtypes", "unchecked" })
- @Override
- List<Future<Object>> getCohortFutures() {
- return ((AbstractThreePhaseCommitCohort)delegate).getCohortFutures();
- }
-
- @VisibleForTesting
- void setLogger(final Logger logger) {
- log = logger;
- }
-}
import java.util.Optional;
import java.util.function.Consumer;
import org.opendaylight.mdsal.dom.api.DOMDataTreeChangeListener;
-import org.opendaylight.mdsal.dom.spi.AbstractDOMDataTreeChangeListenerRegistration;
import org.opendaylight.mdsal.dom.spi.store.AbstractDOMStoreTreeChangePublisher;
-import org.opendaylight.yangtools.concepts.ListenerRegistration;
+import org.opendaylight.yangtools.concepts.Registration;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
import org.opendaylight.yangtools.yang.data.tree.api.DataTreeCandidate;
import org.slf4j.Logger;
}
@Override
- protected void notifyListener(final AbstractDOMDataTreeChangeListenerRegistration<?> registration,
- final List<DataTreeCandidate> changes) {
- LOG.debug("{}: notifyListener: listener: {}", logContext, registration.getInstance());
- registration.getInstance().onDataTreeChanged(changes);
+ protected void notifyListener(final Reg registration, final List<DataTreeCandidate> changes) {
+ final var listener = registration.listener();
+ LOG.debug("{}: notifyListener: listener: {}", logContext, listener);
+ listener.onDataTreeChanged(changes);
}
@Override
- protected void registrationRemoved(final AbstractDOMDataTreeChangeListenerRegistration<?> registration) {
+ protected void registrationRemoved(final Reg registration) {
LOG.debug("Registration {} removed", registration);
}
@Override
public void registerTreeChangeListener(final YangInstanceIdentifier treeId,
final DOMDataTreeChangeListener listener, final Optional<DataTreeCandidate> initialState,
- final Consumer<ListenerRegistration<DOMDataTreeChangeListener>> onRegistration) {
+ final Consumer<Registration> onRegistration) {
registerTreeChangeListener(treeId, listener, onRegistration);
if (initialState.isPresent()) {
- notifySingleListener(treeId, listener, initialState.get(), logContext);
+ notifySingleListener(treeId, listener, initialState.orElseThrow(), logContext);
} else {
listener.onInitialData();
}
}
void registerTreeChangeListener(final YangInstanceIdentifier treeId, final DOMDataTreeChangeListener listener,
- final Consumer<ListenerRegistration<DOMDataTreeChangeListener>> onRegistration) {
+ final Consumer<Registration> onRegistration) {
LOG.debug("{}: registerTreeChangeListener: path: {}, listener: {}", logContext, treeId, listener);
-
- AbstractDOMDataTreeChangeListenerRegistration<DOMDataTreeChangeListener> registration =
- super.registerTreeChangeListener(treeId, listener);
-
- onRegistration.accept(registration);
+ onRegistration.accept(super.registerTreeChangeListener(treeId, listener));
}
static void notifySingleListener(final YangInstanceIdentifier treeId, final DOMDataTreeChangeListener listener,
package org.opendaylight.controller.cluster.datastore;
import akka.actor.ActorRef;
-import java.util.EventListener;
import org.checkerframework.checker.lock.qual.GuardedBy;
import org.opendaylight.controller.cluster.datastore.messages.RegisterDataTreeChangeListener;
-import org.opendaylight.yangtools.concepts.ListenerRegistration;
+import org.opendaylight.yangtools.concepts.Registration;
-class DelayedDataTreeChangeListenerRegistration<L extends EventListener> implements ListenerRegistration<L> {
+class DelayedDataTreeChangeListenerRegistration implements Registration {
private final RegisterDataTreeChangeListener registrationMessage;
private final ActorRef registrationActor;
}
}
- @Override
- public L getInstance() {
- // ObjectRegistration annotates this method as @Nonnull but we could return null if the delegate is not set yet.
- // In reality, we do not and should not ever call this method on DelayedDataTreeChangeListenerRegistration
- // instances anyway but, since we have to provide an implementation to satisfy the interface, we throw
- // UnsupportedOperationException to honor the API contract of not returning null and to avoid a FindBugs error
- // for possibly returning null.
- throw new UnsupportedOperationException(
- "getInstance should not be called on this instance since it could be null");
- }
-
@Override
public synchronized void close() {
closed = true;
+++ /dev/null
-/*
- * Copyright (c) 2015 Brocade Communications Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.cluster.datastore;
-
-import static com.google.common.base.Preconditions.checkState;
-
-import akka.actor.ActorSelection;
-import akka.dispatch.Futures;
-import java.util.AbstractMap.SimpleImmutableEntry;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.List;
-import java.util.Map.Entry;
-import java.util.Optional;
-import java.util.SortedSet;
-import org.checkerframework.checker.lock.qual.GuardedBy;
-import org.eclipse.jdt.annotation.NonNull;
-import org.opendaylight.controller.cluster.access.concepts.TransactionIdentifier;
-import org.opendaylight.controller.cluster.datastore.utils.ActorUtils;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import scala.concurrent.Future;
-import scala.concurrent.Promise;
-
-/**
- * Delayed implementation of TransactionContextWrapper. Operations destined for the target
- * TransactionContext instance are cached until the TransactionContext instance becomes
- * available at which time they are executed.
- *
- * @author Thomas Pantelis
- */
-final class DelayedTransactionContextWrapper extends AbstractTransactionContextWrapper {
- private static final Logger LOG = LoggerFactory.getLogger(DelayedTransactionContextWrapper.class);
-
- /**
- * The list of transaction operations to execute once the TransactionContext becomes available.
- */
- @GuardedBy("queuedTxOperations")
- private final List<Entry<TransactionOperation, Boolean>> queuedTxOperations = new ArrayList<>();
-
- /**
- * The resulting TransactionContext.
- */
- private volatile TransactionContext transactionContext;
- @GuardedBy("queuedTxOperations")
- private TransactionContext deferredTransactionContext;
- @GuardedBy("queuedTxOperations")
- private boolean pendingEnqueue;
-
- DelayedTransactionContextWrapper(@NonNull final TransactionIdentifier identifier,
- @NonNull final ActorUtils actorUtils, @NonNull final String shardName) {
- super(identifier, actorUtils, shardName);
- }
-
- @Override
- TransactionContext getTransactionContext() {
- return transactionContext;
- }
-
- @Override
- void maybeExecuteTransactionOperation(final TransactionOperation op) {
- final TransactionContext localContext = transactionContext;
- if (localContext != null) {
- op.invoke(localContext, null);
- } else {
- // The shard Tx hasn't been created yet so add the Tx operation to the Tx Future
- // callback to be executed after the Tx is created.
- enqueueTransactionOperation(op);
- }
- }
-
- @Override
- Future<ActorSelection> readyTransaction(final Optional<SortedSet<String>> participatingShardNames) {
- // avoid the creation of a promise and a TransactionOperation
- final TransactionContext localContext = transactionContext;
- if (localContext != null) {
- return localContext.readyTransaction(null, participatingShardNames);
- }
-
- final Promise<ActorSelection> promise = Futures.promise();
- enqueueTransactionOperation(new TransactionOperation() {
- @Override
- public void invoke(final TransactionContext newTransactionContext, final Boolean havePermit) {
- promise.completeWith(newTransactionContext.readyTransaction(havePermit, participatingShardNames));
- }
- });
-
- return promise.future();
- }
-
- /**
- * Adds a TransactionOperation to be executed once the TransactionContext becomes available. This method is called
- * only after the caller has checked (without synchronizing with executePriorTransactionOperations()) that the
- * context is not available.
- */
- private void enqueueTransactionOperation(final TransactionOperation operation) {
- // We have three things to do here:
- // - synchronize with executePriorTransactionOperations() so that logical operation ordering is maintained
- // - acquire a permit for the operation if we still need to enqueue it
- // - enqueue the operation
- //
- // Since each operation needs to acquire a permit exactly once and the limiter is shared between us and the
- // TransactionContext, we need to know whether an operation has a permit before we enqueue it. Further
- // complications are:
- // - this method may be called from the thread invoking executePriorTransactionOperations()
- // - user may be violating API contract of using the transaction from a single thread
-
- // As a first step, we will synchronize on the queue and check if the handoff has completed. While we have
- // the lock, we will assert that we will be enqueing another operation.
- final TransactionContext contextOnEntry;
- synchronized (queuedTxOperations) {
- contextOnEntry = transactionContext;
- if (contextOnEntry == null) {
- checkState(!pendingEnqueue, "Concurrent access to transaction %s detected", getIdentifier());
- pendingEnqueue = true;
- }
- }
-
- // Short-circuit if there is a context
- if (contextOnEntry != null) {
- operation.invoke(transactionContext, null);
- return;
- }
-
- boolean cleanupEnqueue = true;
- TransactionContext finishHandoff = null;
- try {
- // Acquire the permit,
- final boolean havePermit = getLimiter().acquire();
- if (!havePermit) {
- LOG.warn("Failed to acquire enqueue operation permit for transaction {} on shard {}", getIdentifier(),
- getShardName());
- }
-
- // Ready to enqueue, take the lock again and append the operation
- synchronized (queuedTxOperations) {
- LOG.debug("Tx {} Queuing TransactionOperation", getIdentifier());
- queuedTxOperations.add(new SimpleImmutableEntry<>(operation, havePermit));
- pendingEnqueue = false;
- cleanupEnqueue = false;
- finishHandoff = deferredTransactionContext;
- deferredTransactionContext = null;
- }
- } finally {
- if (cleanupEnqueue) {
- synchronized (queuedTxOperations) {
- pendingEnqueue = false;
- finishHandoff = deferredTransactionContext;
- deferredTransactionContext = null;
- }
- }
- if (finishHandoff != null) {
- executePriorTransactionOperations(finishHandoff);
- }
- }
- }
-
- void executePriorTransactionOperations(final TransactionContext localTransactionContext) {
- while (true) {
- // Access to queuedTxOperations and transactionContext must be protected and atomic
- // (ie synchronized) with respect to #addTxOperationOnComplete to handle timing
- // issues and ensure no TransactionOperation is missed and that they are processed
- // in the order they occurred.
-
- // We'll make a local copy of the queuedTxOperations list to handle re-entrancy
- // in case a TransactionOperation results in another transaction operation being
- // queued (eg a put operation from a client read Future callback that is notified
- // synchronously).
- final Collection<Entry<TransactionOperation, Boolean>> operationsBatch;
- synchronized (queuedTxOperations) {
- if (queuedTxOperations.isEmpty()) {
- if (!pendingEnqueue) {
- // We're done invoking the TransactionOperations so we can now publish the TransactionContext.
- localTransactionContext.operationHandOffComplete();
-
- // This is null-to-non-null transition after which we are releasing the lock and not doing
- // any further processing.
- transactionContext = localTransactionContext;
- } else {
- deferredTransactionContext = localTransactionContext;
- }
- return;
- }
-
- operationsBatch = new ArrayList<>(queuedTxOperations);
- queuedTxOperations.clear();
- }
-
- // Invoke TransactionOperations outside the sync block to avoid unnecessary blocking. A slight down-side is
- // that we need to re-acquire the lock below but this should be negligible.
- for (Entry<TransactionOperation, Boolean> oper : operationsBatch) {
- final Boolean permit = oper.getValue();
- if (permit.booleanValue() && !localTransactionContext.usesOperationLimiting()) {
- // If the context is not using limiting we need to release operations as we are queueing them, so
- // user threads are not charged for them.
- getLimiter().release();
- }
- oper.getKey().invoke(localTransactionContext, permit);
- }
- }
- }
-
-}
+++ /dev/null
-/*
- * Copyright (c) 2021 PANTHEON.tech, s.r.o. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.cluster.datastore;
-
-import static java.util.Objects.requireNonNull;
-
-import akka.actor.ActorSelection;
-import java.util.Optional;
-import java.util.SortedSet;
-import org.eclipse.jdt.annotation.NonNull;
-import org.opendaylight.controller.cluster.access.concepts.TransactionIdentifier;
-import org.opendaylight.controller.cluster.datastore.utils.ActorUtils;
-import scala.concurrent.Future;
-
-/**
- * Direct implementation of TransactionContextWrapper. Operation are executed directly on TransactionContext. Always
- * has completed context and executes on local shard.
- */
-final class DirectTransactionContextWrapper extends AbstractTransactionContextWrapper {
- private final TransactionContext transactionContext;
-
- DirectTransactionContextWrapper(@NonNull final TransactionIdentifier identifier,
- @NonNull final ActorUtils actorUtils,
- @NonNull final String shardName,
- @NonNull final TransactionContext transactionContext) {
- super(identifier, actorUtils, shardName);
- this.transactionContext = requireNonNull(transactionContext);
- }
-
- @Override
- TransactionContext getTransactionContext() {
- return transactionContext;
- }
-
- @Override
- void maybeExecuteTransactionOperation(final TransactionOperation op) {
- op.invoke(transactionContext, null);
- }
-
- @Override
- Future<ActorSelection> readyTransaction(final Optional<SortedSet<String>> participatingShardNames) {
- return transactionContext.readyTransaction(null, participatingShardNames);
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.cluster.datastore;
-
-import akka.actor.ActorSystem;
-import com.google.common.annotations.VisibleForTesting;
-import org.opendaylight.controller.cluster.access.concepts.ClientIdentifier;
-import org.opendaylight.controller.cluster.datastore.config.Configuration;
-import org.opendaylight.controller.cluster.datastore.persisted.DatastoreSnapshot;
-import org.opendaylight.controller.cluster.datastore.utils.ActorUtils;
-import org.opendaylight.mdsal.dom.spi.store.DOMStoreReadTransaction;
-import org.opendaylight.mdsal.dom.spi.store.DOMStoreReadWriteTransaction;
-import org.opendaylight.mdsal.dom.spi.store.DOMStoreTransactionChain;
-import org.opendaylight.mdsal.dom.spi.store.DOMStoreWriteTransaction;
-
-/**
- * Implements a distributed DOMStore using Akka {@code Patterns.ask()}.
- *
- * @deprecated This implementation is destined for removal,
- */
-@Deprecated(since = "7.0.0", forRemoval = true)
-public class DistributedDataStore extends AbstractDataStore {
- private final TransactionContextFactory txContextFactory;
-
- public DistributedDataStore(final ActorSystem actorSystem, final ClusterWrapper cluster,
- final Configuration configuration, final DatastoreContextFactory datastoreContextFactory,
- final DatastoreSnapshot restoreFromSnapshot) {
- super(actorSystem, cluster, configuration, datastoreContextFactory, restoreFromSnapshot);
- txContextFactory = new TransactionContextFactory(getActorUtils(), getIdentifier());
- }
-
- @VisibleForTesting
- DistributedDataStore(final ActorUtils actorUtils, final ClientIdentifier identifier) {
- super(actorUtils, identifier);
- txContextFactory = new TransactionContextFactory(getActorUtils(), getIdentifier());
- }
-
-
- @Override
- public DOMStoreTransactionChain createTransactionChain() {
- return txContextFactory.createTransactionChain();
- }
-
- @Override
- public DOMStoreReadTransaction newReadOnlyTransaction() {
- return new TransactionProxy(txContextFactory, TransactionType.READ_ONLY);
- }
-
- @Override
- public DOMStoreWriteTransaction newWriteOnlyTransaction() {
- getActorUtils().acquireTxCreationPermit();
- return new TransactionProxy(txContextFactory, TransactionType.WRITE_ONLY);
- }
-
- @Override
- public DOMStoreReadWriteTransaction newReadWriteTransaction() {
- getActorUtils().acquireTxCreationPermit();
- return new TransactionProxy(txContextFactory, TransactionType.READ_WRITE);
- }
-
- @Override
- public void close() {
- txContextFactory.close();
- super.close();
- }
-}
*/
package org.opendaylight.controller.cluster.datastore;
-import akka.actor.ActorSystem;
import org.opendaylight.controller.cluster.ActorSystemProvider;
import org.opendaylight.controller.cluster.databroker.ClientBackedDataStore;
import org.opendaylight.controller.cluster.datastore.config.Configuration;
import org.opendaylight.controller.cluster.datastore.config.ConfigurationImpl;
-import org.opendaylight.controller.cluster.datastore.persisted.DatastoreSnapshot;
import org.opendaylight.mdsal.dom.api.DOMSchemaService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
updater.setListener(dataStore);
- schemaService.registerSchemaContextListener(dataStore);
+ schemaService.registerSchemaContextListener(dataStore::onModelContextUpdated);
dataStore.setCloseable(updater);
dataStore.waitTillReady();
final String datastoreName = initialDatastoreContext.getDataStoreName();
LOG.info("Create data store instance of type : {}", datastoreName);
- final ActorSystem actorSystem = actorSystemProvider.getActorSystem();
- final DatastoreSnapshot restoreFromSnapshot = datastoreSnapshotRestore.getAndRemove(datastoreName).orElse(null);
+ final var actorSystem = actorSystemProvider.getActorSystem();
+ final var restoreFromSnapshot = datastoreSnapshotRestore.getAndRemove(datastoreName).orElse(null);
final Configuration config;
if (orgConfig == null) {
} else {
config = orgConfig;
}
- final ClusterWrapper clusterWrapper = new ClusterWrapperImpl(actorSystem);
- final DatastoreContextFactory contextFactory = introspector.newContextFactory();
+ final var clusterWrapper = new ClusterWrapperImpl(actorSystem);
+ final var contextFactory = introspector.newContextFactory();
- // This is the potentially-updated datastore context, distinct from the initial one
- final DatastoreContext datastoreContext = contextFactory.getBaseDatastoreContext();
-
- final AbstractDataStore dataStore;
- if (datastoreContext.isUseTellBasedProtocol()) {
- dataStore = new ClientBackedDataStore(actorSystem, clusterWrapper, config, contextFactory,
- restoreFromSnapshot);
- LOG.info("Data store {} is using tell-based protocol", datastoreName);
- } else {
- dataStore = new DistributedDataStore(actorSystem, clusterWrapper, config, contextFactory,
- restoreFromSnapshot);
- LOG.warn("Data store {} is using ask-based protocol, which will be removed in the next major release",
- datastoreName);
- }
-
- return dataStore;
+ final var ret = new ClientBackedDataStore(actorSystem, clusterWrapper, config, contextFactory,
+ restoreFromSnapshot);
+ LOG.info("Data store {} is using tell-based protocol", datastoreName);
+ return ret;
}
}
import org.opendaylight.controller.cluster.datastore.utils.ActorUtils;
import org.opendaylight.mdsal.dom.api.DOMDataTreeChangeListener;
import org.opendaylight.mdsal.dom.spi.store.DOMStore;
-import org.opendaylight.yangtools.concepts.ListenerRegistration;
+import org.opendaylight.yangtools.concepts.Registration;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
/**
ActorUtils getActorUtils();
@Beta
- <L extends DOMDataTreeChangeListener> ListenerRegistration<L> registerProxyListener(
- YangInstanceIdentifier shardLookup, YangInstanceIdentifier insideShard,
+ Registration registerProxyListener(YangInstanceIdentifier shardLookup, YangInstanceIdentifier insideShard,
DOMDataTreeChangeListener delegate);
}
*/
package org.opendaylight.controller.cluster.datastore;
-import static com.google.common.base.Verify.verify;
import static java.util.Objects.requireNonNull;
import com.google.common.base.MoreObjects;
import com.google.common.base.MoreObjects.ToStringHelper;
+import com.google.common.base.VerifyException;
import com.google.common.collect.Collections2;
import com.google.common.collect.ImmutableList;
import java.util.HashMap;
import org.opendaylight.controller.cluster.access.concepts.LocalHistoryIdentifier;
import org.opendaylight.controller.cluster.access.concepts.TransactionIdentifier;
import org.opendaylight.controller.cluster.datastore.persisted.FrontendClientMetadata;
-import org.opendaylight.controller.cluster.datastore.persisted.FrontendHistoryMetadata;
import org.opendaylight.controller.cluster.datastore.utils.ImmutableUnsignedLongSet;
import org.opendaylight.controller.cluster.datastore.utils.MutableUnsignedLongSet;
-import org.opendaylight.yangtools.concepts.Identifiable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* This class is NOT thread-safe.
*/
-// FIXME: sealed when we have JDK17+
-abstract class FrontendClientMetadataBuilder implements Identifiable<ClientIdentifier> {
+abstract sealed class FrontendClientMetadataBuilder {
static final class Disabled extends FrontendClientMetadataBuilder {
- Disabled(final String shardName, final ClientIdentifier identifier) {
- super(shardName, identifier);
+ Disabled(final String shardName, final ClientIdentifier clientId) {
+ super(shardName, clientId);
}
@Override
FrontendClientMetadata build() {
- return new FrontendClientMetadata(getIdentifier(), ImmutableUnsignedLongSet.of(), ImmutableList.of());
+ return new FrontendClientMetadata(clientId(), ImmutableUnsignedLongSet.of(), ImmutableList.of());
}
@Override
@Override
LeaderFrontendState toLeaderState(final Shard shard) {
- return new LeaderFrontendState.Disabled(shard.persistenceId(), getIdentifier(), shard.getDataStore());
+ return new LeaderFrontendState.Disabled(shard.persistenceId(), clientId(), shard.getDataStore());
}
}
private final MutableUnsignedLongSet purgedHistories;
private final LocalHistoryIdentifier standaloneId;
- Enabled(final String shardName, final ClientIdentifier identifier) {
- super(shardName, identifier);
+ Enabled(final String shardName, final ClientIdentifier clientId) {
+ super(shardName, clientId);
purgedHistories = MutableUnsignedLongSet.of();
}
Enabled(final String shardName, final FrontendClientMetadata meta) {
- super(shardName, meta.getIdentifier());
+ super(shardName, meta.clientId());
purgedHistories = meta.getPurgedHistories().mutableCopy();
- for (FrontendHistoryMetadata h : meta.getCurrentHistories()) {
- final FrontendHistoryMetadataBuilder b = new FrontendHistoryMetadataBuilder(getIdentifier(), h);
- currentHistories.put(b.getIdentifier(), b);
+ for (var historyMeta : meta.getCurrentHistories()) {
+ final var builder = new FrontendHistoryMetadataBuilder(clientId(), historyMeta);
+ currentHistories.put(builder.getIdentifier(), builder);
}
// Sanity check and recovery
standaloneId = standaloneHistoryId();
if (!currentHistories.containsKey(standaloneId)) {
LOG.warn("{}: Client {} recovered histories {} do not contain stand-alone history, attempting recovery",
- shardName, getIdentifier(), currentHistories);
+ shardName, clientId(), currentHistories);
currentHistories.put(standaloneId, new FrontendHistoryMetadataBuilder(standaloneId));
}
}
@Override
FrontendClientMetadata build() {
- return new FrontendClientMetadata(getIdentifier(), purgedHistories.immutableCopy(),
+ return new FrontendClientMetadata(clientId(), purgedHistories.immutableCopy(),
Collections2.transform(currentHistories.values(), FrontendHistoryMetadataBuilder::build));
}
@Override
void onHistoryCreated(final LocalHistoryIdentifier historyId) {
- final FrontendHistoryMetadataBuilder newMeta = new FrontendHistoryMetadataBuilder(historyId);
- final FrontendHistoryMetadataBuilder oldMeta = currentHistories.putIfAbsent(historyId, newMeta);
+ final var newMeta = new FrontendHistoryMetadataBuilder(historyId);
+ final var oldMeta = currentHistories.putIfAbsent(historyId, newMeta);
if (oldMeta != null) {
// This should not be happening, warn about it
LOG.warn("{}: Reused local history {}", shardName(), historyId);
@Override
void onHistoryClosed(final LocalHistoryIdentifier historyId) {
- final FrontendHistoryMetadataBuilder builder = currentHistories.get(historyId);
+ final var builder = currentHistories.get(historyId);
if (builder != null) {
builder.onHistoryClosed();
LOG.debug("{}: Closed history {}", shardName(), historyId);
@Override
void onHistoryPurged(final LocalHistoryIdentifier historyId) {
- final FrontendHistoryMetadataBuilder history = currentHistories.remove(historyId);
+ final var history = currentHistories.remove(historyId);
final long historyBits = historyId.getHistoryId();
if (history == null) {
if (!purgedHistories.contains(historyBits)) {
@Override
void onTransactionAborted(final TransactionIdentifier txId) {
- final FrontendHistoryMetadataBuilder history = getHistory(txId);
+ final var history = getHistory(txId);
if (history != null) {
history.onTransactionAborted(txId);
LOG.debug("{}: Aborted transaction {}", shardName(), txId);
@Override
void onTransactionCommitted(final TransactionIdentifier txId) {
- final FrontendHistoryMetadataBuilder history = getHistory(txId);
+ final var history = getHistory(txId);
if (history != null) {
history.onTransactionCommitted(txId);
LOG.debug("{}: Committed transaction {}", shardName(), txId);
@Override
void onTransactionPurged(final TransactionIdentifier txId) {
- final FrontendHistoryMetadataBuilder history = getHistory(txId);
+ final var history = getHistory(txId);
if (history != null) {
history.onTransactionPurged(txId);
LOG.debug("{}: Purged transaction {}", shardName(), txId);
LeaderFrontendState toLeaderState(final Shard shard) {
// Note: we have to make sure to *copy* all current state and not leak any views, otherwise leader/follower
// interactions would get intertwined leading to inconsistencies.
- final Map<LocalHistoryIdentifier, LocalFrontendHistory> histories = new HashMap<>();
- for (FrontendHistoryMetadataBuilder e : currentHistories.values()) {
- if (e.getIdentifier().getHistoryId() != 0) {
- final AbstractFrontendHistory state = e.toLeaderState(shard);
- verify(state instanceof LocalFrontendHistory, "Unexpected state %s", state);
- histories.put(e.getIdentifier(), (LocalFrontendHistory) state);
+ final var histories = new HashMap<LocalHistoryIdentifier, LocalFrontendHistory>();
+ for (var historyMetaBuilder : currentHistories.values()) {
+ final var historyId = historyMetaBuilder.getIdentifier();
+ if (historyId.getHistoryId() != 0) {
+ final var state = historyMetaBuilder.toLeaderState(shard);
+ if (state instanceof LocalFrontendHistory localState) {
+ histories.put(historyId, localState);
+ } else {
+ throw new VerifyException("Unexpected state " + state);
+ }
}
}
final AbstractFrontendHistory singleHistory;
- final FrontendHistoryMetadataBuilder singleHistoryMeta = currentHistories.get(
- new LocalHistoryIdentifier(getIdentifier(), 0));
+ final var singleHistoryMeta = currentHistories.get(new LocalHistoryIdentifier(clientId(), 0));
if (singleHistoryMeta == null) {
- final ShardDataTree tree = shard.getDataStore();
- singleHistory = StandaloneFrontendHistory.create(shard.persistenceId(), getIdentifier(), tree);
+ final var tree = shard.getDataStore();
+ singleHistory = StandaloneFrontendHistory.create(shard.persistenceId(), clientId(), tree);
} else {
singleHistory = singleHistoryMeta.toLeaderState(shard);
}
- return new LeaderFrontendState.Enabled(shard.persistenceId(), getIdentifier(), shard.getDataStore(),
+ return new LeaderFrontendState.Enabled(shard.persistenceId(), clientId(), shard.getDataStore(),
purgedHistories.mutableCopy(), singleHistory, histories);
}
}
private LocalHistoryIdentifier standaloneHistoryId() {
- return new LocalHistoryIdentifier(getIdentifier(), 0);
+ return new LocalHistoryIdentifier(clientId(), 0);
}
}
private static final Logger LOG = LoggerFactory.getLogger(FrontendClientMetadataBuilder.class);
- private final @NonNull ClientIdentifier identifier;
+ private final @NonNull ClientIdentifier clientId;
private final @NonNull String shardName;
- FrontendClientMetadataBuilder(final String shardName, final ClientIdentifier identifier) {
+ FrontendClientMetadataBuilder(final String shardName, final ClientIdentifier clientId) {
this.shardName = requireNonNull(shardName);
- this.identifier = requireNonNull(identifier);
+ this.clientId = requireNonNull(clientId);
}
static FrontendClientMetadataBuilder of(final String shardName, final FrontendClientMetadata meta) {
// Completely empty histories imply disabled state, as otherwise we'd have a record of the single history --
// either purged or active
return meta.getCurrentHistories().isEmpty() && meta.getPurgedHistories().isEmpty()
- ? new Disabled(shardName, meta.getIdentifier()) : new Enabled(shardName, meta);
+ ? new Disabled(shardName, meta.clientId()) : new Enabled(shardName, meta);
}
- @Override
- public final ClientIdentifier getIdentifier() {
- return identifier;
+ final ClientIdentifier clientId() {
+ return clientId;
}
final String shardName() {
}
ToStringHelper addToStringAttributes(final ToStringHelper helper) {
- return helper.add("identifier", identifier);
+ return helper.add("clientId", clientId);
}
}
import org.opendaylight.controller.cluster.access.concepts.FrontendIdentifier;
import org.opendaylight.controller.cluster.access.concepts.LocalHistoryIdentifier;
import org.opendaylight.controller.cluster.access.concepts.TransactionIdentifier;
-import org.opendaylight.controller.cluster.datastore.persisted.FrontendClientMetadata;
import org.opendaylight.controller.cluster.datastore.persisted.FrontendShardDataTreeSnapshotMetadata;
import org.opendaylight.controller.cluster.datastore.utils.ImmutableUnsignedLongSet;
import org.slf4j.Logger;
LOG.debug("{}: applying snapshot {} over clients {}", shardName, snapshot, clients);
clients.clear();
- for (FrontendClientMetadata m : snapshot.getClients()) {
- LOG.debug("{}: applying metadata {}", shardName, m);
- final FrontendClientMetadataBuilder b = FrontendClientMetadataBuilder.of(shardName, m);
- final FrontendIdentifier client = m.getIdentifier().getFrontendId();
+ for (var clientMeta : snapshot.getClients()) {
+ LOG.debug("{}: applying metadata {}", shardName, clientMeta);
+ final var builder = FrontendClientMetadataBuilder.of(shardName, clientMeta);
+ final var frontendId = clientMeta.clientId().getFrontendId();
- LOG.debug("{}: client {} updated to {}", shardName, client, b);
- clients.put(client, b);
+ LOG.debug("{}: client {} updated to {}", shardName, frontendId, builder);
+ clients.put(frontendId, builder);
}
}
}
private FrontendClientMetadataBuilder ensureClient(final ClientIdentifier id) {
- final FrontendClientMetadataBuilder existing = clients.get(id.getFrontendId());
- if (existing != null && id.equals(existing.getIdentifier())) {
+ final var existing = clients.get(id.getFrontendId());
+ if (existing != null && id.equals(existing.clientId())) {
return existing;
}
- final FrontendClientMetadataBuilder client = new FrontendClientMetadataBuilder.Enabled(shardName, id);
- final FrontendClientMetadataBuilder previous = clients.put(id.getFrontendId(), client);
+ final var client = new FrontendClientMetadataBuilder.Enabled(shardName, id);
+ final var previous = clients.put(id.getFrontendId(), client);
if (previous != null) {
LOG.debug("{}: Replaced client {} with {}", shardName, previous, client);
} else {
}
void disableTracking(final ClientIdentifier clientId) {
- final FrontendIdentifier frontendId = clientId.getFrontendId();
- final FrontendClientMetadataBuilder client = clients.get(frontendId);
+ final var frontendId = clientId.getFrontendId();
+ final var client = clients.get(frontendId);
if (client == null) {
// When we have not seen the client before, we still need to disable tracking for him since this only gets
// triggered once.
clients.put(frontendId, new FrontendClientMetadataBuilder.Disabled(shardName, clientId));
return;
}
- if (!clientId.equals(client.getIdentifier())) {
+ if (!clientId.equals(client.clientId())) {
LOG.debug("{}: disableTracking {} does not match client {}, ignoring", shardName, clientId, client);
return;
}
ImmutableSet<ClientIdentifier> getClients() {
return clients.values().stream()
- .map(FrontendClientMetadataBuilder::getIdentifier)
- .collect(ImmutableSet.toImmutableSet());
+ .map(FrontendClientMetadataBuilder::clientId)
+ .collect(ImmutableSet.toImmutableSet());
}
}
private FrontendReadOnlyTransaction(final AbstractFrontendHistory history,
final ReadOnlyShardDataTreeTransaction transaction) {
super(history, transaction.getIdentifier());
- this.openTransaction = requireNonNull(transaction);
+ openTransaction = requireNonNull(transaction);
}
static FrontendReadOnlyTransaction create(final AbstractFrontendHistory history,
// The only valid request here is with abort protocol
final Optional<PersistenceProtocol> optProto = request.getPersistenceProtocol();
checkArgument(optProto.isPresent(), "Commit protocol is missing in %s", request);
- checkArgument(optProto.get() == PersistenceProtocol.ABORT, "Unsupported commit protocol in %s", request);
+ checkArgument(optProto.orElseThrow() == PersistenceProtocol.ABORT, "Unsupported commit protocol in %s",
+ request);
openTransaction.abort(() -> recordAndSendSuccess(envelope, now,
new ModifyTransactionSuccess(request.getTarget(), request.getSequence())));
}
@Override
TransactionSuccess<?> doHandleRequest(final TransactionRequest<?> request, final RequestEnvelope envelope,
final long now) throws RequestException {
- if (request instanceof ModifyTransactionRequest) {
- return handleModifyTransaction((ModifyTransactionRequest) request, envelope, now);
- } else if (request instanceof CommitLocalTransactionRequest) {
- handleCommitLocalTransaction((CommitLocalTransactionRequest) request, envelope, now);
+ if (request instanceof ModifyTransactionRequest modifyRequest) {
+ return handleModifyTransaction(modifyRequest, envelope, now);
+ } else if (request instanceof CommitLocalTransactionRequest commitLocalRequest) {
+ handleCommitLocalTransaction(commitLocalRequest, envelope, now);
return null;
- } else if (request instanceof ExistsTransactionRequest) {
- return handleExistsTransaction((ExistsTransactionRequest) request);
- } else if (request instanceof ReadTransactionRequest) {
- return handleReadTransaction((ReadTransactionRequest) request);
- } else if (request instanceof TransactionPreCommitRequest) {
- handleTransactionPreCommit((TransactionPreCommitRequest) request, envelope, now);
+ } else if (request instanceof ExistsTransactionRequest existsRequest) {
+ return handleExistsTransaction(existsRequest);
+ } else if (request instanceof ReadTransactionRequest readRequest) {
+ return handleReadTransaction(readRequest);
+ } else if (request instanceof TransactionPreCommitRequest preCommitRequest) {
+ handleTransactionPreCommit(preCommitRequest, envelope, now);
return null;
- } else if (request instanceof TransactionDoCommitRequest) {
- handleTransactionDoCommit((TransactionDoCommitRequest) request, envelope, now);
+ } else if (request instanceof TransactionDoCommitRequest doCommitRequest) {
+ handleTransactionDoCommit(doCommitRequest, envelope, now);
return null;
} else if (request instanceof TransactionAbortRequest) {
return handleTransactionAbort(request.getSequence(), envelope, now);
final Optional<Exception> optFailure = request.getDelayedFailure();
if (optFailure.isPresent()) {
- state = new Ready(history().createFailedCohort(getIdentifier(), sealedModification, optFailure.get()));
+ state = new Ready(history().createFailedCohort(getIdentifier(), sealedModification,
+ optFailure.orElseThrow()));
} else {
state = new Ready(history().createReadyCohort(getIdentifier(), sealedModification, Optional.empty()));
}
for (TransactionModification m : modifications) {
if (m instanceof TransactionDelete) {
modification.delete(m.getPath());
- } else if (m instanceof TransactionWrite) {
- modification.write(m.getPath(), ((TransactionWrite) m).getData());
- } else if (m instanceof TransactionMerge) {
- modification.merge(m.getPath(), ((TransactionMerge) m).getData());
+ } else if (m instanceof TransactionWrite write) {
+ modification.write(m.getPath(), write.getData());
+ } else if (m instanceof TransactionMerge merge) {
+ modification.merge(m.getPath(), merge.getData());
} else {
LOG.warn("{}: ignoring unhandled modification {}", persistenceId(), m);
}
return replyModifySuccess(request.getSequence());
}
- switch (maybeProto.get()) {
+ switch (maybeProto.orElseThrow()) {
case ABORT:
if (ABORTING.equals(state)) {
LOG.debug("{}: Transaction {} already aborting", persistenceId(), getIdentifier());
coordinatedCommit(envelope, now);
return null;
default:
- LOG.warn("{}: rejecting unsupported protocol {}", persistenceId(), maybeProto.get());
+ LOG.warn("{}: rejecting unsupported protocol {}", persistenceId(), maybeProto.orElseThrow());
throw new UnsupportedRequestException(request);
}
}
import com.google.common.base.MoreObjects;
import com.google.common.base.MoreObjects.ToStringHelper;
import java.util.HashMap;
-import java.util.Iterator;
import java.util.Map;
import org.eclipse.jdt.annotation.NonNull;
import org.eclipse.jdt.annotation.Nullable;
/**
* Frontend state as observed by the shard leader. This class is responsible for tracking generations and sequencing
* in the frontend/backend conversation. This class is NOT thread-safe.
- *
- * @author Robert Varga
*/
-abstract class LeaderFrontendState implements Identifiable<ClientIdentifier> {
+abstract sealed class LeaderFrontendState implements Identifiable<ClientIdentifier> {
static final class Disabled extends LeaderFrontendState {
Disabled(final String persistenceId, final ClientIdentifier clientId, final ShardDataTree tree) {
super(persistenceId, clientId, tree);
checkRequestSequence(envelope);
try {
- if (request instanceof CreateLocalHistoryRequest) {
- return handleCreateHistory((CreateLocalHistoryRequest) request, envelope, now);
- } else if (request instanceof DestroyLocalHistoryRequest) {
- return handleDestroyHistory((DestroyLocalHistoryRequest) request, envelope, now);
- } else if (request instanceof PurgeLocalHistoryRequest) {
- return handlePurgeHistory((PurgeLocalHistoryRequest) request, envelope, now);
+ if (request instanceof CreateLocalHistoryRequest req) {
+ return handleCreateHistory(req, envelope, now);
+ } else if (request instanceof DestroyLocalHistoryRequest req) {
+ return handleDestroyHistory(req, envelope, now);
+ } else if (request instanceof PurgeLocalHistoryRequest req) {
+ return handlePurgeHistory(req, envelope, now);
} else {
LOG.warn("{}: rejecting unsupported request {}", persistenceId(), request);
throw new UnsupportedRequestException(request);
checkRequestSequence(envelope);
try {
- final LocalHistoryIdentifier lhId = request.getTarget().getHistoryId();
+ final var lhId = request.getTarget().getHistoryId();
final AbstractFrontendHistory history;
if (lhId.getHistoryId() != 0) {
private LocalHistorySuccess handleCreateHistory(final CreateLocalHistoryRequest request,
final RequestEnvelope envelope, final long now) throws RequestException {
- final LocalHistoryIdentifier historyId = request.getTarget();
- final AbstractFrontendHistory existing = localHistories.get(historyId);
+ final var historyId = request.getTarget();
+ final var existing = localHistories.get(historyId);
if (existing != null) {
// History already exists: report success
LOG.debug("{}: history {} already exists", persistenceId(), historyId);
}
// We have to send the response only after persistence has completed
- final ShardDataTreeTransactionChain chain = tree().ensureTransactionChain(historyId, () -> {
+ final var chain = tree().ensureTransactionChain(historyId, () -> {
LOG.debug("{}: persisted history {}", persistenceId(), historyId);
envelope.sendSuccess(new LocalHistorySuccess(historyId, request.getSequence()),
tree().readTime() - now);
private LocalHistorySuccess handleDestroyHistory(final DestroyLocalHistoryRequest request,
final RequestEnvelope envelope, final long now) {
- final LocalHistoryIdentifier id = request.getTarget();
- final LocalFrontendHistory existing = localHistories.get(id);
+ final var id = request.getTarget();
+ final var existing = localHistories.get(id);
if (existing == null) {
// History does not exist: report success
LOG.debug("{}: history {} does not exist, nothing to destroy", persistenceId(), id);
private LocalHistorySuccess handlePurgeHistory(final PurgeLocalHistoryRequest request,
final RequestEnvelope envelope, final long now) {
- final LocalHistoryIdentifier id = request.getTarget();
- final LocalFrontendHistory existing = localHistories.remove(id);
+ final var id = request.getTarget();
+ final var existing = localHistories.remove(id);
if (existing == null) {
LOG.debug("{}: history {} has already been purged", persistenceId(), id);
return new LocalHistorySuccess(id, request.getSequence());
void retire() {
// Hunt down any transactions associated with this frontend
- final Iterator<SimpleShardDataTreeCohort> it = tree.cohortIterator();
+ final var it = tree.cohortIterator();
while (it.hasNext()) {
- final SimpleShardDataTreeCohort cohort = it.next();
- if (clientId.equals(cohort.getIdentifier().getHistoryId().getClientId())) {
+ final var cohort = it.next();
+ final var transactionId = cohort.transactionId();
+ if (clientId.equals(transactionId.getHistoryId().getClientId())) {
if (cohort.getState() != State.COMMIT_PENDING) {
- LOG.debug("{}: Retiring transaction {}", persistenceId, cohort.getIdentifier());
+ LOG.debug("{}: Retiring transaction {}", persistenceId, transactionId);
it.remove();
} else {
- LOG.debug("{}: Transaction {} already committing, not retiring it", persistenceId,
- cohort.getIdentifier());
+ LOG.debug("{}: Transaction {} already committing, not retiring it", persistenceId, transactionId);
}
}
}
+++ /dev/null
-/*
- * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.cluster.datastore;
-
-import static java.util.Objects.requireNonNull;
-
-import akka.actor.ActorSelection;
-import akka.dispatch.Futures;
-import akka.dispatch.OnComplete;
-import com.google.common.util.concurrent.ListenableFuture;
-import java.util.Optional;
-import java.util.SortedSet;
-import org.opendaylight.controller.cluster.access.concepts.TransactionIdentifier;
-import org.opendaylight.controller.cluster.datastore.messages.CommitTransactionReply;
-import org.opendaylight.controller.cluster.datastore.messages.ReadyLocalTransaction;
-import org.opendaylight.controller.cluster.datastore.utils.ActorUtils;
-import org.opendaylight.mdsal.common.api.CommitInfo;
-import org.opendaylight.mdsal.dom.spi.store.DOMStoreThreePhaseCommitCohort;
-import org.opendaylight.mdsal.dom.spi.store.SnapshotBackedWriteTransaction;
-import org.opendaylight.yangtools.yang.common.Empty;
-import org.opendaylight.yangtools.yang.data.tree.api.DataTreeModification;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import scala.concurrent.Future;
-
-/**
- * Fake {@link DOMStoreThreePhaseCommitCohort} instantiated for local transactions to conform with the DOM
- * transaction APIs. It is only used to hold the data from a local DOM transaction ready operation and to
- * initiate direct or coordinated commits from the front-end by sending the ReadyLocalTransaction message.
- * It is not actually called by the front-end to perform 3PC thus the canCommit/preCommit/commit methods
- * are no-ops.
- */
-class LocalThreePhaseCommitCohort implements DOMStoreThreePhaseCommitCohort {
- private static final Logger LOG = LoggerFactory.getLogger(LocalThreePhaseCommitCohort.class);
-
- private final SnapshotBackedWriteTransaction<TransactionIdentifier> transaction;
- private final DataTreeModification modification;
- private final ActorUtils actorUtils;
- private final ActorSelection leader;
- private final Exception operationError;
-
- protected LocalThreePhaseCommitCohort(final ActorUtils actorUtils, final ActorSelection leader,
- final SnapshotBackedWriteTransaction<TransactionIdentifier> transaction,
- final DataTreeModification modification,
- final Exception operationError) {
- this.actorUtils = requireNonNull(actorUtils);
- this.leader = requireNonNull(leader);
- this.transaction = requireNonNull(transaction);
- this.modification = requireNonNull(modification);
- this.operationError = operationError;
- }
-
- protected LocalThreePhaseCommitCohort(final ActorUtils actorUtils, final ActorSelection leader,
- final SnapshotBackedWriteTransaction<TransactionIdentifier> transaction, final Exception operationError) {
- this.actorUtils = requireNonNull(actorUtils);
- this.leader = requireNonNull(leader);
- this.transaction = requireNonNull(transaction);
- this.operationError = requireNonNull(operationError);
- modification = null;
- }
-
- private Future<Object> initiateCommit(final boolean immediate,
- final Optional<SortedSet<String>> participatingShardNames) {
- if (operationError != null) {
- return Futures.failed(operationError);
- }
-
- final ReadyLocalTransaction message = new ReadyLocalTransaction(transaction.getIdentifier(),
- modification, immediate, participatingShardNames);
- return actorUtils.executeOperationAsync(leader, message, actorUtils.getTransactionCommitOperationTimeout());
- }
-
- Future<ActorSelection> initiateCoordinatedCommit(final Optional<SortedSet<String>> participatingShardNames) {
- final Future<Object> messageFuture = initiateCommit(false, participatingShardNames);
- final Future<ActorSelection> ret = TransactionReadyReplyMapper.transform(messageFuture, actorUtils,
- transaction.getIdentifier());
- ret.onComplete(new OnComplete<ActorSelection>() {
- @Override
- public void onComplete(final Throwable failure, final ActorSelection success) {
- if (failure != null) {
- LOG.warn("Failed to prepare transaction {} on backend", transaction.getIdentifier(), failure);
- transactionAborted(transaction);
- return;
- }
-
- LOG.debug("Transaction {} resolved to actor {}", transaction.getIdentifier(), success);
- }
- }, actorUtils.getClientDispatcher());
-
- return ret;
- }
-
- Future<Object> initiateDirectCommit() {
- final Future<Object> messageFuture = initiateCommit(true, Optional.empty());
- messageFuture.onComplete(new OnComplete<>() {
- @Override
- public void onComplete(final Throwable failure, final Object message) {
- if (failure != null) {
- LOG.warn("Failed to prepare transaction {} on backend", transaction.getIdentifier(), failure);
- transactionAborted(transaction);
- } else if (CommitTransactionReply.isSerializedType(message)) {
- LOG.debug("Transaction {} committed successfully", transaction.getIdentifier());
- transactionCommitted(transaction);
- } else {
- LOG.error("Transaction {} resulted in unhandled message type {}, aborting",
- transaction.getIdentifier(), message.getClass());
- transactionAborted(transaction);
- }
- }
- }, actorUtils.getClientDispatcher());
-
- return messageFuture;
- }
-
- @Override
- public final ListenableFuture<Boolean> canCommit() {
- // Intended no-op
- throw new UnsupportedOperationException();
- }
-
- @Override
- public final ListenableFuture<Empty> preCommit() {
- // Intended no-op
- throw new UnsupportedOperationException();
- }
-
- @Override
- public final ListenableFuture<Empty> abort() {
- // Intended no-op
- throw new UnsupportedOperationException();
- }
-
- @Override
- public final ListenableFuture<CommitInfo> commit() {
- // Intended no-op
- throw new UnsupportedOperationException();
- }
-
- protected void transactionAborted(final SnapshotBackedWriteTransaction<TransactionIdentifier> aborted) {
- }
-
- protected void transactionCommitted(final SnapshotBackedWriteTransaction<TransactionIdentifier> comitted) {
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.cluster.datastore;
-
-import static com.google.common.base.Preconditions.checkArgument;
-import static java.util.Objects.requireNonNull;
-
-import akka.actor.ActorSelection;
-import org.opendaylight.controller.cluster.access.concepts.TransactionIdentifier;
-import org.opendaylight.mdsal.dom.spi.store.AbstractSnapshotBackedTransactionChain;
-import org.opendaylight.mdsal.dom.spi.store.DOMStoreReadTransaction;
-import org.opendaylight.mdsal.dom.spi.store.DOMStoreReadWriteTransaction;
-import org.opendaylight.mdsal.dom.spi.store.DOMStoreThreePhaseCommitCohort;
-import org.opendaylight.mdsal.dom.spi.store.DOMStoreWriteTransaction;
-import org.opendaylight.mdsal.dom.spi.store.SnapshotBackedWriteTransaction;
-import org.opendaylight.yangtools.yang.data.tree.api.DataTreeModification;
-import org.opendaylight.yangtools.yang.data.tree.api.DataTreeSnapshot;
-import org.opendaylight.yangtools.yang.data.tree.api.ReadOnlyDataTree;
-
-/**
- * Transaction chain instantiated on top of a locally-available DataTree. It does not instantiate
- * a transaction in the leader and rather chains transactions on top of themselves.
- */
-final class LocalTransactionChain extends AbstractSnapshotBackedTransactionChain<TransactionIdentifier>
- implements LocalTransactionFactory {
- private static final Throwable ABORTED = new Throwable("Transaction aborted");
- private final TransactionChainProxy parent;
- private final ActorSelection leader;
- private final ReadOnlyDataTree tree;
-
- LocalTransactionChain(final TransactionChainProxy parent, final ActorSelection leader,
- final ReadOnlyDataTree tree) {
- this.parent = requireNonNull(parent);
- this.leader = requireNonNull(leader);
- this.tree = requireNonNull(tree);
- }
-
- ReadOnlyDataTree getDataTree() {
- return tree;
- }
-
- @Override
- protected TransactionIdentifier nextTransactionIdentifier() {
- throw new UnsupportedOperationException();
- }
-
- @Override
- protected boolean getDebugTransactions() {
- return false;
- }
-
- @Override
- protected DataTreeSnapshot takeSnapshot() {
- return tree.takeSnapshot();
- }
-
- @Override
- protected DOMStoreThreePhaseCommitCohort createCohort(
- final SnapshotBackedWriteTransaction<TransactionIdentifier> transaction,
- final DataTreeModification modification,
- final Exception operationError) {
- return new LocalChainThreePhaseCommitCohort(transaction, modification, operationError);
- }
-
- @Override
- public DOMStoreReadTransaction newReadOnlyTransaction(final TransactionIdentifier identifier) {
- return super.newReadOnlyTransaction(identifier);
- }
-
- @Override
- public DOMStoreReadWriteTransaction newReadWriteTransaction(final TransactionIdentifier identifier) {
- return super.newReadWriteTransaction(identifier);
- }
-
- @Override
- public DOMStoreWriteTransaction newWriteOnlyTransaction(final TransactionIdentifier identifier) {
- return super.newWriteOnlyTransaction(identifier);
- }
-
- @SuppressWarnings({"unchecked", "checkstyle:IllegalCatch"})
- @Override
- public LocalThreePhaseCommitCohort onTransactionReady(final DOMStoreWriteTransaction tx,
- final Exception operationError) {
- checkArgument(tx instanceof SnapshotBackedWriteTransaction);
- if (operationError != null) {
- return new LocalChainThreePhaseCommitCohort((SnapshotBackedWriteTransaction<TransactionIdentifier>)tx,
- operationError);
- }
-
- try {
- return (LocalThreePhaseCommitCohort) tx.ready();
- } catch (Exception e) {
- // Unfortunately we need to cast to SnapshotBackedWriteTransaction here as it's required by
- // LocalThreePhaseCommitCohort and the base class.
- return new LocalChainThreePhaseCommitCohort((SnapshotBackedWriteTransaction<TransactionIdentifier>)tx, e);
- }
- }
-
- private class LocalChainThreePhaseCommitCohort extends LocalThreePhaseCommitCohort {
-
- protected LocalChainThreePhaseCommitCohort(
- final SnapshotBackedWriteTransaction<TransactionIdentifier> transaction,
- final DataTreeModification modification, final Exception operationError) {
- super(parent.getActorUtils(), leader, transaction, modification, operationError);
- }
-
- protected LocalChainThreePhaseCommitCohort(
- final SnapshotBackedWriteTransaction<TransactionIdentifier> transaction,
- final Exception operationError) {
- super(parent.getActorUtils(), leader, transaction, operationError);
- }
-
- @Override
- protected void transactionAborted(final SnapshotBackedWriteTransaction<TransactionIdentifier> transaction) {
- onTransactionFailed(transaction, ABORTED);
- }
-
- @Override
- protected void transactionCommitted(final SnapshotBackedWriteTransaction<TransactionIdentifier> transaction) {
- onTransactionCommited(transaction);
- }
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2015 Brocade Communications Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.cluster.datastore;
-
-import static java.util.Objects.requireNonNull;
-
-import akka.actor.ActorSelection;
-import com.google.common.util.concurrent.FutureCallback;
-import com.google.common.util.concurrent.Futures;
-import com.google.common.util.concurrent.MoreExecutors;
-import com.google.common.util.concurrent.SettableFuture;
-import java.util.Optional;
-import java.util.SortedSet;
-import java.util.function.Consumer;
-import org.opendaylight.controller.cluster.access.concepts.TransactionIdentifier;
-import org.opendaylight.controller.cluster.datastore.messages.AbstractRead;
-import org.opendaylight.mdsal.common.api.ReadFailedException;
-import org.opendaylight.mdsal.dom.spi.store.DOMStoreReadTransaction;
-import org.opendaylight.mdsal.dom.spi.store.DOMStoreTransaction;
-import org.opendaylight.mdsal.dom.spi.store.DOMStoreWriteTransaction;
-import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
-import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
-import scala.concurrent.Future;
-
-/**
- * Processes front-end transaction operations locally before being committed to the destination shard.
- * Instances of this class are used when the destination shard is local to the caller.
- *
- * @author Thomas Pantelis
- */
-abstract class LocalTransactionContext extends TransactionContext {
- private final DOMStoreTransaction txDelegate;
- private final LocalTransactionReadySupport readySupport;
- private Exception operationError;
-
- LocalTransactionContext(final DOMStoreTransaction txDelegate, final TransactionIdentifier identifier,
- final LocalTransactionReadySupport readySupport) {
- super(identifier);
- this.txDelegate = requireNonNull(txDelegate);
- this.readySupport = readySupport;
- }
-
- abstract DOMStoreWriteTransaction getWriteDelegate();
-
- abstract DOMStoreReadTransaction getReadDelegate();
-
- @SuppressWarnings("checkstyle:IllegalCatch")
- private void executeModification(final Consumer<DOMStoreWriteTransaction> consumer) {
- incrementModificationCount();
- if (operationError == null) {
- try {
- consumer.accept(getWriteDelegate());
- } catch (Exception e) {
- operationError = e;
- }
- }
- }
-
- @Override
- void executeDelete(final YangInstanceIdentifier path, final Boolean havePermit) {
- executeModification(transaction -> transaction.delete(path));
- }
-
- @Override
- void executeMerge(final YangInstanceIdentifier path, final NormalizedNode data, final Boolean havePermit) {
- executeModification(transaction -> transaction.merge(path, data));
- }
-
- @Override
- void executeWrite(final YangInstanceIdentifier path, final NormalizedNode data, final Boolean havePermit) {
- executeModification(transaction -> transaction.write(path, data));
- }
-
- @Override
- <T> void executeRead(final AbstractRead<T> readCmd, final SettableFuture<T> proxyFuture,
- final Boolean havePermit) {
- Futures.addCallback(readCmd.apply(getReadDelegate()), new FutureCallback<T>() {
- @Override
- public void onSuccess(final T result) {
- proxyFuture.set(result);
- }
-
- @Override
- public void onFailure(final Throwable failure) {
- proxyFuture.setException(failure instanceof Exception
- ? ReadFailedException.MAPPER.apply((Exception) failure) : failure);
- }
- }, MoreExecutors.directExecutor());
- }
-
- @Override
- Future<ActorSelection> readyTransaction(final Boolean havePermit,
- final Optional<SortedSet<String>> participatingShardNames) {
- final LocalThreePhaseCommitCohort cohort = ready();
- return cohort.initiateCoordinatedCommit(participatingShardNames);
- }
-
- @Override
- Future<Object> directCommit(final Boolean havePermit) {
- final LocalThreePhaseCommitCohort cohort = ready();
- return cohort.initiateDirectCommit();
- }
-
- @Override
- void closeTransaction() {
- txDelegate.close();
- }
-
- private LocalThreePhaseCommitCohort ready() {
- logModificationCount();
- return readySupport.onTransactionReady(getWriteDelegate(), operationError);
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2015 Brocade Communications Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.cluster.datastore;
-
-import org.opendaylight.controller.cluster.access.concepts.TransactionIdentifier;
-import org.opendaylight.mdsal.dom.spi.store.DOMStoreReadTransaction;
-import org.opendaylight.mdsal.dom.spi.store.DOMStoreReadWriteTransaction;
-import org.opendaylight.mdsal.dom.spi.store.DOMStoreWriteTransaction;
-
-/**
- * A factory for creating local transactions used by {@link AbstractTransactionContextFactory} to instantiate
- * transactions on shards which are co-located with the shard leader.
- *
- * @author Thomas Pantelis
- */
-interface LocalTransactionFactory extends LocalTransactionReadySupport {
- DOMStoreReadTransaction newReadOnlyTransaction(TransactionIdentifier identifier);
-
- DOMStoreReadWriteTransaction newReadWriteTransaction(TransactionIdentifier identifier);
-
- DOMStoreWriteTransaction newWriteOnlyTransaction(TransactionIdentifier identifier);
-}
\ No newline at end of file
+++ /dev/null
-/*
- * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.cluster.datastore;
-
-import static com.google.common.base.Preconditions.checkArgument;
-import static java.util.Objects.requireNonNull;
-
-import akka.actor.ActorSelection;
-import org.opendaylight.controller.cluster.access.concepts.TransactionIdentifier;
-import org.opendaylight.controller.cluster.datastore.utils.ActorUtils;
-import org.opendaylight.mdsal.dom.spi.store.DOMStoreReadTransaction;
-import org.opendaylight.mdsal.dom.spi.store.DOMStoreReadWriteTransaction;
-import org.opendaylight.mdsal.dom.spi.store.DOMStoreThreePhaseCommitCohort;
-import org.opendaylight.mdsal.dom.spi.store.DOMStoreWriteTransaction;
-import org.opendaylight.mdsal.dom.spi.store.SnapshotBackedTransactions;
-import org.opendaylight.mdsal.dom.spi.store.SnapshotBackedWriteTransaction;
-import org.opendaylight.mdsal.dom.spi.store.SnapshotBackedWriteTransaction.TransactionReadyPrototype;
-import org.opendaylight.yangtools.yang.data.tree.api.DataTreeModification;
-import org.opendaylight.yangtools.yang.data.tree.api.ReadOnlyDataTree;
-
-/**
- * {@link LocalTransactionFactory} for instantiating backing transactions which are
- * disconnected from each other, ie not chained. These are used by {@link AbstractTransactionContextFactory}
- * to instantiate transactions on shards which are co-located with the shard leader.
- */
-final class LocalTransactionFactoryImpl extends TransactionReadyPrototype<TransactionIdentifier>
- implements LocalTransactionFactory {
-
- private final ActorSelection leader;
- private final ReadOnlyDataTree dataTree;
- private final ActorUtils actorUtils;
-
- LocalTransactionFactoryImpl(final ActorUtils actorUtils, final ActorSelection leader,
- final ReadOnlyDataTree dataTree) {
- this.leader = requireNonNull(leader);
- this.dataTree = requireNonNull(dataTree);
- this.actorUtils = actorUtils;
- }
-
- ReadOnlyDataTree getDataTree() {
- return dataTree;
- }
-
- @Override
- public DOMStoreReadTransaction newReadOnlyTransaction(final TransactionIdentifier identifier) {
- return SnapshotBackedTransactions.newReadTransaction(identifier, false, dataTree.takeSnapshot());
- }
-
- @Override
- public DOMStoreReadWriteTransaction newReadWriteTransaction(final TransactionIdentifier identifier) {
- return SnapshotBackedTransactions.newReadWriteTransaction(identifier, false, dataTree.takeSnapshot(), this);
- }
-
- @Override
- public DOMStoreWriteTransaction newWriteOnlyTransaction(final TransactionIdentifier identifier) {
- return SnapshotBackedTransactions.newWriteTransaction(identifier, false, dataTree.takeSnapshot(), this);
- }
-
- @Override
- protected void transactionAborted(final SnapshotBackedWriteTransaction<TransactionIdentifier> tx) {
- // No-op
- }
-
- @Override
- protected DOMStoreThreePhaseCommitCohort transactionReady(
- final SnapshotBackedWriteTransaction<TransactionIdentifier> tx,
- final DataTreeModification tree,
- final Exception readyError) {
- return new LocalThreePhaseCommitCohort(actorUtils, leader, tx, tree, readyError);
- }
-
- @SuppressWarnings("unchecked")
- @Override
- public LocalThreePhaseCommitCohort onTransactionReady(final DOMStoreWriteTransaction tx,
- final Exception operationError) {
- checkArgument(tx instanceof SnapshotBackedWriteTransaction);
- if (operationError != null) {
- return new LocalThreePhaseCommitCohort(actorUtils, leader,
- (SnapshotBackedWriteTransaction<TransactionIdentifier>)tx, operationError);
- }
-
- return (LocalThreePhaseCommitCohort) tx.ready();
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2015 Brocade Communications Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.cluster.datastore;
-
-import org.eclipse.jdt.annotation.NonNull;
-import org.eclipse.jdt.annotation.Nullable;
-import org.opendaylight.mdsal.dom.spi.store.DOMStoreWriteTransaction;
-
-/**
- * Interface for a class that can "ready" a transaction.
- *
- * @author Thomas Pantelis
- */
-interface LocalTransactionReadySupport {
- LocalThreePhaseCommitCohort onTransactionReady(@NonNull DOMStoreWriteTransaction tx,
- @Nullable Exception operationError);
-}
+++ /dev/null
-/*
- * Copyright (c) 2015 Brocade Communications Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.cluster.datastore;
-
-import com.google.common.util.concurrent.ListenableFuture;
-import java.util.Collections;
-import java.util.List;
-import org.opendaylight.mdsal.common.api.CommitInfo;
-import org.opendaylight.yangtools.yang.common.Empty;
-import scala.concurrent.Future;
-
-/**
- * A {@link org.opendaylight.controller.sal.core.spi.data.DOMStoreThreePhaseCommitCohort}
- * instance given out for empty transactions.
- */
-final class NoOpDOMStoreThreePhaseCommitCohort extends AbstractThreePhaseCommitCohort<Object> {
- static final NoOpDOMStoreThreePhaseCommitCohort INSTANCE = new NoOpDOMStoreThreePhaseCommitCohort();
-
- private NoOpDOMStoreThreePhaseCommitCohort() {
- // Hidden to prevent instantiation
- }
-
- @Override
- public ListenableFuture<Boolean> canCommit() {
- return IMMEDIATE_BOOLEAN_SUCCESS;
- }
-
- @Override
- public ListenableFuture<Empty> preCommit() {
- return IMMEDIATE_EMPTY_SUCCESS;
- }
-
- @Override
- public ListenableFuture<Empty> abort() {
- return IMMEDIATE_EMPTY_SUCCESS;
- }
-
- @Override
- public ListenableFuture<CommitInfo> commit() {
- return CommitInfo.emptyFluentFuture();
- }
-
- @Override
- List<Future<Object>> getCohortFutures() {
- return Collections.emptyList();
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.cluster.datastore;
-
-import akka.actor.ActorSelection;
-import com.google.common.util.concurrent.SettableFuture;
-import java.util.Optional;
-import java.util.SortedSet;
-import org.opendaylight.controller.cluster.access.concepts.TransactionIdentifier;
-import org.opendaylight.controller.cluster.datastore.exceptions.NoShardLeaderException;
-import org.opendaylight.controller.cluster.datastore.messages.AbstractRead;
-import org.opendaylight.mdsal.common.api.DataStoreUnavailableException;
-import org.opendaylight.mdsal.common.api.ReadFailedException;
-import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
-import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import scala.concurrent.Future;
-
-final class NoOpTransactionContext extends TransactionContext {
- private static final Logger LOG = LoggerFactory.getLogger(NoOpTransactionContext.class);
-
- private final Throwable failure;
-
- NoOpTransactionContext(final Throwable failure, final TransactionIdentifier identifier) {
- super(identifier);
- this.failure = failure;
- }
-
- @Override
- void closeTransaction() {
- LOG.debug("NoOpTransactionContext {} closeTransaction called", getIdentifier());
- }
-
- @Override
- Future<Object> directCommit(final Boolean havePermit) {
- LOG.debug("Tx {} directCommit called, failure", getIdentifier(), failure);
- return akka.dispatch.Futures.failed(failure);
- }
-
- @Override
- Future<ActorSelection> readyTransaction(final Boolean havePermit,
- final Optional<SortedSet<String>> participatingShardNamess) {
- LOG.debug("Tx {} readyTransaction called, failure", getIdentifier(), failure);
- return akka.dispatch.Futures.failed(failure);
- }
-
- @Override
- <T> void executeRead(final AbstractRead<T> readCmd, final SettableFuture<T> proxyFuture, final Boolean havePermit) {
- LOG.debug("Tx {} executeRead {} called path = {}", getIdentifier(), readCmd.getClass().getSimpleName(),
- readCmd.getPath());
-
- final Throwable t;
- if (failure instanceof NoShardLeaderException) {
- t = new DataStoreUnavailableException(failure.getMessage(), failure);
- } else {
- t = failure;
- }
- proxyFuture.setException(new ReadFailedException("Error executeRead " + readCmd.getClass().getSimpleName()
- + " for path " + readCmd.getPath(), t));
- }
-
- @Override
- void executeDelete(final YangInstanceIdentifier path, final Boolean havePermit) {
- LOG.debug("Tx {} executeDelete called path = {}", getIdentifier(), path);
- }
-
- @Override
- void executeMerge(final YangInstanceIdentifier path, final NormalizedNode data, final Boolean havePermit) {
- LOG.debug("Tx {} executeMerge called path = {}", getIdentifier(), path);
- }
-
- @Override
- void executeWrite(final YangInstanceIdentifier path, final NormalizedNode data, final Boolean havePermit) {
- LOG.debug("Tx {} executeWrite called path = {}", getIdentifier(), path);
- }
-}
import java.util.Map;
import org.opendaylight.controller.cluster.datastore.utils.ActorUtils;
import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
+import org.opendaylight.mdsal.dom.api.DOMDataBroker.CommitCohortExtension;
import org.opendaylight.mdsal.dom.api.DOMDataTreeChangeListener;
import org.opendaylight.mdsal.dom.api.DOMDataTreeCommitCohort;
-import org.opendaylight.mdsal.dom.api.DOMDataTreeCommitCohortRegistration;
-import org.opendaylight.mdsal.dom.api.DOMDataTreeCommitCohortRegistry;
import org.opendaylight.mdsal.dom.api.DOMDataTreeIdentifier;
import org.opendaylight.mdsal.dom.spi.store.DOMStore;
import org.opendaylight.mdsal.dom.spi.store.DOMStoreReadTransaction;
import org.opendaylight.mdsal.dom.spi.store.DOMStoreTransactionChain;
import org.opendaylight.mdsal.dom.spi.store.DOMStoreTreeChangePublisher;
import org.opendaylight.mdsal.dom.spi.store.DOMStoreWriteTransaction;
-import org.opendaylight.yangtools.concepts.ListenerRegistration;
+import org.opendaylight.yangtools.concepts.Registration;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
import org.osgi.service.component.annotations.Activate;
import org.osgi.service.component.annotations.Component;
@Beta
@Component(factory = OSGiDOMStore.FACTORY_NAME, service = { DOMStore.class, DistributedDataStoreInterface.class })
public final class OSGiDOMStore
- implements DistributedDataStoreInterface, DOMStoreTreeChangePublisher, DOMDataTreeCommitCohortRegistry {
+ implements DistributedDataStoreInterface, DOMStoreTreeChangePublisher, CommitCohortExtension {
// OSGi DS Component Factory name
static final String FACTORY_NAME = "org.opendaylight.controller.cluster.datastore.OSGiDOMStore";
static final String DATASTORE_INST_PROP = ".datastore.instance";
private static final Logger LOG = LoggerFactory.getLogger(OSGiDOMStore.class);
- private LogicalDatastoreType datastoreType;
+ private final LogicalDatastoreType datastoreType;
private AbstractDataStore datastore;
+ @Activate
+ public OSGiDOMStore(final Map<String, ?> properties) {
+ datastoreType = (LogicalDatastoreType) verifyNotNull(properties.get(DATASTORE_TYPE_PROP));
+ datastore = (AbstractDataStore) verifyNotNull(properties.get(DATASTORE_INST_PROP));
+ LOG.info("Datastore service type {} activated", datastoreType);
+ }
+
+ @Deactivate
+ void deactivate() {
+ datastore = null;
+ LOG.info("Datastore service type {} deactivated", datastoreType);
+ }
+
@Override
public ActorUtils getActorUtils() {
return datastore.getActorUtils();
}
@Override
- public <L extends DOMDataTreeChangeListener> ListenerRegistration<L> registerProxyListener(
- final YangInstanceIdentifier shardLookup, final YangInstanceIdentifier insideShard,
- final DOMDataTreeChangeListener delegate) {
+ public Registration registerProxyListener(final YangInstanceIdentifier shardLookup,
+ final YangInstanceIdentifier insideShard, final DOMDataTreeChangeListener delegate) {
return datastore.registerProxyListener(shardLookup, insideShard, delegate);
}
@Override
- public <L extends DOMDataTreeChangeListener> ListenerRegistration<L> registerTreeChangeListener(
- final YangInstanceIdentifier treeId, final L listener) {
+ public Registration registerTreeChangeListener(final YangInstanceIdentifier treeId,
+ final DOMDataTreeChangeListener listener) {
return datastore.registerTreeChangeListener(treeId, listener);
}
@Override
- public <T extends DOMDataTreeCommitCohort> DOMDataTreeCommitCohortRegistration<T> registerCommitCohort(
- final DOMDataTreeIdentifier path, final T cohort) {
+ public Registration registerCommitCohort(final DOMDataTreeIdentifier path, final DOMDataTreeCommitCohort cohort) {
return datastore.registerCommitCohort(path, cohort);
}
return datastore.newReadWriteTransaction();
}
- @Activate
- void activate(final Map<String, ?> properties) {
- datastoreType = (LogicalDatastoreType) verifyNotNull(properties.get(DATASTORE_TYPE_PROP));
- datastore = (AbstractDataStore) verifyNotNull(properties.get(DATASTORE_INST_PROP));
- LOG.info("Datastore service type {} activated", datastoreType);
- }
-
- @Deactivate
- void deactivate() {
- datastore = null;
- LOG.info("Datastore service type {} deactivated", datastoreType);
+ @Override
+ public Registration registerLegacyTreeChangeListener(final YangInstanceIdentifier treeId,
+ final DOMDataTreeChangeListener listener) {
+ return datastore.registerLegacyTreeChangeListener(treeId, listener);
}
}
private static final Logger LOG = LoggerFactory.getLogger(OSGiDistributedDataStore.class);
- @Reference
- DOMSchemaService schemaService = null;
- @Reference
- ActorSystemProvider actorSystemProvider = null;
- @Reference
- DatastoreContextIntrospectorFactory introspectorFactory = null;
- @Reference
- DatastoreSnapshotRestore snapshotRestore = null;
- @Reference
- ModuleShardConfigProvider configProvider = null;
- @Reference(target = "(component.factory=" + OSGiDOMStore.FACTORY_NAME + ")")
- ComponentFactory<OSGiDOMStore> datastoreFactory = null;
-
+ private final ComponentFactory<OSGiDOMStore> datastoreFactory;
private DatastoreState configDatastore;
private DatastoreState operDatastore;
@Activate
- void activate(final Map<String, Object> properties) {
- configDatastore = createDatastore(LogicalDatastoreType.CONFIGURATION, "distributed-config", properties, null);
- operDatastore = createDatastore(LogicalDatastoreType.OPERATIONAL, "distributed-operational", properties,
+ public OSGiDistributedDataStore(@Reference final DOMSchemaService schemaService,
+ @Reference final ActorSystemProvider actorSystemProvider,
+ @Reference final DatastoreContextIntrospectorFactory introspectorFactory,
+ @Reference final DatastoreSnapshotRestore snapshotRestore,
+ @Reference final ModuleShardConfigProvider configProvider,
+ @Reference(target = "(component.factory=" + OSGiDOMStore.FACTORY_NAME + ")")
+ final ComponentFactory<OSGiDOMStore> datastoreFactory, final Map<String, Object> properties) {
+ this.datastoreFactory = requireNonNull(datastoreFactory);
+ configDatastore = createDatastore(schemaService, actorSystemProvider, snapshotRestore, introspectorFactory,
+ LogicalDatastoreType.CONFIGURATION, "distributed-config", properties, null);
+ operDatastore = createDatastore(schemaService, actorSystemProvider, snapshotRestore, introspectorFactory,
+ LogicalDatastoreType.OPERATIONAL, "distributed-operational", properties,
new ConfigurationImpl(configProvider));
}
configDatastore = null;
}
- private DatastoreState createDatastore(final LogicalDatastoreType datastoreType, final String serviceType,
- final Map<String, Object> properties, final Configuration config) {
+ private DatastoreState createDatastore(final DOMSchemaService schemaService,
+ final ActorSystemProvider actorSystemProvider, final DatastoreSnapshotRestore snapshotRestore,
+ final DatastoreContextIntrospectorFactory introspectorFactory, final LogicalDatastoreType datastoreType,
+ final String serviceType, final Map<String, Object> properties,final Configuration config) {
LOG.info("Distributed Datastore type {} starting", datastoreType);
- final DatastoreContextIntrospector introspector = introspectorFactory.newInstance(datastoreType, properties);
- final AbstractDataStore datastore = DistributedDataStoreFactory.createInstance(actorSystemProvider,
+ final var introspector = introspectorFactory.newInstance(datastoreType, properties);
+ final var datastore = DistributedDataStoreFactory.createInstance(actorSystemProvider,
introspector.getContext(), introspector, snapshotRestore, config);
- datastore.setCloseable(schemaService.registerSchemaContextListener(datastore));
- final DatastoreState state = new DatastoreState(introspector, datastoreType, datastore, serviceType);
+ datastore.setCloseable(schemaService.registerSchemaContextListener(datastore::onModelContextUpdated));
+ final var state = new DatastoreState(introspector, datastoreType, datastore, serviceType);
Futures.addCallback(datastore.initialSettleFuture(), state,
// Note we are invoked from shard manager and therefore could block it, hence the round-trip to executor
+++ /dev/null
-/*
- * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.cluster.datastore;
-
-import static com.google.common.base.Preconditions.checkArgument;
-import static java.util.Objects.requireNonNull;
-
-import com.google.common.annotations.VisibleForTesting;
-import java.util.concurrent.Semaphore;
-import java.util.concurrent.TimeUnit;
-import org.opendaylight.controller.cluster.access.concepts.TransactionIdentifier;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * Class for limiting operations.
- */
-public class OperationLimiter {
- private static final Logger LOG = LoggerFactory.getLogger(OperationLimiter.class);
- private final TransactionIdentifier identifier;
- private final long acquireTimeout;
- private final Semaphore semaphore;
- private final int maxPermits;
-
- OperationLimiter(final TransactionIdentifier identifier, final int maxPermits, final long acquireTimeoutSeconds) {
- this.identifier = requireNonNull(identifier);
-
- checkArgument(acquireTimeoutSeconds >= 0);
- this.acquireTimeout = TimeUnit.SECONDS.toNanos(acquireTimeoutSeconds);
-
- checkArgument(maxPermits >= 0);
- this.maxPermits = maxPermits;
- this.semaphore = new Semaphore(maxPermits);
- }
-
- boolean acquire() {
- return acquire(1);
- }
-
- boolean acquire(final int acquirePermits) {
- try {
- if (semaphore.tryAcquire(acquirePermits, acquireTimeout, TimeUnit.NANOSECONDS)) {
- return true;
- }
- } catch (InterruptedException e) {
- if (LOG.isDebugEnabled()) {
- LOG.debug("Interrupted when trying to acquire operation permit for transaction {}", identifier, e);
- } else {
- LOG.warn("Interrupted when trying to acquire operation permit for transaction {}", identifier);
- }
- }
-
- return false;
- }
-
- void release() {
- release(1);
- }
-
- void release(final int permits) {
- this.semaphore.release(permits);
- }
-
- @VisibleForTesting
- TransactionIdentifier getIdentifier() {
- return identifier;
- }
-
- @VisibleForTesting
- int availablePermits() {
- return semaphore.availablePermits();
- }
-
- /**
- * Release all the permits.
- */
- public void releaseAll() {
- this.semaphore.release(maxPermits - availablePermits());
- }
-}
final class ReadOnlyShardDataTreeTransaction extends AbstractShardDataTreeTransaction<DataTreeSnapshot> {
ReadOnlyShardDataTreeTransaction(final ShardDataTreeTransactionParent parent, final TransactionIdentifier id,
- final DataTreeSnapshot snapshot) {
+ final DataTreeSnapshot snapshot) {
super(parent, id, snapshot);
}
}
*/
package org.opendaylight.controller.cluster.datastore;
-import com.google.common.base.Preconditions;
+import static com.google.common.base.Preconditions.checkState;
+
import java.util.Optional;
import java.util.SortedSet;
import org.opendaylight.controller.cluster.access.concepts.TransactionIdentifier;
import org.opendaylight.yangtools.yang.data.tree.api.DataTreeModification;
public final class ReadWriteShardDataTreeTransaction extends AbstractShardDataTreeTransaction<DataTreeModification> {
-
ReadWriteShardDataTreeTransaction(final ShardDataTreeTransactionParent parent, final TransactionIdentifier id,
- final DataTreeModification modification) {
+ final DataTreeModification modification) {
super(parent, id, modification);
}
ShardDataTreeCohort ready(final Optional<SortedSet<String>> participatingShardNames) {
- Preconditions.checkState(close(), "Transaction is already closed");
+ checkState(close(), "Transaction is already closed");
return getParent().finishTransaction(this, participatingShardNames);
}
}
+++ /dev/null
-/*
- * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
- * Copyright (c) 2015 Brocade Communications Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.cluster.datastore;
-
-import static com.google.common.base.Preconditions.checkState;
-import static java.util.Objects.requireNonNull;
-
-import akka.actor.ActorSelection;
-import akka.dispatch.Futures;
-import akka.dispatch.OnComplete;
-import com.google.common.annotations.VisibleForTesting;
-import com.google.common.util.concurrent.SettableFuture;
-import java.util.Optional;
-import java.util.SortedSet;
-import org.opendaylight.controller.cluster.access.concepts.TransactionIdentifier;
-import org.opendaylight.controller.cluster.datastore.messages.AbstractRead;
-import org.opendaylight.controller.cluster.datastore.messages.BatchedModifications;
-import org.opendaylight.controller.cluster.datastore.messages.CloseTransaction;
-import org.opendaylight.controller.cluster.datastore.modification.AbstractModification;
-import org.opendaylight.controller.cluster.datastore.modification.DeleteModification;
-import org.opendaylight.controller.cluster.datastore.modification.MergeModification;
-import org.opendaylight.controller.cluster.datastore.modification.Modification;
-import org.opendaylight.controller.cluster.datastore.modification.WriteModification;
-import org.opendaylight.controller.cluster.datastore.utils.ActorUtils;
-import org.opendaylight.mdsal.common.api.ReadFailedException;
-import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
-import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import scala.concurrent.Future;
-
-/**
- * Redirects front-end transaction operations to a shard for processing. Instances of this class are used
- * when the destination shard is remote to the caller.
- *
- * @author Thomas Pantelis
- */
-final class RemoteTransactionContext extends TransactionContext {
- private static final Logger LOG = LoggerFactory.getLogger(RemoteTransactionContext.class);
-
- private final ActorUtils actorUtils;
- private final ActorSelection actor;
- private final OperationLimiter limiter;
-
- private BatchedModifications batchedModifications;
- private int totalBatchedModificationsSent;
- private int batchPermits;
-
- /**
- * We have observed a failed modification batch. This transaction context is effectively doomed, as the backend
- * does not have a correct view of the world. If this happens, we do not limit operations but rather short-cut them
- * to a either a no-op (modifications) or a failure (reads). Once the transaction is ready, though, we send the
- * message to resynchronize with the backend, sharing a 'lost message' failure path.
- */
- private volatile Throwable failedModification;
-
- RemoteTransactionContext(final TransactionIdentifier identifier, final ActorSelection actor,
- final ActorUtils actorUtils, final short remoteTransactionVersion, final OperationLimiter limiter) {
- super(identifier, remoteTransactionVersion);
- this.limiter = requireNonNull(limiter);
- this.actor = actor;
- this.actorUtils = actorUtils;
- }
-
- private ActorSelection getActor() {
- return actor;
- }
-
- protected ActorUtils getActorUtils() {
- return actorUtils;
- }
-
- @Override
- void closeTransaction() {
- LOG.debug("Tx {} closeTransaction called", getIdentifier());
- TransactionContextCleanup.untrack(this);
-
- actorUtils.sendOperationAsync(getActor(), new CloseTransaction(getTransactionVersion()).toSerializable());
- }
-
- @Override
- Future<Object> directCommit(final Boolean havePermit) {
- LOG.debug("Tx {} directCommit called", getIdentifier());
-
- // Send the remaining batched modifications, if any, with the ready flag set.
- bumpPermits(havePermit);
- return sendBatchedModifications(true, true, Optional.empty());
- }
-
- @Override
- Future<ActorSelection> readyTransaction(final Boolean havePermit,
- final Optional<SortedSet<String>> participatingShardNames) {
- logModificationCount();
-
- LOG.debug("Tx {} readyTransaction called", getIdentifier());
-
- // Send the remaining batched modifications, if any, with the ready flag set.
-
- bumpPermits(havePermit);
- Future<Object> lastModificationsFuture = sendBatchedModifications(true, false, participatingShardNames);
-
- // Transform the last reply Future into a Future that returns the cohort actor path from
- // the last reply message. That's the end result of the ready operation.
- return TransactionReadyReplyMapper.transform(lastModificationsFuture, actorUtils, getIdentifier());
- }
-
- private void bumpPermits(final Boolean havePermit) {
- if (Boolean.TRUE.equals(havePermit)) {
- ++batchPermits;
- }
- }
-
- private BatchedModifications newBatchedModifications() {
- return new BatchedModifications(getIdentifier(), getTransactionVersion());
- }
-
- private void batchModification(final Modification modification, final boolean havePermit) {
- incrementModificationCount();
- if (havePermit) {
- ++batchPermits;
- }
-
- if (batchedModifications == null) {
- batchedModifications = newBatchedModifications();
- }
-
- batchedModifications.addModification(modification);
-
- if (batchedModifications.getModifications().size()
- >= actorUtils.getDatastoreContext().getShardBatchedModificationCount()) {
- sendBatchedModifications();
- }
- }
-
- @VisibleForTesting
- Future<Object> sendBatchedModifications() {
- return sendBatchedModifications(false, false, Optional.empty());
- }
-
- private Future<Object> sendBatchedModifications(final boolean ready, final boolean doCommitOnReady,
- final Optional<SortedSet<String>> participatingShardNames) {
- Future<Object> sent = null;
- if (ready || batchedModifications != null && !batchedModifications.getModifications().isEmpty()) {
- if (batchedModifications == null) {
- batchedModifications = newBatchedModifications();
- }
-
- LOG.debug("Tx {} sending {} batched modifications, ready: {}", getIdentifier(),
- batchedModifications.getModifications().size(), ready);
-
- batchedModifications.setDoCommitOnReady(doCommitOnReady);
- batchedModifications.setTotalMessagesSent(++totalBatchedModificationsSent);
-
- final BatchedModifications toSend = batchedModifications;
- final int permitsToRelease = batchPermits;
- batchPermits = 0;
-
- if (ready) {
- batchedModifications.setReady(participatingShardNames);
- batchedModifications.setDoCommitOnReady(doCommitOnReady);
- batchedModifications = null;
- } else {
- batchedModifications = newBatchedModifications();
-
- final Throwable failure = failedModification;
- if (failure != null) {
- // We have observed a modification failure, it does not make sense to send this batch. This speeds
- // up the time when the application could be blocked due to messages timing out and operation
- // limiter kicking in.
- LOG.debug("Tx {} modifications previously failed, not sending a non-ready batch", getIdentifier());
- limiter.release(permitsToRelease);
- return Futures.failed(failure);
- }
- }
-
- sent = actorUtils.executeOperationAsync(getActor(), toSend.toSerializable(),
- actorUtils.getTransactionCommitOperationTimeout());
- sent.onComplete(new OnComplete<>() {
- @Override
- public void onComplete(final Throwable failure, final Object success) {
- if (failure != null) {
- LOG.debug("Tx {} modifications failed", getIdentifier(), failure);
- failedModification = failure;
- } else {
- LOG.debug("Tx {} modifications completed with {}", getIdentifier(), success);
- }
- limiter.release(permitsToRelease);
- }
- }, actorUtils.getClientDispatcher());
- }
-
- return sent;
- }
-
- @Override
- void executeDelete(final YangInstanceIdentifier path, final Boolean havePermit) {
- LOG.debug("Tx {} executeDelete called path = {}", getIdentifier(), path);
- executeModification(new DeleteModification(path), havePermit);
- }
-
- @Override
- void executeMerge(final YangInstanceIdentifier path, final NormalizedNode data, final Boolean havePermit) {
- LOG.debug("Tx {} executeMerge called path = {}", getIdentifier(), path);
- executeModification(new MergeModification(path, data), havePermit);
- }
-
- @Override
- void executeWrite(final YangInstanceIdentifier path, final NormalizedNode data, final Boolean havePermit) {
- LOG.debug("Tx {} executeWrite called path = {}", getIdentifier(), path);
- executeModification(new WriteModification(path, data), havePermit);
- }
-
- private void executeModification(final AbstractModification modification, final Boolean havePermit) {
- final boolean permitToRelease;
- if (havePermit == null) {
- permitToRelease = failedModification == null && acquireOperation();
- } else {
- permitToRelease = havePermit;
- }
-
- batchModification(modification, permitToRelease);
- }
-
- @Override
- <T> void executeRead(final AbstractRead<T> readCmd, final SettableFuture<T> returnFuture,
- final Boolean havePermit) {
- LOG.debug("Tx {} executeRead {} called path = {}", getIdentifier(), readCmd.getClass().getSimpleName(),
- readCmd.getPath());
-
- final Throwable failure = failedModification;
- if (failure != null) {
- // If we know there was a previous modification failure, we must not send a read request, as it risks
- // returning incorrect data. We check this before acquiring an operation simply because we want the app
- // to complete this transaction as soon as possible.
- returnFuture.setException(new ReadFailedException("Previous modification failed, cannot "
- + readCmd.getClass().getSimpleName() + " for path " + readCmd.getPath(), failure));
- return;
- }
-
- // Send any batched modifications. This is necessary to honor the read uncommitted semantics of the
- // public API contract.
-
- final boolean permitToRelease = havePermit == null ? acquireOperation() : havePermit;
- sendBatchedModifications();
-
- OnComplete<Object> onComplete = new OnComplete<>() {
- @Override
- public void onComplete(final Throwable failure, final Object response) {
- // We have previously acquired an operation, now release it, no matter what happened
- if (permitToRelease) {
- limiter.release();
- }
-
- if (failure != null) {
- LOG.debug("Tx {} {} operation failed", getIdentifier(), readCmd.getClass().getSimpleName(),
- failure);
-
- returnFuture.setException(new ReadFailedException("Error checking "
- + readCmd.getClass().getSimpleName() + " for path " + readCmd.getPath(), failure));
- } else {
- LOG.debug("Tx {} {} operation succeeded", getIdentifier(), readCmd.getClass().getSimpleName());
- readCmd.processResponse(response, returnFuture);
- }
- }
- };
-
- final Future<Object> future = actorUtils.executeOperationAsync(getActor(),
- readCmd.asVersion(getTransactionVersion()).toSerializable(), actorUtils.getOperationTimeout());
- future.onComplete(onComplete, actorUtils.getClientDispatcher());
- }
-
- /**
- * Acquire operation from the limiter if the hand-off has completed. If the hand-off is still ongoing, this method
- * does nothing.
- *
- * @return True if a permit was successfully acquired, false otherwise
- */
- private boolean acquireOperation() {
- checkState(isOperationHandOffComplete(),
- "Attempted to acquire execute operation permit for transaction %s on actor %s during handoff",
- getIdentifier(), actor);
-
- if (limiter.acquire()) {
- return true;
- }
-
- LOG.warn("Failed to acquire execute operation permit for transaction {} on actor {}", getIdentifier(), actor);
- return false;
- }
-
- @Override
- boolean usesOperationLimiting() {
- return true;
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2015 Brocade Communications Systems, Inc. and others. All rights reserved.
- * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.cluster.datastore;
-
-import static java.util.Objects.requireNonNull;
-
-import akka.actor.ActorSelection;
-import akka.dispatch.OnComplete;
-import akka.pattern.AskTimeoutException;
-import akka.util.Timeout;
-import java.util.concurrent.TimeUnit;
-import org.opendaylight.controller.cluster.access.concepts.TransactionIdentifier;
-import org.opendaylight.controller.cluster.datastore.exceptions.NoShardLeaderException;
-import org.opendaylight.controller.cluster.datastore.exceptions.ShardLeaderNotRespondingException;
-import org.opendaylight.controller.cluster.datastore.messages.CreateTransaction;
-import org.opendaylight.controller.cluster.datastore.messages.CreateTransactionReply;
-import org.opendaylight.controller.cluster.datastore.messages.PrimaryShardInfo;
-import org.opendaylight.controller.cluster.datastore.utils.ActorUtils;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import scala.concurrent.Future;
-import scala.concurrent.duration.FiniteDuration;
-
-/**
- * Handles creation of TransactionContext instances for remote transactions. This class creates
- * remote transactions, if necessary, by sending CreateTransaction messages with retries, up to a limit,
- * if the shard doesn't have a leader yet. This is done by scheduling a retry task after a short delay.
- * <p/>
- * The end result from a completed CreateTransaction message is a TransactionContext that is
- * used to perform transaction operations. Transaction operations that occur before the
- * CreateTransaction completes are cached via a DelayedTransactionContextWrapper and executed once the
- * CreateTransaction completes, successfully or not.
- */
-final class RemoteTransactionContextSupport {
- private static final Logger LOG = LoggerFactory.getLogger(RemoteTransactionContextSupport.class);
-
- private static final long CREATE_TX_TRY_INTERVAL_IN_MS = 1000;
- private static final long MAX_CREATE_TX_MSG_TIMEOUT_IN_MS = 5000;
-
- private final TransactionProxy parent;
- private final String shardName;
-
- /**
- * The target primary shard.
- */
- private volatile PrimaryShardInfo primaryShardInfo;
-
- /**
- * The total timeout for creating a tx on the primary shard.
- */
- private volatile long totalCreateTxTimeout;
-
- private final Timeout createTxMessageTimeout;
-
- private final DelayedTransactionContextWrapper transactionContextWrapper;
-
- RemoteTransactionContextSupport(final DelayedTransactionContextWrapper transactionContextWrapper,
- final TransactionProxy parent, final String shardName) {
- this.parent = requireNonNull(parent);
- this.shardName = shardName;
- this.transactionContextWrapper = transactionContextWrapper;
-
- // For the total create tx timeout, use 2 times the election timeout. This should be enough time for
- // a leader re-election to occur if we happen to hit it in transition.
- totalCreateTxTimeout = parent.getActorUtils().getDatastoreContext().getShardRaftConfig()
- .getElectionTimeOutInterval().toMillis() * 2;
-
- // We'll use the operationTimeout for the the create Tx message timeout so it can be set appropriately
- // for unit tests but cap it at MAX_CREATE_TX_MSG_TIMEOUT_IN_MS. The operationTimeout could be set
- // larger than the totalCreateTxTimeout in production which we don't want.
- long operationTimeout = parent.getActorUtils().getOperationTimeout().duration().toMillis();
- createTxMessageTimeout = new Timeout(Math.min(operationTimeout, MAX_CREATE_TX_MSG_TIMEOUT_IN_MS),
- TimeUnit.MILLISECONDS);
- }
-
- String getShardName() {
- return shardName;
- }
-
- private TransactionType getTransactionType() {
- return parent.getType();
- }
-
- private ActorUtils getActorUtils() {
- return parent.getActorUtils();
- }
-
- private TransactionIdentifier getIdentifier() {
- return parent.getIdentifier();
- }
-
- /**
- * Sets the target primary shard and initiates a CreateTransaction try.
- */
- void setPrimaryShard(final PrimaryShardInfo newPrimaryShardInfo) {
- primaryShardInfo = newPrimaryShardInfo;
-
- if (getTransactionType() == TransactionType.WRITE_ONLY
- && getActorUtils().getDatastoreContext().isWriteOnlyTransactionOptimizationsEnabled()) {
- ActorSelection primaryShard = newPrimaryShardInfo.getPrimaryShardActor();
-
- LOG.debug("Tx {} Primary shard {} found - creating WRITE_ONLY transaction context",
- getIdentifier(), primaryShard);
-
- // For write-only Tx's we prepare the transaction modifications directly on the shard actor
- // to avoid the overhead of creating a separate transaction actor.
- transactionContextWrapper.executePriorTransactionOperations(createValidTransactionContext(
- primaryShard, String.valueOf(primaryShard.path()), newPrimaryShardInfo.getPrimaryShardVersion()));
- } else {
- tryCreateTransaction();
- }
- }
-
- /**
- Performs a CreateTransaction try async.
- */
- private void tryCreateTransaction() {
- LOG.debug("Tx {} Primary shard {} found - trying create transaction", getIdentifier(),
- primaryShardInfo.getPrimaryShardActor());
-
- Object serializedCreateMessage = new CreateTransaction(getIdentifier(), getTransactionType().ordinal(),
- primaryShardInfo.getPrimaryShardVersion()).toSerializable();
-
- Future<Object> createTxFuture = getActorUtils().executeOperationAsync(
- primaryShardInfo.getPrimaryShardActor(), serializedCreateMessage, createTxMessageTimeout);
-
- createTxFuture.onComplete(new OnComplete<>() {
- @Override
- public void onComplete(final Throwable failure, final Object response) {
- onCreateTransactionComplete(failure, response);
- }
- }, getActorUtils().getClientDispatcher());
- }
-
- private void tryFindPrimaryShard() {
- LOG.debug("Tx {} Retrying findPrimaryShardAsync for shard {}", getIdentifier(), shardName);
-
- primaryShardInfo = null;
- Future<PrimaryShardInfo> findPrimaryFuture = getActorUtils().findPrimaryShardAsync(shardName);
- findPrimaryFuture.onComplete(new OnComplete<PrimaryShardInfo>() {
- @Override
- public void onComplete(final Throwable failure, final PrimaryShardInfo newPrimaryShardInfo) {
- onFindPrimaryShardComplete(failure, newPrimaryShardInfo);
- }
- }, getActorUtils().getClientDispatcher());
- }
-
- private void onFindPrimaryShardComplete(final Throwable failure, final PrimaryShardInfo newPrimaryShardInfo) {
- if (failure == null) {
- primaryShardInfo = newPrimaryShardInfo;
- tryCreateTransaction();
- } else {
- LOG.debug("Tx {}: Find primary for shard {} failed", getIdentifier(), shardName, failure);
-
- onCreateTransactionComplete(failure, null);
- }
- }
-
- private void onCreateTransactionComplete(final Throwable failure, final Object response) {
- // An AskTimeoutException will occur if the local shard forwards to an unavailable remote leader or
- // the cached remote leader actor is no longer available.
- boolean retryCreateTransaction = primaryShardInfo != null
- && (failure instanceof NoShardLeaderException || failure instanceof AskTimeoutException);
-
- // Schedule a retry unless we're out of retries. Note: totalCreateTxTimeout is volatile as it may
- // be written by different threads however not concurrently, therefore decrementing it
- // non-atomically here is ok.
- if (retryCreateTransaction && totalCreateTxTimeout > 0) {
- long scheduleInterval = CREATE_TX_TRY_INTERVAL_IN_MS;
- if (failure instanceof AskTimeoutException) {
- // Since we use the createTxMessageTimeout for the CreateTransaction request and it timed
- // out, subtract it from the total timeout. Also since the createTxMessageTimeout period
- // has already elapsed, we can immediately schedule the retry (10 ms is virtually immediate).
- totalCreateTxTimeout -= createTxMessageTimeout.duration().toMillis();
- scheduleInterval = 10;
- }
-
- totalCreateTxTimeout -= scheduleInterval;
-
- LOG.debug("Tx {}: create tx on shard {} failed with exception \"{}\" - scheduling retry in {} ms",
- getIdentifier(), shardName, failure, scheduleInterval);
-
- getActorUtils().getActorSystem().scheduler().scheduleOnce(
- FiniteDuration.create(scheduleInterval, TimeUnit.MILLISECONDS),
- this::tryFindPrimaryShard, getActorUtils().getClientDispatcher());
- return;
- }
-
- createTransactionContext(failure, response);
- }
-
- private void createTransactionContext(final Throwable failure, final Object response) {
- // Create the TransactionContext from the response or failure. Store the new
- // TransactionContext locally until we've completed invoking the
- // TransactionOperations. This avoids thread timing issues which could cause
- // out-of-order TransactionOperations. Eg, on a modification operation, if the
- // TransactionContext is non-null, then we directly call the TransactionContext.
- // However, at the same time, the code may be executing the cached
- // TransactionOperations. So to avoid thus timing, we don't publish the
- // TransactionContext until after we've executed all cached TransactionOperations.
- TransactionContext localTransactionContext;
- if (failure != null) {
- LOG.debug("Tx {} Creating NoOpTransaction because of error", getIdentifier(), failure);
-
- Throwable resultingEx = failure;
- if (failure instanceof AskTimeoutException) {
- resultingEx = new ShardLeaderNotRespondingException(String.format(
- "Could not create a %s transaction on shard %s. The shard leader isn't responding.",
- parent.getType(), shardName), failure);
- } else if (!(failure instanceof NoShardLeaderException)) {
- resultingEx = new Exception(String.format(
- "Error creating %s transaction on shard %s", parent.getType(), shardName), failure);
- }
-
- localTransactionContext = new NoOpTransactionContext(resultingEx, getIdentifier());
- } else if (CreateTransactionReply.isSerializedType(response)) {
- localTransactionContext = createValidTransactionContext(
- CreateTransactionReply.fromSerializable(response));
- } else {
- IllegalArgumentException exception = new IllegalArgumentException(String.format(
- "Invalid reply type %s for CreateTransaction", response.getClass()));
-
- localTransactionContext = new NoOpTransactionContext(exception, getIdentifier());
- }
- transactionContextWrapper.executePriorTransactionOperations(localTransactionContext);
- }
-
- private TransactionContext createValidTransactionContext(final CreateTransactionReply reply) {
- LOG.debug("Tx {} Received {}", getIdentifier(), reply);
-
- return createValidTransactionContext(getActorUtils().actorSelection(reply.getTransactionPath()),
- reply.getTransactionPath(), primaryShardInfo.getPrimaryShardVersion());
- }
-
- private TransactionContext createValidTransactionContext(final ActorSelection transactionActor,
- final String transactionPath, final short remoteTransactionVersion) {
- final TransactionContext ret = new RemoteTransactionContext(transactionContextWrapper.getIdentifier(),
- transactionActor, getActorUtils(), remoteTransactionVersion, transactionContextWrapper.getLimiter());
-
- if (parent.getType() == TransactionType.READ_ONLY) {
- TransactionContextCleanup.track(parent, ret);
- }
-
- return ret;
- }
-}
-
private Deque<DataTreeChanged> otherMessages = new ArrayDeque<>();
private RootDataTreeChangeListenerActor(final DOMDataTreeChangeListener listener, final int shardCount) {
- super(listener, YangInstanceIdentifier.empty());
+ super(listener, YangInstanceIdentifier.of());
this.shardCount = shardCount;
}
/*
* We need to make-pretend that the data coming into the listener is coming from a single logical entity, where
* ordering is partially guaranteed (on shard boundaries). The data layout in shards is such that each DataTree
- * is rooted at YangInstanceIdentifier.empty(), but their contents vary:
+ * is rooted at YangInstanceIdentifier.of(), but their contents vary:
*
* 1) non-default shards contain immediate children of root from one module
* 2) default shard contains everything else
initial = Iterables.get(changes, 0);
}
- final NormalizedNode root = initial.getRootNode().getDataAfter().orElseThrow();
+ final NormalizedNode root = initial.getRootNode().getDataAfter();
verify(root instanceof ContainerNode, "Unexpected root node %s", root);
((ContainerNode) root).body().forEach(rootBuilder::withChild);
}
initialMessages = null;
// Replace first element with the combined initial change, report initial changes and clear the map
- initialChanges.set(0, DataTreeCandidates.newDataTreeCandidate(YangInstanceIdentifier.empty(),
+ initialChanges.set(0, DataTreeCandidates.newDataTreeCandidate(YangInstanceIdentifier.of(),
DataTreeCandidateNodes.written(rootBuilder.build())));
super.dataTreeChanged(new DataTreeChanged(initialChanges));
import org.opendaylight.controller.cluster.datastore.messages.RegisterDataTreeNotificationListenerReply;
import org.opendaylight.controller.cluster.datastore.utils.ActorUtils;
import org.opendaylight.mdsal.dom.api.DOMDataTreeChangeListener;
-import org.opendaylight.yangtools.concepts.AbstractListenerRegistration;
+import org.opendaylight.yangtools.concepts.AbstractObjectRegistration;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-final class RootDataTreeChangeListenerProxy<L extends DOMDataTreeChangeListener>
- extends AbstractListenerRegistration<L> {
+final class RootDataTreeChangeListenerProxy<L extends DOMDataTreeChangeListener> extends AbstractObjectRegistration<L> {
private abstract static class State {
}
final Set<String> shardNames) {
super(listener);
this.actorUtils = requireNonNull(actorUtils);
- this.state = new ResolveShards(shardNames.size());
+ state = new ResolveShards(shardNames.size());
for (String shardName : shardNames) {
actorUtils.findLocalShardAsync(shardName).onComplete(new OnComplete<ActorRef>() {
} else if (state instanceof ResolveShards) {
// Simple case: just mark the fact we were closed, terminating when resolution finishes
state = new Terminated();
- } else if (state instanceof Subscribed) {
- terminate((Subscribed) state);
+ } else if (state instanceof Subscribed subscribed) {
+ terminate(subscribed);
} else {
throw new IllegalStateException("Unhandled close in state " + state);
}
private synchronized void onFindLocalShardComplete(final String shardName, final Throwable failure,
final ActorRef shard) {
- if (state instanceof ResolveShards) {
- localShardsResolved((ResolveShards) state, shardName, failure, shard);
+ if (state instanceof ResolveShards resolveShards) {
+ localShardsResolved(resolveShards, shardName, failure, shard);
} else {
LOG.debug("{}: lookup for shard {} turned into a noop on state {}", logContext(), shardName, state);
}
// Subscribe to all shards
final RegisterDataTreeChangeListener regMessage = new RegisterDataTreeChangeListener(
- YangInstanceIdentifier.empty(), dtclActor, true);
+ YangInstanceIdentifier.of(), dtclActor, true);
for (Entry<String, Object> entry : localShards.entrySet()) {
// Do not retain references to localShards
final String shardName = entry.getKey();
}
private synchronized void onShardSubscribed(final String shardName, final Throwable failure, final Object result) {
- if (state instanceof Subscribed) {
- final Subscribed current = (Subscribed) state;
+ if (state instanceof Subscribed current) {
if (failure != null) {
LOG.error("{}: Shard {} failed to subscribe, terminating listener {}", logContext(),
shardName,getInstance(), failure);
import java.util.Optional;
import java.util.OptionalLong;
import java.util.concurrent.TimeUnit;
+import java.util.function.Supplier;
import org.eclipse.jdt.annotation.NonNull;
import org.eclipse.jdt.annotation.Nullable;
import org.opendaylight.controller.cluster.access.ABIVersion;
import org.opendaylight.controller.cluster.access.commands.TransactionRequest;
import org.opendaylight.controller.cluster.access.concepts.ClientIdentifier;
import org.opendaylight.controller.cluster.access.concepts.FrontendIdentifier;
-import org.opendaylight.controller.cluster.access.concepts.LocalHistoryIdentifier;
-import org.opendaylight.controller.cluster.access.concepts.Request;
import org.opendaylight.controller.cluster.access.concepts.RequestEnvelope;
import org.opendaylight.controller.cluster.access.concepts.RequestException;
import org.opendaylight.controller.cluster.access.concepts.RequestSuccess;
import org.opendaylight.controller.cluster.common.actor.Dispatchers;
import org.opendaylight.controller.cluster.common.actor.Dispatchers.DispatcherType;
import org.opendaylight.controller.cluster.common.actor.MessageTracker;
-import org.opendaylight.controller.cluster.common.actor.MessageTracker.Error;
import org.opendaylight.controller.cluster.common.actor.MeteringBehavior;
import org.opendaylight.controller.cluster.datastore.actors.JsonExportActor;
import org.opendaylight.controller.cluster.datastore.exceptions.NoShardLeaderException;
import org.opendaylight.controller.cluster.raft.messages.Payload;
import org.opendaylight.controller.cluster.raft.messages.RequestLeadership;
import org.opendaylight.controller.cluster.raft.messages.ServerRemoved;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.distributed.datastore.provider.rev140612.DataStoreProperties.ExportOnRecovery;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.distributed.datastore.provider.rev231229.DataStoreProperties.ExportOnRecovery;
import org.opendaylight.yangtools.concepts.Identifier;
import org.opendaylight.yangtools.yang.data.tree.api.DataTree;
import org.opendaylight.yangtools.yang.data.tree.api.DataValidationFailedException;
import org.opendaylight.yangtools.yang.data.tree.api.TreeType;
import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
-import org.opendaylight.yangtools.yang.model.api.EffectiveModelContextProvider;
import scala.concurrent.duration.FiniteDuration;
/**
private DatastoreContext datastoreContext;
+ @Deprecated(since = "9.0.0", forRemoval = true)
private final ShardCommitCoordinator commitCoordinator;
private long transactionCommitTimeout;
private final MessageTracker appendEntriesReplyTracker;
+ @Deprecated(since = "9.0.0", forRemoval = true)
private final ShardTransactionActorFactory transactionActorFactory;
private final ShardSnapshotCohort snapshotCohort;
private ShardSnapshot restoreFromSnapshot;
+ @Deprecated(since = "9.0.0", forRemoval = true)
private final ShardTransactionMessageRetrySupport messageRetrySupport;
@VisibleForTesting
switch (exportOnRecovery) {
case Json:
if (message instanceof SnapshotOffer) {
- exportActor.tell(new JsonExportActor.ExportSnapshot(store.readCurrentData().get(), name),
- ActorRef.noSender());
- } else if (message instanceof ReplicatedLogEntry) {
- exportActor.tell(new JsonExportActor.ExportJournal((ReplicatedLogEntry) message),
+ exportActor.tell(new JsonExportActor.ExportSnapshot(store.readCurrentData().orElseThrow(), name),
ActorRef.noSender());
+ } else if (message instanceof ReplicatedLogEntry replicatedLogEntry) {
+ exportActor.tell(new JsonExportActor.ExportJournal(replicatedLogEntry), ActorRef.noSender());
} else if (message instanceof RecoveryCompleted) {
exportActor.tell(new JsonExportActor.FinishExport(name), ActorRef.noSender());
exportActor.tell(PoisonPill.getInstance(), ActorRef.noSender());
@Override
// non-final for TestShard
protected void handleNonRaftCommand(final Object message) {
- try (MessageTracker.Context context = appendEntriesReplyTracker.received(message)) {
- final Optional<Error> maybeError = context.error();
+ try (var context = appendEntriesReplyTracker.received(message)) {
+ final var maybeError = context.error();
if (maybeError.isPresent()) {
LOG.trace("{} : AppendEntriesReply failed to arrive at the expected interval {}", persistenceId(),
- maybeError.get());
+ maybeError.orElseThrow());
}
store.resetTransactionBatch();
- if (message instanceof RequestEnvelope) {
- handleRequestEnvelope((RequestEnvelope)message);
+ if (message instanceof RequestEnvelope request) {
+ handleRequestEnvelope(request);
} else if (MessageAssembler.isHandledMessage(message)) {
handleRequestAssemblerMessage(message);
- } else if (message instanceof ConnectClientRequest) {
- handleConnectClient((ConnectClientRequest)message);
- } else if (CreateTransaction.isSerializedType(message)) {
- handleCreateTransaction(message);
- } else if (message instanceof BatchedModifications) {
- handleBatchedModifications((BatchedModifications)message);
- } else if (message instanceof ForwardedReadyTransaction) {
- handleForwardedReadyTransaction((ForwardedReadyTransaction) message);
- } else if (message instanceof ReadyLocalTransaction) {
- handleReadyLocalTransaction((ReadyLocalTransaction)message);
- } else if (CanCommitTransaction.isSerializedType(message)) {
- handleCanCommitTransaction(CanCommitTransaction.fromSerializable(message));
- } else if (CommitTransaction.isSerializedType(message)) {
- handleCommitTransaction(CommitTransaction.fromSerializable(message));
- } else if (AbortTransaction.isSerializedType(message)) {
- handleAbortTransaction(AbortTransaction.fromSerializable(message));
- } else if (CloseTransactionChain.isSerializedType(message)) {
- closeTransactionChain(CloseTransactionChain.fromSerializable(message));
+ } else if (message instanceof ConnectClientRequest request) {
+ handleConnectClient(request);
} else if (message instanceof DataTreeChangedReply) {
// Ignore reply
- } else if (message instanceof RegisterDataTreeChangeListener) {
- treeChangeSupport.onMessage((RegisterDataTreeChangeListener) message, isLeader(), hasLeader());
- } else if (message instanceof UpdateSchemaContext) {
- updateSchemaContext((UpdateSchemaContext) message);
+ } else if (message instanceof RegisterDataTreeChangeListener request) {
+ treeChangeSupport.onMessage(request, isLeader(), hasLeader());
+ } else if (message instanceof UpdateSchemaContext request) {
+ updateSchemaContext(request);
} else if (message instanceof PeerAddressResolved resolved) {
setPeerAddress(resolved.getPeerId(), resolved.getPeerAddress());
} else if (TX_COMMIT_TIMEOUT_CHECK_MESSAGE.equals(message)) {
commitTimeoutCheck();
- } else if (message instanceof DatastoreContext) {
- onDatastoreContext((DatastoreContext)message);
+ } else if (message instanceof DatastoreContext request) {
+ onDatastoreContext(request);
} else if (message instanceof RegisterRoleChangeListener) {
- roleChangeNotifier.get().forward(message, context());
- } else if (message instanceof FollowerInitialSyncUpStatus) {
- shardMBean.setFollowerInitialSyncStatus(((FollowerInitialSyncUpStatus) message).isInitialSyncDone());
+ roleChangeNotifier.orElseThrow().forward(message, context());
+ } else if (message instanceof FollowerInitialSyncUpStatus request) {
+ shardMBean.setFollowerInitialSyncStatus(request.isInitialSyncDone());
context().parent().tell(message, self());
} else if (GET_SHARD_MBEAN_MESSAGE.equals(message)) {
sender().tell(getShardMBean(), self());
sender().tell(store.getDataTree(), self());
} else if (message instanceof ServerRemoved) {
context().parent().forward(message, context());
- } else if (ShardTransactionMessageRetrySupport.TIMER_MESSAGE_CLASS.isInstance(message)) {
- messageRetrySupport.onTimerMessage(message);
- } else if (message instanceof DataTreeCohortActorRegistry.CohortRegistryCommand) {
- store.processCohortRegistryCommand(getSender(),
- (DataTreeCohortActorRegistry.CohortRegistryCommand) message);
+ } else if (message instanceof DataTreeCohortActorRegistry.CohortRegistryCommand request) {
+ store.processCohortRegistryCommand(getSender(), request);
} else if (message instanceof MakeLeaderLocal) {
onMakeLeaderLocal();
} else if (RESUME_NEXT_PENDING_TRANSACTION.equals(message)) {
} else if (GetKnownClients.INSTANCE.equals(message)) {
handleGetKnownClients();
} else if (!responseMessageSlicer.handleMessage(message)) {
- super.handleNonRaftCommand(message);
+ // Ask-based protocol messages
+ if (CreateTransaction.isSerializedType(message)) {
+ handleCreateTransaction(message);
+ } else if (message instanceof BatchedModifications request) {
+ handleBatchedModifications(request);
+ } else if (message instanceof ForwardedReadyTransaction request) {
+ handleForwardedReadyTransaction(request);
+ } else if (message instanceof ReadyLocalTransaction request) {
+ handleReadyLocalTransaction(request);
+ } else if (CanCommitTransaction.isSerializedType(message)) {
+ handleCanCommitTransaction(CanCommitTransaction.fromSerializable(message));
+ } else if (CommitTransaction.isSerializedType(message)) {
+ handleCommitTransaction(CommitTransaction.fromSerializable(message));
+ } else if (AbortTransaction.isSerializedType(message)) {
+ handleAbortTransaction(AbortTransaction.fromSerializable(message));
+ } else if (CloseTransactionChain.isSerializedType(message)) {
+ closeTransactionChain(CloseTransactionChain.fromSerializable(message));
+ } else if (ShardTransactionMessageRetrySupport.TIMER_MESSAGE_CLASS.isInstance(message)) {
+ messageRetrySupport.onTimerMessage(message);
+ } else {
+ super.handleNonRaftCommand(message);
+ }
}
}
}
}
private OptionalLong updateAccess(final SimpleShardDataTreeCohort cohort) {
- final FrontendIdentifier frontend = cohort.getIdentifier().getHistoryId().getClientId().getFrontendId();
+ final FrontendIdentifier frontend = cohort.transactionId().getHistoryId().getClientId().getFrontendId();
final LeaderFrontendState state = knownFrontends.get(frontend);
if (state == null) {
// Not tell-based protocol, do nothing
throw new NotLeaderException(getSelf());
}
- final Request<?, ?> request = envelope.getMessage();
- if (request instanceof TransactionRequest) {
- final TransactionRequest<?> txReq = (TransactionRequest<?>)request;
- final ClientIdentifier clientId = txReq.getTarget().getHistoryId().getClientId();
+ final var request = envelope.getMessage();
+ if (request instanceof TransactionRequest<?> txReq) {
+ final var clientId = txReq.getTarget().getHistoryId().getClientId();
return getFrontend(clientId).handleTransactionRequest(txReq, envelope, now);
- } else if (request instanceof LocalHistoryRequest) {
- final LocalHistoryRequest<?> lhReq = (LocalHistoryRequest<?>)request;
- final ClientIdentifier clientId = lhReq.getTarget().getClientId();
+ } else if (request instanceof LocalHistoryRequest<?> lhReq) {
+ final var clientId = lhReq.getTarget().getClientId();
return getFrontend(clientId).handleLocalHistoryRequest(lhReq, envelope, now);
} else {
LOG.warn("{}: rejecting unsupported request {}", persistenceId(), request);
}
}
+ @Deprecated(since = "9.0.0", forRemoval = true)
private void handleCommitTransaction(final CommitTransaction commit) {
- final TransactionIdentifier txId = commit.getTransactionId();
+ final var txId = commit.getTransactionId();
if (isLeader()) {
askProtocolEncountered(txId);
commitCoordinator.handleCommit(txId, getSender(), this);
} else {
- ActorSelection leader = getLeader();
+ final var leader = getLeader();
if (leader == null) {
messageRetrySupport.addMessageToRetry(commit, getSender(), "Could not commit transaction " + txId);
} else {
}
}
+ @Deprecated(since = "9.0.0", forRemoval = true)
private void handleCanCommitTransaction(final CanCommitTransaction canCommit) {
- final TransactionIdentifier txId = canCommit.getTransactionId();
+ final var txId = canCommit.getTransactionId();
LOG.debug("{}: Can committing transaction {}", persistenceId(), txId);
if (isLeader()) {
askProtocolEncountered(txId);
commitCoordinator.handleCanCommit(txId, getSender(), this);
} else {
- ActorSelection leader = getLeader();
+ final var leader = getLeader();
if (leader == null) {
messageRetrySupport.addMessageToRetry(canCommit, getSender(),
"Could not canCommit transaction " + txId);
}
@SuppressWarnings("checkstyle:IllegalCatch")
+ @Deprecated(since = "9.0.0", forRemoval = true)
private void handleBatchedModificationsLocal(final BatchedModifications batched, final ActorRef sender) {
askProtocolEncountered(batched.getTransactionId());
}
}
+ @Deprecated(since = "9.0.0", forRemoval = true)
private void handleBatchedModifications(final BatchedModifications batched) {
// This message is sent to prepare the modifications transaction directly on the Shard as an
// optimization to avoid the extra overhead of a separate ShardTransaction actor. On the last
if (isLeader() && isLeaderActive) {
handleBatchedModificationsLocal(batched, getSender());
} else {
- ActorSelection leader = getLeader();
+ final var leader = getLeader();
if (!isLeaderActive || leader == null) {
messageRetrySupport.addMessageToRetry(batched, getSender(),
"Could not process BatchedModifications " + batched.getTransactionId());
// we need to reconstruct previous BatchedModifications from the transaction
// DataTreeModification, honoring the max batched modification count, and forward all the
// previous BatchedModifications to the new leader.
- Collection<BatchedModifications> newModifications = commitCoordinator
- .createForwardedBatchedModifications(batched,
- datastoreContext.getShardBatchedModificationCount());
+ final var newModifications = commitCoordinator.createForwardedBatchedModifications(batched,
+ datastoreContext.getShardBatchedModificationCount());
LOG.debug("{}: Forwarding {} BatchedModifications to leader {}", persistenceId(),
newModifications.size(), leader);
}
@SuppressWarnings("checkstyle:IllegalCatch")
- private void handleReadyLocalTransaction(final ReadyLocalTransaction message) {
- final TransactionIdentifier txId = message.getTransactionId();
+ @Deprecated(since = "9.0.0", forRemoval = true)
+ private void handleReadyLocalTransaction(final ReadyLocalTransaction message) {
+ final var txId = message.getTransactionId();
LOG.debug("{}: handleReadyLocalTransaction for {}", persistenceId(), txId);
- boolean isLeaderActive = isLeaderActive();
+ final var isLeaderActive = isLeaderActive();
if (isLeader() && isLeaderActive) {
askProtocolEncountered(txId);
try {
getSender().tell(new Failure(e), getSelf());
}
} else {
- ActorSelection leader = getLeader();
+ final var leader = getLeader();
if (!isLeaderActive || leader == null) {
messageRetrySupport.addMessageToRetry(message, getSender(),
"Could not process ready local transaction " + txId);
}
}
+ @Deprecated(since = "9.0.0", forRemoval = true)
private void handleForwardedReadyTransaction(final ForwardedReadyTransaction forwardedReady) {
LOG.debug("{}: handleForwardedReadyTransaction for {}", persistenceId(), forwardedReady.getTransactionId());
- boolean isLeaderActive = isLeaderActive();
+ final var isLeaderActive = isLeaderActive();
if (isLeader() && isLeaderActive) {
askProtocolEncountered(forwardedReady.getTransactionId());
commitCoordinator.handleForwardedReadyTransaction(forwardedReady, getSender(), this);
} else {
- ActorSelection leader = getLeader();
+ final var leader = getLeader();
if (!isLeaderActive || leader == null) {
messageRetrySupport.addMessageToRetry(forwardedReady, getSender(),
"Could not process forwarded ready transaction " + forwardedReady.getTransactionId());
} else {
LOG.debug("{}: Forwarding ForwardedReadyTransaction to leader {}", persistenceId(), leader);
- ReadyLocalTransaction readyLocal = new ReadyLocalTransaction(forwardedReady.getTransactionId(),
+ final var readyLocal = new ReadyLocalTransaction(forwardedReady.getTransactionId(),
forwardedReady.getTransaction().getSnapshot(), forwardedReady.isDoImmediateCommit(),
forwardedReady.getParticipatingShardNames());
readyLocal.setRemoteVersion(getCurrentBehavior().getLeaderPayloadVersion());
}
}
+ @Deprecated(since = "9.0.0", forRemoval = true)
private void handleAbortTransaction(final AbortTransaction abort) {
- final TransactionIdentifier transactionId = abort.getTransactionId();
+ final var transactionId = abort.getTransactionId();
askProtocolEncountered(transactionId);
doAbortTransaction(transactionId, getSender());
}
commitCoordinator.handleAbort(transactionID, sender, this);
}
+ @Deprecated(since = "9.0.0", forRemoval = true)
private void handleCreateTransaction(final Object message) {
if (isLeader()) {
createTransaction(CreateTransaction.fromSerializable(message));
}
}
+ @Deprecated(since = "9.0.0", forRemoval = true)
private void closeTransactionChain(final CloseTransactionChain closeTransactionChain) {
if (isLeader()) {
- final LocalHistoryIdentifier id = closeTransactionChain.getIdentifier();
+ final var id = closeTransactionChain.getIdentifier();
askProtocolEncountered(id.getClientId());
store.closeTransactionChain(id);
} else if (getLeader() != null) {
}
}
+ @Deprecated(since = "9.0.0", forRemoval = true)
@SuppressWarnings("checkstyle:IllegalCatch")
private void createTransaction(final CreateTransaction createTransaction) {
askProtocolEncountered(createTransaction.getTransactionId());
return;
}
- ActorRef transactionActor = createTransaction(createTransaction.getTransactionType(),
+ final var transactionActor = createTransaction(createTransaction.getTransactionType(),
createTransaction.getTransactionId());
getSender().tell(new CreateTransactionReply(Serialization.serializedActorPath(transactionActor),
}
}
+ @Deprecated(since = "9.0.0", forRemoval = true)
private ActorRef createTransaction(final int transactionType, final TransactionIdentifier transactionId) {
LOG.debug("{}: Creating transaction : {} ", persistenceId(), transactionId);
return transactionActorFactory.newShardTransaction(TransactionType.fromInt(transactionType),
}
// Called on leader only
+ @Deprecated(since = "9.0.0", forRemoval = true)
private void askProtocolEncountered(final TransactionIdentifier transactionId) {
askProtocolEncountered(transactionId.getHistoryId().getClientId());
}
// Called on leader only
+ @Deprecated(since = "9.0.0", forRemoval = true)
private void askProtocolEncountered(final ClientIdentifier clientId) {
- final FrontendIdentifier frontend = clientId.getFrontendId();
- final LeaderFrontendState state = knownFrontends.get(frontend);
+ final var frontend = clientId.getFrontendId();
+ final var state = knownFrontends.get(frontend);
if (!(state instanceof LeaderFrontendState.Disabled)) {
LOG.debug("{}: encountered ask-based client {}, disabling transaction tracking", persistenceId(), clientId);
if (knownFrontends.isEmpty()) {
}
private void updateSchemaContext(final UpdateSchemaContext message) {
- updateSchemaContext(message.getEffectiveModelContext());
+ updateSchemaContext(message.modelContext());
}
@VisibleForTesting
restoreFromSnapshot = null;
//notify shard manager
- getContext().parent().tell(new ActorInitialized(), getSelf());
+ getContext().parent().tell(new ActorInitialized(getSelf()), ActorRef.noSender());
// Being paranoid here - this method should only be called once but just in case...
if (txCommitTimeoutCheckSchedule == null) {
// Schedule a message to be periodically sent to check if the current in-progress
// transaction should be expired and aborted.
- FiniteDuration period = FiniteDuration.create(transactionCommitTimeout / 3, TimeUnit.MILLISECONDS);
+ final var period = FiniteDuration.create(transactionCommitTimeout / 3, TimeUnit.MILLISECONDS);
txCommitTimeoutCheckSchedule = getContext().system().scheduler().schedule(
period, period, getSelf(),
TX_COMMIT_TIMEOUT_CHECK_MESSAGE, getContext().dispatcher(), ActorRef.noSender());
@Override
protected final void applyState(final ActorRef clientActor, final Identifier identifier, final Object data) {
- if (data instanceof Payload) {
- if (data instanceof DisableTrackingPayload) {
- disableTracking((DisableTrackingPayload) data);
+ if (data instanceof Payload payload) {
+ if (payload instanceof DisableTrackingPayload disableTracking) {
+ disableTracking(disableTracking);
return;
}
try {
- store.applyReplicatedPayload(identifier, (Payload)data);
+ store.applyReplicatedPayload(identifier, payload);
} catch (DataValidationFailedException | IOException e) {
LOG.error("{}: Error applying replica {}", persistenceId(), identifier, e);
}
paused = true;
// Tell-based protocol can replay transaction state, so it is safe to blow it up when we are paused.
- if (datastoreContext.isUseTellBasedProtocol()) {
- knownFrontends.values().forEach(LeaderFrontendState::retire);
- knownFrontends = ImmutableMap.of();
- }
+ knownFrontends.values().forEach(LeaderFrontendState::retire);
+ knownFrontends = ImmutableMap.of();
store.setRunOnPendingTransactionsComplete(operation);
}
private ShardIdentifier id;
private Map<String, String> peerAddresses = Collections.emptyMap();
private DatastoreContext datastoreContext;
- private EffectiveModelContextProvider schemaContextProvider;
+ private Supplier<@NonNull EffectiveModelContext> schemaContextProvider;
private DatastoreSnapshot.ShardSnapshot restoreFromSnapshot;
private DataTree dataTree;
public T id(final ShardIdentifier newId) {
checkSealed();
- this.id = newId;
+ id = newId;
return self();
}
public T peerAddresses(final Map<String, String> newPeerAddresses) {
checkSealed();
- this.peerAddresses = newPeerAddresses;
+ peerAddresses = newPeerAddresses;
return self();
}
public T datastoreContext(final DatastoreContext newDatastoreContext) {
checkSealed();
- this.datastoreContext = newDatastoreContext;
+ datastoreContext = newDatastoreContext;
return self();
}
- public T schemaContextProvider(final EffectiveModelContextProvider newSchemaContextProvider) {
+ public T schemaContextProvider(final Supplier<@NonNull EffectiveModelContext> newSchemaContextProvider) {
checkSealed();
- this.schemaContextProvider = requireNonNull(newSchemaContextProvider);
+ schemaContextProvider = requireNonNull(newSchemaContextProvider);
return self();
}
public T restoreFromSnapshot(final DatastoreSnapshot.ShardSnapshot newRestoreFromSnapshot) {
checkSealed();
- this.restoreFromSnapshot = newRestoreFromSnapshot;
+ restoreFromSnapshot = newRestoreFromSnapshot;
return self();
}
public T dataTree(final DataTree newDataTree) {
checkSealed();
- this.dataTree = newDataTree;
+ dataTree = newDataTree;
return self();
}
}
public EffectiveModelContext getSchemaContext() {
- return verifyNotNull(schemaContextProvider.getEffectiveModelContext());
+ return verifyNotNull(schemaContextProvider.get());
}
public DatastoreSnapshot.ShardSnapshot getRestoreFromSnapshot() {
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
-import java.util.Deque;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
*
* @author Thomas Pantelis
*/
+@Deprecated(since = "9.0.0", forRemoval = true)
final class ShardCommitCoordinator {
// Interface hook for unit tests to replace or decorate the ShardDataTreeCohorts.
}
}
+ @Deprecated(since = "9.0.0", forRemoval = true)
Collection<BatchedModifications> createForwardedBatchedModifications(final BatchedModifications from,
final int maxModificationsPerBatch) {
CohortEntry cohortEntry = cohortCache.remove(from.getTransactionId());
}
void abortPendingTransactions(final String reason, final Shard shard) {
- final Failure failure = new Failure(new RuntimeException(reason));
- Collection<ShardDataTreeCohort> pending = dataTree.getAndClearPendingTransactions();
+ final var failure = new Failure(new RuntimeException(reason));
+ final var pending = dataTree.getAndClearPendingTransactions();
log.debug("{}: Aborting {} pending queued transactions", name, pending.size());
- for (ShardDataTreeCohort cohort : pending) {
- CohortEntry cohortEntry = cohortCache.remove(cohort.getIdentifier());
- if (cohortEntry == null) {
- continue;
- }
-
- if (cohortEntry.getReplySender() != null) {
- cohortEntry.getReplySender().tell(failure, shard.self());
+ for (var cohort : pending) {
+ final var cohortEntry = cohortCache.remove(cohort.transactionId());
+ if (cohortEntry != null) {
+ final var replySender = cohortEntry.getReplySender();
+ if (replySender != null) {
+ replySender.tell(failure, shard.self());
+ }
}
}
}
Collection<?> convertPendingTransactionsToMessages(final int maxModificationsPerBatch) {
- final Collection<VersionedExternalizableMessage> messages = new ArrayList<>();
- for (ShardDataTreeCohort cohort : dataTree.getAndClearPendingTransactions()) {
- CohortEntry cohortEntry = cohortCache.remove(cohort.getIdentifier());
+ final var messages = new ArrayList<VersionedExternalizableMessage>();
+ for (var cohort : dataTree.getAndClearPendingTransactions()) {
+ final var cohortEntry = cohortCache.remove(cohort.transactionId());
if (cohortEntry == null) {
continue;
}
- final Deque<BatchedModifications> newMessages = new ArrayDeque<>();
+ final var newMessages = new ArrayDeque<BatchedModifications>();
cohortEntry.getDataTreeModification().applyToCursor(new AbstractBatchedModificationsCursor() {
@Override
protected BatchedModifications getModifications() {
- final BatchedModifications lastBatch = newMessages.peekLast();
-
+ final var lastBatch = newMessages.peekLast();
if (lastBatch != null && lastBatch.getModifications().size() >= maxModificationsPerBatch) {
return lastBatch;
}
// Allocate a new message
- final BatchedModifications ret = new BatchedModifications(cohortEntry.getTransactionId(),
+ final var ret = new BatchedModifications(cohortEntry.getTransactionId(),
cohortEntry.getClientVersion());
newMessages.add(ret);
return ret;
}
});
- final BatchedModifications last = newMessages.peekLast();
+ final var last = newMessages.peekLast();
if (last != null) {
final boolean immediate = cohortEntry.isDoImmediateCommit();
last.setDoCommitOnReady(immediate);
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
-import java.util.Map.Entry;
import java.util.Optional;
import java.util.OptionalLong;
import java.util.Queue;
import org.opendaylight.controller.cluster.datastore.persisted.CloseLocalHistoryPayload;
import org.opendaylight.controller.cluster.datastore.persisted.CommitTransactionPayload;
import org.opendaylight.controller.cluster.datastore.persisted.CreateLocalHistoryPayload;
-import org.opendaylight.controller.cluster.datastore.persisted.DataTreeCandidateInputOutput.DataTreeCandidateWithVersion;
import org.opendaylight.controller.cluster.datastore.persisted.MetadataShardDataTreeSnapshot;
import org.opendaylight.controller.cluster.datastore.persisted.PayloadVersion;
import org.opendaylight.controller.cluster.datastore.persisted.PurgeLocalHistoryPayload;
import org.opendaylight.mdsal.common.api.TransactionCommitFailedException;
import org.opendaylight.mdsal.dom.api.DOMDataTreeChangeListener;
import org.opendaylight.yangtools.concepts.Identifier;
-import org.opendaylight.yangtools.concepts.ListenerRegistration;
+import org.opendaylight.yangtools.concepts.Registration;
import org.opendaylight.yangtools.yang.common.Empty;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
import org.opendaylight.yangtools.yang.data.tree.spi.DataTreeCandidates;
import org.opendaylight.yangtools.yang.data.util.DataSchemaContextTree;
import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
-import org.opendaylight.yangtools.yang.model.api.SchemaContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import scala.concurrent.duration.FiniteDuration;
@Override
public String toString() {
- return "CommitEntry [tx=" + cohort.getIdentifier() + ", state=" + cohort.getState() + "]";
+ return "CommitEntry [tx=" + cohort.transactionId() + ", state=" + cohort.getState() + "]";
}
}
*/
private DataTreeTip tip;
- private SchemaContext schemaContext;
+ private EffectiveModelContext schemaContext;
private DataSchemaContextTree dataSchemaContext;
private int currentTransactionBatch;
@VisibleForTesting
public ShardDataTree(final Shard shard, final EffectiveModelContext schemaContext, final TreeType treeType) {
- this(shard, schemaContext, treeType, YangInstanceIdentifier.empty(),
+ this(shard, schemaContext, treeType, YangInstanceIdentifier.of(),
new DefaultShardDataTreeChangeListenerPublisher(""), "");
}
}
@VisibleForTesting
- final SchemaContext getSchemaContext() {
+ final EffectiveModelContext getSchemaContext() {
return schemaContext;
}
* @return A state snapshot
*/
@NonNull ShardDataTreeSnapshot takeStateSnapshot() {
- final NormalizedNode rootNode = dataTree.takeSnapshot().readNode(YangInstanceIdentifier.empty()).get();
+ final NormalizedNode rootNode = takeSnapshot().readNode(YangInstanceIdentifier.of()).orElseThrow();
final Builder<Class<? extends ShardDataTreeSnapshotMetadata<?>>, ShardDataTreeSnapshotMetadata<?>> metaBuilder =
ImmutableMap.builder();
}
final Map<Class<? extends ShardDataTreeSnapshotMetadata<?>>, ShardDataTreeSnapshotMetadata<?>> snapshotMeta;
- if (snapshot instanceof MetadataShardDataTreeSnapshot) {
- snapshotMeta = ((MetadataShardDataTreeSnapshot) snapshot).getMetadata();
+ if (snapshot instanceof MetadataShardDataTreeSnapshot metaSnapshot) {
+ snapshotMeta = metaSnapshot.getMetadata();
} else {
snapshotMeta = ImmutableMap.of();
}
- for (ShardDataTreeMetadata<?> m : metadata) {
- final ShardDataTreeSnapshotMetadata<?> s = snapshotMeta.get(m.getSupportedType());
+ for (var m : metadata) {
+ final var s = snapshotMeta.get(m.getSupportedType());
if (s != null) {
m.applySnapshot(s);
} else {
}
}
- final DataTreeModification unwrapped = dataTree.takeSnapshot().newModification();
+ final DataTreeModification unwrapped = newModification();
final DataTreeModification mod = wrapper.apply(unwrapped);
// delete everything first
- mod.delete(YangInstanceIdentifier.empty());
+ mod.delete(YangInstanceIdentifier.of());
- final Optional<NormalizedNode> maybeNode = snapshot.getRootNode();
- if (maybeNode.isPresent()) {
+ snapshot.getRootNode().ifPresent(rootNode -> {
// Add everything from the remote node back
- mod.write(YangInstanceIdentifier.empty(), maybeNode.get());
- }
+ mod.write(YangInstanceIdentifier.of(), rootNode);
+ });
+
mod.ready();
dataTree.validate(unwrapped);
@SuppressWarnings("checkstyle:IllegalCatch")
private void applyRecoveryCandidate(final CommitTransactionPayload payload) throws IOException {
- final Entry<TransactionIdentifier, DataTreeCandidateWithVersion> entry = payload.acquireCandidate();
- final DataTreeModification unwrapped = dataTree.takeSnapshot().newModification();
- final PruningDataTreeModification mod = createPruningModification(unwrapped,
- NormalizedNodeStreamVersion.MAGNESIUM.compareTo(entry.getValue().getVersion()) > 0);
+ final var entry = payload.acquireCandidate();
+ final var unwrapped = newModification();
+ final var pruningMod = createPruningModification(unwrapped,
+ NormalizedNodeStreamVersion.MAGNESIUM.compareTo(entry.streamVersion()) > 0);
- DataTreeCandidates.applyToModification(mod, entry.getValue().getCandidate());
- mod.ready();
+ DataTreeCandidates.applyToModification(pruningMod, entry.candidate());
+ pruningMod.ready();
LOG.trace("{}: Applying recovery modification {}", logContext, unwrapped);
try {
dataTree.validate(unwrapped);
dataTree.commit(dataTree.prepare(unwrapped));
} catch (Exception e) {
- File file = new File(System.getProperty("karaf.data", "."),
+ final var file = new File(System.getProperty("karaf.data", "."),
"failed-recovery-payload-" + logContext + ".out");
DataTreeModificationOutput.toFile(file, unwrapped);
- throw new IllegalStateException(String.format(
- "%s: Failed to apply recovery payload. Modification data was written to file %s",
- logContext, file), e);
+ throw new IllegalStateException(
+ "%s: Failed to apply recovery payload. Modification data was written to file %s".formatted(
+ logContext, file),
+ e);
}
- allMetadataCommittedTransaction(entry.getKey());
+ allMetadataCommittedTransaction(entry.transactionId());
}
private PruningDataTreeModification createPruningModification(final DataTreeModification unwrapped,
final boolean uintAdapting) {
// TODO: we should be able to reuse the pruner, provided we are not reentrant
- final ReusableNormalizedNodePruner pruner = ReusableNormalizedNodePruner.forDataSchemaContext(
- dataSchemaContext);
+ final var pruner = ReusableNormalizedNodePruner.forDataSchemaContext(dataSchemaContext);
return uintAdapting ? new PruningDataTreeModification.Proactive(unwrapped, dataTree, pruner.withUintAdaption())
: new PruningDataTreeModification.Reactive(unwrapped, dataTree, pruner);
}
* @throws DataValidationFailedException when the snapshot fails to apply
*/
final void applyRecoveryPayload(final @NonNull Payload payload) throws IOException {
- if (payload instanceof CommitTransactionPayload) {
- applyRecoveryCandidate((CommitTransactionPayload) payload);
- } else if (payload instanceof AbortTransactionPayload) {
- allMetadataAbortedTransaction(((AbortTransactionPayload) payload).getIdentifier());
- } else if (payload instanceof PurgeTransactionPayload) {
- allMetadataPurgedTransaction(((PurgeTransactionPayload) payload).getIdentifier());
- } else if (payload instanceof CreateLocalHistoryPayload) {
- allMetadataCreatedLocalHistory(((CreateLocalHistoryPayload) payload).getIdentifier());
- } else if (payload instanceof CloseLocalHistoryPayload) {
- allMetadataClosedLocalHistory(((CloseLocalHistoryPayload) payload).getIdentifier());
- } else if (payload instanceof PurgeLocalHistoryPayload) {
- allMetadataPurgedLocalHistory(((PurgeLocalHistoryPayload) payload).getIdentifier());
- } else if (payload instanceof SkipTransactionsPayload) {
- allMetadataSkipTransactions((SkipTransactionsPayload) payload);
+ if (payload instanceof CommitTransactionPayload commit) {
+ applyRecoveryCandidate(commit);
+ } else if (payload instanceof AbortTransactionPayload abort) {
+ allMetadataAbortedTransaction(abort.getIdentifier());
+ } else if (payload instanceof PurgeTransactionPayload purge) {
+ allMetadataPurgedTransaction(purge.getIdentifier());
+ } else if (payload instanceof CreateLocalHistoryPayload create) {
+ allMetadataCreatedLocalHistory(create.getIdentifier());
+ } else if (payload instanceof CloseLocalHistoryPayload close) {
+ allMetadataClosedLocalHistory(close.getIdentifier());
+ } else if (payload instanceof PurgeLocalHistoryPayload purge) {
+ allMetadataPurgedLocalHistory(purge.getIdentifier());
+ } else if (payload instanceof SkipTransactionsPayload skip) {
+ allMetadataSkipTransactions(skip);
} else {
LOG.debug("{}: ignoring unhandled payload {}", logContext, payload);
}
private void applyReplicatedCandidate(final CommitTransactionPayload payload)
throws DataValidationFailedException, IOException {
- final Entry<TransactionIdentifier, DataTreeCandidateWithVersion> entry = payload.acquireCandidate();
- final TransactionIdentifier identifier = entry.getKey();
- LOG.debug("{}: Applying foreign transaction {}", logContext, identifier);
+ final var payloadCandidate = payload.acquireCandidate();
+ final var transactionId = payloadCandidate.transactionId();
+ LOG.debug("{}: Applying foreign transaction {}", logContext, transactionId);
- final DataTreeModification mod = dataTree.takeSnapshot().newModification();
+ final var mod = newModification();
// TODO: check version here, which will enable us to perform forward-compatibility transformations
- DataTreeCandidates.applyToModification(mod, entry.getValue().getCandidate());
+ DataTreeCandidates.applyToModification(mod, payloadCandidate.candidate());
mod.ready();
LOG.trace("{}: Applying foreign modification {}", logContext, mod);
dataTree.validate(mod);
- final DataTreeCandidate candidate = dataTree.prepare(mod);
+ final var candidate = dataTree.prepare(mod);
dataTree.commit(candidate);
- allMetadataCommittedTransaction(identifier);
+ allMetadataCommittedTransaction(transactionId);
notifyListeners(candidate);
}
* In any case, we know that this is an entry coming from replication, hence we can be sure we will not observe
* pre-Boron state -- which limits the number of options here.
*/
- if (payload instanceof CommitTransactionPayload) {
+ if (payload instanceof CommitTransactionPayload commit) {
if (identifier == null) {
- applyReplicatedCandidate((CommitTransactionPayload) payload);
+ applyReplicatedCandidate(commit);
} else {
verify(identifier instanceof TransactionIdentifier);
// if we did not track this transaction before, it means that it came from another leader and we are in
// the process of commiting it while in PreLeader state. That means that it hasnt yet been committed to
// the local DataTree and would be lost if it was only applied via payloadReplicationComplete().
if (!payloadReplicationComplete((TransactionIdentifier) identifier)) {
- applyReplicatedCandidate((CommitTransactionPayload) payload);
+ applyReplicatedCandidate(commit);
}
}
// make sure acquireCandidate() is the last call touching the payload data as we want it to be GC-ed.
- checkRootOverwrite(((CommitTransactionPayload) payload).acquireCandidate().getValue()
- .getCandidate());
- } else if (payload instanceof AbortTransactionPayload) {
+ checkRootOverwrite(commit.acquireCandidate().candidate());
+ } else if (payload instanceof AbortTransactionPayload abort) {
if (identifier != null) {
- payloadReplicationComplete((AbortTransactionPayload) payload);
+ payloadReplicationComplete(abort);
}
- allMetadataAbortedTransaction(((AbortTransactionPayload) payload).getIdentifier());
- } else if (payload instanceof PurgeTransactionPayload) {
+ allMetadataAbortedTransaction(abort.getIdentifier());
+ } else if (payload instanceof PurgeTransactionPayload purge) {
if (identifier != null) {
- payloadReplicationComplete((PurgeTransactionPayload) payload);
+ payloadReplicationComplete(purge);
}
- allMetadataPurgedTransaction(((PurgeTransactionPayload) payload).getIdentifier());
- } else if (payload instanceof CloseLocalHistoryPayload) {
+ allMetadataPurgedTransaction(purge.getIdentifier());
+ } else if (payload instanceof CloseLocalHistoryPayload close) {
if (identifier != null) {
- payloadReplicationComplete((CloseLocalHistoryPayload) payload);
+ payloadReplicationComplete(close);
}
- allMetadataClosedLocalHistory(((CloseLocalHistoryPayload) payload).getIdentifier());
- } else if (payload instanceof CreateLocalHistoryPayload) {
+ allMetadataClosedLocalHistory(close.getIdentifier());
+ } else if (payload instanceof CreateLocalHistoryPayload create) {
if (identifier != null) {
- payloadReplicationComplete((CreateLocalHistoryPayload)payload);
+ payloadReplicationComplete(create);
}
- allMetadataCreatedLocalHistory(((CreateLocalHistoryPayload) payload).getIdentifier());
- } else if (payload instanceof PurgeLocalHistoryPayload) {
+ allMetadataCreatedLocalHistory(create.getIdentifier());
+ } else if (payload instanceof PurgeLocalHistoryPayload purge) {
if (identifier != null) {
- payloadReplicationComplete((PurgeLocalHistoryPayload)payload);
+ payloadReplicationComplete(purge);
}
- allMetadataPurgedLocalHistory(((PurgeLocalHistoryPayload) payload).getIdentifier());
- } else if (payload instanceof SkipTransactionsPayload) {
+ allMetadataPurgedLocalHistory(purge.getIdentifier());
+ } else if (payload instanceof SkipTransactionsPayload skip) {
if (identifier != null) {
- payloadReplicationComplete((SkipTransactionsPayload)payload);
+ payloadReplicationComplete(skip);
}
- allMetadataSkipTransactions((SkipTransactionsPayload) payload);
+ allMetadataSkipTransactions(skip);
} else {
LOG.warn("{}: ignoring unhandled identifier {} payload {}", logContext, identifier, payload);
}
}
// top level container ie "/"
- if (candidate.getRootPath().isEmpty()
- && candidate.getRootNode().getModificationType() == ModificationType.WRITE) {
+ if (candidate.getRootPath().isEmpty() && candidate.getRootNode().modificationType() == ModificationType.WRITE) {
LOG.debug("{}: shard root overwritten, enqueuing snapshot", logContext);
shard.self().tell(new InitiateCaptureSnapshot(), noSender());
}
}
private boolean payloadReplicationComplete(final TransactionIdentifier txId) {
- final CommitEntry current = pendingFinishCommits.peek();
+ final var current = pendingFinishCommits.peek();
if (current == null) {
LOG.warn("{}: No outstanding transactions, ignoring consensus on transaction {}", logContext, txId);
allMetadataCommittedTransaction(txId);
return false;
}
- if (!current.cohort.getIdentifier().equals(txId)) {
+ final var cohortTxId = current.cohort.transactionId();
+ if (!cohortTxId.equals(txId)) {
LOG.debug("{}: Head of pendingFinishCommits queue is {}, ignoring consensus on transaction {}", logContext,
- current.cohort.getIdentifier(), txId);
+ cohortTxId, txId);
allMetadataCommittedTransaction(txId);
return false;
}
return chain;
}
- final ReadOnlyShardDataTreeTransaction newReadOnlyTransaction(final TransactionIdentifier txId) {
+ final @NonNull ReadOnlyShardDataTreeTransaction newReadOnlyTransaction(final TransactionIdentifier txId) {
shard.getShardMBean().incrementReadOnlyTransactionCount();
- if (txId.getHistoryId().getHistoryId() == 0) {
- return new ReadOnlyShardDataTreeTransaction(this, txId, dataTree.takeSnapshot());
- }
+ final var historyId = txId.getHistoryId();
+ return historyId.getHistoryId() == 0 ? newStandaloneReadOnlyTransaction(txId)
+ : ensureTransactionChain(historyId, null).newReadOnlyTransaction(txId);
+ }
- return ensureTransactionChain(txId.getHistoryId(), null).newReadOnlyTransaction(txId);
+ final @NonNull ReadOnlyShardDataTreeTransaction newStandaloneReadOnlyTransaction(final TransactionIdentifier txId) {
+ return new ReadOnlyShardDataTreeTransaction(this, txId, takeSnapshot());
}
- final ReadWriteShardDataTreeTransaction newReadWriteTransaction(final TransactionIdentifier txId) {
+ final @NonNull ReadWriteShardDataTreeTransaction newReadWriteTransaction(final TransactionIdentifier txId) {
shard.getShardMBean().incrementReadWriteTransactionCount();
- if (txId.getHistoryId().getHistoryId() == 0) {
- return new ReadWriteShardDataTreeTransaction(ShardDataTree.this, txId, dataTree.takeSnapshot()
- .newModification());
- }
+ final var historyId = txId.getHistoryId();
+ return historyId.getHistoryId() == 0 ? newStandaloneReadWriteTransaction(txId)
+ : ensureTransactionChain(historyId, null).newReadWriteTransaction(txId);
+ }
- return ensureTransactionChain(txId.getHistoryId(), null).newReadWriteTransaction(txId);
+ final @NonNull ReadWriteShardDataTreeTransaction newStandaloneReadWriteTransaction(
+ final TransactionIdentifier txId) {
+ return new ReadWriteShardDataTreeTransaction(this, txId, newModification());
}
@VisibleForTesting
}
final Optional<DataTreeCandidate> readCurrentData() {
- return dataTree.takeSnapshot().readNode(YangInstanceIdentifier.empty())
- .map(state -> DataTreeCandidates.fromNormalizedNode(YangInstanceIdentifier.empty(), state));
+ return readNode(YangInstanceIdentifier.of())
+ .map(state -> DataTreeCandidates.fromNormalizedNode(YangInstanceIdentifier.of(), state));
}
final void registerTreeChangeListener(final YangInstanceIdentifier path, final DOMDataTreeChangeListener listener,
- final Optional<DataTreeCandidate> initialState,
- final Consumer<ListenerRegistration<DOMDataTreeChangeListener>> onRegistration) {
+ final Optional<DataTreeCandidate> initialState, final Consumer<Registration> onRegistration) {
treeChangeListenerPublisher.registerTreeChangeListener(path, listener, initialState, onRegistration);
}
@VisibleForTesting
public final Optional<NormalizedNode> readNode(final YangInstanceIdentifier path) {
- return dataTree.takeSnapshot().readNode(path);
+ return takeSnapshot().readNode(path);
}
final DataTreeSnapshot takeSnapshot() {
@VisibleForTesting
final DataTreeModification newModification() {
- return dataTree.takeSnapshot().newModification();
+ return takeSnapshot().newModification();
}
final Collection<ShardDataTreeCohort> getAndClearPendingTransactions() {
final SimpleShardDataTreeCohort cohort = entry.cohort;
final DataTreeModification modification = cohort.getDataTreeModification();
- LOG.debug("{}: Validating transaction {}", logContext, cohort.getIdentifier());
+ LOG.debug("{}: Validating transaction {}", logContext, cohort.transactionId());
Exception cause;
try {
tip.validate(modification);
- LOG.debug("{}: Transaction {} validated", logContext, cohort.getIdentifier());
+ LOG.debug("{}: Transaction {} validated", logContext, cohort.transactionId());
cohort.successfulCanCommit();
entry.lastAccess = readTime();
return;
} catch (ConflictingModificationAppliedException e) {
- LOG.warn("{}: Store Tx {}: Conflicting modification for path {}.", logContext, cohort.getIdentifier(),
+ LOG.warn("{}: Store Tx {}: Conflicting modification for path {}.", logContext, cohort.transactionId(),
e.getPath());
cause = new OptimisticLockFailedException("Optimistic lock failed for path " + e.getPath(), e);
} catch (DataValidationFailedException e) {
- LOG.warn("{}: Store Tx {}: Data validation failed for path {}.", logContext, cohort.getIdentifier(),
+ LOG.warn("{}: Store Tx {}: Data validation failed for path {}.", logContext, cohort.transactionId(),
e.getPath(), e);
// For debugging purposes, allow dumping of the modification. Coupled with the above
// precondition log, it should allow us to understand what went on.
- LOG.debug("{}: Store Tx {}: modifications: {}", logContext, cohort.getIdentifier(), modification);
+ LOG.debug("{}: Store Tx {}: modifications: {}", logContext, cohort.transactionId(), modification);
LOG.trace("{}: Current tree: {}", logContext, dataTree);
cause = new TransactionCommitFailedException("Data did not pass validation for path " + e.getPath(), e);
} catch (Exception e) {
final SimpleShardDataTreeCohort cohort = entry.cohort;
if (cohort.isFailed()) {
- LOG.debug("{}: Removing failed transaction {}", logContext, cohort.getIdentifier());
+ LOG.debug("{}: Removing failed transaction {}", logContext, cohort.transactionId());
queue.remove();
continue;
}
Collection<String> precedingShardNames = extractPrecedingShardNames(cohort.getParticipatingShardNames());
if (precedingShardNames.isEmpty()) {
- LOG.debug("{}: Tx {} is scheduled for canCommit step", logContext, cohort.getIdentifier());
+ LOG.debug("{}: Tx {} is scheduled for canCommit step", logContext, cohort.transactionId());
return;
}
LOG.debug("{}: Evaluating tx {} for canCommit - preceding participating shard names {}",
- logContext, cohort.getIdentifier(), precedingShardNames);
+ logContext, cohort.transactionId(), precedingShardNames);
final Iterator<CommitEntry> iter = pendingTransactions.iterator();
int index = -1;
int moveToIndex = -1;
if (cohort.equals(entry.cohort)) {
if (moveToIndex < 0) {
LOG.debug("{}: Not moving tx {} - cannot proceed with canCommit",
- logContext, cohort.getIdentifier());
+ logContext, cohort.transactionId());
return;
}
LOG.debug("{}: Moving {} to index {} in the pendingTransactions queue",
- logContext, cohort.getIdentifier(), moveToIndex);
+ logContext, cohort.transactionId(), moveToIndex);
iter.remove();
insertEntry(pendingTransactions, entry, moveToIndex);
if (!cohort.equals(pendingTransactions.peek().cohort)) {
LOG.debug("{}: Tx {} is not at the head of the queue - cannot proceed with canCommit",
- logContext, cohort.getIdentifier());
+ logContext, cohort.transactionId());
return;
}
LOG.debug("{}: Tx {} is now at the head of the queue - proceeding with canCommit",
- logContext, cohort.getIdentifier());
+ logContext, cohort.transactionId());
break;
}
if (entry.cohort.getState() != State.READY) {
LOG.debug("{}: Skipping pending transaction {} in state {}",
- logContext, entry.cohort.getIdentifier(), entry.cohort.getState());
+ logContext, entry.cohort.transactionId(), entry.cohort.getState());
continue;
}
if (precedingShardNames.equals(pendingPrecedingShardNames)) {
if (moveToIndex < 0) {
LOG.debug("{}: Preceding shard names {} for pending tx {} match - saving moveToIndex {}",
- logContext, pendingPrecedingShardNames, entry.cohort.getIdentifier(), index);
+ logContext, pendingPrecedingShardNames, entry.cohort.transactionId(), index);
moveToIndex = index;
} else {
LOG.debug(
"{}: Preceding shard names {} for pending tx {} match but moveToIndex already set to {}",
- logContext, pendingPrecedingShardNames, entry.cohort.getIdentifier(), moveToIndex);
+ logContext, pendingPrecedingShardNames, entry.cohort.transactionId(), moveToIndex);
}
} else {
LOG.debug("{}: Preceding shard names {} for pending tx {} differ - skipping",
- logContext, pendingPrecedingShardNames, entry.cohort.getIdentifier());
+ logContext, pendingPrecedingShardNames, entry.cohort.transactionId());
}
}
}
final SimpleShardDataTreeCohort current = entry.cohort;
verify(cohort.equals(current), "Attempted to pre-commit %s while %s is pending", cohort, current);
- final TransactionIdentifier currentId = current.getIdentifier();
+ final TransactionIdentifier currentId = current.transactionId();
LOG.debug("{}: Preparing transaction {}", logContext, currentId);
final DataTreeCandidateTip candidate;
@SuppressWarnings("checkstyle:IllegalCatch")
private void finishCommit(final SimpleShardDataTreeCohort cohort) {
- final TransactionIdentifier txId = cohort.getIdentifier();
+ final TransactionIdentifier txId = cohort.transactionId();
final DataTreeCandidate candidate = cohort.getCandidate();
LOG.debug("{}: Resuming commit of transaction {}", logContext, txId);
final SimpleShardDataTreeCohort current = entry.cohort;
if (!cohort.equals(current)) {
- LOG.debug("{}: Transaction {} scheduled for commit step", logContext, cohort.getIdentifier());
+ LOG.debug("{}: Transaction {} scheduled for commit step", logContext, cohort.transactionId());
return;
}
- LOG.debug("{}: Starting commit for transaction {}", logContext, current.getIdentifier());
+ LOG.debug("{}: Starting commit for transaction {}", logContext, current.transactionId());
- final TransactionIdentifier txId = cohort.getIdentifier();
+ final TransactionIdentifier txId = cohort.transactionId();
final Payload payload;
try {
payload = CommitTransactionPayload.create(txId, candidate, PayloadVersion.current(),
// the newReadWriteTransaction()
final ShardDataTreeCohort newReadyCohort(final TransactionIdentifier txId, final DataTreeModification mod,
final Optional<SortedSet<String>> participatingShardNames) {
- if (txId.getHistoryId().getHistoryId() == 0) {
+ final var historyId = txId.getHistoryId();
+ if (historyId.getHistoryId() == 0) {
return createReadyCohort(txId, mod, participatingShardNames);
}
-
- return ensureTransactionChain(txId.getHistoryId(), null).createReadyCohort(txId, mod, participatingShardNames);
+ return ensureTransactionChain(historyId, null).createReadyCohort(txId, mod, participatingShardNames);
}
@SuppressFBWarnings(value = "DB_DUPLICATE_SWITCH_CLAUSES", justification = "See inline comments below.")
final OptionalLong updateOpt = accessTimeUpdater.apply(currentTx.cohort);
if (updateOpt.isPresent()) {
- final long newAccess = updateOpt.getAsLong();
+ final long newAccess = updateOpt.orElseThrow();
final long newDelta = now - newAccess;
if (newDelta < delta) {
LOG.debug("{}: Updated current transaction {} access time", logContext,
- currentTx.cohort.getIdentifier());
+ currentTx.cohort.transactionId());
currentTx.lastAccess = newAccess;
delta = newDelta;
}
final State state = currentTx.cohort.getState();
LOG.warn("{}: Current transaction {} has timed out after {} ms in state {}", logContext,
- currentTx.cohort.getIdentifier(), deltaMillis, state);
+ currentTx.cohort.transactionId(), deltaMillis, state);
boolean processNext = true;
final TimeoutException cohortFailure = new TimeoutException("Backend timeout in state " + state + " after "
+ deltaMillis + "ms");
break;
case COMMIT_PENDING:
LOG.warn("{}: Transaction {} is still committing, cannot abort", logContext,
- currentTx.cohort.getIdentifier());
+ currentTx.cohort.transactionId());
currentTx.lastAccess = now;
processNext = false;
return;
final Iterator<CommitEntry> it = Iterables.concat(pendingFinishCommits, pendingCommits,
pendingTransactions).iterator();
if (!it.hasNext()) {
- LOG.debug("{}: no open transaction while attempting to abort {}", logContext, cohort.getIdentifier());
+ LOG.debug("{}: no open transaction while attempting to abort {}", logContext, cohort.transactionId());
return true;
}
final CommitEntry first = it.next();
if (cohort.equals(first.cohort)) {
if (cohort.getState() != State.COMMIT_PENDING) {
- LOG.debug("{}: aborting head of queue {} in state {}", logContext, cohort.getIdentifier(),
- cohort.getIdentifier());
+ LOG.debug("{}: aborting head of queue {} in state {}", logContext, cohort.transactionId(),
+ cohort.transactionId());
it.remove();
if (cohort.getCandidate() != null) {
return true;
}
- LOG.warn("{}: transaction {} is committing, skipping abort", logContext, cohort.getIdentifier());
+ LOG.warn("{}: transaction {} is committing, skipping abort", logContext, cohort.transactionId());
return false;
}
while (it.hasNext()) {
final CommitEntry e = it.next();
if (cohort.equals(e.cohort)) {
- LOG.debug("{}: aborting queued transaction {}", logContext, cohort.getIdentifier());
+ LOG.debug("{}: aborting queued transaction {}", logContext, cohort.transactionId());
it.remove();
if (cohort.getCandidate() != null) {
}
return true;
- } else {
- newTip = requireNonNullElse(e.cohort.getCandidate(), newTip);
}
+
+ newTip = requireNonNullElse(e.cohort.getCandidate(), newTip);
}
- LOG.debug("{}: aborted transaction {} not found in the queue", logContext, cohort.getIdentifier());
+ LOG.debug("{}: aborted transaction {} not found in the queue", logContext, cohort.transactionId());
return true;
}
while (iter.hasNext()) {
final SimpleShardDataTreeCohort cohort = iter.next().cohort;
if (cohort.getState() == State.CAN_COMMIT_COMPLETE) {
- LOG.debug("{}: Revalidating queued transaction {}", logContext, cohort.getIdentifier());
+ LOG.debug("{}: Revalidating queued transaction {}", logContext, cohort.transactionId());
try {
tip.validate(cohort.getDataTreeModification());
} catch (DataValidationFailedException | RuntimeException e) {
- LOG.debug("{}: Failed to revalidate queued transaction {}", logContext, cohort.getIdentifier(), e);
+ LOG.debug("{}: Failed to revalidate queued transaction {}", logContext, cohort.transactionId(), e);
cohort.reportFailure(e);
}
} else if (cohort.getState() == State.PRE_COMMIT_COMPLETE) {
- LOG.debug("{}: Repreparing queued transaction {}", logContext, cohort.getIdentifier());
+ LOG.debug("{}: Repreparing queued transaction {}", logContext, cohort.transactionId());
try {
tip.validate(cohort.getDataTreeModification());
cohort.setNewCandidate(candidate);
tip = candidate;
} catch (RuntimeException | DataValidationFailedException e) {
- LOG.debug("{}: Failed to reprepare queued transaction {}", logContext, cohort.getIdentifier(), e);
+ LOG.debug("{}: Failed to reprepare queued transaction {}", logContext, cohort.transactionId(), e);
cohort.reportFailure(e);
}
}
import java.util.Optional;
import java.util.function.Consumer;
import org.opendaylight.mdsal.dom.api.DOMDataTreeChangeListener;
-import org.opendaylight.yangtools.concepts.ListenerRegistration;
+import org.opendaylight.yangtools.concepts.Registration;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
import org.opendaylight.yangtools.yang.data.tree.api.DataTreeCandidate;
*/
interface ShardDataTreeChangeListenerPublisher extends ShardDataTreeNotificationPublisher {
void registerTreeChangeListener(YangInstanceIdentifier treeId, DOMDataTreeChangeListener listener,
- Optional<DataTreeCandidate> initialState,
- Consumer<ListenerRegistration<DOMDataTreeChangeListener>> onRegistration);
+ Optional<DataTreeCandidate> initialState, Consumer<Registration> onRegistration);
}
import java.util.Optional;
import java.util.function.Consumer;
import org.opendaylight.mdsal.dom.api.DOMDataTreeChangeListener;
-import org.opendaylight.yangtools.concepts.ListenerRegistration;
+import org.opendaylight.yangtools.concepts.Registration;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
import org.opendaylight.yangtools.yang.data.tree.api.DataTreeCandidate;
@Override
public void registerTreeChangeListener(final YangInstanceIdentifier treeId,
final DOMDataTreeChangeListener listener, final Optional<DataTreeCandidate> currentState,
- final Consumer<ListenerRegistration<DOMDataTreeChangeListener>> onRegistration) {
+ final Consumer<Registration> onRegistration) {
final ShardDataTreeChangePublisherActor.RegisterListener regMessage =
new ShardDataTreeChangePublisherActor.RegisterListener(treeId, listener, currentState, onRegistration);
log.debug("{}: Sending {} to publisher actor {}", logContext(), regMessage, publisherActor());
import java.util.Optional;
import java.util.function.Consumer;
import org.opendaylight.mdsal.dom.api.DOMDataTreeChangeListener;
-import org.opendaylight.yangtools.concepts.ListenerRegistration;
+import org.opendaylight.yangtools.concepts.Registration;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
import org.opendaylight.yangtools.yang.data.tree.api.DataTreeCandidate;
@Override
protected void handleReceive(final Object message) {
- if (message instanceof RegisterListener) {
- RegisterListener reg = (RegisterListener)message;
+ if (message instanceof RegisterListener reg) {
LOG.debug("{}: Received {}", logContext(), reg);
if (reg.initialState.isPresent()) {
DefaultShardDataTreeChangeListenerPublisher.notifySingleListener(reg.path, reg.listener,
- reg.initialState.get(), logContext());
+ reg.initialState.orElseThrow(), logContext());
} else {
reg.listener.onInitialData();
}
private final YangInstanceIdentifier path;
private final DOMDataTreeChangeListener listener;
private final Optional<DataTreeCandidate> initialState;
- private final Consumer<ListenerRegistration<DOMDataTreeChangeListener>> onRegistration;
+ private final Consumer<Registration> onRegistration;
RegisterListener(final YangInstanceIdentifier path, final DOMDataTreeChangeListener listener,
- final Optional<DataTreeCandidate> initialState,
- final Consumer<ListenerRegistration<DOMDataTreeChangeListener>> onRegistration) {
+ final Optional<DataTreeCandidate> initialState, final Consumer<Registration> onRegistration) {
this.path = requireNonNull(path);
this.listener = requireNonNull(listener);
this.initialState = requireNonNull(initialState);
import com.google.common.util.concurrent.FutureCallback;
import java.util.Optional;
import java.util.SortedSet;
+import org.eclipse.jdt.annotation.NonNull;
import org.opendaylight.controller.cluster.access.concepts.TransactionIdentifier;
-import org.opendaylight.yangtools.concepts.Identifiable;
import org.opendaylight.yangtools.yang.common.Empty;
import org.opendaylight.yangtools.yang.data.tree.api.DataTreeCandidate;
import org.opendaylight.yangtools.yang.data.tree.api.DataTreeCandidateTip;
import org.opendaylight.yangtools.yang.data.tree.api.DataTreeModification;
@VisibleForTesting
-public abstract class ShardDataTreeCohort implements Identifiable<TransactionIdentifier> {
+public abstract class ShardDataTreeCohort {
public enum State {
READY,
CAN_COMMIT_PENDING,
// Prevent foreign instantiation
}
+ abstract @NonNull TransactionIdentifier transactionId();
+
// FIXME: This leaks internal state generated in preCommit,
// should be result of canCommit
abstract DataTreeCandidateTip getCandidate();
}
ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
- return toStringHelper.add("id", getIdentifier()).add("state", getState());
+ return toStringHelper.add("id", transactionId()).add("state", getState());
}
}
import com.google.common.base.MoreObjects;
import java.util.Optional;
import java.util.SortedSet;
+import org.eclipse.jdt.annotation.NonNull;
import org.opendaylight.controller.cluster.access.concepts.LocalHistoryIdentifier;
import org.opendaylight.controller.cluster.access.concepts.TransactionIdentifier;
import org.opendaylight.yangtools.concepts.Identifiable;
return previousTx.getSnapshot();
}
- ReadOnlyShardDataTreeTransaction newReadOnlyTransaction(final TransactionIdentifier txId) {
+ @NonNull ReadOnlyShardDataTreeTransaction newReadOnlyTransaction(final TransactionIdentifier txId) {
final DataTreeSnapshot snapshot = getSnapshot();
LOG.debug("Allocated read-only transaction {} snapshot {}", txId, snapshot);
return new ReadOnlyShardDataTreeTransaction(this, txId, snapshot);
}
- ReadWriteShardDataTreeTransaction newReadWriteTransaction(final TransactionIdentifier txId) {
+ @NonNull ReadWriteShardDataTreeTransaction newReadWriteTransaction(final TransactionIdentifier txId) {
final DataTreeSnapshot snapshot = getSnapshot();
LOG.debug("Allocated read-write transaction {} snapshot {}", txId, snapshot);
- openTransaction = new ReadWriteShardDataTreeTransaction(this, txId, snapshot.newModification());
- return openTransaction;
+ final var ret = new ReadWriteShardDataTreeTransaction(this, txId, snapshot.newModification());
+ openTransaction = ret;
+ return ret;
}
void close() {
*
* @author syedbahm
*/
-public class ShardReadTransaction extends ShardTransaction {
+@Deprecated(since = "9.0.0", forRemoval = true)
+public final class ShardReadTransaction extends ShardTransaction {
private final AbstractShardDataTreeTransaction<?> transaction;
public ShardReadTransaction(final AbstractShardDataTreeTransaction<?> transaction, final ActorRef shardActor,
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
-
package org.opendaylight.controller.cluster.datastore;
import akka.actor.ActorRef;
*
* @author syedbahm
*/
+@Deprecated(since = "9.0.0", forRemoval = true)
public class ShardReadWriteTransaction extends ShardWriteTransaction {
- public ShardReadWriteTransaction(ReadWriteShardDataTreeTransaction transaction, ActorRef shardActor,
- ShardStats shardStats) {
+ public ShardReadWriteTransaction(final ReadWriteShardDataTreeTransaction transaction, final ActorRef shardActor,
+ final ShardStats shardStats) {
super(transaction, shardActor, shardStats);
}
@Override
- public void handleReceive(Object message) {
+ public void handleReceive(final Object message) {
if (ReadData.isSerializedType(message)) {
readData(ReadData.fromSerializable(message));
} else if (DataExists.isSerializedType(message)) {
/**
* The ShardTransaction Actor represents a remote transaction that delegates all actions to DOMDataReadWriteTransaction.
*/
+@Deprecated(since = "9.0.0", forRemoval = true)
public abstract class ShardTransaction extends AbstractUntypedActorWithMetering {
private final ActorRef shardActor;
private final ShardStats shardStats;
@SuppressFBWarnings(value = "SE_BAD_FIELD", justification = "Some fields are not Serializable but we don't "
+ "create remote instances of this actor and thus don't need it to be Serializable.")
private static class ShardTransactionCreator implements Creator<ShardTransaction> {
-
+ @java.io.Serial
private static final long serialVersionUID = 1L;
final AbstractShardDataTreeTransaction<?> transaction;
@Override
public ShardTransaction create() {
- final ShardTransaction tx;
- switch (type) {
- case READ_ONLY:
- tx = new ShardReadTransaction(transaction, shardActor, shardStats);
- break;
- case READ_WRITE:
- tx = new ShardReadWriteTransaction((ReadWriteShardDataTreeTransaction)transaction, shardActor,
- shardStats);
- break;
- case WRITE_ONLY:
- tx = new ShardWriteTransaction((ReadWriteShardDataTreeTransaction)transaction, shardActor,
- shardStats);
- break;
- default:
- throw new IllegalArgumentException("Unhandled transaction type " + type);
- }
-
+ final var tx = switch (type) {
+ case READ_ONLY -> new ShardReadTransaction(transaction, shardActor, shardStats);
+ case READ_WRITE -> new ShardReadWriteTransaction((ReadWriteShardDataTreeTransaction) transaction,
+ shardActor, shardStats);
+ case WRITE_ONLY -> new ShardWriteTransaction((ReadWriteShardDataTreeTransaction) transaction,
+ shardActor, shardStats);
+ default -> throw new IllegalArgumentException("Unhandled transaction type " + type);
+ };
tx.getContext().setReceiveTimeout(datastoreContext.getShardTransactionIdleTimeout());
return tx;
}
*
* @author Thomas Pantelis
*/
-class ShardTransactionActorFactory {
+@Deprecated(since = "9.0.0", forRemoval = true)
+final class ShardTransactionActorFactory {
private static final AtomicLong ACTOR_NAME_COUNTER = new AtomicLong();
private final ShardDataTree dataTree;
private final ActorRef shardActor;
private final String shardName;
- ShardTransactionActorFactory(ShardDataTree dataTree, DatastoreContext datastoreContext,
- String txnDispatcherPath, ActorRef shardActor, ActorContext actorContext, ShardStats shardMBean,
- String shardName) {
+ ShardTransactionActorFactory(final ShardDataTree dataTree, final DatastoreContext datastoreContext,
+ final String txnDispatcherPath, final ActorRef shardActor, final ActorContext actorContext,
+ final ShardStats shardMBean, final String shardName) {
this.dataTree = requireNonNull(dataTree);
this.datastoreContext = requireNonNull(datastoreContext);
this.txnDispatcherPath = requireNonNull(txnDispatcherPath);
return sb.append(txId.getTransactionId()).append('_').append(ACTOR_NAME_COUNTER.incrementAndGet()).toString();
}
- ActorRef newShardTransaction(TransactionType type, TransactionIdentifier transactionID) {
- final AbstractShardDataTreeTransaction<?> transaction;
- switch (type) {
- case READ_ONLY:
- transaction = dataTree.newReadOnlyTransaction(transactionID);
- break;
- case READ_WRITE:
- case WRITE_ONLY:
- transaction = dataTree.newReadWriteTransaction(transactionID);
- break;
- default:
- throw new IllegalArgumentException("Unsupported transaction type " + type);
- }
-
+ ActorRef newShardTransaction(final TransactionType type, final TransactionIdentifier transactionID) {
+ final AbstractShardDataTreeTransaction<?> transaction = switch (type) {
+ case READ_ONLY -> dataTree.newReadOnlyTransaction(transactionID);
+ case READ_WRITE, WRITE_ONLY -> dataTree.newReadWriteTransaction(transactionID);
+ default -> throw new IllegalArgumentException("Unsupported transaction type " + type);
+ };
return actorContext.actorOf(ShardTransaction.props(type, transaction, shardActor, datastoreContext, shardMBean)
.withDispatcher(txnDispatcherPath), actorNameFor(transactionID));
}
*
* @author Thomas Pantelis
*/
+@Deprecated(since = "9.0.0", forRemoval = true)
class ShardTransactionMessageRetrySupport implements Closeable {
private static final Logger LOG = LoggerFactory.getLogger(ShardTransactionMessageRetrySupport.class);
messagesToRetry.clear();
}
- private static class MessageInfo {
+ private static final class MessageInfo {
final Object message;
final ActorRef replyTo;
final String failureMessage;
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
-
package org.opendaylight.controller.cluster.datastore;
import akka.actor.ActorRef;
*
* @author syedbahm
*/
+@Deprecated(since = "9.0.0", forRemoval = true)
public class ShardWriteTransaction extends ShardTransaction {
-
private int totalBatchedModificationsReceived;
private Exception lastBatchedModificationsException;
private final ReadWriteShardDataTreeTransaction transaction;
import java.util.Optional;
import java.util.SortedSet;
import java.util.concurrent.CompletionStage;
+import org.eclipse.jdt.annotation.NonNull;
import org.eclipse.jdt.annotation.Nullable;
import org.opendaylight.controller.cluster.access.concepts.TransactionIdentifier;
import org.opendaylight.yangtools.yang.common.Empty;
private final DataTreeModification transaction;
private final ShardDataTree dataTree;
- private final TransactionIdentifier transactionId;
+ private final @NonNull TransactionIdentifier transactionId;
private final CompositeDataTreeCohort userCohorts;
private final @Nullable SortedSet<String> participatingShardNames;
}
@Override
- public TransactionIdentifier getIdentifier() {
+ TransactionIdentifier transactionId() {
return transactionId;
}
private void checkState(final State expected) {
Preconditions.checkState(state == expected, "State %s does not match expected state %s for %s",
- state, expected, getIdentifier());
+ state, expected, transactionId());
}
@Override
return;
}
- maybeAborts.get().whenComplete((noop, failure) -> {
+ maybeAborts.orElseThrow().whenComplete((noop, failure) -> {
if (failure != null) {
abortCallback.onFailure(failure);
} else {
return;
}
- maybeCanCommitFuture.get().whenComplete((noop, failure) -> {
+ maybeCanCommitFuture.orElseThrow().whenComplete((noop, failure) -> {
if (failure != null) {
futureCallback.onFailure(failure);
} else {
return;
}
- maybePreCommitFuture.get().whenComplete((noop, failure) -> {
+ maybePreCommitFuture.orElseThrow().whenComplete((noop, failure) -> {
if (failure != null) {
futureCallback.onFailure(failure);
} else {
return;
}
- maybeCommitFuture.get().whenComplete((noop, failure) -> {
+ maybeCommitFuture.orElseThrow().whenComplete((noop, failure) -> {
if (failure != null) {
LOG.error("User cohorts failed to commit", failure);
}
+++ /dev/null
-/*
- * Copyright (c) 2015 Brocade Communications Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.cluster.datastore;
-
-import static java.util.Objects.requireNonNull;
-
-import akka.dispatch.OnComplete;
-import com.google.common.util.concurrent.ListenableFuture;
-import com.google.common.util.concurrent.SettableFuture;
-import java.util.List;
-import org.opendaylight.controller.cluster.access.concepts.TransactionIdentifier;
-import org.opendaylight.controller.cluster.datastore.utils.ActorUtils;
-import org.opendaylight.mdsal.common.api.CommitInfo;
-import org.opendaylight.mdsal.dom.spi.store.DOMStoreThreePhaseCommitCohort;
-import org.opendaylight.yangtools.yang.common.Empty;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import scala.concurrent.Future;
-
-/**
- * A cohort proxy implementation for a single-shard transaction commit. If the transaction was a direct commit
- * to the shard, this implementation elides the CanCommitTransaction and CommitTransaction messages to the
- * shard as an optimization.
- *
- * @author Thomas Pantelis
- */
-class SingleCommitCohortProxy extends AbstractThreePhaseCommitCohort<Object> {
- private static final Logger LOG = LoggerFactory.getLogger(SingleCommitCohortProxy.class);
-
- private final ActorUtils actorUtils;
- private final Future<Object> cohortFuture;
- private final TransactionIdentifier transactionId;
- private volatile DOMStoreThreePhaseCommitCohort delegateCohort = NoOpDOMStoreThreePhaseCommitCohort.INSTANCE;
- private final OperationCallback.Reference operationCallbackRef;
-
- SingleCommitCohortProxy(final ActorUtils actorUtils, final Future<Object> cohortFuture,
- final TransactionIdentifier transactionId, final OperationCallback.Reference operationCallbackRef) {
- this.actorUtils = actorUtils;
- this.cohortFuture = cohortFuture;
- this.transactionId = requireNonNull(transactionId);
- this.operationCallbackRef = operationCallbackRef;
- }
-
- @Override
- public ListenableFuture<Boolean> canCommit() {
- LOG.debug("Tx {} canCommit", transactionId);
-
- final SettableFuture<Boolean> returnFuture = SettableFuture.create();
-
- cohortFuture.onComplete(new OnComplete<>() {
- @Override
- public void onComplete(final Throwable failure, final Object cohortResponse) {
- if (failure != null) {
- operationCallbackRef.get().failure();
- returnFuture.setException(failure);
- return;
- }
-
- operationCallbackRef.get().success();
-
- LOG.debug("Tx {} successfully completed direct commit", transactionId);
-
- // The Future was the result of a direct commit to the shard, essentially eliding the
- // front-end 3PC coordination. We don't really care about the specific Future
- // response object, only that it completed successfully. At this point the Tx is complete
- // so return true. The subsequent preCommit and commit phases will be no-ops, ie return
- // immediate success, to complete the 3PC for the front-end.
- returnFuture.set(Boolean.TRUE);
- }
- }, actorUtils.getClientDispatcher());
-
- return returnFuture;
- }
-
- @Override
- public ListenableFuture<Empty> preCommit() {
- return delegateCohort.preCommit();
- }
-
- @Override
- public ListenableFuture<Empty> abort() {
- return delegateCohort.abort();
- }
-
- @Override
- public ListenableFuture<? extends CommitInfo> commit() {
- return delegateCohort.commit();
- }
-
- @Override
- List<Future<Object>> getCohortFutures() {
- return List.of(cohortFuture);
- }
-}
@Override
FrontendTransaction createOpenSnapshot(final TransactionIdentifier id) {
- return FrontendReadOnlyTransaction.create(this, tree.newReadOnlyTransaction(id));
+ return FrontendReadOnlyTransaction.create(this, tree.newStandaloneReadOnlyTransaction(id));
}
@Override
FrontendTransaction createOpenTransaction(final TransactionIdentifier id) {
- return FrontendReadWriteTransaction.createOpen(this, tree.newReadWriteTransaction(id));
+ return FrontendReadWriteTransaction.createOpen(this, tree.newStandaloneReadWriteTransaction(id));
}
@Override
+++ /dev/null
-/*
- * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.cluster.datastore;
-
-import static com.google.common.base.Preconditions.checkState;
-import static java.util.Objects.requireNonNull;
-
-import akka.actor.ActorSelection;
-import akka.dispatch.Futures;
-import akka.dispatch.OnComplete;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.List;
-import java.util.Map.Entry;
-import java.util.concurrent.ConcurrentHashMap;
-import java.util.concurrent.ConcurrentMap;
-import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
-import org.opendaylight.controller.cluster.access.concepts.LocalHistoryIdentifier;
-import org.opendaylight.controller.cluster.access.concepts.TransactionIdentifier;
-import org.opendaylight.controller.cluster.datastore.messages.CloseTransactionChain;
-import org.opendaylight.controller.cluster.datastore.messages.PrimaryShardInfo;
-import org.opendaylight.mdsal.dom.api.DOMTransactionChainClosedException;
-import org.opendaylight.mdsal.dom.spi.store.DOMStoreReadTransaction;
-import org.opendaylight.mdsal.dom.spi.store.DOMStoreReadWriteTransaction;
-import org.opendaylight.mdsal.dom.spi.store.DOMStoreTransactionChain;
-import org.opendaylight.mdsal.dom.spi.store.DOMStoreWriteTransaction;
-import org.opendaylight.yangtools.yang.data.tree.api.ReadOnlyDataTree;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import scala.concurrent.Future;
-import scala.concurrent.Promise;
-
-/**
- * A chain of {@link TransactionProxy}s. It allows a single open transaction to be open
- * at a time. For remote transactions, it also tracks the outstanding readiness requests
- * towards the shard and unblocks operations only after all have completed.
- */
-final class TransactionChainProxy extends AbstractTransactionContextFactory<LocalTransactionChain>
- implements DOMStoreTransactionChain {
- private abstract static class State {
- /**
- * Check if it is okay to allocate a new transaction.
- * @throws IllegalStateException if a transaction may not be allocated.
- */
- abstract void checkReady();
-
- /**
- * Return the future which needs to be waited for before shard information
- * is returned (which unblocks remote transactions).
- * @return Future to wait for, or null of no wait is necessary
- */
- abstract Future<?> previousFuture();
- }
-
- private abstract static class Pending extends State {
- private final TransactionIdentifier transaction;
- private final Future<?> previousFuture;
-
- Pending(final TransactionIdentifier transaction, final Future<?> previousFuture) {
- this.previousFuture = previousFuture;
- this.transaction = requireNonNull(transaction);
- }
-
- @Override
- final Future<?> previousFuture() {
- return previousFuture;
- }
-
- final TransactionIdentifier getIdentifier() {
- return transaction;
- }
- }
-
- private static final class Allocated extends Pending {
- Allocated(final TransactionIdentifier transaction, final Future<?> previousFuture) {
- super(transaction, previousFuture);
- }
-
- @Override
- void checkReady() {
- throw new IllegalStateException(String.format("Previous transaction %s is not ready yet", getIdentifier()));
- }
- }
-
- private static final class Submitted extends Pending {
- Submitted(final TransactionIdentifier transaction, final Future<?> previousFuture) {
- super(transaction, previousFuture);
- }
-
- @Override
- void checkReady() {
- // Okay to allocate
- }
- }
-
- private abstract static class DefaultState extends State {
- @Override
- final Future<?> previousFuture() {
- return null;
- }
- }
-
- private static final State IDLE_STATE = new DefaultState() {
- @Override
- void checkReady() {
- // Okay to allocate
- }
- };
-
- private static final State CLOSED_STATE = new DefaultState() {
- @Override
- void checkReady() {
- throw new DOMTransactionChainClosedException("Transaction chain has been closed");
- }
- };
-
- private static final Logger LOG = LoggerFactory.getLogger(TransactionChainProxy.class);
- private static final AtomicReferenceFieldUpdater<TransactionChainProxy, State> STATE_UPDATER =
- AtomicReferenceFieldUpdater.newUpdater(TransactionChainProxy.class, State.class, "currentState");
-
- private final TransactionContextFactory parent;
- private volatile State currentState = IDLE_STATE;
-
- /**
- * This map holds Promise instances for each read-only tx. It is used to maintain ordering of tx creates
- * wrt to read-only tx's between this class and a LocalTransactionChain since they're bridged by
- * asynchronous futures. Otherwise, in the following scenario, eg:
- * <p/>
- * 1) Create write tx1 on chain
- * 2) do write and submit
- * 3) Create read-only tx2 on chain and issue read
- * 4) Create write tx3 on chain, do write but do not submit
- * <p/>
- * if the sequence/timing is right, tx3 may create its local tx on the LocalTransactionChain before tx2,
- * which results in tx2 failing b/c tx3 isn't ready yet. So maintaining ordering prevents this issue
- * (see Bug 4774).
- * <p/>
- * A Promise is added via newReadOnlyTransaction. When the parent class completes the primary shard
- * lookup and creates the TransactionContext (either success or failure), onTransactionContextCreated is
- * called which completes the Promise. A write tx that is created prior to completion will wait on the
- * Promise's Future via findPrimaryShard.
- */
- private final ConcurrentMap<TransactionIdentifier, Promise<Object>> priorReadOnlyTxPromises =
- new ConcurrentHashMap<>();
-
- TransactionChainProxy(final TransactionContextFactory parent, final LocalHistoryIdentifier historyId) {
- super(parent.getActorUtils(), historyId);
- this.parent = parent;
- }
-
- @Override
- public DOMStoreReadTransaction newReadOnlyTransaction() {
- currentState.checkReady();
- TransactionProxy transactionProxy = new TransactionProxy(this, TransactionType.READ_ONLY);
- priorReadOnlyTxPromises.put(transactionProxy.getIdentifier(), Futures.<Object>promise());
- return transactionProxy;
- }
-
- @Override
- public DOMStoreReadWriteTransaction newReadWriteTransaction() {
- getActorUtils().acquireTxCreationPermit();
- return allocateWriteTransaction(TransactionType.READ_WRITE);
- }
-
- @Override
- public DOMStoreWriteTransaction newWriteOnlyTransaction() {
- getActorUtils().acquireTxCreationPermit();
- return allocateWriteTransaction(TransactionType.WRITE_ONLY);
- }
-
- @Override
- public void close() {
- currentState = CLOSED_STATE;
-
- // Send a close transaction chain request to each and every shard
-
- getActorUtils().broadcast(version -> new CloseTransactionChain(getHistoryId(), version).toSerializable(),
- CloseTransactionChain.class);
- }
-
- private TransactionProxy allocateWriteTransaction(final TransactionType type) {
- State localState = currentState;
- localState.checkReady();
-
- final TransactionProxy ret = new TransactionProxy(this, type);
- currentState = new Allocated(ret.getIdentifier(), localState.previousFuture());
- return ret;
- }
-
- @Override
- protected LocalTransactionChain factoryForShard(final String shardName, final ActorSelection shardLeader,
- final ReadOnlyDataTree dataTree) {
- final LocalTransactionChain ret = new LocalTransactionChain(this, shardLeader, dataTree);
- LOG.debug("Allocated transaction chain {} for shard {} leader {}", ret, shardName, shardLeader);
- return ret;
- }
-
- /**
- * This method is overridden to ensure the previous Tx's ready operations complete
- * before we initiate the next Tx in the chain to avoid creation failures if the
- * previous Tx's ready operations haven't completed yet.
- */
- @SuppressWarnings({ "unchecked", "rawtypes" })
- @Override
- protected Future<PrimaryShardInfo> findPrimaryShard(final String shardName, final TransactionIdentifier txId) {
- // Read current state atomically
- final State localState = currentState;
-
- // There are no outstanding futures, shortcut
- Future<?> previous = localState.previousFuture();
- if (previous == null) {
- return combineFutureWithPossiblePriorReadOnlyTxFutures(parent.findPrimaryShard(shardName, txId), txId);
- }
-
- final String previousTransactionId;
-
- if (localState instanceof Pending) {
- previousTransactionId = ((Pending) localState).getIdentifier().toString();
- LOG.debug("Tx: {} - waiting for ready futures with pending Tx {}", txId, previousTransactionId);
- } else {
- previousTransactionId = "";
- LOG.debug("Waiting for ready futures on chain {}", getHistoryId());
- }
-
- previous = combineFutureWithPossiblePriorReadOnlyTxFutures(previous, txId);
-
- // Add a callback for completion of the combined Futures.
- final Promise<PrimaryShardInfo> returnPromise = Futures.promise();
-
- final OnComplete onComplete = new OnComplete() {
- @Override
- public void onComplete(final Throwable failure, final Object notUsed) {
- if (failure != null) {
- // A Ready Future failed so fail the returned Promise.
- LOG.error("Tx: {} - ready future failed for previous Tx {}", txId, previousTransactionId);
- returnPromise.failure(failure);
- } else {
- LOG.debug("Tx: {} - previous Tx {} readied - proceeding to FindPrimaryShard",
- txId, previousTransactionId);
-
- // Send the FindPrimaryShard message and use the resulting Future to complete the
- // returned Promise.
- returnPromise.completeWith(parent.findPrimaryShard(shardName, txId));
- }
- }
- };
-
- previous.onComplete(onComplete, getActorUtils().getClientDispatcher());
- return returnPromise.future();
- }
-
- private <T> Future<T> combineFutureWithPossiblePriorReadOnlyTxFutures(final Future<T> future,
- final TransactionIdentifier txId) {
- return priorReadOnlyTxPromises.isEmpty() || priorReadOnlyTxPromises.containsKey(txId) ? future
- // Tough luck, we need do some work
- : combineWithPriorReadOnlyTxFutures(future, txId);
- }
-
- // Split out of the common path
- private <T> Future<T> combineWithPriorReadOnlyTxFutures(final Future<T> future, final TransactionIdentifier txId) {
- // Take a stable snapshot, and check if we raced
- final List<Entry<TransactionIdentifier, Promise<Object>>> priorReadOnlyTxPromiseEntries =
- new ArrayList<>(priorReadOnlyTxPromises.entrySet());
- if (priorReadOnlyTxPromiseEntries.isEmpty()) {
- return future;
- }
-
- final List<Future<Object>> priorReadOnlyTxFutures = new ArrayList<>(priorReadOnlyTxPromiseEntries.size());
- for (Entry<TransactionIdentifier, Promise<Object>> entry: priorReadOnlyTxPromiseEntries) {
- LOG.debug("Tx: {} - waiting on future for prior read-only Tx {}", txId, entry.getKey());
- priorReadOnlyTxFutures.add(entry.getValue().future());
- }
-
- final Future<Iterable<Object>> combinedFutures = Futures.sequence(priorReadOnlyTxFutures,
- getActorUtils().getClientDispatcher());
-
- final Promise<T> returnPromise = Futures.promise();
- final OnComplete<Iterable<Object>> onComplete = new OnComplete<>() {
- @Override
- public void onComplete(final Throwable failure, final Iterable<Object> notUsed) {
- LOG.debug("Tx: {} - prior read-only Tx futures complete", txId);
-
- // Complete the returned Promise with the original Future.
- returnPromise.completeWith(future);
- }
- };
-
- combinedFutures.onComplete(onComplete, getActorUtils().getClientDispatcher());
- return returnPromise.future();
- }
-
- @Override
- protected <T> void onTransactionReady(final TransactionIdentifier transaction,
- final Collection<Future<T>> cohortFutures) {
- final State localState = currentState;
- checkState(localState instanceof Allocated, "Readying transaction %s while state is %s", transaction,
- localState);
- final TransactionIdentifier currentTx = ((Allocated)localState).getIdentifier();
- checkState(transaction.equals(currentTx), "Readying transaction %s while %s is allocated", transaction,
- currentTx);
-
- // Transaction ready and we are not waiting for futures -- go to idle
- if (cohortFutures.isEmpty()) {
- currentState = IDLE_STATE;
- return;
- }
-
- // Combine the ready Futures into 1
- final Future<Iterable<T>> combined = Futures.sequence(cohortFutures, getActorUtils().getClientDispatcher());
-
- // Record the we have outstanding futures
- final State newState = new Submitted(transaction, combined);
- currentState = newState;
-
- // Attach a completion reset, but only if we do not allocate a transaction
- // in-between
- combined.onComplete(new OnComplete<Iterable<T>>() {
- @Override
- public void onComplete(final Throwable arg0, final Iterable<T> arg1) {
- STATE_UPDATER.compareAndSet(TransactionChainProxy.this, newState, IDLE_STATE);
- }
- }, getActorUtils().getClientDispatcher());
- }
-
- @Override
- protected void onTransactionContextCreated(final TransactionIdentifier transactionId) {
- Promise<Object> promise = priorReadOnlyTxPromises.remove(transactionId);
- if (promise != null) {
- promise.success(null);
- }
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.cluster.datastore;
-
-import akka.actor.ActorSelection;
-import com.google.common.util.concurrent.SettableFuture;
-import java.util.Optional;
-import java.util.SortedSet;
-import org.opendaylight.controller.cluster.access.concepts.TransactionIdentifier;
-import org.opendaylight.controller.cluster.datastore.messages.AbstractRead;
-import org.opendaylight.yangtools.concepts.AbstractSimpleIdentifiable;
-import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
-import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import scala.concurrent.Future;
-
-abstract class TransactionContext extends AbstractSimpleIdentifiable<TransactionIdentifier> {
- private static final Logger LOG = LoggerFactory.getLogger(TransactionContext.class);
-
- private final short transactionVersion;
-
- private long modificationCount = 0;
- private boolean handOffComplete;
-
- TransactionContext(final TransactionIdentifier transactionIdentifier) {
- this(transactionIdentifier, DataStoreVersions.CURRENT_VERSION);
- }
-
- TransactionContext(final TransactionIdentifier transactionIdentifier, final short transactionVersion) {
- super(transactionIdentifier);
- this.transactionVersion = transactionVersion;
- }
-
- final short getTransactionVersion() {
- return transactionVersion;
- }
-
- final void incrementModificationCount() {
- modificationCount++;
- }
-
- final void logModificationCount() {
- LOG.debug("Total modifications on Tx {} = [ {} ]", getIdentifier(), modificationCount);
- }
-
- /**
- * Invoked by {@link AbstractTransactionContextWrapper} when it has finished handing
- * off operations to this context. From this point on, the context is responsible
- * for throttling operations.
- *
- * <p>
- * Implementations can rely on the wrapper calling this operation in a synchronized
- * block, so they do not need to ensure visibility of this state transition themselves.
- */
- final void operationHandOffComplete() {
- handOffComplete = true;
- }
-
- final boolean isOperationHandOffComplete() {
- return handOffComplete;
- }
-
- /**
- * A TransactionContext that uses operation limiting should return true else false.
- *
- * @return true if operation limiting is used, false otherwise
- */
- boolean usesOperationLimiting() {
- return false;
- }
-
- abstract void executeDelete(YangInstanceIdentifier path, Boolean havePermit);
-
- abstract void executeMerge(YangInstanceIdentifier path, NormalizedNode data, Boolean havePermit);
-
- abstract void executeWrite(YangInstanceIdentifier path, NormalizedNode data, Boolean havePermit);
-
- abstract <T> void executeRead(AbstractRead<T> readCmd, SettableFuture<T> proxyFuture, Boolean havePermit);
-
- abstract Future<ActorSelection> readyTransaction(Boolean havePermit,
- Optional<SortedSet<String>> participatingShardNames);
-
- abstract Future<Object> directCommit(Boolean havePermit);
-
- abstract void closeTransaction();
-}
+++ /dev/null
-/*
- * Copyright (c) 2015 Brocade Communications Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.cluster.datastore;
-
-import com.google.common.base.FinalizablePhantomReference;
-import com.google.common.base.FinalizableReferenceQueue;
-import java.util.Map;
-import java.util.concurrent.ConcurrentHashMap;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * A PhantomReference that closes remote transactions for a TransactionContext when it's
- * garbage collected. This is used for read-only transactions as they're not explicitly closed
- * by clients. So the only way to detect that a transaction is no longer in use and it's safe
- * to clean up is when it's garbage collected. It's inexact as to when an instance will be GC'ed
- * but TransactionProxy instances should generally be short-lived enough to avoid being moved
- * to the old generation space and thus should be cleaned up in a timely manner as the GC
- * runs on the young generation (eden, swap1...) space much more frequently.
- */
-final class TransactionContextCleanup extends FinalizablePhantomReference<TransactionProxy> {
- private static final Logger LOG = LoggerFactory.getLogger(TransactionContextCleanup.class);
- /**
- * Used to enqueue the PhantomReferences for read-only TransactionProxy instances. The
- * FinalizableReferenceQueue is safe to use statically in an OSGi environment as it uses some
- * trickery to clean up its internal thread when the bundle is unloaded.
- */
- private static final FinalizableReferenceQueue QUEUE = new FinalizableReferenceQueue();
-
- /**
- * This stores the TransactionProxyCleanupPhantomReference instances statically, This is
- * necessary because PhantomReferences need a hard reference so they're not garbage collected.
- * Once finalized, the TransactionProxyCleanupPhantomReference removes itself from this map
- * and thus becomes eligible for garbage collection.
- */
- private static final Map<TransactionContext, TransactionContextCleanup> CACHE = new ConcurrentHashMap<>();
-
- private final TransactionContext cleanup;
-
- private TransactionContextCleanup(final TransactionProxy referent, final TransactionContext cleanup) {
- super(referent, QUEUE);
- this.cleanup = cleanup;
- }
-
- static void track(final TransactionProxy referent, final TransactionContext cleanup) {
- final TransactionContextCleanup ret = new TransactionContextCleanup(referent, cleanup);
- CACHE.put(cleanup, ret);
- }
-
- @Override
- public void finalizeReferent() {
- LOG.trace("Cleaning up {} Tx actors", cleanup);
-
- if (CACHE.remove(cleanup) != null) {
- cleanup.closeTransaction();
- }
- }
-
- static void untrack(final TransactionContext cleanup) {
- CACHE.remove(cleanup);
- }
-}
\ No newline at end of file
+++ /dev/null
-/*
- * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.cluster.datastore;
-
-import akka.actor.ActorSelection;
-import java.util.Collection;
-import java.util.concurrent.atomic.AtomicLong;
-import org.opendaylight.controller.cluster.access.concepts.ClientIdentifier;
-import org.opendaylight.controller.cluster.access.concepts.LocalHistoryIdentifier;
-import org.opendaylight.controller.cluster.access.concepts.TransactionIdentifier;
-import org.opendaylight.controller.cluster.datastore.messages.PrimaryShardInfo;
-import org.opendaylight.controller.cluster.datastore.utils.ActorUtils;
-import org.opendaylight.mdsal.dom.spi.store.DOMStoreTransactionChain;
-import org.opendaylight.yangtools.yang.data.tree.api.ReadOnlyDataTree;
-import scala.concurrent.Future;
-
-/**
- * An {@link AbstractTransactionContextFactory} which produces TransactionContext instances for single
- * transactions (ie not chained).
- */
-final class TransactionContextFactory extends AbstractTransactionContextFactory<LocalTransactionFactoryImpl> {
- private final AtomicLong nextHistory = new AtomicLong(1);
-
- TransactionContextFactory(final ActorUtils actorUtils, final ClientIdentifier clientId) {
- super(actorUtils, new LocalHistoryIdentifier(clientId, 0));
- }
-
- @Override
- public void close() {
- }
-
- @Override
- protected LocalTransactionFactoryImpl factoryForShard(final String shardName, final ActorSelection shardLeader,
- final ReadOnlyDataTree dataTree) {
- return new LocalTransactionFactoryImpl(getActorUtils(), shardLeader, dataTree);
- }
-
- @Override
- protected Future<PrimaryShardInfo> findPrimaryShard(final String shardName, final TransactionIdentifier txId) {
- return getActorUtils().findPrimaryShardAsync(shardName);
- }
-
- @Override
- protected <T> void onTransactionReady(final TransactionIdentifier transaction,
- final Collection<Future<T>> cohortFutures) {
- // Transactions are disconnected, this is a no-op
- }
-
- DOMStoreTransactionChain createTransactionChain() {
- return new TransactionChainProxy(this, new LocalHistoryIdentifier(getHistoryId().getClientId(),
- nextHistory.getAndIncrement()));
- }
-
- @Override
- protected void onTransactionContextCreated(final TransactionIdentifier transactionId) {
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2020 PANTHEON.tech, s.r.o. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.cluster.datastore;
-
-import static java.util.Objects.requireNonNull;
-
-import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
-import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
-
-/**
- * A TransactionOperation to apply a specific modification. Subclasses provide type capture of required data, so that
- * we instantiate AbstractModification subclasses for the bare minimum time required.
- */
-abstract class TransactionModificationOperation extends TransactionOperation {
- private abstract static class AbstractDataOperation extends TransactionModificationOperation {
- private final NormalizedNode data;
-
- AbstractDataOperation(final YangInstanceIdentifier path, final NormalizedNode data) {
- super(path);
- this.data = requireNonNull(data);
- }
-
- final NormalizedNode data() {
- return data;
- }
- }
-
- static final class DeleteOperation extends TransactionModificationOperation {
- DeleteOperation(final YangInstanceIdentifier path) {
- super(path);
- }
-
- @Override
- protected void invoke(final TransactionContext transactionContext, final Boolean havePermit) {
- transactionContext.executeDelete(path(), havePermit);
- }
- }
-
- static final class MergeOperation extends AbstractDataOperation {
- MergeOperation(final YangInstanceIdentifier path, final NormalizedNode data) {
- super(path, data);
- }
-
- @Override
- protected void invoke(final TransactionContext transactionContext, final Boolean havePermit) {
- transactionContext.executeMerge(path(), data(), havePermit);
- }
- }
-
- static final class WriteOperation extends AbstractDataOperation {
- WriteOperation(final YangInstanceIdentifier path, final NormalizedNode data) {
- super(path, data);
- }
-
- @Override
- protected void invoke(final TransactionContext transactionContext, final Boolean havePermit) {
- transactionContext.executeWrite(path(), data(), havePermit);
- }
- }
-
- private final YangInstanceIdentifier path;
-
- TransactionModificationOperation(final YangInstanceIdentifier path) {
- this.path = requireNonNull(path);
- }
-
- final YangInstanceIdentifier path() {
- return path;
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.cluster.datastore;
-
-import org.eclipse.jdt.annotation.Nullable;
-
-/**
- * Abstract superclass for transaction operations which should be executed
- * on a {@link TransactionContext} at a later point in time.
- */
-abstract class TransactionOperation {
- /**
- * Execute the delayed operation.
- *
- * @param transactionContext the TransactionContext
- * @param havePermit Boolean indicator if this operation has tried and acquired a permit, null if there was no
- * attempt to acquire a permit.
- */
- protected abstract void invoke(TransactionContext transactionContext, @Nullable Boolean havePermit);
-}
+++ /dev/null
-/*
- * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.cluster.datastore;
-
-import static com.google.common.base.Preconditions.checkState;
-import static java.util.Objects.requireNonNull;
-
-import akka.actor.ActorSelection;
-import com.google.common.annotations.VisibleForTesting;
-import com.google.common.collect.Iterables;
-import com.google.common.util.concurrent.FluentFuture;
-import com.google.common.util.concurrent.SettableFuture;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Map;
-import java.util.Map.Entry;
-import java.util.Optional;
-import java.util.SortedSet;
-import java.util.TreeMap;
-import java.util.TreeSet;
-import org.opendaylight.controller.cluster.access.concepts.TransactionIdentifier;
-import org.opendaylight.controller.cluster.datastore.TransactionModificationOperation.DeleteOperation;
-import org.opendaylight.controller.cluster.datastore.TransactionModificationOperation.MergeOperation;
-import org.opendaylight.controller.cluster.datastore.TransactionModificationOperation.WriteOperation;
-import org.opendaylight.controller.cluster.datastore.messages.AbstractRead;
-import org.opendaylight.controller.cluster.datastore.messages.DataExists;
-import org.opendaylight.controller.cluster.datastore.messages.ReadData;
-import org.opendaylight.controller.cluster.datastore.utils.ActorUtils;
-import org.opendaylight.controller.cluster.datastore.utils.RootScatterGather;
-import org.opendaylight.mdsal.dom.spi.store.AbstractDOMStoreTransaction;
-import org.opendaylight.mdsal.dom.spi.store.DOMStoreReadWriteTransaction;
-import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
-import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
-import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
-import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import scala.concurrent.Future;
-import scala.concurrent.Promise;
-
-/**
- * A transaction potentially spanning multiple backend shards.
- */
-public class TransactionProxy extends AbstractDOMStoreTransaction<TransactionIdentifier>
- implements DOMStoreReadWriteTransaction {
- private enum TransactionState {
- OPEN,
- READY,
- CLOSED,
- }
-
- private static final Logger LOG = LoggerFactory.getLogger(TransactionProxy.class);
- private static final DeleteOperation ROOT_DELETE_OPERATION = new DeleteOperation(YangInstanceIdentifier.empty());
-
- private final Map<String, AbstractTransactionContextWrapper> txContextWrappers = new TreeMap<>();
- private final AbstractTransactionContextFactory<?> txContextFactory;
- private final TransactionType type;
- private TransactionState state = TransactionState.OPEN;
-
- @VisibleForTesting
- public TransactionProxy(final AbstractTransactionContextFactory<?> txContextFactory, final TransactionType type) {
- super(txContextFactory.nextIdentifier(), txContextFactory.getActorUtils().getDatastoreContext()
- .isTransactionDebugContextEnabled());
- this.txContextFactory = txContextFactory;
- this.type = requireNonNull(type);
-
- LOG.debug("New {} Tx - {}", type, getIdentifier());
- }
-
- @Override
- public FluentFuture<Boolean> exists(final YangInstanceIdentifier path) {
- return executeRead(shardNameFromIdentifier(path), new DataExists(path, DataStoreVersions.CURRENT_VERSION));
- }
-
- private <T> FluentFuture<T> executeRead(final String shardName, final AbstractRead<T> readCmd) {
- checkState(type != TransactionType.WRITE_ONLY, "Reads from write-only transactions are not allowed");
-
- LOG.trace("Tx {} {} {}", getIdentifier(), readCmd.getClass().getSimpleName(), readCmd.getPath());
-
- final SettableFuture<T> proxyFuture = SettableFuture.create();
- AbstractTransactionContextWrapper contextWrapper = wrapperFromShardName(shardName);
- contextWrapper.maybeExecuteTransactionOperation(new TransactionOperation() {
- @Override
- public void invoke(final TransactionContext transactionContext, final Boolean havePermit) {
- transactionContext.executeRead(readCmd, proxyFuture, havePermit);
- }
- });
-
- return FluentFuture.from(proxyFuture);
- }
-
- @Override
- public FluentFuture<Optional<NormalizedNode>> read(final YangInstanceIdentifier path) {
- checkState(type != TransactionType.WRITE_ONLY, "Reads from write-only transactions are not allowed");
- requireNonNull(path, "path should not be null");
-
- LOG.trace("Tx {} read {}", getIdentifier(), path);
- return path.isEmpty() ? readAllData() : singleShardRead(shardNameFromIdentifier(path), path);
- }
-
- private FluentFuture<Optional<NormalizedNode>> singleShardRead(final String shardName,
- final YangInstanceIdentifier path) {
- return executeRead(shardName, new ReadData(path, DataStoreVersions.CURRENT_VERSION));
- }
-
- private FluentFuture<Optional<NormalizedNode>> readAllData() {
- final var actorUtils = getActorUtils();
- return RootScatterGather.gather(actorUtils, actorUtils.getConfiguration().getAllShardNames().stream()
- .map(shardName -> singleShardRead(shardName, YangInstanceIdentifier.empty())));
- }
-
- @Override
- public void delete(final YangInstanceIdentifier path) {
- checkModificationState("delete", path);
-
- if (path.isEmpty()) {
- deleteAllData();
- } else {
- executeModification(new DeleteOperation(path));
- }
- }
-
- private void deleteAllData() {
- for (String shardName : getActorUtils().getConfiguration().getAllShardNames()) {
- wrapperFromShardName(shardName).maybeExecuteTransactionOperation(ROOT_DELETE_OPERATION);
- }
- }
-
- @Override
- public void merge(final YangInstanceIdentifier path, final NormalizedNode data) {
- checkModificationState("merge", path);
-
- if (path.isEmpty()) {
- mergeAllData(RootScatterGather.castRootNode(data));
- } else {
- executeModification(new MergeOperation(path, data));
- }
- }
-
- private void mergeAllData(final ContainerNode rootData) {
- if (!rootData.isEmpty()) {
- RootScatterGather.scatterTouched(rootData, this::wrapperFromRootChild).forEach(
- scattered -> scattered.shard().maybeExecuteTransactionOperation(
- new MergeOperation(YangInstanceIdentifier.empty(), scattered.container())));
- }
- }
-
- @Override
- public void write(final YangInstanceIdentifier path, final NormalizedNode data) {
- checkModificationState("write", path);
-
- if (path.isEmpty()) {
- writeAllData(RootScatterGather.castRootNode(data));
- } else {
- executeModification(new WriteOperation(path, data));
- }
- }
-
- private void writeAllData(final ContainerNode rootData) {
- RootScatterGather.scatterAll(rootData, this::wrapperFromRootChild,
- getActorUtils().getConfiguration().getAllShardNames().stream().map(this::wrapperFromShardName)).forEach(
- scattered -> scattered.shard().maybeExecuteTransactionOperation(
- new WriteOperation(YangInstanceIdentifier.empty(), scattered.container())));
- }
-
- private void executeModification(final TransactionModificationOperation operation) {
- wrapperFromShardName(shardNameFromIdentifier(operation.path())).maybeExecuteTransactionOperation(operation);
- }
-
- private void checkModificationState(final String opName, final YangInstanceIdentifier path) {
- checkState(type != TransactionType.READ_ONLY, "Modification operation on read-only transaction is not allowed");
- checkState(state == TransactionState.OPEN, "Transaction is sealed - further modifications are not allowed");
- LOG.trace("Tx {} {} {}", getIdentifier(), opName, path);
- }
-
- private boolean seal(final TransactionState newState) {
- if (state == TransactionState.OPEN) {
- state = newState;
- return true;
- }
- return false;
- }
-
- @Override
- public final void close() {
- if (!seal(TransactionState.CLOSED)) {
- checkState(state == TransactionState.CLOSED, "Transaction %s is ready, it cannot be closed",
- getIdentifier());
- // Idempotent no-op as per AutoCloseable recommendation
- return;
- }
-
- for (AbstractTransactionContextWrapper contextWrapper : txContextWrappers.values()) {
- contextWrapper.maybeExecuteTransactionOperation(new TransactionOperation() {
- @Override
- public void invoke(final TransactionContext transactionContext, final Boolean havePermit) {
- transactionContext.closeTransaction();
- }
- });
- }
-
-
- txContextWrappers.clear();
- }
-
- @Override
- public final AbstractThreePhaseCommitCohort<?> ready() {
- checkState(type != TransactionType.READ_ONLY, "Read-only transactions cannot be readied");
-
- final boolean success = seal(TransactionState.READY);
- checkState(success, "Transaction %s is %s, it cannot be readied", getIdentifier(), state);
-
- LOG.debug("Tx {} Readying {} components for commit", getIdentifier(), txContextWrappers.size());
-
- final AbstractThreePhaseCommitCohort<?> ret;
- switch (txContextWrappers.size()) {
- case 0:
- ret = NoOpDOMStoreThreePhaseCommitCohort.INSTANCE;
- break;
- case 1:
- final Entry<String, AbstractTransactionContextWrapper> e = Iterables.getOnlyElement(
- txContextWrappers.entrySet());
- ret = createSingleCommitCohort(e.getKey(), e.getValue());
- break;
- default:
- ret = createMultiCommitCohort();
- }
-
- txContextFactory.onTransactionReady(getIdentifier(), ret.getCohortFutures());
-
- final Throwable debugContext = getDebugContext();
- return debugContext == null ? ret : new DebugThreePhaseCommitCohort(getIdentifier(), ret, debugContext);
- }
-
- @SuppressWarnings({ "rawtypes", "unchecked" })
- private AbstractThreePhaseCommitCohort<?> createSingleCommitCohort(final String shardName,
- final AbstractTransactionContextWrapper contextWrapper) {
-
- LOG.debug("Tx {} Readying transaction for shard {}", getIdentifier(), shardName);
-
- final OperationCallback.Reference operationCallbackRef =
- new OperationCallback.Reference(OperationCallback.NO_OP_CALLBACK);
-
- final TransactionContext transactionContext = contextWrapper.getTransactionContext();
- final Future future;
- if (transactionContext == null) {
- final Promise promise = akka.dispatch.Futures.promise();
- contextWrapper.maybeExecuteTransactionOperation(new TransactionOperation() {
- @Override
- public void invoke(final TransactionContext newTransactionContext, final Boolean havePermit) {
- promise.completeWith(getDirectCommitFuture(newTransactionContext, operationCallbackRef,
- havePermit));
- }
- });
- future = promise.future();
- } else {
- // avoid the creation of a promise and a TransactionOperation
- future = getDirectCommitFuture(transactionContext, operationCallbackRef, null);
- }
-
- return new SingleCommitCohortProxy(txContextFactory.getActorUtils(), future, getIdentifier(),
- operationCallbackRef);
- }
-
- private Future<?> getDirectCommitFuture(final TransactionContext transactionContext,
- final OperationCallback.Reference operationCallbackRef, final Boolean havePermit) {
- TransactionRateLimitingCallback rateLimitingCallback = new TransactionRateLimitingCallback(
- txContextFactory.getActorUtils());
- operationCallbackRef.set(rateLimitingCallback);
- rateLimitingCallback.run();
- return transactionContext.directCommit(havePermit);
- }
-
- private AbstractThreePhaseCommitCohort<ActorSelection> createMultiCommitCohort() {
-
- final List<ThreePhaseCommitCohortProxy.CohortInfo> cohorts = new ArrayList<>(txContextWrappers.size());
- final Optional<SortedSet<String>> shardNames = Optional.of(new TreeSet<>(txContextWrappers.keySet()));
- for (Entry<String, AbstractTransactionContextWrapper> e : txContextWrappers.entrySet()) {
- LOG.debug("Tx {} Readying transaction for shard {}", getIdentifier(), e.getKey());
-
- final AbstractTransactionContextWrapper wrapper = e.getValue();
-
- // The remote tx version is obtained the via TransactionContext which may not be available yet so
- // we pass a Supplier to dynamically obtain it. Once the ready Future is resolved the
- // TransactionContext is available.
- cohorts.add(new ThreePhaseCommitCohortProxy.CohortInfo(wrapper.readyTransaction(shardNames),
- () -> wrapper.getTransactionContext().getTransactionVersion()));
- }
-
- return new ThreePhaseCommitCohortProxy(txContextFactory.getActorUtils(), cohorts, getIdentifier());
- }
-
- private String shardNameFromIdentifier(final YangInstanceIdentifier path) {
- return getActorUtils().getShardStrategyFactory().getStrategy(path).findShard(path);
- }
-
- private AbstractTransactionContextWrapper wrapperFromRootChild(final PathArgument childId) {
- return wrapperFromShardName(shardNameFromIdentifier(YangInstanceIdentifier.create(childId)));
- }
-
- private AbstractTransactionContextWrapper wrapperFromShardName(final String shardName) {
- final AbstractTransactionContextWrapper existing = txContextWrappers.get(shardName);
- if (existing != null) {
- return existing;
- }
-
- final AbstractTransactionContextWrapper fresh = txContextFactory.newTransactionContextWrapper(this, shardName);
- txContextWrappers.put(shardName, fresh);
- return fresh;
- }
-
- TransactionType getType() {
- return type;
- }
-
- boolean isReady() {
- return state != TransactionState.OPEN;
- }
-
- final ActorUtils getActorUtils() {
- return txContextFactory.getActorUtils();
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.cluster.datastore;
-
-import static java.util.Objects.requireNonNull;
-
-import akka.actor.ActorSelection;
-import akka.dispatch.Mapper;
-import org.opendaylight.controller.cluster.access.concepts.TransactionIdentifier;
-import org.opendaylight.controller.cluster.datastore.messages.ReadyTransactionReply;
-import org.opendaylight.controller.cluster.datastore.utils.ActorUtils;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import scala.concurrent.Future;
-
-/**
- * A {@link Mapper} extracting the {@link ActorSelection} pointing to the actor which
- * is backing a particular transaction.
- *
- * <p>
- * This class is not for general consumption. It is public only to support the pre-lithium compatibility
- * package.
- * TODO: once we remove compatibility, make this class package-private and final.
- */
-public class TransactionReadyReplyMapper extends Mapper<Object, ActorSelection> {
- protected static final Mapper<Throwable, Throwable> SAME_FAILURE_TRANSFORMER = new Mapper<>() {
- @Override
- public Throwable apply(final Throwable failure) {
- return failure;
- }
- };
- private static final Logger LOG = LoggerFactory.getLogger(TransactionReadyReplyMapper.class);
- private final TransactionIdentifier identifier;
- private final ActorUtils actorUtils;
-
- protected TransactionReadyReplyMapper(final ActorUtils actorUtils, final TransactionIdentifier identifier) {
- this.actorUtils = requireNonNull(actorUtils);
- this.identifier = requireNonNull(identifier);
- }
-
- protected final ActorUtils getActorUtils() {
- return actorUtils;
- }
-
- protected String extractCohortPathFrom(final ReadyTransactionReply readyTxReply) {
- return readyTxReply.getCohortPath();
- }
-
- @Override
- public final ActorSelection checkedApply(final Object serializedReadyReply) {
- LOG.debug("Tx {} readyTransaction", identifier);
-
- // At this point the ready operation succeeded and we need to extract the cohort
- // actor path from the reply.
- if (ReadyTransactionReply.isSerializedType(serializedReadyReply)) {
- ReadyTransactionReply readyTxReply = ReadyTransactionReply.fromSerializable(serializedReadyReply);
- return actorUtils.actorSelection(extractCohortPathFrom(readyTxReply));
- }
-
- // Throwing an exception here will fail the Future.
- throw new IllegalArgumentException(String.format("%s: Invalid reply type %s",
- identifier, serializedReadyReply.getClass()));
- }
-
- static Future<ActorSelection> transform(final Future<Object> readyReplyFuture, final ActorUtils actorUtils,
- final TransactionIdentifier identifier) {
- return readyReplyFuture.transform(new TransactionReadyReplyMapper(actorUtils, identifier),
- SAME_FAILURE_TRANSFORMER, actorUtils.getClientDispatcher());
- }
-}
WRITE_ONLY,
READ_WRITE;
- // Cache all values
- private static final TransactionType[] VALUES = values();
-
public static TransactionType fromInt(final int type) {
- try {
- return VALUES[type];
- } catch (IndexOutOfBoundsException e) {
- throw new IllegalArgumentException("In TransactionType enum value " + type, e);
- }
+ return switch (type) {
+ case 0 -> READ_ONLY;
+ case 1 -> WRITE_ONLY;
+ case 2 -> READ_WRITE;
+ default -> throw new IllegalArgumentException("In TransactionType enum value " + type);
+ };
}
}
\ No newline at end of file
import akka.actor.Props;
import com.google.common.annotations.VisibleForTesting;
import java.util.concurrent.TimeUnit;
+import org.eclipse.jdt.annotation.NonNullByDefault;
import org.opendaylight.controller.cluster.common.actor.AbstractUntypedActor;
import org.opendaylight.controller.cluster.datastore.messages.CloseDataTreeNotificationListenerRegistration;
import org.opendaylight.controller.cluster.datastore.messages.CloseDataTreeNotificationListenerRegistrationReply;
-import org.opendaylight.yangtools.concepts.ListenerRegistration;
+import org.opendaylight.yangtools.concepts.Registration;
import scala.concurrent.duration.FiniteDuration;
/**
@VisibleForTesting
static long killDelay = TimeUnit.MILLISECONDS.convert(5, TimeUnit.SECONDS);
- private ListenerRegistration<?> registration;
- private Runnable onClose;
+ private SetRegistration registration = null;
+ private Cancellable killSchedule = null;
private boolean closed;
- private Cancellable killSchedule;
@Override
protected void handleReceive(final Object message) {
if (isValidSender(getSender())) {
getSender().tell(CloseDataTreeNotificationListenerRegistrationReply.getInstance(), getSelf());
}
- } else if (message instanceof SetRegistration) {
- registration = ((SetRegistration)message).registration;
- onClose = ((SetRegistration)message).onClose;
+ } else if (message instanceof SetRegistration setRegistration) {
+ registration = setRegistration;
if (closed) {
closeListenerRegistration();
}
private void closeListenerRegistration() {
closed = true;
- if (registration != null) {
- registration.close();
- onClose.run();
+
+ final var reg = registration;
+ if (reg != null) {
registration = null;
+ reg.registration.close();
+ reg.onClose.run();
if (killSchedule == null) {
killSchedule = getContext().system().scheduler().scheduleOnce(FiniteDuration.create(killDelay,
return Props.create(DataTreeNotificationListenerRegistrationActor.class);
}
- public static class SetRegistration {
- private final ListenerRegistration<?> registration;
- private final Runnable onClose;
-
- public SetRegistration(final ListenerRegistration<?> registration, final Runnable onClose) {
- this.registration = requireNonNull(registration);
- this.onClose = requireNonNull(onClose);
+ @NonNullByDefault
+ public record SetRegistration(Registration registration, Runnable onClose) {
+ public SetRegistration {
+ requireNonNull(registration);
+ requireNonNull(onClose);
}
}
}
final Path filePath = snapshotDir.resolve(exportSnapshot.id + "-snapshot.json");
LOG.debug("Creating JSON file : {}", filePath);
- final NormalizedNode root = exportSnapshot.dataTreeCandidate.getRootNode().getDataAfter().get();
+ final NormalizedNode root = exportSnapshot.dataTreeCandidate.getRootNode().getDataAfter();
checkState(root instanceof NormalizedNodeContainer, "Unexpected root %s", root);
writeSnapshot(filePath, (NormalizedNodeContainer<?>) root);
try (JsonWriter jsonWriter = new JsonWriter(Files.newBufferedWriter(path))) {
jsonWriter.beginObject();
- try (NormalizedNodeWriter nnWriter = NormalizedNodeWriter.forStreamWriter(
- JSONNormalizedNodeStreamWriter.createNestedWriter(
+ try (var nnWriter = NormalizedNodeWriter.forStreamWriter(JSONNormalizedNodeStreamWriter.createNestedWriter(
JSONCodecFactorySupplier.RFC7951.getShared(schemaContext),
SchemaInferenceStack.of(schemaContext).toInference(), null, jsonWriter),
true)) {
try (JsonWriter jsonWriter = new JsonWriter(Files.newBufferedWriter(path))) {
jsonWriter.beginObject().name("Entries");
jsonWriter.beginArray();
- for (ReplicatedLogEntry entry : entries) {
+ for (var entry : entries) {
final var data = entry.getData();
- if (data instanceof CommitTransactionPayload) {
- final CommitTransactionPayload payload = (CommitTransactionPayload) entry.getData();
- final DataTreeCandidate candidate = payload.getCandidate().getValue().getCandidate();
+ if (data instanceof CommitTransactionPayload payload) {
+ final var candidate = payload.getCandidate().candidate();
writeNode(jsonWriter, candidate);
} else {
jsonWriter.beginObject().name("Payload").value(data.toString()).endObject();
}
private static void writeNode(final JsonWriter writer, final DataTreeCandidate candidate) throws IOException {
- writer.beginObject();
- writer.name("Entry");
- writer.beginArray();
+ writer.beginObject().name("Entry").beginArray();
doWriteNode(writer, candidate.getRootPath(), candidate.getRootNode());
- writer.endArray();
- writer.endObject();
+ writer.endArray().endObject();
}
private static void doWriteNode(final JsonWriter writer, final YangInstanceIdentifier path,
final DataTreeCandidateNode node) throws IOException {
- switch (node.getModificationType()) {
+ switch (node.modificationType()) {
case APPEARED:
case DISAPPEARED:
case SUBTREE_MODIFIED:
- NodeIterator iterator = new NodeIterator(null, path, node.getChildNodes().iterator());
+ NodeIterator iterator = new NodeIterator(null, path, node.childNodes().iterator());
do {
iterator = iterator.next(writer);
} while (iterator != null);
private static void outputNodeInfo(final JsonWriter writer, final YangInstanceIdentifier path,
final DataTreeCandidateNode node) throws IOException {
- final ModificationType modificationType = node.getModificationType();
+ final ModificationType modificationType = node.modificationType();
writer.beginObject().name("Node");
writer.beginArray();
writer.beginObject().name("Path").value(path.toString()).endObject();
writer.beginObject().name("ModificationType").value(modificationType.toString()).endObject();
if (modificationType == ModificationType.WRITE) {
- writer.beginObject().name("Data").value(node.getDataAfter().get().body().toString()).endObject();
+ writer.beginObject().name("Data").value(node.getDataAfter().body().toString()).endObject();
}
writer.endArray();
writer.endObject();
writer.beginArray();
writer.beginObject().name("Path").value(path.toString()).endObject();
writer.beginObject().name("ModificationType")
- .value("UNSUPPORTED MODIFICATION: " + node.getModificationType()).endObject();
+ .value("UNSUPPORTED MODIFICATION: " + node.modificationType()).endObject();
writer.endArray();
writer.endObject();
}
NodeIterator next(final JsonWriter writer) throws IOException {
while (iterator.hasNext()) {
- final DataTreeCandidateNode node = iterator.next();
- final YangInstanceIdentifier child = path.node(node.getIdentifier());
+ final var node = iterator.next();
+ final var child = path.node(node.name());
- switch (node.getModificationType()) {
+ switch (node.modificationType()) {
case APPEARED:
case DISAPPEARED:
case SUBTREE_MODIFIED:
- return new NodeIterator(this, child, node.getChildNodes().iterator());
+ return new NodeIterator(this, child, node.childNodes().iterator());
case DELETE:
case UNMODIFIED:
case WRITE:
private void onSerializeSnapshot(final SerializeSnapshot request) {
Optional<OutputStream> installSnapshotStream = request.getInstallSnapshotStream();
if (installSnapshotStream.isPresent()) {
- try (ObjectOutputStream out = getOutputStream(installSnapshotStream.get())) {
+ try (ObjectOutputStream out = getOutputStream(installSnapshotStream.orElseThrow())) {
request.getSnapshot().serialize(out);
} catch (IOException e) {
// TODO - we should communicate the failure in the CaptureSnapshotReply.
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
-
package org.opendaylight.controller.cluster.datastore.messages;
import com.google.common.base.Preconditions;
import org.opendaylight.controller.cluster.access.concepts.TransactionIdentifier;
-public class AbortTransaction extends AbstractThreePhaseCommitMessage {
+@Deprecated(since = "9.0.0", forRemoval = true)
+public final class AbortTransaction extends AbstractThreePhaseCommitMessage {
+ @java.io.Serial
private static final long serialVersionUID = 1L;
public AbortTransaction() {
}
- public AbortTransaction(TransactionIdentifier transactionID, final short version) {
+ public AbortTransaction(final TransactionIdentifier transactionID, final short version) {
super(transactionID, version);
}
- public static AbortTransaction fromSerializable(Object serializable) {
+ public static AbortTransaction fromSerializable(final Object serializable) {
Preconditions.checkArgument(serializable instanceof AbortTransaction);
return (AbortTransaction)serializable;
}
- public static boolean isSerializedType(Object message) {
+ public static boolean isSerializedType(final Object message) {
return message instanceof AbortTransaction;
}
}
import org.opendaylight.controller.cluster.datastore.DataStoreVersions;
-public class AbortTransactionReply extends VersionedExternalizableMessage {
+@Deprecated(since = "9.0.0", forRemoval = true)
+public final class AbortTransactionReply extends VersionedExternalizableMessage {
@java.io.Serial
private static final long serialVersionUID = 7251132353204199793L;
private static final AbortTransactionReply INSTANCE = new AbortTransactionReply();
public AbortTransactionReply() {
}
- private AbortTransactionReply(short version) {
+ private AbortTransactionReply(final short version) {
super(version);
}
- public static AbortTransactionReply instance(short version) {
+ public static AbortTransactionReply instance(final short version) {
return version == DataStoreVersions.CURRENT_VERSION ? INSTANCE : new AbortTransactionReply(version);
}
- public static boolean isSerializedType(Object message) {
+ public static boolean isSerializedType(final Object message) {
return message instanceof AbortTransactionReply;
}
}
* @author gwu
*
*/
+@Deprecated(since = "9.0.0", forRemoval = true)
public abstract class AbstractRead<T> extends VersionedExternalizableMessage {
private static final long serialVersionUID = 1L;
*
* @author Thomas Pantelis
*/
+@Deprecated(since = "9.0.0", forRemoval = true)
public abstract class AbstractThreePhaseCommitMessage extends VersionedExternalizableMessage {
private static final long serialVersionUID = 1L;
*/
package org.opendaylight.controller.cluster.datastore.messages;
-import java.io.Serializable;
+import static java.util.Objects.requireNonNull;
-public class ActorInitialized implements Serializable {
- private static final long serialVersionUID = 1L;
+import akka.actor.ActorRef;
+import org.eclipse.jdt.annotation.NonNullByDefault;
- public ActorInitialized() {
+@NonNullByDefault
+public record ActorInitialized(ActorRef actorRef) {
+ public ActorInitialized {
+ requireNonNull(actorRef);
}
}
*
* @author Thomas Pantelis
*/
-public class BatchedModifications extends MutableCompositeModification {
+@Deprecated(since = "9.0.0", forRemoval = true)
+public final class BatchedModifications extends MutableCompositeModification {
+ @java.io.Serial
private static final long serialVersionUID = 1L;
private boolean ready;
public BatchedModifications() {
}
- public BatchedModifications(TransactionIdentifier transactionId, short version) {
+ public BatchedModifications(final TransactionIdentifier transactionId, final short version) {
super(version);
this.transactionId = requireNonNull(transactionId, "transactionID can't be null");
}
return ready;
}
- public void setReady(Optional<SortedSet<String>> possibleParticipatingShardNames) {
- this.ready = true;
- this.participatingShardNames = requireNonNull(possibleParticipatingShardNames).orElse(null);
- Preconditions.checkArgument(this.participatingShardNames == null || this.participatingShardNames.size() > 1);
+ public void setReady(final Optional<SortedSet<String>> possibleParticipatingShardNames) {
+ ready = true;
+ participatingShardNames = requireNonNull(possibleParticipatingShardNames).orElse(null);
+ Preconditions.checkArgument(participatingShardNames == null || participatingShardNames.size() > 1);
}
public void setReady() {
return doCommitOnReady;
}
- public void setDoCommitOnReady(boolean doCommitOnReady) {
+ public void setDoCommitOnReady(final boolean doCommitOnReady) {
this.doCommitOnReady = doCommitOnReady;
}
return totalMessagesSent;
}
- public void setTotalMessagesSent(int totalMessagesSent) {
+ public void setTotalMessagesSent(final int totalMessagesSent) {
this.totalMessagesSent = totalMessagesSent;
}
}
@Override
- public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
+ public void readExternal(final ObjectInput in) throws IOException, ClassNotFoundException {
super.readExternal(in);
transactionId = TransactionIdentifier.readFrom(in);
ready = in.readBoolean();
}
@Override
- public void writeExternal(ObjectOutput out) throws IOException {
+ public void writeExternal(final ObjectOutput out) throws IOException {
super.writeExternal(out);
transactionId.writeTo(out);
out.writeBoolean(ready);
if (getVersion() >= DataStoreVersions.FLUORINE_VERSION) {
if (participatingShardNames != null) {
out.writeInt(participatingShardNames.size());
- for (String shardName: participatingShardNames) {
+ for (String shardName : participatingShardNames) {
out.writeObject(shardName);
}
} else {
*
* @author Thomas Pantelis
*/
-public class BatchedModificationsReply extends VersionedExternalizableMessage {
+@Deprecated(since = "9.0.0", forRemoval = true)
+public final class BatchedModificationsReply extends VersionedExternalizableMessage {
+ @java.io.Serial
private static final long serialVersionUID = 1L;
private int numBatched;
public BatchedModificationsReply() {
}
- public BatchedModificationsReply(int numBatched) {
+ public BatchedModificationsReply(final int numBatched) {
this.numBatched = numBatched;
}
}
@Override
- public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
+ public void readExternal(final ObjectInput in) throws IOException, ClassNotFoundException {
super.readExternal(in);
numBatched = in.readInt();
}
@Override
- public void writeExternal(ObjectOutput out) throws IOException {
+ public void writeExternal(final ObjectOutput out) throws IOException {
super.writeExternal(out);
out.writeInt(numBatched);
}
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
-
package org.opendaylight.controller.cluster.datastore.messages;
import com.google.common.base.Preconditions;
import org.opendaylight.controller.cluster.access.concepts.TransactionIdentifier;
-public class CanCommitTransaction extends AbstractThreePhaseCommitMessage {
+@Deprecated(since = "9.0.0", forRemoval = true)
+public final class CanCommitTransaction extends AbstractThreePhaseCommitMessage {
+ @java.io.Serial
private static final long serialVersionUID = 1L;
public CanCommitTransaction() {
}
- public CanCommitTransaction(TransactionIdentifier transactionID, final short version) {
+ public CanCommitTransaction(final TransactionIdentifier transactionID, final short version) {
super(transactionID, version);
}
- public static CanCommitTransaction fromSerializable(Object serializable) {
+ public static CanCommitTransaction fromSerializable(final Object serializable) {
Preconditions.checkArgument(serializable instanceof CanCommitTransaction);
return (CanCommitTransaction)serializable;
}
- public static boolean isSerializedType(Object message) {
+ public static boolean isSerializedType(final Object message) {
return message instanceof CanCommitTransaction;
}
}
import java.io.ObjectOutput;
import org.opendaylight.controller.cluster.datastore.DataStoreVersions;
-public class CanCommitTransactionReply extends VersionedExternalizableMessage {
+@Deprecated(since = "9.0.0", forRemoval = true)
+public final class CanCommitTransactionReply extends VersionedExternalizableMessage {
@java.io.Serial
private static final long serialVersionUID = 4355566635423934872L;
}
@Override
- public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
+ public void readExternal(final ObjectInput in) throws IOException, ClassNotFoundException {
super.readExternal(in);
canCommit = in.readBoolean();
}
@Override
- public void writeExternal(ObjectOutput out) throws IOException {
+ public void writeExternal(final ObjectOutput out) throws IOException {
super.writeExternal(out);
out.writeBoolean(canCommit);
}
return "CanCommitTransactionReply [canCommit=" + canCommit + ", version=" + getVersion() + "]";
}
- public static CanCommitTransactionReply yes(short version) {
+ public static CanCommitTransactionReply yes(final short version) {
return version == DataStoreVersions.CURRENT_VERSION ? YES : new CanCommitTransactionReply(true, version);
}
- public static CanCommitTransactionReply no(short version) {
+ public static CanCommitTransactionReply no(final short version) {
return version == DataStoreVersions.CURRENT_VERSION ? NO : new CanCommitTransactionReply(false, version);
}
return (CanCommitTransactionReply)serializable;
}
- public static boolean isSerializedType(Object message) {
+ public static boolean isSerializedType(final Object message) {
return message instanceof CanCommitTransactionReply;
}
}
import java.io.Serializable;
public final class CloseDataTreeNotificationListenerRegistration implements Serializable {
+ @java.io.Serial
private static final long serialVersionUID = 1L;
private static final CloseDataTreeNotificationListenerRegistration INSTANCE =
new CloseDataTreeNotificationListenerRegistration();
return INSTANCE;
}
+ @java.io.Serial
private Object readResolve() {
return INSTANCE;
}
import java.io.Serializable;
public final class CloseDataTreeNotificationListenerRegistrationReply implements Serializable {
+ @java.io.Serial
private static final long serialVersionUID = 1L;
private static final CloseDataTreeNotificationListenerRegistrationReply INSTANCE =
new CloseDataTreeNotificationListenerRegistrationReply();
return INSTANCE;
}
+ @java.io.Serial
private Object readResolve() {
return INSTANCE;
}
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
-
package org.opendaylight.controller.cluster.datastore.messages;
-public class CloseTransaction extends VersionedExternalizableMessage {
+@Deprecated(since = "9.0.0", forRemoval = true)
+public final class CloseTransaction extends VersionedExternalizableMessage {
+ @java.io.Serial
private static final long serialVersionUID = 1L;
public CloseTransaction() {
}
- public CloseTransaction(short version) {
+ public CloseTransaction(final short version) {
super(version);
}
- public static boolean isSerializedType(Object message) {
+ public static boolean isSerializedType(final Object message) {
return message instanceof CloseTransaction;
}
}
import org.opendaylight.controller.cluster.access.concepts.LocalHistoryIdentifier;
import org.opendaylight.yangtools.concepts.Identifiable;
-public class CloseTransactionChain extends VersionedExternalizableMessage
+@Deprecated(since = "9.0.0", forRemoval = true)
+public final class CloseTransactionChain extends VersionedExternalizableMessage
implements Identifiable<LocalHistoryIdentifier> {
+ @java.io.Serial
private static final long serialVersionUID = 1L;
private LocalHistoryIdentifier transactionChainId;
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
-
package org.opendaylight.controller.cluster.datastore.messages;
+@Deprecated(since = "9.0.0", forRemoval = true)
public class CloseTransactionReply extends VersionedExternalizableMessage {
private static final long serialVersionUID = 1L;
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
-
package org.opendaylight.controller.cluster.datastore.messages;
import com.google.common.base.Preconditions;
import org.opendaylight.controller.cluster.access.concepts.TransactionIdentifier;
-public class CommitTransaction extends AbstractThreePhaseCommitMessage {
+@Deprecated(since = "9.0.0", forRemoval = true)
+public final class CommitTransaction extends AbstractThreePhaseCommitMessage {
+ @java.io.Serial
private static final long serialVersionUID = 1L;
public CommitTransaction() {
}
- public CommitTransaction(TransactionIdentifier transactionID, final short version) {
+ public CommitTransaction(final TransactionIdentifier transactionID, final short version) {
super(transactionID, version);
}
- public static CommitTransaction fromSerializable(Object serializable) {
+ public static CommitTransaction fromSerializable(final Object serializable) {
Preconditions.checkArgument(serializable instanceof CommitTransaction);
return (CommitTransaction)serializable;
}
- public static boolean isSerializedType(Object message) {
+ public static boolean isSerializedType(final Object message) {
return message instanceof CommitTransaction;
}
}
import org.opendaylight.controller.cluster.datastore.DataStoreVersions;
-public class CommitTransactionReply extends VersionedExternalizableMessage {
+@Deprecated(since = "9.0.0", forRemoval = true)
+public final class CommitTransactionReply extends VersionedExternalizableMessage {
@java.io.Serial
private static final long serialVersionUID = -8342450250867395000L;
public CommitTransactionReply() {
}
- private CommitTransactionReply(short version) {
+ private CommitTransactionReply(final short version) {
super(version);
}
- public static CommitTransactionReply instance(short version) {
+ public static CommitTransactionReply instance(final short version) {
return version == DataStoreVersions.CURRENT_VERSION ? INSTANCE : new CommitTransactionReply(version);
}
- public static boolean isSerializedType(Object message) {
+ public static boolean isSerializedType(final Object message) {
return message instanceof CommitTransactionReply;
}
}
import java.io.ObjectOutput;
import org.opendaylight.controller.cluster.access.concepts.TransactionIdentifier;
-public class CreateTransaction extends VersionedExternalizableMessage {
+@Deprecated(since = "9.0.0", forRemoval = true)
+public final class CreateTransaction extends VersionedExternalizableMessage {
+ @java.io.Serial
private static final long serialVersionUID = 1L;
private TransactionIdentifier transactionId;
import java.io.ObjectOutput;
import org.opendaylight.controller.cluster.access.concepts.TransactionIdentifier;
-public class CreateTransactionReply extends VersionedExternalizableMessage {
+@Deprecated(since = "9.0.0", forRemoval = true)
+public final class CreateTransactionReply extends VersionedExternalizableMessage {
+ @java.io.Serial
private static final long serialVersionUID = 1L;
private String transactionPath;
}
@Override
- public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
+ public void readExternal(final ObjectInput in) throws IOException, ClassNotFoundException {
super.readExternal(in);
transactionId = TransactionIdentifier.readFrom(in);
transactionPath = in.readUTF();
}
@Override
- public void writeExternal(ObjectOutput out) throws IOException {
+ public void writeExternal(final ObjectOutput out) throws IOException {
super.writeExternal(out);
transactionId.writeTo(out);
out.writeUTF(transactionPath);
+ ", version=" + getVersion() + "]";
}
- public static CreateTransactionReply fromSerializable(Object serializable) {
+ public static CreateTransactionReply fromSerializable(final Object serializable) {
checkArgument(serializable instanceof CreateTransactionReply);
return (CreateTransactionReply)serializable;
}
- public static boolean isSerializedType(Object message) {
+ public static boolean isSerializedType(final Object message) {
return message instanceof CreateTransactionReply;
}
}
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
-
package org.opendaylight.controller.cluster.datastore.messages;
import com.google.common.base.Preconditions;
import org.opendaylight.mdsal.dom.spi.store.DOMStoreReadTransaction;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
+@Deprecated(since = "9.0.0", forRemoval = true)
public class DataExists extends AbstractRead<Boolean> {
private static final long serialVersionUID = 1L;
}
@Override
- public FluentFuture<Boolean> apply(DOMStoreReadTransaction readDelegate) {
+ public FluentFuture<Boolean> apply(final DOMStoreReadTransaction readDelegate) {
return readDelegate.exists(getPath());
}
@Override
- public void processResponse(Object response, SettableFuture<Boolean> returnFuture) {
+ public void processResponse(final Object response, final SettableFuture<Boolean> returnFuture) {
if (DataExistsReply.isSerializedType(response)) {
returnFuture.set(Boolean.valueOf(DataExistsReply.fromSerializable(response).exists()));
} else {
}
@Override
- protected AbstractRead<Boolean> newInstance(short withVersion) {
+ protected AbstractRead<Boolean> newInstance(final short withVersion) {
return new DataExists(getPath(), withVersion);
}
return (DataExists)serializable;
}
- public static boolean isSerializedType(Object message) {
+ public static boolean isSerializedType(final Object message) {
return message instanceof DataExists;
}
}
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
-
package org.opendaylight.controller.cluster.datastore.messages;
import com.google.common.base.Preconditions;
import java.io.ObjectInput;
import java.io.ObjectOutput;
+@Deprecated(since = "9.0.0", forRemoval = true)
public class DataExistsReply extends VersionedExternalizableMessage {
private static final long serialVersionUID = 1L;
}
@Override
- public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
+ public void readExternal(final ObjectInput in) throws IOException, ClassNotFoundException {
super.readExternal(in);
exists = in.readBoolean();
}
@Override
- public void writeExternal(ObjectOutput out) throws IOException {
+ public void writeExternal(final ObjectOutput out) throws IOException {
super.writeExternal(out);
out.writeBoolean(exists);
}
return (DataExistsReply)serializable;
}
- public static boolean isSerializedType(Object message) {
+ public static boolean isSerializedType(final Object message) {
return message instanceof DataExistsReply;
}
}
import java.io.Serializable;
public final class DataTreeChangedReply implements Serializable {
+ @java.io.Serial
private static final long serialVersionUID = 1L;
private static final DataTreeChangedReply INSTANCE = new DataTreeChangedReply();
return INSTANCE;
}
+ @java.io.Serial
private Object readResolve() {
return INSTANCE;
}
+++ /dev/null
-/*
- * Copyright (c) 2015 Brocade Communications Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.cluster.datastore.messages;
-
-import java.io.Externalizable;
-import java.io.ObjectInput;
-import java.io.ObjectOutput;
-
-/**
- * Externalizable with no data.
- *
- * @author Thomas Pantelis
- */
-public class EmptyExternalizable implements Externalizable {
- @java.io.Serial
- private static final long serialVersionUID = 8413772905242947276L;
-
- @Override
- public void readExternal(ObjectInput in) {
- }
-
- @Override
- public void writeExternal(ObjectOutput out) {
- }
-}
*
* @author Thomas Pantelis
*/
-public class ForwardedReadyTransaction {
+@Deprecated(since = "9.0.0", forRemoval = true)
+public final class ForwardedReadyTransaction {
private final TransactionIdentifier transactionId;
private final ReadWriteShardDataTreeTransaction transaction;
private final boolean doImmediateCommit;
* Request a shard to report the clients it knows about. Shard is required to respond with {@link GetKnownClientsReply}.
*/
public final class GetKnownClients implements Serializable {
+ @java.io.Serial
private static final long serialVersionUID = 1L;
public static final @NonNull GetKnownClients INSTANCE = new GetKnownClients();
}
+ @java.io.Serial
private Object readResolve() {
return INSTANCE;
}
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
+@Deprecated(since = "9.0.0", forRemoval = true)
public class ReadData extends AbstractRead<Optional<NormalizedNode>> {
private static final long serialVersionUID = 1L;
import org.opendaylight.controller.cluster.datastore.node.utils.stream.SerializationUtils;
import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
+@Deprecated(since = "9.0.0", forRemoval = true)
public class ReadDataReply extends VersionedExternalizableMessage {
private static final long serialVersionUID = 1L;
* to be sent out to a remote system, it needs to be intercepted by {@link ReadyLocalTransactionSerializer}
* and turned into {@link BatchedModifications}.
*/
+@Deprecated(since = "9.0.0", forRemoval = true)
public final class ReadyLocalTransaction {
private final DataTreeModification modification;
private final TransactionIdentifier transactionId;
* into akka serialization to allow forwarding of ReadyLocalTransaction to remote
* shards.
*/
+@Deprecated(since = "9.0.0", forRemoval = true)
public final class ReadyLocalTransactionSerializer extends JSerializer {
-
private final ExtendedActorSystem system;
public ReadyLocalTransactionSerializer(final ExtendedActorSystem system) {
import java.io.ObjectOutput;
import org.opendaylight.controller.cluster.datastore.DataStoreVersions;
+@Deprecated(since = "9.0.0", forRemoval = true)
public class ReadyTransactionReply extends VersionedExternalizableMessage {
private static final long serialVersionUID = 1L;
public ReadyTransactionReply() {
}
- public ReadyTransactionReply(String cohortPath) {
+ public ReadyTransactionReply(final String cohortPath) {
this(cohortPath, DataStoreVersions.CURRENT_VERSION);
}
- public ReadyTransactionReply(String cohortPath, short version) {
+ public ReadyTransactionReply(final String cohortPath, final short version) {
super(version);
this.cohortPath = cohortPath;
}
}
@Override
- public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
+ public void readExternal(final ObjectInput in) throws IOException, ClassNotFoundException {
super.readExternal(in);
cohortPath = in.readUTF();
}
@Override
- public void writeExternal(ObjectOutput out) throws IOException {
+ public void writeExternal(final ObjectOutput out) throws IOException {
super.writeExternal(out);
out.writeUTF(cohortPath);
}
- public static ReadyTransactionReply fromSerializable(Object serializable) {
+ public static ReadyTransactionReply fromSerializable(final Object serializable) {
return (ReadyTransactionReply)serializable;
}
- public static boolean isSerializedType(Object message) {
+ public static boolean isSerializedType(final Object message) {
return message instanceof ReadyTransactionReply;
}
}
import static java.util.Objects.requireNonNull;
-import java.util.Optional;
import org.eclipse.jdt.annotation.NonNull;
import org.eclipse.jdt.annotation.Nullable;
import org.opendaylight.controller.cluster.notifications.LeaderStateChanged;
*
* @author Thomas Pantelis
*/
-public class ShardLeaderStateChanged extends LeaderStateChanged {
- private final ReadOnlyDataTree localShardDataTree;
+public final class ShardLeaderStateChanged extends LeaderStateChanged {
+ private final @Nullable ReadOnlyDataTree localShardDataTree;
public ShardLeaderStateChanged(final @NonNull String memberId, final @Nullable String leaderId,
final @NonNull ReadOnlyDataTree localShardDataTree, final short leaderPayloadVersion) {
localShardDataTree = null;
}
- public @NonNull Optional<ReadOnlyDataTree> getLocalShardDataTree() {
- return Optional.ofNullable(localShardDataTree);
+ public @Nullable ReadOnlyDataTree localShardDataTree() {
+ return localShardDataTree;
}
}
+++ /dev/null
-/*
- * Copyright (c) 2015 Brocade Communications Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.cluster.datastore.messages;
-
-import java.io.Serializable;
-
-/**
- * A reply message indicating success.
- *
- * @author Thomas Pantelis
- */
-public final class SuccessReply implements Serializable {
- private static final long serialVersionUID = 1L;
-
- public static final SuccessReply INSTANCE = new SuccessReply();
-
- private SuccessReply() {
- }
-}
*/
package org.opendaylight.controller.cluster.datastore.messages;
+import static java.util.Objects.requireNonNull;
+
+import org.eclipse.jdt.annotation.NonNullByDefault;
import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
-import org.opendaylight.yangtools.yang.model.spi.AbstractEffectiveModelContextProvider;
-public class UpdateSchemaContext extends AbstractEffectiveModelContextProvider {
- public UpdateSchemaContext(final EffectiveModelContext modelContext) {
- super(modelContext);
+@NonNullByDefault
+public record UpdateSchemaContext(EffectiveModelContext modelContext) {
+ public UpdateSchemaContext {
+ requireNonNull(modelContext);
}
}
*
* @author Thomas Pantelis
*/
+@Deprecated(since = "9.0.0", forRemoval = true)
public abstract class VersionedExternalizableMessage implements Externalizable, SerializableMessage {
private static final long serialVersionUID = 1L;
}
protected final @NonNull NormalizedNodeStreamVersion getStreamVersion() {
- if (version >= DataStoreVersions.PHOSPHORUS_VERSION) {
+ if (version >= DataStoreVersions.POTASSIUM_VERSION) {
+ return NormalizedNodeStreamVersion.POTASSIUM;
+ } else if (version >= DataStoreVersions.PHOSPHORUS_VERSION) {
return NormalizedNodeStreamVersion.MAGNESIUM;
- } else if (version == DataStoreVersions.SODIUM_SR1_VERSION) {
- return NormalizedNodeStreamVersion.SODIUM_SR1;
} else {
throw new IllegalStateException("Unsupported version " + version);
}
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
-
package org.opendaylight.controller.cluster.datastore.modification;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
/**
* Base class to be used for all simple modifications that can be applied to a DOMStoreTransaction.
*/
+@Deprecated(since = "9.0.0", forRemoval = true)
public abstract class AbstractModification implements Modification {
@java.io.Serial
private static final long serialVersionUID = 2647778426312509718L;
* A CompositeModification gets stored in the transaction log for a Shard. During recovery when the transaction log
* is being replayed a DOMStoreWriteTransaction could be created and a CompositeModification could be applied to it.
*/
+@Deprecated(since = "9.0.0", forRemoval = true)
public interface CompositeModification extends Modification {
/**
* Get a list of modifications contained by this composite.
/**
* DeleteModification store all the parameters required to delete a path from the data tree.
*/
-public class DeleteModification extends AbstractModification {
+@Deprecated(since = "9.0.0", forRemoval = true)
+public final class DeleteModification extends AbstractModification {
+ @java.io.Serial
private static final long serialVersionUID = 1L;
public DeleteModification() {
/**
* MergeModification stores all the parameters required to merge data into the specified path.
*/
-public class MergeModification extends WriteModification {
+@Deprecated(since = "9.0.0", forRemoval = true)
+public final class MergeModification extends WriteModification {
private static final long serialVersionUID = 1L;
public MergeModification() {
/**
* MutableCompositeModification is just a mutable version of a CompositeModification.
*/
+@Deprecated(since = "9.0.0", forRemoval = true)
public class MutableCompositeModification extends VersionedExternalizableMessage implements CompositeModification {
private static final long serialVersionUID = 1L;
/**
* WriteModification stores all the parameters required to write data to the specified path.
*/
+@Deprecated(since = "9.0.0", forRemoval = true)
public class WriteModification extends AbstractModification {
private static final long serialVersionUID = 1L;
import com.google.common.io.ByteArrayDataOutput;
import com.google.common.io.ByteStreams;
-import java.io.DataInput;
import java.io.IOException;
import org.opendaylight.controller.cluster.access.concepts.TransactionIdentifier;
-import org.opendaylight.controller.cluster.raft.persisted.LegacySerializable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
*
* @author Robert Varga
*/
-public sealed class AbortTransactionPayload extends AbstractIdentifiablePayload<TransactionIdentifier> {
- @Deprecated(since = "7.0.0", forRemoval = true)
- private static final class Magnesium extends AbortTransactionPayload implements LegacySerializable {
- @java.io.Serial
- private static final long serialVersionUID = 1L;
-
- Magnesium(final TransactionIdentifier transactionId, final byte[] serialized) {
- super(transactionId, serialized);
- }
- }
-
- @Deprecated(since = "7.0.0", forRemoval = true)
- private static final class Proxy extends AbstractProxy<TransactionIdentifier> {
- @java.io.Serial
- private static final long serialVersionUID = 1L;
-
- // checkstyle flags the public modifier as redundant which really doesn't make sense since it clearly isn't
- // redundant. It is explicitly needed for Java serialization to be able to create instances via reflection.
- @SuppressWarnings("checkstyle:RedundantModifier")
- public Proxy() {
- // For Externalizable
- }
-
- @Override
- protected TransactionIdentifier readIdentifier(final DataInput in) throws IOException {
- return TransactionIdentifier.readFrom(in);
- }
-
- @Override
- protected AbortTransactionPayload createObject(final TransactionIdentifier identifier,
- final byte[] serialized) {
- return new Magnesium(identifier, serialized);
- }
- }
-
+public final class AbortTransactionPayload extends AbstractIdentifiablePayload<TransactionIdentifier> {
private static final Logger LOG = LoggerFactory.getLogger(AbortTransactionPayload.class);
@java.io.Serial
private static final long serialVersionUID = 1L;
import static java.util.Objects.requireNonNull;
import java.util.Collection;
-import java.util.Optional;
+import org.eclipse.jdt.annotation.NonNull;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
import org.opendaylight.yangtools.yang.data.tree.api.DataTreeCandidateNode;
import org.opendaylight.yangtools.yang.data.tree.api.ModificationType;
/**
- * Abstract base class for our internal implementation of {@link DataTreeCandidateNode},
- * which we instantiate from a serialized stream. We do not retain the before-image and
- * do not implement {@link #getModifiedChild(PathArgument)}, as that method is only
- * useful for end users. Instances based on this class should never be leaked outside of
- * this component.
+ * Abstract base class for our internal implementation of {@link DataTreeCandidateNode}, which we instantiate from a
+ * serialized stream. We do not retain the before-image and do not implement {@link #modifiedChild(PathArgument)}, as
+ * that method is only useful for end users. Instances based on this class should never be leaked outside of this
+ * component.
*/
abstract class AbstractDataTreeCandidateNode implements DataTreeCandidateNode {
- private final ModificationType type;
+ private final @NonNull ModificationType type;
protected AbstractDataTreeCandidateNode(final ModificationType type) {
this.type = requireNonNull(type);
}
@Override
- public final Optional<DataTreeCandidateNode> getModifiedChild(final PathArgument identifier) {
+ public final DataTreeCandidateNode modifiedChild(final PathArgument identifier) {
throw new UnsupportedOperationException("Not implemented");
}
@Override
- public final ModificationType getModificationType() {
+ public final ModificationType modificationType() {
return type;
}
@Override
- public final Optional<NormalizedNode> getDataBefore() {
+ public final NormalizedNode dataBefore() {
throw new UnsupportedOperationException("Before-image not available after serialization");
}
static DataTreeCandidateNode createUnmodified() {
return new AbstractDataTreeCandidateNode(ModificationType.UNMODIFIED) {
@Override
- public PathArgument getIdentifier() {
+ public PathArgument name() {
throw new UnsupportedOperationException("Root node does not have an identifier");
}
@Override
- public Optional<NormalizedNode> getDataAfter() {
+ public NormalizedNode dataAfter() {
throw new UnsupportedOperationException("After-image not available after serialization");
}
@Override
- public Collection<DataTreeCandidateNode> getChildNodes() {
+ public Collection<DataTreeCandidateNode> childNodes() {
throw new UnsupportedOperationException("Children not available after serialization");
}
};
import static java.util.Objects.requireNonNull;
import com.google.common.base.MoreObjects;
-import com.google.common.io.ByteStreams;
-import java.io.DataInput;
import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
-import java.io.Serializable;
import java.util.function.Function;
import org.apache.commons.lang3.SerializationUtils;
import org.eclipse.jdt.annotation.NonNull;
import org.opendaylight.controller.cluster.raft.messages.IdentifiablePayload;
-import org.opendaylight.yangtools.concepts.Identifiable;
import org.opendaylight.yangtools.concepts.Identifier;
/**
* Abstract base class for {@link IdentifiablePayload}s which hold a single {@link Identifier}.
- *
- * @author Robert Varga
*/
-public abstract class AbstractIdentifiablePayload<T extends Identifier> extends IdentifiablePayload<T>
- implements Serializable {
+public abstract class AbstractIdentifiablePayload<T extends Identifier> extends IdentifiablePayload<T> {
/**
* An {@link Externalizable} with default implementations we expect our implementations to comply with. On-wire
* serialization format is defined by {@link #bytes()}.
}
}
- @Deprecated(since = "7.0.0", forRemoval = true)
- protected abstract static class AbstractProxy<T extends Identifier> implements SerialForm {
- @java.io.Serial
- private static final long serialVersionUID = 1L;
-
- private byte[] serialized;
- private T identifier;
-
- public AbstractProxy() {
- // For Externalizable
- }
-
- protected AbstractProxy(final byte[] serialized) {
- this.serialized = requireNonNull(serialized);
- }
-
- @Override
- public final byte[] bytes() {
- return serialized;
- }
-
- @Override
- public final void readExternal(final byte[] bytes) throws IOException {
- serialized = requireNonNull(bytes);
- identifier = verifyNotNull(readIdentifier(ByteStreams.newDataInput(serialized)));
- }
-
- @Override
- public final Object readResolve() {
- return verifyNotNull(createObject(identifier, serialized));
- }
-
- protected abstract @NonNull T readIdentifier(@NonNull DataInput in) throws IOException;
-
- @SuppressWarnings("checkstyle:hiddenField")
- protected abstract @NonNull Identifiable<T> createObject(@NonNull T identifier, byte @NonNull[] serialized);
- }
-
+ @java.io.Serial
private static final long serialVersionUID = 1L;
private final byte @NonNull [] serialized;
static @NonNull ShardSnapshotState versionedDeserialize(final ObjectInput in) throws IOException {
final PayloadVersion version = PayloadVersion.readFrom(in);
switch (version) {
- case SODIUM_SR1:
- case MAGNESIUM:
- return new ShardSnapshotState(readSnapshot(in), true);
case CHLORINE_SR2:
+ return new ShardSnapshotState(readSnapshot(in), true);
+ case POTASSIUM:
return new ShardSnapshotState(readSnapshot(in), false);
case TEST_FUTURE_VERSION:
case TEST_PAST_VERSION:
private void versionedSerialize(final ObjectOutput out, final PayloadVersion version) throws IOException {
switch (version) {
- case SODIUM_SR1:
- case MAGNESIUM:
case CHLORINE_SR2:
- // Sodium and Magnesium snapshots use Java Serialization, but differ in stream format
+ case POTASSIUM:
+ // Sodium onwards snapshots use Java Serialization, but differ in stream format
out.writeObject(this);
return;
case TEST_FUTURE_VERSION:
}
}
+ @java.io.Serial
private Object readResolve() {
return verifyNotNull(payload);
}
import com.google.common.io.ByteArrayDataOutput;
import com.google.common.io.ByteStreams;
-import java.io.DataInput;
import java.io.IOException;
import org.opendaylight.controller.cluster.access.concepts.LocalHistoryIdentifier;
-import org.opendaylight.controller.cluster.raft.persisted.LegacySerializable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
*
* @author Robert Varga
*/
-public sealed class CloseLocalHistoryPayload extends AbstractIdentifiablePayload<LocalHistoryIdentifier> {
- @Deprecated(since = "7.0.0", forRemoval = true)
- private static final class Magnesium extends CloseLocalHistoryPayload implements LegacySerializable {
- @java.io.Serial
- private static final long serialVersionUID = 1L;
-
- Magnesium(final LocalHistoryIdentifier historyId, final byte[] serialized) {
- super(historyId, serialized);
- }
- }
-
- @Deprecated(since = "7.0.0", forRemoval = true)
- private static final class Proxy extends AbstractProxy<LocalHistoryIdentifier> {
- @java.io.Serial
- private static final long serialVersionUID = 1L;
-
- // checkstyle flags the public modifier as redundant which really doesn't make sense since it clearly isn't
- // redundant. It is explicitly needed for Java serialization to be able to create instances via reflection.
- @SuppressWarnings("checkstyle:RedundantModifier")
- public Proxy() {
- // For Externalizable
- }
-
- @Override
- protected LocalHistoryIdentifier readIdentifier(final DataInput in) throws IOException {
- return LocalHistoryIdentifier.readFrom(in);
- }
-
- @Override
- protected CloseLocalHistoryPayload createObject(final LocalHistoryIdentifier identifier,
- final byte[] serialized) {
- return new Magnesium(identifier, serialized);
- }
- }
-
+public final class CloseLocalHistoryPayload extends AbstractIdentifiablePayload<LocalHistoryIdentifier> {
private static final Logger LOG = LoggerFactory.getLogger(CloseLocalHistoryPayload.class);
@java.io.Serial
private static final long serialVersionUID = 1L;
*/
package org.opendaylight.controller.cluster.datastore.persisted;
-import static com.google.common.base.Verify.verifyNotNull;
import static com.google.common.math.IntMath.ceilingPowerOfTwo;
import static java.util.Objects.requireNonNull;
import java.io.DataInput;
import java.io.DataInputStream;
import java.io.DataOutputStream;
-import java.io.Externalizable;
import java.io.IOException;
-import java.io.ObjectInput;
import java.io.ObjectOutput;
import java.io.Serializable;
-import java.io.StreamCorruptedException;
-import java.util.AbstractMap.SimpleImmutableEntry;
-import java.util.Map.Entry;
import org.apache.commons.lang3.SerializationUtils;
import org.eclipse.jdt.annotation.NonNull;
+import org.eclipse.jdt.annotation.NonNullByDefault;
import org.opendaylight.controller.cluster.access.concepts.TransactionIdentifier;
-import org.opendaylight.controller.cluster.datastore.persisted.DataTreeCandidateInputOutput.DataTreeCandidateWithVersion;
import org.opendaylight.controller.cluster.io.ChunkedByteArray;
import org.opendaylight.controller.cluster.io.ChunkedOutputStream;
import org.opendaylight.controller.cluster.raft.messages.IdentifiablePayload;
-import org.opendaylight.controller.cluster.raft.persisted.LegacySerializable;
-import org.opendaylight.yangtools.concepts.Either;
import org.opendaylight.yangtools.yang.data.api.schema.stream.ReusableStreamReceiver;
+import org.opendaylight.yangtools.yang.data.codec.binfmt.NormalizedNodeStreamVersion;
import org.opendaylight.yangtools.yang.data.impl.schema.ReusableImmutableNormalizedNodeStreamWriter;
import org.opendaylight.yangtools.yang.data.tree.api.DataTreeCandidate;
import org.slf4j.Logger;
@Beta
public abstract sealed class CommitTransactionPayload extends IdentifiablePayload<TransactionIdentifier>
implements Serializable {
+ @NonNullByDefault
+ public record CandidateTransaction(
+ TransactionIdentifier transactionId,
+ DataTreeCandidate candidate,
+ NormalizedNodeStreamVersion streamVersion) {
+ public CandidateTransaction {
+ requireNonNull(transactionId);
+ requireNonNull(candidate);
+ requireNonNull(streamVersion);
+ }
+ }
+
private static final Logger LOG = LoggerFactory.getLogger(CommitTransactionPayload.class);
private static final long serialVersionUID = 1L;
static final int MAX_ARRAY_SIZE = ceilingPowerOfTwo(Integer.getInteger(
"org.opendaylight.controller.cluster.datastore.persisted.max-array-size", 256 * 1024));
- private volatile Entry<TransactionIdentifier, DataTreeCandidateWithVersion> candidate = null;
+ private volatile CandidateTransaction candidate = null;
- CommitTransactionPayload() {
+ private CommitTransactionPayload() {
// hidden on purpose
}
public static @NonNull CommitTransactionPayload create(final TransactionIdentifier transactionId,
final DataTreeCandidate candidate, final PayloadVersion version, final int initialSerializedBufferCapacity)
throws IOException {
- final ChunkedOutputStream cos = new ChunkedOutputStream(initialSerializedBufferCapacity, MAX_ARRAY_SIZE);
- try (DataOutputStream dos = new DataOutputStream(cos)) {
+ final var cos = new ChunkedOutputStream(initialSerializedBufferCapacity, MAX_ARRAY_SIZE);
+ try (var dos = new DataOutputStream(cos)) {
transactionId.writeTo(dos);
DataTreeCandidateInputOutput.writeDataTreeCandidate(dos, version, candidate);
}
- final Either<byte[], ChunkedByteArray> source = cos.toVariant();
+ final var source = cos.toVariant();
LOG.debug("Initial buffer capacity {}, actual serialized size {}", initialSerializedBufferCapacity, cos.size());
return source.isFirst() ? new Simple(source.getFirst()) : new Chunked(source.getSecond());
}
return create(transactionId, candidate, PayloadVersion.current());
}
- public @NonNull Entry<TransactionIdentifier, DataTreeCandidateWithVersion> getCandidate() throws IOException {
- Entry<TransactionIdentifier, DataTreeCandidateWithVersion> localCandidate = candidate;
+ public @NonNull CandidateTransaction getCandidate() throws IOException {
+ var localCandidate = candidate;
if (localCandidate == null) {
synchronized (this) {
localCandidate = candidate;
return localCandidate;
}
- public final @NonNull Entry<TransactionIdentifier, DataTreeCandidateWithVersion> getCandidate(
- final ReusableStreamReceiver receiver) throws IOException {
- final DataInput in = newDataInput();
- return new SimpleImmutableEntry<>(TransactionIdentifier.readFrom(in),
- DataTreeCandidateInputOutput.readDataTreeCandidate(in, receiver));
+ public final @NonNull CandidateTransaction getCandidate(final ReusableStreamReceiver receiver) throws IOException {
+ final var in = newDataInput();
+ final var transactionId = TransactionIdentifier.readFrom(in);
+ final var readCandidate = DataTreeCandidateInputOutput.readDataTreeCandidate(in, receiver);
+
+ return new CandidateTransaction(transactionId, readCandidate.candidate(), readCandidate.version());
}
@Override
public TransactionIdentifier getIdentifier() {
try {
- return getCandidate().getKey();
+ return getCandidate().transactionId();
} catch (IOException e) {
throw new IllegalStateException("Candidate deserialization failed.", e);
}
* deserialized in memory which are not needed anymore leading to wasted memory. This lets the payload know that
* this was the last time the candidate was needed ant it is safe to be cleared.
*/
- public Entry<TransactionIdentifier, DataTreeCandidateWithVersion> acquireCandidate() throws IOException {
- final Entry<TransactionIdentifier, DataTreeCandidateWithVersion> localCandidate = getCandidate();
+ public @NonNull CandidateTransaction acquireCandidate() throws IOException {
+ final var localCandidate = getCandidate();
candidate = null;
return localCandidate;
}
final var helper = MoreObjects.toStringHelper(this);
final var localCandidate = candidate;
if (localCandidate != null) {
- helper.add("identifier", candidate.getKey());
+ helper.add("identifier", candidate.transactionId());
}
return helper.add("size", size()).toString();
}
return new CT(this);
}
- static sealed class Simple extends CommitTransactionPayload {
+ static final class Simple extends CommitTransactionPayload {
@java.io.Serial
private static final long serialVersionUID = 1L;
}
}
- static sealed class Chunked extends CommitTransactionPayload {
+ static final class Chunked extends CommitTransactionPayload {
@java.io.Serial
private static final long serialVersionUID = 1L;
// Hidden on purpose
}
}
-
- @Deprecated(since = "7.0.0", forRemoval = true)
- private static final class SimpleMagnesium extends Simple implements LegacySerializable {
- @java.io.Serial
- private static final long serialVersionUID = 1L;
-
- SimpleMagnesium(final byte[] serialized) {
- super(serialized);
- }
- }
-
- @Deprecated(since = "7.0.0", forRemoval = true)
- private static final class ChunkedMagnesium extends Chunked implements LegacySerializable {
- @java.io.Serial
- private static final long serialVersionUID = 1L;
-
- ChunkedMagnesium(final ChunkedByteArray source) {
- super(source);
- }
- }
-
- @Deprecated(since = "7.0.0", forRemoval = true)
- private static final class Proxy implements Externalizable {
- @java.io.Serial
- private static final long serialVersionUID = 1L;
-
- private CommitTransactionPayload payload;
-
- // checkstyle flags the public modifier as redundant which really doesn't make sense since it clearly isn't
- // redundant. It is explicitly needed for Java serialization to be able to create instances via reflection.
- @SuppressWarnings("checkstyle:RedundantModifier")
- public Proxy() {
- // For Externalizable
- }
-
- Proxy(final CommitTransactionPayload payload) {
- this.payload = requireNonNull(payload);
- }
-
- @Override
- public void writeExternal(final ObjectOutput out) throws IOException {
- out.writeInt(payload.size());
- payload.writeBytes(out);
- }
-
- @Override
- public void readExternal(final ObjectInput in) throws IOException {
- final int length = in.readInt();
- if (length < 0) {
- throw new StreamCorruptedException("Invalid payload length " + length);
- } else if (length < MAX_ARRAY_SIZE) {
- final byte[] serialized = new byte[length];
- in.readFully(serialized);
- payload = new SimpleMagnesium(serialized);
- } else {
- payload = new ChunkedMagnesium(ChunkedByteArray.readFrom(in, length, MAX_ARRAY_SIZE));
- }
- }
-
- @java.io.Serial
- private Object readResolve() {
- return verifyNotNull(payload);
- }
- }
}
import com.google.common.io.ByteArrayDataOutput;
import com.google.common.io.ByteStreams;
-import java.io.DataInput;
import java.io.IOException;
import org.opendaylight.controller.cluster.access.concepts.LocalHistoryIdentifier;
-import org.opendaylight.controller.cluster.raft.persisted.LegacySerializable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
*
* @author Robert Varga
*/
-public sealed class CreateLocalHistoryPayload extends AbstractIdentifiablePayload<LocalHistoryIdentifier> {
- @Deprecated(since = "7.0.0", forRemoval = true)
- private static final class Magnesium extends CreateLocalHistoryPayload implements LegacySerializable {
- @java.io.Serial
- private static final long serialVersionUID = 1L;
-
- Magnesium(final LocalHistoryIdentifier historyId, final byte[] serialized) {
- super(historyId, serialized);
- }
- }
-
- @Deprecated(since = "7.0.0", forRemoval = true)
- private static final class Proxy extends AbstractProxy<LocalHistoryIdentifier> {
- @java.io.Serial
- private static final long serialVersionUID = 1L;
-
- // checkstyle flags the public modifier as redundant which really doesn't make sense since it clearly isn't
- // redundant. It is explicitly needed for Java serialization to be able to create instances via reflection.
- @SuppressWarnings("checkstyle:RedundantModifier")
- public Proxy() {
- // For Externalizable
- }
-
- @Override
- protected LocalHistoryIdentifier readIdentifier(final DataInput in) throws IOException {
- return LocalHistoryIdentifier.readFrom(in);
- }
-
- @Override
- protected CreateLocalHistoryPayload createObject(final LocalHistoryIdentifier identifier,
- final byte[] serialized) {
- return new Magnesium(identifier, serialized);
- }
- }
-
+public final class CreateLocalHistoryPayload extends AbstractIdentifiablePayload<LocalHistoryIdentifier> {
private static final Logger LOG = LoggerFactory.getLogger(CreateLocalHistoryPayload.class);
@java.io.Serial
private static final long serialVersionUID = 1L;
import static com.google.common.base.Verify.verifyNotNull;
import static java.util.Objects.requireNonNull;
+import java.io.Externalizable;
+import java.io.IOException;
+import java.io.ObjectInput;
+import java.io.ObjectOutput;
+import java.util.ArrayList;
+import org.opendaylight.controller.cluster.datastore.persisted.DatastoreSnapshot.ShardSnapshot;
+
/**
* Serialization proxy for {@link DatastoreSnapshot}.
*/
-final class DS implements DatastoreSnapshot.SerialForm {
+final class DS implements Externalizable {
@java.io.Serial
private static final long serialVersionUID = 1L;
}
@Override
- public DatastoreSnapshot datastoreSnapshot() {
- return datastoreSnapshot;
+ public void readExternal(final ObjectInput in) throws IOException, ClassNotFoundException {
+ final var type = (String) in.readObject();
+ final var snapshot = (ShardManagerSnapshot) in.readObject();
+
+ final int size = in.readInt();
+ var localShardSnapshots = new ArrayList<ShardSnapshot>(size);
+ for (int i = 0; i < size; i++) {
+ localShardSnapshots.add((ShardSnapshot) in.readObject());
+ }
+
+ datastoreSnapshot = new DatastoreSnapshot(type, snapshot, localShardSnapshots);
}
@Override
- public void resolveTo(final DatastoreSnapshot newDatastoreSnapshot) {
- datastoreSnapshot = requireNonNull(newDatastoreSnapshot);
+ public void writeExternal(final ObjectOutput out) throws IOException {
+ out.writeObject(datastoreSnapshot.getType());
+ out.writeObject(datastoreSnapshot.getShardManagerSnapshot());
+
+ final var shardSnapshots = datastoreSnapshot.getShardSnapshots();
+ out.writeInt(shardSnapshots.size());
+ for (var shardSnapshot : shardSnapshots) {
+ out.writeObject(shardSnapshot);
+ }
}
- @Override
- public Object readResolve() {
+ @java.io.Serial
+ private Object readResolve() {
return verifyNotNull(datastoreSnapshot);
}
}
import static com.google.common.base.Verify.verifyNotNull;
import static java.util.Objects.requireNonNull;
+import java.io.Externalizable;
+import java.io.IOException;
+import java.io.ObjectInput;
+import java.io.ObjectOutput;
import org.opendaylight.controller.cluster.datastore.persisted.DatastoreSnapshot.ShardSnapshot;
import org.opendaylight.controller.cluster.raft.persisted.Snapshot;
/**
* Serialization proxy for {@link ShardDataTreeSnapshot}.
*/
-final class DSS implements ShardSnapshot.SerialForm {
+final class DSS implements Externalizable {
@java.io.Serial
private static final long serialVersionUID = 1L;
}
@Override
- public ShardSnapshot shardSnapshot() {
- return shardSnapshot;
+ public void writeExternal(final ObjectOutput out) throws IOException {
+ out.writeObject(shardSnapshot.getName());
+ out.writeObject(shardSnapshot.getSnapshot());
}
@Override
- public void resolveTo(final String name, final Snapshot snapshot) {
- shardSnapshot = new ShardSnapshot(name, snapshot);
+ public void readExternal(final ObjectInput in) throws IOException, ClassNotFoundException {
+ shardSnapshot = new ShardSnapshot((String) in.readObject(), (Snapshot) in.readObject());
}
- @Override
- public Object readResolve() {
+ @java.io.Serial
+ private Object readResolve() {
return verifyNotNull(shardSnapshot);
}
}
import com.google.common.annotations.Beta;
import com.google.common.annotations.VisibleForTesting;
-import com.google.common.collect.ImmutableList;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
-import org.eclipse.jdt.annotation.NonNullByDefault;
+import java.util.List;
+import org.eclipse.jdt.annotation.NonNull;
import org.opendaylight.yangtools.concepts.Immutable;
-import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
-import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
import org.opendaylight.yangtools.yang.data.api.schema.stream.ReusableStreamReceiver;
import org.opendaylight.yangtools.yang.data.codec.binfmt.NormalizedNodeDataInput;
import org.opendaylight.yangtools.yang.data.codec.binfmt.NormalizedNodeDataOutput;
/**
* Utility serialization/deserialization for {@link DataTreeCandidate}. Note that this utility does not maintain
* before-image information across serialization.
- *
- * @author Robert Varga
*/
@Beta
public final class DataTreeCandidateInputOutput {
+ public record DataTreeCandidateWithVersion(
+ @NonNull DataTreeCandidate candidate,
+ @NonNull NormalizedNodeStreamVersion version) implements Immutable {
+ public DataTreeCandidateWithVersion {
+ requireNonNull(candidate);
+ requireNonNull(version);
+ }
+ }
+
private static final Logger LOG = LoggerFactory.getLogger(DataTreeCandidateInputOutput.class);
private static final byte DELETE = 0;
private static final byte SUBTREE_MODIFIED = 1;
private static DataTreeCandidateNode readModifiedNode(final ModificationType type, final NormalizedNodeDataInput in,
final ReusableStreamReceiver receiver) throws IOException {
- final PathArgument identifier = in.readPathArgument();
- final Collection<DataTreeCandidateNode> children = readChildren(in, receiver);
+ final var pathArg = in.readPathArgument();
+ final var children = readChildren(in, receiver);
if (children.isEmpty()) {
- LOG.debug("Modified node {} does not have any children, not instantiating it", identifier);
+ LOG.debug("Modified node {} does not have any children, not instantiating it", pathArg);
return null;
}
- return ModifiedDataTreeCandidateNode.create(identifier, type, children);
+ return ModifiedDataTreeCandidateNode.create(pathArg, type, children);
}
- private static Collection<DataTreeCandidateNode> readChildren(final NormalizedNodeDataInput in,
+ private static List<DataTreeCandidateNode> readChildren(final NormalizedNodeDataInput in,
final ReusableStreamReceiver receiver) throws IOException {
final int size = in.readInt();
if (size == 0) {
- return ImmutableList.of();
+ return List.of();
}
- final Collection<DataTreeCandidateNode> ret = new ArrayList<>(size);
+ final var ret = new ArrayList<DataTreeCandidateNode>(size);
for (int i = 0; i < size; ++i) {
- final DataTreeCandidateNode child = readNode(in, receiver);
+ final var child = readNode(in, receiver);
if (child != null) {
ret.add(child);
}
private static DataTreeCandidateNode readNode(final NormalizedNodeDataInput in,
final ReusableStreamReceiver receiver) throws IOException {
final byte type = in.readByte();
- switch (type) {
- case APPEARED:
- return readModifiedNode(ModificationType.APPEARED, in, receiver);
- case DELETE:
- return DeletedDataTreeCandidateNode.create(in.readPathArgument());
- case DISAPPEARED:
- return readModifiedNode(ModificationType.DISAPPEARED, in, receiver);
- case SUBTREE_MODIFIED:
- return readModifiedNode(ModificationType.SUBTREE_MODIFIED, in, receiver);
- case UNMODIFIED:
- return null;
- case WRITE:
- return DataTreeCandidateNodes.written(in.readNormalizedNode(receiver));
- default:
- throw new IllegalArgumentException("Unhandled node type " + type);
- }
- }
-
- @NonNullByDefault
- public static final class DataTreeCandidateWithVersion implements Immutable {
- private final DataTreeCandidate candidate;
- private final NormalizedNodeStreamVersion version;
-
- public DataTreeCandidateWithVersion(final DataTreeCandidate candidate,
- final NormalizedNodeStreamVersion version) {
- this.candidate = requireNonNull(candidate);
- this.version = requireNonNull(version);
- }
-
- public DataTreeCandidate getCandidate() {
- return candidate;
- }
-
- public NormalizedNodeStreamVersion getVersion() {
- return version;
- }
+ return switch (type) {
+ case APPEARED -> readModifiedNode(ModificationType.APPEARED, in, receiver);
+ case DELETE -> DeletedDataTreeCandidateNode.create(in.readPathArgument());
+ case DISAPPEARED -> readModifiedNode(ModificationType.DISAPPEARED, in, receiver);
+ case SUBTREE_MODIFIED -> readModifiedNode(ModificationType.SUBTREE_MODIFIED, in, receiver);
+ case UNMODIFIED -> null;
+ case WRITE -> DataTreeCandidateNodes.written(in.readNormalizedNode(receiver));
+ default -> throw new IllegalArgumentException("Unhandled node type " + type);
+ };
}
public static DataTreeCandidateWithVersion readDataTreeCandidate(final DataInput in,
final ReusableStreamReceiver receiver) throws IOException {
- final NormalizedNodeDataInput reader = NormalizedNodeDataInput.newDataInput(in);
- final YangInstanceIdentifier rootPath = reader.readYangInstanceIdentifier();
+ final var reader = NormalizedNodeDataInput.newDataInput(in);
+ final var rootPath = reader.readYangInstanceIdentifier();
final byte type = reader.readByte();
- final DataTreeCandidateNode rootNode;
- switch (type) {
- case APPEARED:
- rootNode = ModifiedDataTreeCandidateNode.create(ModificationType.APPEARED,
- readChildren(reader, receiver));
- break;
- case DELETE:
- rootNode = DeletedDataTreeCandidateNode.create();
- break;
- case DISAPPEARED:
- rootNode = ModifiedDataTreeCandidateNode.create(ModificationType.DISAPPEARED,
- readChildren(reader, receiver));
- break;
- case SUBTREE_MODIFIED:
- rootNode = ModifiedDataTreeCandidateNode.create(ModificationType.SUBTREE_MODIFIED,
- readChildren(reader, receiver));
- break;
- case WRITE:
- rootNode = DataTreeCandidateNodes.written(reader.readNormalizedNode(receiver));
- break;
- case UNMODIFIED:
- rootNode = AbstractDataTreeCandidateNode.createUnmodified();
- break;
- default:
- throw new IllegalArgumentException("Unhandled node type " + type);
- }
-
+ final DataTreeCandidateNode rootNode = switch (type) {
+ case APPEARED -> ModifiedDataTreeCandidateNode.create(ModificationType.APPEARED,
+ readChildren(reader, receiver));
+ case DELETE -> DeletedDataTreeCandidateNode.create();
+ case DISAPPEARED -> ModifiedDataTreeCandidateNode.create(ModificationType.DISAPPEARED,
+ readChildren(reader, receiver));
+ case SUBTREE_MODIFIED -> ModifiedDataTreeCandidateNode.create(ModificationType.SUBTREE_MODIFIED,
+ readChildren(reader, receiver));
+ case WRITE -> DataTreeCandidateNodes.written(reader.readNormalizedNode(receiver));
+ case UNMODIFIED -> AbstractDataTreeCandidateNode.createUnmodified();
+ default -> throw new IllegalArgumentException("Unhandled node type " + type);
+ };
return new DataTreeCandidateWithVersion(DataTreeCandidates.newDataTreeCandidate(rootPath, rootNode),
reader.getVersion());
}
private static void writeChildren(final NormalizedNodeDataOutput out,
final Collection<DataTreeCandidateNode> children) throws IOException {
out.writeInt(children.size());
- for (DataTreeCandidateNode child : children) {
+ for (var child : children) {
writeNode(out, child);
}
}
private static void writeNode(final NormalizedNodeDataOutput out, final DataTreeCandidateNode node)
throws IOException {
- switch (node.getModificationType()) {
- case APPEARED:
+ switch (node.modificationType()) {
+ case APPEARED -> {
out.writeByte(APPEARED);
- out.writePathArgument(node.getIdentifier());
- writeChildren(out, node.getChildNodes());
- break;
- case DELETE:
+ out.writePathArgument(node.name());
+ writeChildren(out, node.childNodes());
+ }
+ case DELETE -> {
out.writeByte(DELETE);
- out.writePathArgument(node.getIdentifier());
- break;
- case DISAPPEARED:
+ out.writePathArgument(node.name());
+ }
+ case DISAPPEARED -> {
out.writeByte(DISAPPEARED);
- out.writePathArgument(node.getIdentifier());
- writeChildren(out, node.getChildNodes());
- break;
- case SUBTREE_MODIFIED:
+ out.writePathArgument(node.name());
+ writeChildren(out, node.childNodes());
+ }
+ case SUBTREE_MODIFIED -> {
out.writeByte(SUBTREE_MODIFIED);
- out.writePathArgument(node.getIdentifier());
- writeChildren(out, node.getChildNodes());
- break;
- case WRITE:
+ out.writePathArgument(node.name());
+ writeChildren(out, node.childNodes());
+ }
+ case WRITE -> {
out.writeByte(WRITE);
- out.writeNormalizedNode(node.getDataAfter().get());
- break;
- case UNMODIFIED:
- out.writeByte(UNMODIFIED);
- break;
- default:
- throwUnhandledNodeType(node);
+ out.writeNormalizedNode(node.getDataAfter());
+ }
+ case UNMODIFIED -> out.writeByte(UNMODIFIED);
+ default -> throwUnhandledNodeType(node);
}
}
@VisibleForTesting
public static void writeDataTreeCandidate(final DataOutput out, final PayloadVersion version,
final DataTreeCandidate candidate) throws IOException {
- try (NormalizedNodeDataOutput writer = version.getStreamVersion().newDataOutput(out)) {
+ try (var writer = version.getStreamVersion().newDataOutput(out)) {
writer.writeYangInstanceIdentifier(candidate.getRootPath());
- final DataTreeCandidateNode node = candidate.getRootNode();
- switch (node.getModificationType()) {
- case APPEARED:
+ final var node = candidate.getRootNode();
+ switch (node.modificationType()) {
+ case APPEARED -> {
writer.writeByte(APPEARED);
- writeChildren(writer, node.getChildNodes());
- break;
- case DELETE:
- writer.writeByte(DELETE);
- break;
- case DISAPPEARED:
+ writeChildren(writer, node.childNodes());
+ }
+ case DELETE -> writer.writeByte(DELETE);
+ case DISAPPEARED -> {
writer.writeByte(DISAPPEARED);
- writeChildren(writer, node.getChildNodes());
- break;
- case SUBTREE_MODIFIED:
+ writeChildren(writer, node.childNodes());
+ }
+ case SUBTREE_MODIFIED -> {
writer.writeByte(SUBTREE_MODIFIED);
- writeChildren(writer, node.getChildNodes());
- break;
- case UNMODIFIED:
- writer.writeByte(UNMODIFIED);
- break;
- case WRITE:
+ writeChildren(writer, node.childNodes());
+ }
+ case UNMODIFIED -> writer.writeByte(UNMODIFIED);
+ case WRITE -> {
writer.writeByte(WRITE);
- writer.writeNormalizedNode(node.getDataAfter().get());
- break;
- default:
- throwUnhandledNodeType(node);
+ writer.writeNormalizedNode(node.getDataAfter());
+ }
+ default -> throwUnhandledNodeType(node);
}
}
}
}
private static void throwUnhandledNodeType(final DataTreeCandidateNode node) {
- throw new IllegalArgumentException("Unhandled node type " + node.getModificationType());
+ throw new IllegalArgumentException("Unhandled node type " + node.modificationType());
}
}
*/
package org.opendaylight.controller.cluster.datastore.persisted;
-import static com.google.common.base.Verify.verifyNotNull;
import static java.util.Objects.requireNonNull;
import com.google.common.collect.ImmutableList;
-import java.io.Externalizable;
-import java.io.IOException;
-import java.io.ObjectInput;
-import java.io.ObjectOutput;
import java.io.Serializable;
-import java.util.ArrayList;
import java.util.List;
import org.eclipse.jdt.annotation.NonNull;
import org.eclipse.jdt.annotation.Nullable;
* @author Thomas Pantelis
*/
public final class DatastoreSnapshot implements Serializable {
- interface SerialForm extends Externalizable {
-
- DatastoreSnapshot datastoreSnapshot();
-
- Object readResolve();
-
- void resolveTo(@NonNull DatastoreSnapshot newDatastoreSnapshot);
-
- @Override
- default void readExternal(final ObjectInput in) throws IOException, ClassNotFoundException {
- final var type = (String)in.readObject();
- final var snapshot = (ShardManagerSnapshot) in.readObject();
-
- final int size = in.readInt();
- var localShardSnapshots = new ArrayList<ShardSnapshot>(size);
- for (int i = 0; i < size; i++) {
- localShardSnapshots.add((ShardSnapshot) in.readObject());
- }
-
- resolveTo(new DatastoreSnapshot(type, snapshot, localShardSnapshots));
- }
-
- @Override
- default void writeExternal(final ObjectOutput out) throws IOException {
- final var datastoreSnapshot = datastoreSnapshot();
- out.writeObject(datastoreSnapshot.type);
- out.writeObject(datastoreSnapshot.shardManagerSnapshot);
-
- out.writeInt(datastoreSnapshot.shardSnapshots.size());
- for (ShardSnapshot shardSnapshot: datastoreSnapshot.shardSnapshots) {
- out.writeObject(shardSnapshot);
- }
- }
- }
-
- private static final class Proxy implements SerialForm {
- private static final long serialVersionUID = 1L;
-
- private DatastoreSnapshot datastoreSnapshot;
-
- // checkstyle flags the public modifier as redundant which really doesn't make sense since it clearly isn't
- // redundant. It is explicitly needed for Java serialization to be able to create instances via reflection.
- @SuppressWarnings("checkstyle:RedundantModifier")
- public Proxy() {
- // For Externalizable
- }
-
- Proxy(final DatastoreSnapshot datastoreSnapshot) {
- this.datastoreSnapshot = requireNonNull(datastoreSnapshot);
- }
-
- @Override
- public DatastoreSnapshot datastoreSnapshot() {
- return datastoreSnapshot;
- }
-
- @Override
- public void resolveTo(final DatastoreSnapshot newDatastoreSnapshot) {
- datastoreSnapshot = requireNonNull(newDatastoreSnapshot);
- }
-
- @Override
- public Object readResolve() {
- return verifyNotNull(datastoreSnapshot);
- }
- }
-
+ @java.io.Serial
private static final long serialVersionUID = 1L;
private final @NonNull String type;
return shardSnapshots;
}
+ @java.io.Serial
private Object writeReplace() {
- return new Proxy(this);
+ return new DS(this);
}
public static final class ShardSnapshot implements Serializable {
- interface SerialForm extends Externalizable {
-
- ShardSnapshot shardSnapshot();
-
- Object readResolve();
-
- void resolveTo(String name, Snapshot snapshot);
-
- @Override
- default void writeExternal(final ObjectOutput out) throws IOException {
- final var shardSnapshot = shardSnapshot();
- out.writeObject(shardSnapshot.name);
- out.writeObject(shardSnapshot.snapshot);
- }
-
- @Override
- default void readExternal(final ObjectInput in) throws IOException, ClassNotFoundException {
- resolveTo((String) in.readObject(), (Snapshot) in.readObject());
- }
- }
-
- private static final class Proxy implements SerialForm {
- private static final long serialVersionUID = 1L;
-
- private ShardSnapshot shardSnapshot;
-
- // checkstyle flags the public modifier as redundant which really doesn't make sense since it clearly isn't
- // redundant. It is explicitly needed for Java serialization to be able to create instances via reflection.
- @SuppressWarnings("checkstyle:RedundantModifier")
- public Proxy() {
- // For Externalizable
- }
-
- Proxy(final ShardSnapshot shardSnapshot) {
- this.shardSnapshot = shardSnapshot;
- }
-
- @Override
- public ShardSnapshot shardSnapshot() {
- return shardSnapshot;
- }
-
- @Override
- public void resolveTo(final String name, final Snapshot snapshot) {
- shardSnapshot = new ShardSnapshot(name, snapshot);
- }
-
- @Override
- public Object readResolve() {
- return verifyNotNull(shardSnapshot);
- }
- }
-
+ @java.io.Serial
private static final long serialVersionUID = 1L;
private final @NonNull String name;
return snapshot;
}
+ @java.io.Serial
private Object writeReplace() {
- return new Proxy(this);
+ return new DSS(this);
}
}
}
package org.opendaylight.controller.cluster.datastore.persisted;
import java.util.Collection;
-import java.util.Optional;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
import org.opendaylight.yangtools.yang.data.tree.api.DataTreeCandidateNode;
static DataTreeCandidateNode create() {
return new DeletedDataTreeCandidateNode() {
@Override
- public PathArgument getIdentifier() {
+ public PathArgument name() {
throw new UnsupportedOperationException("Root node does not have an identifier");
}
};
static DataTreeCandidateNode create(final PathArgument identifier) {
return new DeletedDataTreeCandidateNode() {
@Override
- public PathArgument getIdentifier() {
+ public PathArgument name() {
return identifier;
}
};
}
@Override
- public final Optional<NormalizedNode> getDataAfter() {
- return Optional.empty();
+ public final NormalizedNode dataAfter() {
+ return null;
}
@Override
- public final Collection<DataTreeCandidateNode> getChildNodes() {
- // We would require the before-image to reconstruct the list of nodes which
- // were deleted.
+ public final Collection<DataTreeCandidateNode> childNodes() {
+ // We would require the before-image to reconstruct the list of nodes which were deleted.
throw new UnsupportedOperationException("Children not available after serialization");
}
}
import com.google.common.io.ByteArrayDataOutput;
import com.google.common.io.ByteStreams;
-import java.io.DataInput;
import java.io.IOException;
import org.opendaylight.controller.cluster.access.concepts.ClientIdentifier;
-import org.opendaylight.controller.cluster.raft.persisted.LegacySerializable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-public sealed class DisableTrackingPayload extends AbstractIdentifiablePayload<ClientIdentifier> {
- @Deprecated(since = "7.0.0", forRemoval = true)
- private static final class Magnesium extends DisableTrackingPayload implements LegacySerializable {
- @java.io.Serial
- private static final long serialVersionUID = 1L;
-
- Magnesium(final ClientIdentifier clientId, final byte[] serialized) {
- super(clientId, serialized);
- }
- }
-
- @Deprecated(since = "7.0.0", forRemoval = true)
- private static final class Proxy extends AbstractProxy<ClientIdentifier> {
- @java.io.Serial
- private static final long serialVersionUID = -5490519942445085251L;
-
- @SuppressWarnings("checkstyle:RedundantModifier")
- public Proxy() {
- // For Externalizable
- }
-
- @Override
- protected ClientIdentifier readIdentifier(final DataInput in) throws IOException {
- return ClientIdentifier.readFrom(in);
- }
-
- @Override
- protected DisableTrackingPayload createObject(final ClientIdentifier identifier,
- final byte[] serialized) {
- return new Magnesium(identifier, serialized);
- }
- }
-
+public final class DisableTrackingPayload extends AbstractIdentifiablePayload<ClientIdentifier> {
private static final Logger LOG = LoggerFactory.getLogger(DisableTrackingPayload.class);
@java.io.Serial
private static final long serialVersionUID = 1L;
import org.eclipse.jdt.annotation.NonNull;
import org.opendaylight.controller.cluster.access.concepts.ClientIdentifier;
import org.opendaylight.controller.cluster.datastore.utils.ImmutableUnsignedLongSet;
-import org.opendaylight.yangtools.concepts.Identifiable;
import org.opendaylight.yangtools.concepts.WritableObject;
-public final class FrontendClientMetadata implements Identifiable<ClientIdentifier>, WritableObject {
+public final class FrontendClientMetadata implements WritableObject {
private final @NonNull ImmutableList<FrontendHistoryMetadata> currentHistories;
private final @NonNull ImmutableUnsignedLongSet purgedHistories;
- private final @NonNull ClientIdentifier identifier;
+ private final @NonNull ClientIdentifier clientId;
- public FrontendClientMetadata(final ClientIdentifier identifier, final ImmutableUnsignedLongSet purgedHistories,
+ public FrontendClientMetadata(final ClientIdentifier clientId, final ImmutableUnsignedLongSet purgedHistories,
final Collection<FrontendHistoryMetadata> currentHistories) {
- this.identifier = requireNonNull(identifier);
+ this.clientId = requireNonNull(clientId);
this.purgedHistories = requireNonNull(purgedHistories);
this.currentHistories = ImmutableList.copyOf(currentHistories);
}
+ public ClientIdentifier clientId() {
+ return clientId;
+ }
+
public ImmutableList<FrontendHistoryMetadata> getCurrentHistories() {
return currentHistories;
}
return purgedHistories;
}
- @Override
- public ClientIdentifier getIdentifier() {
- return identifier;
- }
-
@Override
public void writeTo(final DataOutput out) throws IOException {
- identifier.writeTo(out);
+ clientId.writeTo(out);
purgedHistories.writeTo(out);
out.writeInt(currentHistories.size());
}
public static FrontendClientMetadata readFrom(final DataInput in) throws IOException {
- final ClientIdentifier id = ClientIdentifier.readFrom(in);
+ final var clientId = ClientIdentifier.readFrom(in);
final var purgedHistories = ImmutableUnsignedLongSet.readFrom(in);
final int currentSize = in.readInt();
currentBuilder.add(FrontendHistoryMetadata.readFrom(in));
}
- return new FrontendClientMetadata(id, purgedHistories, currentBuilder.build());
+ return new FrontendClientMetadata(clientId, purgedHistories, currentBuilder.build());
}
@Override
public String toString() {
- return MoreObjects.toStringHelper(FrontendClientMetadata.class).add("identifer", identifier)
- .add("current", currentHistories).add("purged", purgedHistories).toString();
+ return MoreObjects.toStringHelper(FrontendClientMetadata.class)
+ .add("clientId", clientId).add("current", currentHistories).add("purged", purgedHistories).toString();
}
}
import com.google.common.collect.ImmutableList;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import java.io.Externalizable;
-import java.io.IOException;
-import java.io.ObjectInput;
-import java.io.ObjectOutput;
-import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
-public final class FrontendShardDataTreeSnapshotMetadata extends
- ShardDataTreeSnapshotMetadata<FrontendShardDataTreeSnapshotMetadata> {
-
- private static final class Proxy implements Externalizable {
- private static final long serialVersionUID = 1L;
-
- private List<FrontendClientMetadata> clients;
-
- // checkstyle flags the public modifier as redundant which really doesn't make sense since it clearly isn't
- // redundant. It is explicitly needed for Java serialization to be able to create instances via reflection.
- @SuppressWarnings("checkstyle:RedundantModifier")
- public Proxy() {
- // For Externalizable
- }
-
- Proxy(final FrontendShardDataTreeSnapshotMetadata metadata) {
- this.clients = metadata.getClients();
- }
-
- @Override
- public void writeExternal(final ObjectOutput out) throws IOException {
- out.writeInt(clients.size());
- for (final FrontendClientMetadata c : clients) {
- c.writeTo(out);
- }
- }
-
- @Override
- public void readExternal(final ObjectInput in) throws IOException {
- final int size = in.readInt();
- final List<FrontendClientMetadata> readedClients = new ArrayList<>(size);
- for (int i = 0; i < size ; ++i) {
- readedClients.add(FrontendClientMetadata.readFrom(in));
- }
- this.clients = ImmutableList.copyOf(readedClients);
- }
-
- private Object readResolve() {
- return new FrontendShardDataTreeSnapshotMetadata(clients);
- }
- }
-
+public final class FrontendShardDataTreeSnapshotMetadata
+ extends ShardDataTreeSnapshotMetadata<FrontendShardDataTreeSnapshotMetadata> {
+ @java.io.Serial
private static final long serialVersionUID = 1L;
@SuppressFBWarnings(value = "SE_BAD_FIELD", justification = "This field is not Serializable but this class "
@Override
protected Externalizable externalizableProxy() {
- return new Proxy(this);
+ return new FM(this);
}
@Override
@Override
public String toString() {
- return MoreObjects.toStringHelper(FrontendShardDataTreeSnapshotMetadata.class).add("clients", clients)
- .toString();
+ return MoreObjects.toStringHelper(FrontendShardDataTreeSnapshotMetadata.class)
+ .add("clients", clients)
+ .toString();
}
}
*/
package org.opendaylight.controller.cluster.datastore.persisted;
-import static com.google.common.base.Preconditions.checkArgument;
import static java.util.Objects.requireNonNull;
import com.google.common.annotations.Beta;
import com.google.common.base.MoreObjects;
import com.google.common.collect.ImmutableMap;
-import com.google.common.collect.ImmutableMap.Builder;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
-import java.io.Externalizable;
-import java.io.IOException;
-import java.io.ObjectInput;
-import java.io.ObjectOutput;
import java.io.Serializable;
-import java.io.StreamCorruptedException;
import java.util.Map;
import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
-import org.opendaylight.yangtools.yang.data.codec.binfmt.NormalizedNodeDataInput;
-import org.opendaylight.yangtools.yang.data.codec.binfmt.NormalizedNodeDataOutput;
-import org.opendaylight.yangtools.yang.data.codec.binfmt.NormalizedNodeStreamVersion;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
/**
* An {@link AbstractVersionedShardDataTreeSnapshot} which contains additional metadata.
@Beta
public final class MetadataShardDataTreeSnapshot extends AbstractVersionedShardDataTreeSnapshot
implements Serializable {
- private static final class Proxy implements Externalizable {
- private static final long serialVersionUID = 1L;
- private static final Logger LOG = LoggerFactory.getLogger(MetadataShardDataTreeSnapshot.class);
-
- private Map<Class<? extends ShardDataTreeSnapshotMetadata<?>>, ShardDataTreeSnapshotMetadata<?>> metadata;
- private NormalizedNodeStreamVersion version;
- private NormalizedNode rootNode;
-
- // checkstyle flags the public modifier as redundant which really doesn't make sense since it clearly isn't
- // redundant. It is explicitly needed for Java serialization to be able to create instances via reflection.
- @SuppressWarnings("checkstyle:RedundantModifier")
- public Proxy() {
- // For Externalizable
- }
-
- Proxy(final MetadataShardDataTreeSnapshot snapshot) {
- this.rootNode = snapshot.getRootNode().get();
- this.metadata = snapshot.getMetadata();
- this.version = snapshot.version().getStreamVersion();
- }
-
- @Override
- public void writeExternal(final ObjectOutput out) throws IOException {
- out.writeInt(metadata.size());
- for (ShardDataTreeSnapshotMetadata<?> m : metadata.values()) {
- out.writeObject(m);
- }
- out.writeBoolean(true);
- try (NormalizedNodeDataOutput stream = version.newDataOutput(out)) {
- stream.writeNormalizedNode(rootNode);
- }
- }
-
- @Override
- public void readExternal(final ObjectInput in) throws IOException, ClassNotFoundException {
- final int metaSize = in.readInt();
- checkArgument(metaSize >= 0, "Invalid negative metadata map length %s", metaSize);
-
- // Default pre-allocate is 4, which should be fine
- final Builder<Class<? extends ShardDataTreeSnapshotMetadata<?>>, ShardDataTreeSnapshotMetadata<?>>
- metaBuilder = ImmutableMap.builder();
- for (int i = 0; i < metaSize; ++i) {
- final ShardDataTreeSnapshotMetadata<?> m = (ShardDataTreeSnapshotMetadata<?>) in.readObject();
- if (m != null) {
- metaBuilder.put(m.getType(), m);
- } else {
- LOG.warn("Skipping null metadata");
- }
- }
-
- metadata = metaBuilder.build();
- final boolean present = in.readBoolean();
- if (!present) {
- throw new StreamCorruptedException("Unexpected missing root node");
- }
-
- final NormalizedNodeDataInput stream = NormalizedNodeDataInput.newDataInput(in);
- version = stream.getVersion();
- rootNode = stream.readNormalizedNode();
- }
-
- private Object readResolve() {
- return new MetadataShardDataTreeSnapshot(rootNode, metadata);
- }
- }
-
+ @java.io.Serial
private static final long serialVersionUID = 1L;
@SuppressFBWarnings(value = "SE_BAD_FIELD", justification = "This field is not Serializable but this class "
@Override
PayloadVersion version() {
- return PayloadVersion.MAGNESIUM;
+ return PayloadVersion.POTASSIUM;
}
+ @java.io.Serial
private Object writeReplace() {
- return new Proxy(this);
+ return new MS(this);
}
@Override
import static java.util.Objects.requireNonNull;
import java.util.Collection;
-import java.util.Optional;
+import org.eclipse.jdt.annotation.NonNull;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
import org.opendaylight.yangtools.yang.data.tree.api.DataTreeCandidateNode;
* one of its children.
*/
abstract class ModifiedDataTreeCandidateNode extends AbstractDataTreeCandidateNode {
- private final Collection<DataTreeCandidateNode> children;
+ private final @NonNull Collection<DataTreeCandidateNode> children;
private ModifiedDataTreeCandidateNode(final ModificationType type,
final Collection<DataTreeCandidateNode> children) {
static DataTreeCandidateNode create(final ModificationType type, final Collection<DataTreeCandidateNode> children) {
return new ModifiedDataTreeCandidateNode(type, children) {
@Override
- public PathArgument getIdentifier() {
+ public PathArgument name() {
throw new UnsupportedOperationException("Root node does not have an identifier");
}
};
final Collection<DataTreeCandidateNode> children) {
return new ModifiedDataTreeCandidateNode(type, children) {
@Override
- public PathArgument getIdentifier() {
+ public PathArgument name() {
return identifier;
}
};
}
@Override
- public final Optional<NormalizedNode> getDataAfter() {
+ public final NormalizedNode dataAfter() {
throw new UnsupportedOperationException("After-image not available after serialization");
}
@Override
- public final Collection<DataTreeCandidateNode> getChildNodes() {
+ public final Collection<DataTreeCandidateNode> childNodes() {
return children;
}
}
* participant instance should oppose RAFT candidates which produce persistence of an unsupported version. If a follower
* encounters an unsupported version it must not become fully-operational, as it does not have an accurate view
* of shard state.
- *
- * @author Robert Varga
*/
@Beta
public enum PayloadVersion implements WritableObject {
},
/**
- * ABI version as shipped in Sodium SR1 Simultaneous Release. QName-bearing messages are using
- * {@link NormalizedNodeStreamVersion#SODIUM_SR1}, which improves encoding.
- */
- @Deprecated(since = "7.0.0", forRemoval = true)
- SODIUM_SR1(7) {
- @Override
- public NormalizedNodeStreamVersion getStreamVersion() {
- return NormalizedNodeStreamVersion.SODIUM_SR1;
- }
- },
-
- /**
- * Revised payload version. Payloads remain the same as {@link #SODIUM_SR1}, but messages bearing QNames in any
- * shape are using {@link NormalizedNodeStreamVersion#MAGNESIUM}, which improves encoding.
+ * ABI version shipped enabled {@code 2022.09 Chlorine SR2}. This version revises the serialization format of
+ * payloads proxies to reduce their size. Otherwise this format is equivalent to {@code #MAGNESIUM}.
+ *
+ * @deprecated Use {@link #POTASSIUM} instead.
*/
- @Deprecated(since = "7.0.0", forRemoval = true)
- MAGNESIUM(8) {
+ @Deprecated(since = "8.0.0", forRemoval = true)
+ CHLORINE_SR2(9) {
@Override
public NormalizedNodeStreamVersion getStreamVersion() {
return NormalizedNodeStreamVersion.MAGNESIUM;
},
/**
- * ABI version shipped enabled {@code 2022.09 Chlorine SR2}. This version revises the serialization format of
- * payloads proxies to reduce their size. Otherwise this format is equivalent to {@link #MAGNESIUM}.
+ * ABI version shipped enabled {@code 2023.09 Potassium}. This version removes Augmentation identifier and nodes.
+ * Otherwise this format is equivalent to {@link #CHLORINE_SR2}.
*/
- CHLORINE_SR2(9) {
+ POTASSIUM(10) {
@Override
public NormalizedNodeStreamVersion getStreamVersion() {
- return NormalizedNodeStreamVersion.MAGNESIUM;
+ return NormalizedNodeStreamVersion.POTASSIUM;
}
},
* @return Current {@link PayloadVersion}
*/
public static @NonNull PayloadVersion current() {
- return CHLORINE_SR2;
+ return POTASSIUM;
}
/**
public static @NonNull PayloadVersion valueOf(final short version)
throws FutureVersionException, PastVersionException {
return switch (Short.toUnsignedInt(version)) {
- case 0, 1, 2, 3, 4, 5, 6 -> throw new PastVersionException(version, SODIUM_SR1);
- case 7 -> SODIUM_SR1;
- case 8 -> MAGNESIUM;
+ case 0, 1, 2, 3, 4, 5, 6, 7, 8 -> throw new PastVersionException(version, CHLORINE_SR2);
case 9 -> CHLORINE_SR2;
+ case 10 -> POTASSIUM;
default -> throw new FutureVersionException(version, CHLORINE_SR2);
};
}
import com.google.common.io.ByteArrayDataOutput;
import com.google.common.io.ByteStreams;
-import java.io.DataInput;
import java.io.IOException;
import org.opendaylight.controller.cluster.access.concepts.LocalHistoryIdentifier;
-import org.opendaylight.controller.cluster.raft.persisted.LegacySerializable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
*
* @author Robert Varga
*/
-public sealed class PurgeLocalHistoryPayload extends AbstractIdentifiablePayload<LocalHistoryIdentifier> {
- @Deprecated(since = "7.0.0", forRemoval = true)
- private static final class Magnesium extends PurgeLocalHistoryPayload implements LegacySerializable {
- @java.io.Serial
- private static final long serialVersionUID = 1L;
-
- Magnesium(final LocalHistoryIdentifier historyId, final byte[] serialized) {
- super(historyId, serialized);
- }
- }
-
- @Deprecated(since = "7.0.0", forRemoval = true)
- private static final class Proxy extends AbstractProxy<LocalHistoryIdentifier> {
- @java.io.Serial
- private static final long serialVersionUID = 1L;
-
- // checkstyle flags the public modifier as redundant which really doesn't make sense since it clearly isn't
- // redundant. It is explicitly needed for Java serialization to be able to create instances via reflection.
- @SuppressWarnings("checkstyle:RedundantModifier")
- public Proxy() {
- // For Externalizable
- }
-
- @Override
- protected LocalHistoryIdentifier readIdentifier(final DataInput in) throws IOException {
- return LocalHistoryIdentifier.readFrom(in);
- }
-
- @Override
- protected PurgeLocalHistoryPayload createObject(final LocalHistoryIdentifier identifier,
- final byte[] serialized) {
- return new Magnesium(identifier, serialized);
- }
- }
-
+public final class PurgeLocalHistoryPayload extends AbstractIdentifiablePayload<LocalHistoryIdentifier> {
private static final Logger LOG = LoggerFactory.getLogger(PurgeLocalHistoryPayload.class);
@java.io.Serial
private static final long serialVersionUID = 1L;
import com.google.common.io.ByteArrayDataOutput;
import com.google.common.io.ByteStreams;
-import java.io.DataInput;
import java.io.IOException;
import org.opendaylight.controller.cluster.access.concepts.TransactionIdentifier;
-import org.opendaylight.controller.cluster.raft.persisted.LegacySerializable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
*
* @author Robert Varga
*/
-public sealed class PurgeTransactionPayload extends AbstractIdentifiablePayload<TransactionIdentifier> {
- @Deprecated(since = "7.0.0", forRemoval = true)
- private static final class Magnesium extends PurgeTransactionPayload implements LegacySerializable {
- @java.io.Serial
- private static final long serialVersionUID = 1L;
-
- Magnesium(final TransactionIdentifier transactionId, final byte[] serialized) {
- super(transactionId, serialized);
- }
- }
-
- @Deprecated(since = "7.0.0", forRemoval = true)
- private static final class Proxy extends AbstractProxy<TransactionIdentifier> {
- @java.io.Serial
- private static final long serialVersionUID = 1L;
-
- // checkstyle flags the public modifier as redundant which really doesn't make sense since it clearly isn't
- // redundant. It is explicitly needed for Java serialization to be able to create instances via reflection.
- @SuppressWarnings("checkstyle:RedundantModifier")
- public Proxy() {
- // For Externalizable
- }
-
- @Override
- protected TransactionIdentifier readIdentifier(final DataInput in) throws IOException {
- return TransactionIdentifier.readFrom(in);
- }
-
- @Override
- protected PurgeTransactionPayload createObject(final TransactionIdentifier identifier,
- final byte[] serialized) {
- return new Magnesium(identifier, serialized);
- }
- }
-
+public final class PurgeTransactionPayload extends AbstractIdentifiablePayload<TransactionIdentifier> {
private static final Logger LOG = LoggerFactory.getLogger(PurgeTransactionPayload.class);
@java.io.Serial
private static final long serialVersionUID = 1L;
import static com.google.common.base.Verify.verifyNotNull;
import static java.util.Objects.requireNonNull;
-import java.util.List;
+import java.io.Externalizable;
+import java.io.IOException;
+import java.io.ObjectInput;
+import java.io.ObjectOutput;
+import java.util.ArrayList;
/**
* Serialization proxy for {@link ShardManagerSnapshot}.
*/
-final class SM implements ShardManagerSnapshot.SerializedForm {
+final class SM implements Externalizable {
@java.io.Serial
private static final long serialVersionUID = 1L;
}
@Override
- public List<String> shardNames() {
- return snapshot.getShardList();
+ public void readExternal(final ObjectInput in) throws IOException, ClassNotFoundException {
+ final int size = in.readInt();
+ final var shardList = new ArrayList<String>(size);
+ for (int i = 0; i < size; i++) {
+ shardList.add((String) in.readObject());
+ }
+ snapshot = new ShardManagerSnapshot(shardList);
}
@Override
- public void resolveTo(final ShardManagerSnapshot newSnapshot) {
- snapshot = requireNonNull(newSnapshot);
+ public void writeExternal(final ObjectOutput out) throws IOException {
+ final var shardList = snapshot.getShardList();
+ out.writeInt(shardList.size());
+ for (var shardName : shardList) {
+ out.writeObject(shardName);
+ }
}
- @Override
- public Object readResolve() {
+ @java.io.Serial
+ private Object readResolve() {
return verifyNotNull(snapshot);
}
}
import static com.google.common.base.Verify.verifyNotNull;
import static java.util.Objects.requireNonNull;
+import java.io.Externalizable;
+import java.io.IOException;
+import java.io.ObjectInput;
+import java.io.ObjectOutput;
+
/**
* Serialization proxy for {@link ShardSnapshotState}.
*/
-final class SS implements ShardSnapshotState.SerialForm {
+final class SS implements Externalizable {
@java.io.Serial
private static final long serialVersionUID = 1L;
}
@Override
- public ShardSnapshotState snapshotState() {
- return snapshotState;
+ public void readExternal(final ObjectInput in) throws IOException {
+ snapshotState = ShardDataTreeSnapshot.deserialize(in);
}
@Override
- public void resolveTo(final ShardSnapshotState newSnapshotState) {
- snapshotState = requireNonNull(newSnapshotState);
+ public void writeExternal(final ObjectOutput out) throws IOException {
+ snapshotState.getSnapshot().serialize(out);
}
- @Override
- public Object readResolve() {
+ @java.io.Serial
+ private Object readResolve() {
return verifyNotNull(snapshotState);
}
}
*/
package org.opendaylight.controller.cluster.datastore.persisted;
-import static java.util.Objects.requireNonNull;
-
import com.google.common.collect.ImmutableList;
-import java.io.Externalizable;
-import java.io.IOException;
-import java.io.ObjectInput;
-import java.io.ObjectOutput;
import java.io.Serializable;
-import java.util.ArrayList;
import java.util.List;
import org.eclipse.jdt.annotation.NonNull;
-import org.opendaylight.controller.cluster.raft.persisted.MigratedSerializable;
/**
* Represents the persisted snapshot state for the ShardManager.
*
* @author Thomas Pantelis
*/
-public sealed class ShardManagerSnapshot implements Serializable {
- interface SerializedForm extends Externalizable {
- /**
- * Return the serial form of this object contents, corresponding to {@link ShardManagerSnapshot#shardList}.
- *
- * @return List of shards names.
- */
- List<String> shardNames();
-
- /**
- * Resolve this proxy to an actual {@link ShardManagerSnapshot}. Implementations can rely on the object to be
- * set via {@link #resolveTo(ShardManagerSnapshot)}.
- *
- * @return A snapshot
- */
- Object readResolve();
-
- /**
- * Set this proxy to return {@code snapshot} on next {@link #readResolve()}.
- *
- * @param newSnapshot Snapshot to set
- */
- void resolveTo(@NonNull ShardManagerSnapshot newSnapshot);
-
- @Override
- default void readExternal(final ObjectInput in) throws IOException, ClassNotFoundException {
- final int size = in.readInt();
- final var shardList = new ArrayList<String>(size);
- for (int i = 0; i < size; i++) {
- shardList.add((String) in.readObject());
- }
- resolveTo(new ShardManagerSnapshot(shardList));
- }
-
- @Override
- default void writeExternal(final ObjectOutput out) throws IOException {
- final var shardList = shardNames();
- out.writeInt(shardList.size());
- for (var shardName : shardList) {
- out.writeObject(shardName);
- }
- }
- }
-
- @Deprecated(since = "7.0.0", forRemoval = true)
- private static final class Magnesium extends ShardManagerSnapshot implements MigratedSerializable {
- @java.io.Serial
- private static final long serialVersionUID = 1L;
-
- Magnesium(final List<String> shardList) {
- super(shardList);
- }
-
- @Override
- public boolean isMigrated() {
- return true;
- }
- }
-
- @Deprecated(since = "7.0.0", forRemoval = true)
- private static final class Proxy implements SerializedForm {
- @java.io.Serial
- private static final long serialVersionUID = 1L;
-
- private ShardManagerSnapshot snapshot = null;
-
- // checkstyle flags the public modifier as redundant which really doesn't make sense since it clearly isn't
- // redundant. It is explicitly needed for Java serialization to be able to create instances via reflection.
- @SuppressWarnings("checkstyle:RedundantModifier")
- public Proxy() {
- // For Externalizable
- }
-
- @Override
- public List<String> shardNames() {
- return snapshot.getShardList();
- }
-
- @Override
- public void resolveTo(final ShardManagerSnapshot newSnapshot) {
- snapshot = requireNonNull(newSnapshot);
- }
-
- @Override
- public Object readResolve() {
- return new Magnesium(snapshot.getShardList());
- }
- }
-
+public final class ShardManagerSnapshot implements Serializable {
@java.io.Serial
private static final long serialVersionUID = 1L;
this.shardList = ImmutableList.copyOf(shardList);
}
- public final List<String> getShardList() {
+ public List<String> getShardList() {
return shardList;
}
@java.io.Serial
- public final Object writeReplace() {
+ private Object writeReplace() {
return new SM(this);
}
@Override
- public final String toString() {
+ public String toString() {
return "ShardManagerSnapshot [ShardList = " + shardList + " ]";
}
}
*/
package org.opendaylight.controller.cluster.datastore.persisted;
-import static com.google.common.base.Verify.verifyNotNull;
import static java.util.Objects.requireNonNull;
import com.google.common.annotations.VisibleForTesting;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
-import java.io.Externalizable;
-import java.io.IOException;
-import java.io.ObjectInput;
-import java.io.ObjectOutput;
import org.eclipse.jdt.annotation.NonNull;
import org.opendaylight.controller.cluster.raft.persisted.Snapshot;
* @author Thomas Pantelis
*/
public final class ShardSnapshotState implements Snapshot.State {
- interface SerialForm extends Externalizable {
-
- ShardSnapshotState snapshotState();
-
- void resolveTo(@NonNull ShardSnapshotState newSnapshotState);
-
- Object readResolve();
-
- @Override
- default void readExternal(final ObjectInput in) throws IOException {
- resolveTo(ShardDataTreeSnapshot.deserialize(in));
- }
-
- @Override
- default void writeExternal(final ObjectOutput out) throws IOException {
- snapshotState().getSnapshot().serialize(out);
- }
- }
-
- @Deprecated(since = "7.0.0", forRemoval = true)
- private static final class Proxy implements SerialForm {
- @java.io.Serial
- private static final long serialVersionUID = 1L;
-
- private ShardSnapshotState snapshotState;
-
- // checkstyle flags the public modifier as redundant which really doesn't make sense since it clearly isn't
- // redundant. It is explicitly needed for Java serialization to be able to create instances via reflection.
- @SuppressWarnings("checkstyle:RedundantModifier")
- public Proxy() {
- // For Externalizable
- }
-
- @Override
- public ShardSnapshotState snapshotState() {
- return snapshotState;
- }
-
- @Override
- public void resolveTo(final ShardSnapshotState newSnapshotState) {
- snapshotState = requireNonNull(newSnapshotState);
- }
-
- @Override
- public Object readResolve() {
- return verifyNotNull(snapshotState);
- }
- }
-
@java.io.Serial
private static final long serialVersionUID = 1L;
*/
package org.opendaylight.controller.cluster.datastore.persisted;
-import static com.google.common.base.Verify.verifyNotNull;
import static java.util.Objects.requireNonNull;
import com.google.common.io.ByteStreams;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
-import java.io.DataInput;
import java.io.IOException;
import org.eclipse.jdt.annotation.NonNull;
import org.opendaylight.controller.cluster.access.concepts.LocalHistoryIdentifier;
import org.opendaylight.controller.cluster.datastore.utils.ImmutableUnsignedLongSet;
-import org.opendaylight.controller.cluster.raft.persisted.LegacySerializable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
* for other purposes. It contains a {@link LocalHistoryIdentifier} and a list of transaction identifiers within that
* local history.
*/
-public sealed class SkipTransactionsPayload extends AbstractIdentifiablePayload<LocalHistoryIdentifier> {
- private static final class Magnesium extends SkipTransactionsPayload implements LegacySerializable {
- @java.io.Serial
- private static final long serialVersionUID = 1L;
-
- Magnesium(final LocalHistoryIdentifier historyId, final byte[] serialized,
- final ImmutableUnsignedLongSet transactionIds) {
- super(historyId, serialized, transactionIds);
- }
- }
-
- @Deprecated(since = "7.0.0", forRemoval = true)
- private static final class Proxy extends AbstractProxy<LocalHistoryIdentifier> {
- @java.io.Serial
- private static final long serialVersionUID = 1L;
-
- private ImmutableUnsignedLongSet transactionIds;
-
- // checkstyle flags the public modifier as redundant which really doesn't make sense since it clearly isn't
- // redundant. It is explicitly needed for Java serialization to be able to create instances via reflection.
- @SuppressWarnings("checkstyle:RedundantModifier")
- public Proxy() {
- // For Externalizable
- }
-
- @Override
- protected LocalHistoryIdentifier readIdentifier(final DataInput in) throws IOException {
- final var id = LocalHistoryIdentifier.readFrom(in);
- transactionIds = ImmutableUnsignedLongSet.readFrom(in);
- return id;
- }
-
- @Override
- protected SkipTransactionsPayload createObject(final LocalHistoryIdentifier identifier,
- final byte[] serialized) {
- return new Magnesium(identifier, serialized, verifyNotNull(transactionIds));
- }
- }
-
+public final class SkipTransactionsPayload extends AbstractIdentifiablePayload<LocalHistoryIdentifier> {
private static final Logger LOG = LoggerFactory.getLogger(SkipTransactionsPayload.class);
@java.io.Serial
private static final long serialVersionUID = 1L;
*/
package org.opendaylight.controller.cluster.datastore.shardmanager;
-import com.google.common.base.Verify;
+import static com.google.common.base.Verify.verifyNotNull;
+
import java.util.concurrent.atomic.AtomicReference;
+import org.eclipse.jdt.annotation.NonNull;
import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
-import org.opendaylight.yangtools.yang.model.api.EffectiveModelContextProvider;
-final class AtomicShardContextProvider extends AtomicReference<EffectiveModelContext>
- implements EffectiveModelContextProvider {
+final class AtomicShardContextProvider extends AtomicReference<EffectiveModelContext> {
+ @java.io.Serial
private static final long serialVersionUID = 1L;
- @Override
- public EffectiveModelContext getEffectiveModelContext() {
- return Verify.verifyNotNull(get());
+ @NonNull EffectiveModelContext modelContext() {
+ return verifyNotNull(get());
}
}
\ No newline at end of file
Props newProps() {
Props props = requireNonNull(builder).id(shardId).peerAddresses(initialPeerAddresses)
- .datastoreContext(datastoreContext).schemaContextProvider(schemaContextProvider).props();
+ .datastoreContext(datastoreContext).schemaContextProvider(schemaContextProvider::modelContext).props();
builder = null;
return props;
}
return shardId;
}
- void setLocalDataTree(final Optional<ReadOnlyDataTree> dataTree) {
- localShardDataTree = dataTree;
+ void setLocalDataTree(final ReadOnlyDataTree dataTree) {
+ localShardDataTree = Optional.ofNullable(dataTree);
}
Optional<ReadOnlyDataTree> getLocalShardDataTree() {
}
EffectiveModelContext getSchemaContext() {
- return schemaContextProvider.getEffectiveModelContext();
+ return schemaContextProvider.modelContext();
}
void setSchemaContext(final EffectiveModelContext schemaContext) {
*/
package org.opendaylight.controller.cluster.datastore.shardmanager;
-import static akka.pattern.Patterns.ask;
import static java.util.Objects.requireNonNull;
import akka.actor.ActorRef;
@VisibleForTesting
final ShardPeerAddressResolver peerAddressResolver;
- private EffectiveModelContext schemaContext;
+ private EffectiveModelContext modelContext;
private DatastoreSnapshot restoreFromSnapshot;
@Override
public void handleCommand(final Object message) throws Exception {
- if (message instanceof FindPrimary) {
- findPrimary((FindPrimary)message);
- } else if (message instanceof FindLocalShard) {
- findLocalShard((FindLocalShard) message);
- } else if (message instanceof UpdateSchemaContext) {
- updateSchemaContext(message);
- } else if (message instanceof ActorInitialized) {
- onActorInitialized(message);
- } else if (message instanceof ClusterEvent.MemberUp) {
- memberUp((ClusterEvent.MemberUp) message);
- } else if (message instanceof ClusterEvent.MemberWeaklyUp) {
- memberWeaklyUp((ClusterEvent.MemberWeaklyUp) message);
- } else if (message instanceof ClusterEvent.MemberExited) {
- memberExited((ClusterEvent.MemberExited) message);
- } else if (message instanceof ClusterEvent.MemberRemoved) {
- memberRemoved((ClusterEvent.MemberRemoved) message);
- } else if (message instanceof ClusterEvent.UnreachableMember) {
- memberUnreachable((ClusterEvent.UnreachableMember) message);
- } else if (message instanceof ClusterEvent.ReachableMember) {
- memberReachable((ClusterEvent.ReachableMember) message);
- } else if (message instanceof DatastoreContextFactory) {
- onDatastoreContextFactory((DatastoreContextFactory) message);
- } else if (message instanceof RoleChangeNotification) {
- onRoleChangeNotification((RoleChangeNotification) message);
- } else if (message instanceof FollowerInitialSyncUpStatus) {
- onFollowerInitialSyncStatus((FollowerInitialSyncUpStatus) message);
- } else if (message instanceof ShardNotInitializedTimeout) {
- onShardNotInitializedTimeout((ShardNotInitializedTimeout) message);
- } else if (message instanceof ShardLeaderStateChanged) {
- onLeaderStateChanged((ShardLeaderStateChanged) message);
- } else if (message instanceof SwitchShardBehavior) {
- onSwitchShardBehavior((SwitchShardBehavior) message);
- } else if (message instanceof CreateShard) {
- onCreateShard((CreateShard)message);
- } else if (message instanceof AddShardReplica) {
- onAddShardReplica((AddShardReplica) message);
- } else if (message instanceof ForwardedAddServerReply) {
- ForwardedAddServerReply msg = (ForwardedAddServerReply)message;
- onAddServerReply(msg.shardInfo, msg.addServerReply, getSender(), msg.leaderPath,
- msg.removeShardOnFailure);
- } else if (message instanceof ForwardedAddServerFailure) {
- ForwardedAddServerFailure msg = (ForwardedAddServerFailure)message;
+ if (message instanceof FindPrimary msg) {
+ findPrimary(msg);
+ } else if (message instanceof FindLocalShard msg) {
+ findLocalShard(msg);
+ } else if (message instanceof UpdateSchemaContext msg) {
+ updateSchemaContext(msg);
+ } else if (message instanceof ActorInitialized msg) {
+ onActorInitialized(msg);
+ } else if (message instanceof ClusterEvent.MemberUp msg) {
+ memberUp(msg);
+ } else if (message instanceof ClusterEvent.MemberWeaklyUp msg) {
+ memberWeaklyUp(msg);
+ } else if (message instanceof ClusterEvent.MemberExited msg) {
+ memberExited(msg);
+ } else if (message instanceof ClusterEvent.MemberRemoved msg) {
+ memberRemoved(msg);
+ } else if (message instanceof ClusterEvent.UnreachableMember msg) {
+ memberUnreachable(msg);
+ } else if (message instanceof ClusterEvent.ReachableMember msg) {
+ memberReachable(msg);
+ } else if (message instanceof DatastoreContextFactory msg) {
+ onDatastoreContextFactory(msg);
+ } else if (message instanceof RoleChangeNotification msg) {
+ onRoleChangeNotification(msg);
+ } else if (message instanceof FollowerInitialSyncUpStatus msg) {
+ onFollowerInitialSyncStatus(msg);
+ } else if (message instanceof ShardNotInitializedTimeout msg) {
+ onShardNotInitializedTimeout(msg);
+ } else if (message instanceof ShardLeaderStateChanged msg) {
+ onLeaderStateChanged(msg);
+ } else if (message instanceof SwitchShardBehavior msg) {
+ onSwitchShardBehavior(msg);
+ } else if (message instanceof CreateShard msg) {
+ onCreateShard(msg);
+ } else if (message instanceof AddShardReplica msg) {
+ onAddShardReplica(msg);
+ } else if (message instanceof ForwardedAddServerReply msg) {
+ onAddServerReply(msg.shardInfo, msg.addServerReply, getSender(), msg.leaderPath, msg.removeShardOnFailure);
+ } else if (message instanceof ForwardedAddServerFailure msg) {
onAddServerFailure(msg.shardName, msg.failureMessage, msg.failure, getSender(), msg.removeShardOnFailure);
- } else if (message instanceof RemoveShardReplica) {
- onRemoveShardReplica((RemoveShardReplica) message);
- } else if (message instanceof WrappedShardResponse) {
- onWrappedShardResponse((WrappedShardResponse) message);
- } else if (message instanceof GetSnapshot) {
- onGetSnapshot((GetSnapshot) message);
- } else if (message instanceof ServerRemoved) {
- onShardReplicaRemoved((ServerRemoved) message);
- } else if (message instanceof ChangeShardMembersVotingStatus) {
- onChangeShardServersVotingStatus((ChangeShardMembersVotingStatus) message);
- } else if (message instanceof FlipShardMembersVotingStatus) {
- onFlipShardMembersVotingStatus((FlipShardMembersVotingStatus) message);
- } else if (message instanceof SaveSnapshotSuccess) {
- onSaveSnapshotSuccess((SaveSnapshotSuccess) message);
- } else if (message instanceof SaveSnapshotFailure) {
- LOG.error("{}: SaveSnapshotFailure received for saving snapshot of shards", persistenceId(),
- ((SaveSnapshotFailure) message).cause());
+ } else if (message instanceof RemoveShardReplica msg) {
+ onRemoveShardReplica(msg);
+ } else if (message instanceof WrappedShardResponse msg) {
+ onWrappedShardResponse(msg);
+ } else if (message instanceof GetSnapshot msg) {
+ onGetSnapshot(msg);
+ } else if (message instanceof ServerRemoved msg) {
+ onShardReplicaRemoved(msg);
+ } else if (message instanceof ChangeShardMembersVotingStatus msg) {
+ onChangeShardServersVotingStatus(msg);
+ } else if (message instanceof FlipShardMembersVotingStatus msg) {
+ onFlipShardMembersVotingStatus(msg);
+ } else if (message instanceof SaveSnapshotSuccess msg) {
+ onSaveSnapshotSuccess(msg);
+ } else if (message instanceof SaveSnapshotFailure msg) {
+ LOG.error("{}: SaveSnapshotFailure received for saving snapshot of shards", persistenceId(), msg.cause());
} else if (message instanceof Shutdown) {
onShutDown();
} else if (message instanceof GetLocalShardIds) {
onGetLocalShardIds();
- } else if (message instanceof GetShardRole) {
- onGetShardRole((GetShardRole) message);
- } else if (message instanceof RunnableMessage) {
- ((RunnableMessage)message).run();
- } else if (message instanceof RegisterForShardAvailabilityChanges) {
- onRegisterForShardAvailabilityChanges((RegisterForShardAvailabilityChanges)message);
- } else if (message instanceof DeleteSnapshotsFailure) {
- LOG.warn("{}: Failed to delete prior snapshots", persistenceId(),
- ((DeleteSnapshotsFailure) message).cause());
+ } else if (message instanceof GetShardRole msg) {
+ onGetShardRole(msg);
+ } else if (message instanceof RunnableMessage msg) {
+ msg.run();
+ } else if (message instanceof RegisterForShardAvailabilityChanges msg) {
+ onRegisterForShardAvailabilityChanges(msg);
+ } else if (message instanceof DeleteSnapshotsFailure msg) {
+ LOG.warn("{}: Failed to delete prior snapshots", persistenceId(), msg.cause());
} else if (message instanceof DeleteSnapshotsSuccess) {
LOG.debug("{}: Successfully deleted prior snapshots", persistenceId());
} else if (message instanceof RegisterRoleChangeListenerReply) {
LOG.trace("{}: Received RegisterRoleChangeListenerReply", persistenceId());
- } else if (message instanceof ClusterEvent.MemberEvent) {
- LOG.trace("{}: Received other ClusterEvent.MemberEvent: {}", persistenceId(), message);
+ } else if (message instanceof ClusterEvent.MemberEvent msg) {
+ LOG.trace("{}: Received other ClusterEvent.MemberEvent: {}", persistenceId(), msg);
} else {
unknownMessage(message);
}
primaryPath, shardId);
Timeout removeServerTimeout = new Timeout(datastoreContext.getShardLeaderElectionTimeout().duration());
- Future<Object> futureObj = ask(getContext().actorSelection(primaryPath),
+ Future<Object> futureObj = Patterns.ask(getContext().actorSelection(primaryPath),
new RemoveServer(shardId.toString()), removeServerTimeout);
futureObj.onComplete(new OnComplete<>() {
info.setActiveMember(isActiveMember);
localShards.put(info.getShardName(), info);
- if (schemaContext != null) {
- info.setSchemaContext(schemaContext);
+ if (modelContext != null) {
+ info.setSchemaContext(modelContext);
info.setActor(newShardActor(info));
}
}
ShardInformation shardInformation = findShardInformation(leaderStateChanged.getMemberId());
if (shardInformation != null) {
- shardInformation.setLocalDataTree(leaderStateChanged.getLocalShardDataTree());
+ shardInformation.setLocalDataTree(leaderStateChanged.localShardDataTree());
shardInformation.setLeaderVersion(leaderStateChanged.getLeaderPayloadVersion());
if (shardInformation.setLeaderId(leaderStateChanged.getLeaderId())) {
primaryShardInfoCache.remove(shardInformation.getShardName());
return true;
}
- private void onActorInitialized(final Object message) {
- final ActorRef sender = getSender();
-
- if (sender == null) {
- // why is a non-actor sending this message? Just ignore.
- return;
- }
+ private void onActorInitialized(final ActorInitialized message) {
+ final var sender = message.actorRef();
String actorName = sender.path().name();
//find shard name from actor name; actor name is stringified shardId
protected void handleRecover(final Object message) throws Exception {
if (message instanceof RecoveryCompleted) {
onRecoveryCompleted();
- } else if (message instanceof SnapshotOffer) {
- applyShardManagerSnapshot((ShardManagerSnapshot)((SnapshotOffer) message).snapshot());
+ } else if (message instanceof SnapshotOffer msg) {
+ applyShardManagerSnapshot((ShardManagerSnapshot) msg.snapshot());
}
}
*
* @param message the message to send
*/
- private void updateSchemaContext(final Object message) {
- schemaContext = ((UpdateSchemaContext) message).getEffectiveModelContext();
+ private void updateSchemaContext(final UpdateSchemaContext message) {
+ modelContext = message.modelContext();
- LOG.debug("Got updated SchemaContext: # of modules {}", schemaContext.getModules().size());
+ LOG.debug("Got updated SchemaContext: # of modules {}", modelContext.getModules().size());
for (ShardInformation info : localShards.values()) {
- info.setSchemaContext(schemaContext);
+ info.setSchemaContext(modelContext);
if (info.getActor() == null) {
LOG.debug("Creating Shard {}", info.getShardId());
sendResponse(info, message.isWaitUntilReady(), true, () -> {
String primaryPath = info.getSerializedLeaderActor();
Object found = canReturnLocalShardState && info.isLeader()
- ? new LocalPrimaryShardFound(primaryPath, info.getLocalShardDataTree().get()) :
+ ? new LocalPrimaryShardFound(primaryPath, info.getLocalShardDataTree().orElseThrow()) :
new RemotePrimaryShardFound(primaryPath, info.getLeaderVersion());
LOG.debug("{}: Found primary for {}: {}", persistenceId(), shardName, found);
Timeout findPrimaryTimeout = new Timeout(datastoreContextFactory.getBaseDatastoreContext()
.getShardInitializationTimeout().duration().$times(2));
- Future<Object> futureObj = ask(getSelf(), new FindPrimary(shardName, true), findPrimaryTimeout);
+ Future<Object> futureObj = Patterns.ask(getSelf(), new FindPrimary(shardName, true), findPrimaryTimeout);
futureObj.onComplete(new OnComplete<>() {
@Override
public void onComplete(final Throwable failure, final Object response) {
if (failure != null) {
handler.onFailure(failure);
+ } else if (response instanceof RemotePrimaryShardFound msg) {
+ handler.onRemotePrimaryShardFound(msg);
+ } else if (response instanceof LocalPrimaryShardFound msg) {
+ handler.onLocalPrimaryFound(msg);
} else {
- if (response instanceof RemotePrimaryShardFound) {
- handler.onRemotePrimaryShardFound((RemotePrimaryShardFound) response);
- } else if (response instanceof LocalPrimaryShardFound) {
- handler.onLocalPrimaryFound((LocalPrimaryShardFound) response);
- } else {
- handler.onUnknownResponse(response);
- }
+ handler.onUnknownResponse(response);
}
}
}, new Dispatchers(context().system().dispatchers()).getDispatcher(Dispatchers.DispatcherType.Client));
}
// Create the localShard
- if (schemaContext == null) {
+ if (modelContext == null) {
LOG.debug("{}: No SchemaContext is available in order to create a local shard instance for {}",
persistenceId(), shardName);
getSender().tell(new Status.Failure(new IllegalStateException(
shardInfo = new ShardInformation(shardName, shardId, getPeerAddresses(shardName), datastoreContext,
Shard.builder(), peerAddressResolver);
shardInfo.setActiveMember(false);
- shardInfo.setSchemaContext(schemaContext);
+ shardInfo.setSchemaContext(modelContext);
localShards.put(shardName, shardInfo);
shardInfo.setActor(newShardActor(shardInfo));
} else {
final Timeout addServerTimeout = new Timeout(shardInfo.getDatastoreContext()
.getShardLeaderElectionTimeout().duration());
- final Future<Object> futureObj = ask(getContext().actorSelection(response.getPrimaryPath()),
+ final Future<Object> futureObj = Patterns.ask(getContext().actorSelection(response.getPrimaryPath()),
new AddServer(shardInfo.getShardId().toString(), localShardAddress, true), addServerTimeout);
futureObj.onComplete(new OnComplete<>() {
private static Exception getServerChangeException(final Class<?> serverChange,
final ServerChangeStatus serverChangeStatus, final String leaderPath, final ShardIdentifier shardId) {
- switch (serverChangeStatus) {
- case TIMEOUT:
- return new TimeoutException(String.format(
- "The shard leader %s timed out trying to replicate the initial data to the new shard %s."
- + "Possible causes - there was a problem replicating the data or shard leadership changed "
- + "while replicating the shard data", leaderPath, shardId.getShardName()));
- case NO_LEADER:
- return new NoShardLeaderException(shardId);
- case NOT_SUPPORTED:
- return new UnsupportedOperationException(String.format("%s request is not supported for shard %s",
- serverChange.getSimpleName(), shardId.getShardName()));
- default :
- return new RuntimeException(String.format("%s request to leader %s for shard %s failed with status %s",
- serverChange.getSimpleName(), leaderPath, shardId.getShardName(), serverChangeStatus));
- }
+ return switch (serverChangeStatus) {
+ case TIMEOUT -> new TimeoutException("""
+ The shard leader %s timed out trying to replicate the initial data to the new shard %s. Possible \
+ causes - there was a problem replicating the data or shard leadership changed while replicating the \
+ shard data""".formatted(leaderPath, shardId.getShardName()));
+ case NO_LEADER -> new NoShardLeaderException(shardId);
+ case NOT_SUPPORTED -> new UnsupportedOperationException(
+ "%s request is not supported for shard %s".formatted(
+ serverChange.getSimpleName(), shardId.getShardName()));
+ default -> new RuntimeException("%s request to leader %s for shard %s failed with status %s".formatted(
+ serverChange.getSimpleName(), leaderPath, shardId.getShardName(), serverChangeStatus));
+ };
}
private void onRemoveShardReplica(final RemoveShardReplica shardReplicaMsg) {
ActorRef sender = getSender();
final String shardName = flipMembersVotingStatus.getShardName();
findLocalShard(shardName, sender, localShardFound -> {
- Future<Object> future = ask(localShardFound.getPath(), GetOnDemandRaftState.INSTANCE,
+ Future<Object> future = Patterns.ask(localShardFound.getPath(), GetOnDemandRaftState.INSTANCE,
Timeout.apply(30, TimeUnit.SECONDS));
future.onComplete(new OnComplete<>() {
Timeout findLocalTimeout = new Timeout(datastoreContextFactory.getBaseDatastoreContext()
.getShardInitializationTimeout().duration().$times(2));
- Future<Object> futureObj = ask(getSelf(), new FindLocalShard(shardName, true), findLocalTimeout);
+ Future<Object> futureObj = Patterns.ask(getSelf(), new FindLocalShard(shardName, true), findLocalTimeout);
futureObj.onComplete(new OnComplete<>() {
@Override
public void onComplete(final Throwable failure, final Object response) {
if (failure != null) {
LOG.debug("{}: Received failure from FindLocalShard for shard {}", persistenceId, shardName,
- failure);
+ failure);
sender.tell(new Status.Failure(new RuntimeException(
- String.format("Failed to find local shard %s", shardName), failure)), self());
+ String.format("Failed to find local shard %s", shardName), failure)), self());
+ } if (response instanceof LocalShardFound msg) {
+ getSelf().tell((RunnableMessage) () -> onLocalShardFound.accept(msg), sender);
+ } else if (response instanceof LocalShardNotFound) {
+ LOG.debug("{}: Local shard {} does not exist", persistenceId, shardName);
+ sender.tell(new Status.Failure(new IllegalArgumentException(
+ String.format("Local shard %s does not exist", shardName))), self());
} else {
- if (response instanceof LocalShardFound) {
- getSelf().tell((RunnableMessage) () -> onLocalShardFound.accept((LocalShardFound) response),
- sender);
- } else if (response instanceof LocalShardNotFound) {
- LOG.debug("{}: Local shard {} does not exist", persistenceId, shardName);
- sender.tell(new Status.Failure(new IllegalArgumentException(
- String.format("Local shard %s does not exist", shardName))), self());
- } else {
- LOG.debug("{}: Failed to find local shard {}: received response: {}", persistenceId, shardName,
- response);
- sender.tell(new Status.Failure(response instanceof Throwable ? (Throwable) response
- : new RuntimeException(
- String.format("Failed to find local shard %s: received response: %s", shardName,
- response))), self());
- }
+ LOG.debug("{}: Failed to find local shard {}: received response: {}", persistenceId, shardName,
+ response);
+ sender.tell(new Status.Failure(response instanceof Throwable throwable ? throwable
+ : new RuntimeException(String.format("Failed to find local shard %s: received response: %s",
+ shardName, response))), self());
}
}
}, new Dispatchers(context().system().dispatchers()).getDispatcher(Dispatchers.DispatcherType.Client));
changeServersVotingStatus, shardActorRef.path());
Timeout timeout = new Timeout(datastoreContext.getShardLeaderElectionTimeout().duration().$times(2));
- Future<Object> futureObj = ask(shardActorRef, changeServersVotingStatus, timeout);
+ Future<Object> futureObj = Patterns.ask(shardActorRef, changeServersVotingStatus, timeout);
futureObj.onComplete(new OnComplete<>() {
@Override
*
* @author Thomas Pantelis
*/
+@Deprecated(since = "9.0.0", forRemoval = true)
public abstract class AbstractBatchedModificationsCursor extends AbstractDataTreeModificationCursor {
protected abstract BatchedModifications getModifications();
*/
package org.opendaylight.controller.cluster.datastore.utils;
-import static akka.pattern.Patterns.ask;
-
import akka.actor.ActorPath;
import akka.actor.ActorRef;
import akka.actor.ActorSelection;
import akka.actor.ActorSystem;
-import akka.actor.Address;
import akka.dispatch.Mapper;
import akka.dispatch.OnComplete;
import akka.pattern.AskTimeoutException;
import com.codahale.metrics.Timer;
import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
+import java.lang.invoke.VarHandle;
import java.util.Optional;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.LongAdder;
private static final Mapper<Throwable, Throwable> FIND_PRIMARY_FAILURE_TRANSFORMER = new Mapper<>() {
@Override
public Throwable apply(final Throwable failure) {
- Throwable actualFailure = failure;
if (failure instanceof AskTimeoutException) {
// A timeout exception most likely means the shard isn't initialized.
- actualFailure = new NotInitializedException(
+ return new NotInitializedException(
"Timed out trying to find the primary shard. Most likely cause is the "
+ "shard is not initialized yet.");
}
-
- return actualFailure;
+ return failure;
}
};
public static final String BOUNDED_MAILBOX = "bounded-mailbox";
private volatile EffectiveModelContext schemaContext;
- // Used as a write memory barrier.
- @SuppressWarnings("unused")
- private volatile boolean updated;
-
private final MetricRegistry metricRegistry = MetricsReporter.getInstance(DatastoreContext.METRICS_DOMAIN)
.getMetricsRegistry();
setCachedProperties();
- Address selfAddress = clusterWrapper.getSelfAddress();
+ final var selfAddress = clusterWrapper.getSelfAddress();
if (selfAddress != null && !selfAddress.host().isEmpty()) {
selfAddressHostPort = selfAddress.host().get() + ":" + selfAddress.port().get();
} else {
TimeUnit.MILLISECONDS);
operationTimeout = new Timeout(operationDuration);
- transactionCommitOperationTimeout = new Timeout(FiniteDuration.create(
+ transactionCommitOperationTimeout = new Timeout(FiniteDuration.create(
datastoreContext.getShardTransactionCommitTimeoutInSeconds(), TimeUnit.SECONDS));
shardInitializationTimeout = new Timeout(datastoreContext.getShardInitializationTimeout().duration().$times(2));
datastoreContext = contextFactory.getBaseDatastoreContext();
setCachedProperties();
- // We write the 'updated' volatile to trigger a write memory barrier so that the writes above
- // will be published immediately even though they may not be immediately visible to other
- // threads due to unsynchronized reads. That's OK though - we're going for eventual
- // consistency here as immediately visible updates to these members aren't critical. These
- // members could've been made volatile but wanted to avoid volatile reads as these are
- // accessed often and updates will be infrequent.
-
- updated = true;
+ // Trigger a write memory barrier so that the writes above will be published immediately even though they may
+ // not be immediately visible to other threads due to unsynchronized reads. That is OK though - we are going for
+ // eventual consistency here as immediately visible updates to these members are not critical. These members
+ // could have been made volatile but wanted to avoid volatile reads as these are accessed often and updates will
+ // be infrequent.
+ VarHandle.fullFence();
if (shardManager != null) {
shardManager.tell(contextFactory, ActorRef.noSender());
}
public Future<PrimaryShardInfo> findPrimaryShardAsync(final String shardName) {
- Future<PrimaryShardInfo> ret = primaryShardInfoCache.getIfPresent(shardName);
+ final var ret = primaryShardInfoCache.getIfPresent(shardName);
if (ret != null) {
return ret;
}
- Future<Object> future = executeOperationAsync(shardManager,
- new FindPrimary(shardName, true), shardInitializationTimeout);
-
- return future.transform(new Mapper<Object, PrimaryShardInfo>() {
- @Override
- public PrimaryShardInfo checkedApply(final Object response) throws UnknownMessageException {
- if (response instanceof RemotePrimaryShardFound) {
- LOG.debug("findPrimaryShardAsync received: {}", response);
- RemotePrimaryShardFound found = (RemotePrimaryShardFound)response;
- return onPrimaryShardFound(shardName, found.getPrimaryPath(), found.getPrimaryVersion(), null);
- } else if (response instanceof LocalPrimaryShardFound) {
- LOG.debug("findPrimaryShardAsync received: {}", response);
- LocalPrimaryShardFound found = (LocalPrimaryShardFound)response;
- return onPrimaryShardFound(shardName, found.getPrimaryPath(), DataStoreVersions.CURRENT_VERSION,
+
+ return executeOperationAsync(shardManager, new FindPrimary(shardName, true), shardInitializationTimeout)
+ .transform(new Mapper<>() {
+ @Override
+ public PrimaryShardInfo checkedApply(final Object response) throws UnknownMessageException {
+ if (response instanceof RemotePrimaryShardFound found) {
+ LOG.debug("findPrimaryShardAsync received: {}", found);
+ return onPrimaryShardFound(shardName, found.getPrimaryPath(), found.getPrimaryVersion(), null);
+ } else if (response instanceof LocalPrimaryShardFound found) {
+ LOG.debug("findPrimaryShardAsync received: {}", found);
+ return onPrimaryShardFound(shardName, found.getPrimaryPath(), DataStoreVersions.CURRENT_VERSION,
found.getLocalShardDataTree());
- } else if (response instanceof NotInitializedException) {
- throw (NotInitializedException)response;
- } else if (response instanceof PrimaryNotFoundException) {
- throw (PrimaryNotFoundException)response;
- } else if (response instanceof NoShardLeaderException) {
- throw (NoShardLeaderException)response;
- }
+ } else if (response instanceof NotInitializedException notInitialized) {
+ throw notInitialized;
+ } else if (response instanceof PrimaryNotFoundException primaryNotFound) {
+ throw primaryNotFound;
+ } else if (response instanceof NoShardLeaderException noShardLeader) {
+ throw noShardLeader;
+ }
- throw new UnknownMessageException(String.format(
+ throw new UnknownMessageException(String.format(
"FindPrimary returned unkown response: %s", response));
- }
- }, FIND_PRIMARY_FAILURE_TRANSFORMER, getClientDispatcher());
+ }
+ }, FIND_PRIMARY_FAILURE_TRANSFORMER, getClientDispatcher());
}
private PrimaryShardInfo onPrimaryShardFound(final String shardName, final String primaryActorPath,
final short primaryVersion, final ReadOnlyDataTree localShardDataTree) {
- ActorSelection actorSelection = actorSystem.actorSelection(primaryActorPath);
- PrimaryShardInfo info = localShardDataTree == null ? new PrimaryShardInfo(actorSelection, primaryVersion) :
+ final var actorSelection = actorSystem.actorSelection(primaryActorPath);
+ final var info = localShardDataTree == null ? new PrimaryShardInfo(actorSelection, primaryVersion) :
new PrimaryShardInfo(actorSelection, primaryVersion, localShardDataTree);
primaryShardInfoCache.putSuccessful(shardName, info);
return info;
* specified by the shardName
*/
public Optional<ActorRef> findLocalShard(final String shardName) {
- Object result = executeOperation(shardManager, new FindLocalShard(shardName, false));
-
- if (result instanceof LocalShardFound) {
- LocalShardFound found = (LocalShardFound) result;
+ final var result = executeOperation(shardManager, new FindLocalShard(shardName, false));
+ if (result instanceof LocalShardFound found) {
LOG.debug("Local shard found {}", found.getPath());
return Optional.of(found.getPath());
}
* @param shardName the name of the local shard that needs to be found
*/
public Future<ActorRef> findLocalShardAsync(final String shardName) {
- Future<Object> future = executeOperationAsync(shardManager,
- new FindLocalShard(shardName, true), shardInitializationTimeout);
-
- return future.map(new Mapper<Object, ActorRef>() {
- @Override
- public ActorRef checkedApply(final Object response) throws Throwable {
- if (response instanceof LocalShardFound) {
- LocalShardFound found = (LocalShardFound)response;
- LOG.debug("Local shard found {}", found.getPath());
- return found.getPath();
- } else if (response instanceof NotInitializedException) {
- throw (NotInitializedException)response;
- } else if (response instanceof LocalShardNotFound) {
- throw new LocalShardNotFoundException(
+ return executeOperationAsync(shardManager, new FindLocalShard(shardName, true), shardInitializationTimeout)
+ .map(new Mapper<>() {
+ @Override
+ public ActorRef checkedApply(final Object response) throws Throwable {
+ if (response instanceof LocalShardFound found) {
+ LOG.debug("Local shard found {}", found.getPath());
+ return found.getPath();
+ } else if (response instanceof NotInitializedException) {
+ throw (NotInitializedException)response;
+ } else if (response instanceof LocalShardNotFound) {
+ throw new LocalShardNotFoundException(
String.format("Local shard for %s does not exist.", shardName));
- }
+ }
- throw new UnknownMessageException(String.format(
- "FindLocalShard returned unkown response: %s", response));
- }
- }, getClientDispatcher());
+ throw new UnknownMessageException("FindLocalShard returned unkown response: " + response);
+ }
+ }, getClientDispatcher());
}
/**
@SuppressWarnings("checkstyle:IllegalCatch")
public void shutdown() {
- FiniteDuration duration = datastoreContext.getShardRaftConfig().getElectionTimeOutInterval().$times(3);
+ final var duration = datastoreContext.getShardRaftConfig().getElectionTimeOutInterval().$times(3);
try {
Await.ready(Patterns.gracefulStop(shardManager, duration, Shutdown.INSTANCE), duration);
} catch (Exception e) {
public void broadcast(final Function<Short, Object> messageSupplier, final Class<?> messageClass) {
for (final String shardName : configuration.getAllShardNames()) {
- Future<PrimaryShardInfo> primaryFuture = findPrimaryShardAsync(shardName);
- primaryFuture.onComplete(new OnComplete<PrimaryShardInfo>() {
+ final var primaryFuture = findPrimaryShardAsync(shardName);
+ primaryFuture.onComplete(new OnComplete<>() {
@Override
public void onComplete(final Throwable failure, final PrimaryShardInfo primaryShardInfo) {
if (failure != null) {
LOG.warn("broadcast failed to send message {} to shard {}", messageClass.getSimpleName(),
shardName, failure);
} else {
- Object message = messageSupplier.apply(primaryShardInfo.getPrimaryShardVersion());
+ final var message = messageSupplier.apply(primaryShardInfo.getPrimaryShardVersion());
primaryShardInfo.getPrimaryShardActor().tell(message, ActorRef.noSender());
}
}
return false;
}
- String hostPort = path.substring(pathAtIndex + 1, slashIndex);
+ final var hostPort = path.substring(pathAtIndex + 1, slashIndex);
return hostPort.equals(selfAddressHostPort);
} else {
}
public Timer getOperationTimer(final String dataStoreType, final String operationName) {
- final String rate = MetricRegistry.name(DISTRIBUTED_DATA_STORE_METRIC_REGISTRY, dataStoreType,
- operationName, METRIC_RATE);
+ final var rate = MetricRegistry.name(DISTRIBUTED_DATA_STORE_METRIC_REGISTRY, dataStoreType, operationName,
+ METRIC_RATE);
return metricRegistry.timer(rate);
}
}
protected Future<Object> doAsk(final ActorRef actorRef, final Object message, final Timeout timeout) {
- return ask(actorRef, message, timeout);
+ return Patterns.ask(actorRef, message, timeout);
}
protected Future<Object> doAsk(final ActorSelection actorRef, final Object message, final Timeout timeout) {
- final Future<Object> ret = ask(actorRef, message, timeout);
+ final var ret = Patterns.ask(actorRef, message, timeout);
ret.onComplete(askTimeoutCounter, askTimeoutCounter);
return ret;
}
}
@Override
- public final EffectiveModelContext getEffectiveModelContext() {
- return delegate.getEffectiveModelContext();
+ public final EffectiveModelContext modelContext() {
+ return delegate.modelContext();
}
@Override
import java.util.stream.Stream;
import org.eclipse.jdt.annotation.NonNull;
import org.eclipse.jdt.annotation.NonNullByDefault;
-import org.eclipse.jdt.annotation.Nullable;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
-import org.opendaylight.yangtools.yang.data.api.schema.builder.DataContainerNodeBuilder;
-import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
+import org.opendaylight.yangtools.yang.data.spi.node.ImmutableNodes;
import org.opendaylight.yangtools.yang.data.tree.api.DataValidationFailedException;
/**
* Utility methods for dealing with datastore root {@link ContainerNode} with respect to module shards.
*/
public final class RootScatterGather {
- // FIXME: Record when we have JDK17+
@NonNullByDefault
- public static final class ShardContainer<T> {
- private final ContainerNode container;
- private final T shard;
-
- ShardContainer(final T shard, final ContainerNode container) {
- this.shard = requireNonNull(shard);
- this.container = requireNonNull(container);
- }
-
- public T shard() {
- return shard;
- }
-
- public ContainerNode container() {
- return container;
- }
-
- @Override
- public int hashCode() {
- return shard.hashCode();
- }
-
- @Override
- public boolean equals(final @Nullable Object obj) {
- return obj == this || obj instanceof ShardContainer && shard.equals(((ShardContainer<?>) obj).shard);
+ public record ShardContainer<T>(T shard, ContainerNode container) {
+ public ShardContainer {
+ requireNonNull(shard);
+ requireNonNull(container);
}
@Override
return FluentFuture.from(Futures.transform(
Futures.allAsList(readFutures.collect(ImmutableList.toImmutableList())), input -> {
try {
- return NormalizedNodeAggregator.aggregate(YangInstanceIdentifier.empty(), input,
+ return NormalizedNodeAggregator.aggregate(YangInstanceIdentifier.of(), input,
actorUtils.getSchemaContext(), actorUtils.getDatastoreContext().getLogicalStoreType());
} catch (DataValidationFailedException e) {
throw new IllegalArgumentException("Failed to aggregate", e);
public static <T> @NonNull Stream<ShardContainer<T>> scatterAll(final ContainerNode rootNode,
final Function<PathArgument, T> childToShard, final Stream<T> allShards) {
final var builders = allShards
- .collect(Collectors.toUnmodifiableMap(Function.identity(), unused -> Builders.containerBuilder()));
+ .collect(Collectors.toUnmodifiableMap(Function.identity(), unused -> ImmutableNodes.newContainerBuilder()));
for (var child : rootNode.body()) {
- final var shard = childToShard.apply(child.getIdentifier());
+ final var shard = childToShard.apply(child.name());
verifyNotNull(builders.get(shard), "Failed to find builder for %s", shard).addChild(child);
}
- return streamContainers(rootNode.getIdentifier(), builders);
+ return streamContainers(rootNode.name(), builders);
}
/**
*/
public static <T> @NonNull Stream<ShardContainer<T>> scatterTouched(final ContainerNode rootNode,
final Function<PathArgument, T> childToShard) {
- final var builders = new HashMap<T, DataContainerNodeBuilder<NodeIdentifier, ContainerNode>>();
+ final var builders = new HashMap<T, ContainerNode.Builder>();
for (var child : rootNode.body()) {
- builders.computeIfAbsent(childToShard.apply(child.getIdentifier()), unused -> Builders.containerBuilder())
+ builders.computeIfAbsent(childToShard.apply(child.name()), unused -> ImmutableNodes.newContainerBuilder())
.addChild(child);
}
- return streamContainers(rootNode.getIdentifier(), builders);
+ return streamContainers(rootNode.name(), builders);
}
private static <T> @NonNull Stream<ShardContainer<T>> streamContainers(final NodeIdentifier rootId,
- final Map<T, DataContainerNodeBuilder<NodeIdentifier, ContainerNode>> builders) {
+ final Map<T, ContainerNode.Builder> builders) {
return builders.entrySet().stream()
.map(entry -> new ShardContainer<>(entry.getKey(), entry.getValue().withNodeIdentifier(rootId).build()));
}
// vi: set smarttab et sw=4 tabstop=4:
module distributed-datastore-provider {
-
yang-version 1;
namespace "urn:opendaylight:params:xml:ns:yang:controller:config:distributed-datastore-provider";
prefix "distributed-datastore-provider";
description
"This module contains the base YANG definitions for
- the distributed datastore provider implementation";
+ the distributed datastore provider implementation";
+
+ revision "2023-12-29" {
+ description "Remote use-tell-based-protocol and shard-snapshot-chunk-size leaves";
+ }
revision "2014-06-12" {
description
cannot be found then the default raft behavior will be applied";
}
- leaf shard-snapshot-chunk-size {
- status deprecated;
- default 491520;
- type non-zero-uint32-type;
- description "When sending a snapshot to a follower, this is the maximum size in bytes for
- a chunk of data.";
- }
-
leaf maximum-message-slice-size {
default 491520;
type non-zero-uint32-type;
maximum size in bytes for a message slice.";
}
- leaf use-tell-based-protocol {
- status obsolete;
- default false;
- type boolean;
- description "Use a newer protocol between the frontend and backend. This feature is considered
- exprerimental at this point.";
- }
-
leaf file-backed-streaming-threshold-in-megabytes {
default 128;
type non-zero-uint32-type;
+++ /dev/null
-/*
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.cluster.databroker;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertSame;
-import static org.junit.Assert.assertThrows;
-import static org.junit.Assert.assertTrue;
-import static org.mockito.ArgumentMatchers.any;
-import static org.mockito.Mockito.doThrow;
-import static org.opendaylight.mdsal.common.api.LogicalDatastoreType.CONFIGURATION;
-import static org.opendaylight.mdsal.common.api.LogicalDatastoreType.OPERATIONAL;
-
-import com.google.common.util.concurrent.FluentFuture;
-import java.util.Map;
-import java.util.concurrent.ExecutionException;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.mockito.Mock;
-import org.mockito.junit.MockitoJUnitRunner;
-import org.opendaylight.mdsal.common.api.CommitInfo;
-import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
-import org.opendaylight.mdsal.common.api.TransactionCommitFailedException;
-import org.opendaylight.mdsal.common.api.TransactionDatastoreMismatchException;
-import org.opendaylight.mdsal.dom.spi.store.DOMStoreTransactionFactory;
-import org.opendaylight.mdsal.dom.spi.store.DOMStoreWriteTransaction;
-
-@RunWith(MockitoJUnitRunner.StrictStubs.class)
-public class AbstractDOMBrokerWriteTransactionTest {
-
- @Mock
- private DOMStoreTransactionFactory txFactory;
- @Mock
- private AbstractDOMTransactionFactory<?> abstractDOMTransactionFactory;
- @Mock
- private DOMStoreWriteTransaction domStoreWriteTransaction;
-
- private class AbstractDOMBrokerWriteTransactionTestImpl
- extends AbstractDOMBrokerWriteTransaction<DOMStoreWriteTransaction> {
-
- AbstractDOMBrokerWriteTransactionTestImpl() {
- this(Map.of(CONFIGURATION, txFactory));
- }
-
- AbstractDOMBrokerWriteTransactionTestImpl(Map<LogicalDatastoreType, DOMStoreTransactionFactory> txFactoryMap) {
- super(new Object(), txFactoryMap, abstractDOMTransactionFactory);
- }
-
- @Override
- protected DOMStoreWriteTransaction createTransaction(final LogicalDatastoreType key) {
- return domStoreWriteTransaction;
- }
-
- @Override
- protected DOMStoreWriteTransaction getSubtransaction() {
- return domStoreWriteTransaction;
- }
- }
-
- @Test
- public void readyRuntimeExceptionAndCancel() {
- RuntimeException thrown = new RuntimeException();
- doThrow(thrown).when(domStoreWriteTransaction).ready();
- AbstractDOMBrokerWriteTransactionTestImpl abstractDOMBrokerWriteTransactionTestImpl =
- new AbstractDOMBrokerWriteTransactionTestImpl();
-
- FluentFuture<? extends CommitInfo> submitFuture = abstractDOMBrokerWriteTransactionTestImpl.commit();
- final var cause = assertThrows(ExecutionException.class, submitFuture::get).getCause();
- assertTrue(cause instanceof TransactionCommitFailedException);
- assertSame(thrown, cause.getCause());
- abstractDOMBrokerWriteTransactionTestImpl.cancel();
- }
-
- @Test
- public void submitRuntimeExceptionAndCancel() throws InterruptedException {
- RuntimeException thrown = new RuntimeException();
- doThrow(thrown).when(abstractDOMTransactionFactory).commit(any(), any());
- AbstractDOMBrokerWriteTransactionTestImpl abstractDOMBrokerWriteTransactionTestImpl
- = new AbstractDOMBrokerWriteTransactionTestImpl();
-
- FluentFuture<? extends CommitInfo> submitFuture = abstractDOMBrokerWriteTransactionTestImpl.commit();
- final var cause = assertThrows(ExecutionException.class, submitFuture::get).getCause();
- assertTrue(cause instanceof TransactionCommitFailedException);
- assertSame(thrown, cause.getCause());
- abstractDOMBrokerWriteTransactionTestImpl.cancel();
- }
-
- @Test
- public void getSubtransactionStoreMismatch() {
- final var testTx = new AbstractDOMBrokerWriteTransactionTestImpl(
- Map.of(CONFIGURATION, txFactory, OPERATIONAL, txFactory));
-
- assertEquals(domStoreWriteTransaction, testTx.getSubtransaction(CONFIGURATION));
-
- final var exception = assertThrows(TransactionDatastoreMismatchException.class,
- () -> testTx.getSubtransaction(OPERATIONAL));
- assertEquals(CONFIGURATION, exception.expected());
- assertEquals(OPERATIONAL, exception.encountered());
- }
-
- @Test
- public void getSubtransactionStoreUndefined() {
- final var testTx = new AbstractDOMBrokerWriteTransactionTestImpl(Map.of(OPERATIONAL, txFactory));
-
- final var exception = assertThrows(IllegalArgumentException.class,
- () -> testTx.getSubtransaction(CONFIGURATION));
- assertEquals("CONFIGURATION is not supported", exception.getMessage());
- }
-}
package org.opendaylight.controller.cluster.databroker;
import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
+import akka.util.Timeout;
+import com.google.common.base.Stopwatch;
+import com.google.common.util.concurrent.Uninterruptibles;
+import java.util.concurrent.ForkJoinPool;
+import java.util.concurrent.TimeUnit;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.opendaylight.controller.cluster.databroker.actors.dds.DataStoreClient;
import org.opendaylight.controller.cluster.datastore.DatastoreContext;
import org.opendaylight.controller.cluster.datastore.utils.ActorUtils;
-import org.opendaylight.mdsal.dom.spi.store.DOMStoreReadTransaction;
-import org.opendaylight.mdsal.dom.spi.store.DOMStoreReadWriteTransaction;
-import org.opendaylight.mdsal.dom.spi.store.DOMStoreTransactionChain;
-import org.opendaylight.mdsal.dom.spi.store.DOMStoreWriteTransaction;
+import org.opendaylight.yangtools.yang.common.Empty;
+import scala.concurrent.duration.FiniteDuration;
@RunWith(MockitoJUnitRunner.StrictStubs.class)
public class ClientBackedDataStoreTest {
@Mock
private DataStoreClient clientActor;
-
+ @Mock
+ private DatastoreContext datastoreContext;
+ @Mock
+ private Timeout shardElectionTimeout;
@Mock
private ActorUtils actorUtils;
-
@Mock
private ClientLocalHistory clientLocalHistory;
-
@Mock
private ClientTransaction clientTransaction;
-
@Mock
private ClientSnapshot clientSnapshot;
+
@Before
public void setUp() {
doReturn(DatastoreContext.newBuilder().build()).when(actorUtils).getDatastoreContext();
@Test
public void testCreateTransactionChain() {
- try (ClientBackedDataStore clientBackedDataStore = new ClientBackedDataStore(
- actorUtils, UNKNOWN_ID, clientActor)) {
- final DOMStoreTransactionChain txChain = clientBackedDataStore.createTransactionChain();
- assertNotNull(txChain);
+ try (var clientBackedDataStore = new ClientBackedDataStore(actorUtils, UNKNOWN_ID, clientActor)) {
+ assertNotNull(clientBackedDataStore.createTransactionChain());
verify(clientActor, times(1)).createLocalHistory();
}
}
@Test
public void testNewReadOnlyTransaction() {
- try (ClientBackedDataStore clientBackedDataStore = new ClientBackedDataStore(
- actorUtils, UNKNOWN_ID, clientActor)) {
- final DOMStoreReadTransaction tx = clientBackedDataStore.newReadOnlyTransaction();
- assertNotNull(tx);
+ try (var clientBackedDataStore = new ClientBackedDataStore(actorUtils, UNKNOWN_ID, clientActor)) {
+ assertNotNull(clientBackedDataStore.newReadOnlyTransaction());
verify(clientActor, times(1)).createSnapshot();
}
}
@Test
public void testNewWriteOnlyTransaction() {
- try (ClientBackedDataStore clientBackedDataStore = new ClientBackedDataStore(
- actorUtils, UNKNOWN_ID, clientActor)) {
- final DOMStoreWriteTransaction tx = clientBackedDataStore.newWriteOnlyTransaction();
- assertNotNull(tx);
+ try (var clientBackedDataStore = new ClientBackedDataStore(actorUtils, UNKNOWN_ID, clientActor)) {
+ assertNotNull(clientBackedDataStore.newWriteOnlyTransaction());
verify(clientActor, times(1)).createTransaction();
}
}
@Test
public void testNewReadWriteTransaction() {
- try (ClientBackedDataStore clientBackedDataStore = new ClientBackedDataStore(
- actorUtils, UNKNOWN_ID, clientActor)) {
- final DOMStoreReadWriteTransaction tx = clientBackedDataStore.newReadWriteTransaction();
- assertNotNull(tx);
+ try (var clientBackedDataStore = new ClientBackedDataStore(actorUtils, UNKNOWN_ID, clientActor)) {
+ assertNotNull(clientBackedDataStore.newReadWriteTransaction());
verify(clientActor, times(1)).createTransaction();
}
}
+
+ @Test
+ public void testWaitTillReadyBlocking() {
+ doReturn(datastoreContext).when(actorUtils).getDatastoreContext();
+ doReturn(shardElectionTimeout).when(datastoreContext).getShardLeaderElectionTimeout();
+ doReturn(1).when(datastoreContext).getInitialSettleTimeoutMultiplier();
+ doReturn(FiniteDuration.apply(50, TimeUnit.MILLISECONDS)).when(shardElectionTimeout).duration();
+ try (var clientBackedDataStore = new ClientBackedDataStore(actorUtils, UNKNOWN_ID, clientActor)) {
+ final var sw = Stopwatch.createStarted();
+ clientBackedDataStore.waitTillReady();
+ final var elapsedMillis = sw.stop().elapsed(TimeUnit.MILLISECONDS);
+
+ assertTrue("Expected to be blocked for 50 millis", elapsedMillis >= 50);
+ }
+ }
+
+ @Test
+ public void testWaitTillReadyCountDown() {
+ try (var clientBackedDataStore = new ClientBackedDataStore(actorUtils, UNKNOWN_ID, clientActor)) {
+ doReturn(datastoreContext).when(actorUtils).getDatastoreContext();
+
+ ForkJoinPool.commonPool().submit(() -> {
+ Uninterruptibles.sleepUninterruptibly(500, TimeUnit.MILLISECONDS);
+ clientBackedDataStore.readinessFuture().set(Empty.value());
+ });
+
+ final var sw = Stopwatch.createStarted();
+ clientBackedDataStore.waitTillReady();
+ final var elapsedMillis = sw.stop().elapsed(TimeUnit.MILLISECONDS);
+
+ assertTrue("Expected to be released in 500 millis", elapsedMillis < 5000);
+ }
+ }
}
package org.opendaylight.controller.cluster.databroker;
import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.doReturn;
import static org.opendaylight.yangtools.util.concurrent.FluentFutures.immediateFluentFuture;
import static org.opendaylight.yangtools.util.concurrent.FluentFutures.immediateTrueFluentFuture;
-import com.google.common.util.concurrent.ListenableFuture;
import java.util.Optional;
import org.junit.Before;
import org.junit.Test;
import org.opendaylight.controller.cluster.access.client.ClientActorContext;
import org.opendaylight.controller.cluster.databroker.actors.dds.ClientSnapshot;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
-import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
+import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
@RunWith(MockitoJUnitRunner.StrictStubs.class)
public class ClientBackedReadTransactionTest extends ClientBackedTransactionTest<ClientBackedReadTransaction> {
private ClientBackedReadTransaction object;
@Mock
- private NormalizedNode data;
+ private ContainerNode data;
@Mock
private ClientActorContext clientContext;
@Mock
public void setUp() {
doReturn(TRANSACTION_ID).when(delegate).getIdentifier();
- doReturn(immediateTrueFluentFuture()).when(delegate).exists(YangInstanceIdentifier.empty());
- doReturn(immediateFluentFuture(Optional.of(data))).when(delegate).read(YangInstanceIdentifier.empty());
+ doReturn(immediateTrueFluentFuture()).when(delegate).exists(YangInstanceIdentifier.of());
+ doReturn(immediateFluentFuture(Optional.of(data))).when(delegate).read(YangInstanceIdentifier.of());
object = new ClientBackedReadTransaction(delegate, null, null);
}
@Test
public void testRead() throws Exception {
- final ListenableFuture<Optional<NormalizedNode>> result = object().read(YangInstanceIdentifier.empty());
- final Optional<NormalizedNode> resultData = result.get();
- assertTrue(resultData.isPresent());
- assertEquals(data, resultData.get());
+ assertEquals(Optional.of(data), object().read(YangInstanceIdentifier.of()).get());
}
@Test
public void testExists() throws Exception {
- final ListenableFuture<Boolean> result = object().exists(YangInstanceIdentifier.empty());
- assertEquals(Boolean.TRUE, result.get());
+ assertEquals(Boolean.TRUE, object().exists(YangInstanceIdentifier.of()).get());
}
}
package org.opendaylight.controller.cluster.databroker;
import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.doReturn;
import static org.opendaylight.yangtools.util.concurrent.FluentFutures.immediateFluentFuture;
import static org.opendaylight.yangtools.util.concurrent.FluentFutures.immediateTrueFluentFuture;
-import com.google.common.util.concurrent.FluentFuture;
import java.util.Optional;
import org.junit.Before;
import org.junit.Test;
import org.mockito.junit.MockitoJUnitRunner;
import org.opendaylight.controller.cluster.databroker.actors.dds.ClientTransaction;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
-import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
+import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
@RunWith(MockitoJUnitRunner.StrictStubs.class)
public class ClientBackedReadWriteTransactionTest
@Mock
private ClientTransaction delegate;
@Mock
- private NormalizedNode data;
+ private ContainerNode data;
@Override
ClientBackedReadWriteTransaction object() {
public void setUp() {
doReturn(TRANSACTION_ID).when(delegate).getIdentifier();
- doReturn(immediateTrueFluentFuture()).when(delegate).exists(YangInstanceIdentifier.empty());
- doReturn(immediateFluentFuture(Optional.of(data))).when(delegate).read(YangInstanceIdentifier.empty());
+ doReturn(immediateTrueFluentFuture()).when(delegate).exists(YangInstanceIdentifier.of());
+ doReturn(immediateFluentFuture(Optional.of(data))).when(delegate).read(YangInstanceIdentifier.of());
object = new ClientBackedReadWriteTransaction(delegate, null);
}
@Test
public void testRead() throws Exception {
- final FluentFuture<Optional<NormalizedNode>> result = object().read(YangInstanceIdentifier.empty());
- final Optional<NormalizedNode> resultData = result.get();
- assertTrue(resultData.isPresent());
- assertEquals(data, resultData.get());
+ assertEquals(Optional.of(data), object().read(YangInstanceIdentifier.of()).get());
}
@Test
public void testExists() throws Exception {
- assertEquals(Boolean.TRUE, object().exists(YangInstanceIdentifier.empty()).get());
+ assertEquals(Boolean.TRUE, object().exists(YangInstanceIdentifier.of()).get());
}
}
import org.opendaylight.controller.cluster.databroker.actors.dds.ClientTransaction;
import org.opendaylight.mdsal.dom.spi.store.DOMStoreThreePhaseCommitCohort;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
-import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
+import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
@RunWith(MockitoJUnitRunner.StrictStubs.class)
public class ClientBackedWriteTransactionTest extends ClientBackedTransactionTest<ClientBackedWriteTransaction> {
@Mock
private ClientTransaction delegate;
@Mock
- private NormalizedNode data;
+ private ContainerNode data;
@Mock
private DOMStoreThreePhaseCommitCohort readyCohort;
@Test
public void testWrite() {
- object().write(YangInstanceIdentifier.empty(), data);
- verify(delegate).write(YangInstanceIdentifier.empty(), data);
+ object().write(YangInstanceIdentifier.of(), data);
+ verify(delegate).write(YangInstanceIdentifier.of(), data);
}
@Test
public void testMerge() {
- object().merge(YangInstanceIdentifier.empty(), data);
- verify(delegate).merge(YangInstanceIdentifier.empty(), data);
+ object().merge(YangInstanceIdentifier.of(), data);
+ verify(delegate).merge(YangInstanceIdentifier.of(), data);
}
@Test
public void testDelete() {
- object().delete(YangInstanceIdentifier.empty());
- verify(delegate).delete(YangInstanceIdentifier.empty());
+ object().delete(YangInstanceIdentifier.of());
+ verify(delegate).delete(YangInstanceIdentifier.of());
}
@Test
import static org.opendaylight.yangtools.util.concurrent.FluentFutures.immediateTrueFluentFuture;
import com.google.common.base.Throwables;
-import com.google.common.collect.ClassToInstanceMap;
import com.google.common.collect.ImmutableMap;
import com.google.common.util.concurrent.FluentFuture;
import com.google.common.util.concurrent.FutureCallback;
import org.junit.Test;
import org.mockito.InOrder;
import org.mockito.stubbing.Answer;
-import org.opendaylight.controller.cluster.datastore.AbstractDataStore;
import org.opendaylight.mdsal.common.api.CommitInfo;
import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
import org.opendaylight.mdsal.common.api.TransactionCommitFailedException;
-import org.opendaylight.mdsal.dom.api.DOMDataBrokerExtension;
-import org.opendaylight.mdsal.dom.api.DOMDataTreeChangeService;
+import org.opendaylight.mdsal.dom.api.DOMDataBroker.CommitCohortExtension;
+import org.opendaylight.mdsal.dom.api.DOMDataBroker.DataTreeChangeExtension;
import org.opendaylight.mdsal.dom.api.DOMDataTreeCommitCohort;
-import org.opendaylight.mdsal.dom.api.DOMDataTreeCommitCohortRegistry;
import org.opendaylight.mdsal.dom.api.DOMDataTreeIdentifier;
import org.opendaylight.mdsal.dom.api.DOMDataTreeReadTransaction;
import org.opendaylight.mdsal.dom.api.DOMDataTreeReadWriteTransaction;
import org.opendaylight.mdsal.dom.api.DOMDataTreeWriteTransaction;
import org.opendaylight.mdsal.dom.api.DOMTransactionChain;
-import org.opendaylight.mdsal.dom.api.DOMTransactionChainListener;
-import org.opendaylight.mdsal.dom.broker.TransactionCommitFailedExceptionMapper;
+import org.opendaylight.mdsal.dom.spi.TransactionCommitFailedExceptionMapper;
import org.opendaylight.mdsal.dom.spi.store.DOMStore;
import org.opendaylight.mdsal.dom.spi.store.DOMStoreReadTransaction;
import org.opendaylight.mdsal.dom.spi.store.DOMStoreReadWriteTransaction;
import org.opendaylight.mdsal.dom.spi.store.DOMStoreWriteTransaction;
import org.opendaylight.mdsal.dom.store.inmemory.InMemoryDOMDataStore;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
-import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
+import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
/**
* Unit tests for DOMConcurrentDataCommitCoordinator.
configDomStore), futureExecutor)) {
DOMDataTreeReadWriteTransaction dataTxn = dataBroker.newReadWriteTransaction();
- dataTxn.put(LogicalDatastoreType.OPERATIONAL, YangInstanceIdentifier.empty(), mock(NormalizedNode.class));
- dataTxn.put(LogicalDatastoreType.OPERATIONAL, YangInstanceIdentifier.empty(), mock(NormalizedNode.class));
- dataTxn.read(LogicalDatastoreType.OPERATIONAL, YangInstanceIdentifier.empty());
+ dataTxn.put(LogicalDatastoreType.OPERATIONAL, YangInstanceIdentifier.of(), mock(ContainerNode.class));
+ dataTxn.put(LogicalDatastoreType.OPERATIONAL, YangInstanceIdentifier.of(), mock(ContainerNode.class));
+ dataTxn.read(LogicalDatastoreType.OPERATIONAL, YangInstanceIdentifier.of());
verify(configDomStore, never()).newReadWriteTransaction();
verify(operationalDomStore, times(1)).newReadWriteTransaction();
configDomStore), futureExecutor)) {
DOMDataTreeWriteTransaction dataTxn = dataBroker.newWriteOnlyTransaction();
- dataTxn.put(LogicalDatastoreType.OPERATIONAL, YangInstanceIdentifier.empty(), mock(NormalizedNode.class));
- dataTxn.put(LogicalDatastoreType.OPERATIONAL, YangInstanceIdentifier.empty(), mock(NormalizedNode.class));
+ dataTxn.put(LogicalDatastoreType.OPERATIONAL, YangInstanceIdentifier.of(), mock(ContainerNode.class));
+ dataTxn.put(LogicalDatastoreType.OPERATIONAL, YangInstanceIdentifier.of(), mock(ContainerNode.class));
verify(configDomStore, never()).newWriteOnlyTransaction();
verify(operationalDomStore, times(1)).newWriteOnlyTransaction();
configDomStore), futureExecutor)) {
DOMDataTreeReadTransaction dataTxn = dataBroker.newReadOnlyTransaction();
- dataTxn.read(LogicalDatastoreType.OPERATIONAL, YangInstanceIdentifier.empty());
- dataTxn.read(LogicalDatastoreType.OPERATIONAL, YangInstanceIdentifier.empty());
+ dataTxn.read(LogicalDatastoreType.OPERATIONAL, YangInstanceIdentifier.of());
+ dataTxn.read(LogicalDatastoreType.OPERATIONAL, YangInstanceIdentifier.of());
verify(configDomStore, never()).newReadOnlyTransaction();
verify(operationalDomStore, times(1)).newReadOnlyTransaction();
}) {
DOMDataTreeReadWriteTransaction domDataReadWriteTransaction = dataBroker.newReadWriteTransaction();
- domDataReadWriteTransaction.delete(LogicalDatastoreType.OPERATIONAL, YangInstanceIdentifier.empty());
+ domDataReadWriteTransaction.delete(LogicalDatastoreType.OPERATIONAL, YangInstanceIdentifier.of());
domDataReadWriteTransaction.commit();
LogicalDatastoreType.OPERATIONAL, domStore, LogicalDatastoreType.CONFIGURATION, domStore),
futureExecutor)) {
- dataBroker.createTransactionChain(mock(DOMTransactionChainListener.class));
+ dataBroker.createTransactionChain();
verify(domStore, times(2)).createTransactionChain();
}
doReturn(mockChain).when(domStore).createTransactionChain();
doReturn(operationalTransaction).when(mockChain).newWriteOnlyTransaction();
- DOMTransactionChain transactionChain = dataBroker.createTransactionChain(
- mock(DOMTransactionChainListener.class));
+ DOMTransactionChain transactionChain = dataBroker.createTransactionChain();
DOMDataTreeWriteTransaction domDataWriteTransaction = transactionChain.newWriteOnlyTransaction();
verify(mockChain, never()).newWriteOnlyTransaction();
- domDataWriteTransaction.put(LogicalDatastoreType.OPERATIONAL, YangInstanceIdentifier.empty(),
- mock(NormalizedNode.class));
+ domDataWriteTransaction.put(LogicalDatastoreType.OPERATIONAL, YangInstanceIdentifier.of(),
+ mock(ContainerNode.class));
}
}
@Test
public void testExtensions() {
- final var mockConfigStore = mock(AbstractDataStore.class);
- final var mockOperStore = mock(AbstractDataStore.class);
- try (ConcurrentDOMDataBroker dataBroker = new ConcurrentDOMDataBroker(ImmutableMap.of(
+ final var mockConfigStore = mock(ClientBackedDataStore.class);
+ final var mockOperStore = mock(ClientBackedDataStore.class);
+ try (var dataBroker = new ConcurrentDOMDataBroker(ImmutableMap.of(
LogicalDatastoreType.OPERATIONAL, mockOperStore,
LogicalDatastoreType.CONFIGURATION, mockConfigStore), futureExecutor)) {
+ assertNotNull(dataBroker.extension(DataTreeChangeExtension.class));
- ClassToInstanceMap<DOMDataBrokerExtension> supportedExtensions = dataBroker.getExtensions();
- assertNotNull(supportedExtensions.getInstance(DOMDataTreeChangeService.class));
-
- DOMDataTreeCommitCohortRegistry cohortRegistry = supportedExtensions.getInstance(
- DOMDataTreeCommitCohortRegistry.class);
+ final var cohortRegistry = dataBroker.extension(CommitCohortExtension.class);
assertNotNull(cohortRegistry);
- DOMDataTreeCommitCohort cohort = mock(DOMDataTreeCommitCohort.class);
- DOMDataTreeIdentifier path = new DOMDataTreeIdentifier(
- org.opendaylight.mdsal.common.api.LogicalDatastoreType.CONFIGURATION,
- YangInstanceIdentifier.empty());
+ final var cohort = mock(DOMDataTreeCommitCohort.class);
+ final var path = DOMDataTreeIdentifier.of(LogicalDatastoreType.CONFIGURATION, YangInstanceIdentifier.of());
cohortRegistry.registerCommitCohort(path, cohort);
verify(mockConfigStore).registerCommitCohort(path, cohort);
@RunWith(MockitoJUnitRunner.StrictStubs.class)
public abstract class AbstractClientHandleTest<T extends AbstractClientHandle<AbstractProxyTransaction>> {
private static final String PERSISTENCE_ID = "per-1";
- private static final YangInstanceIdentifier PATH = YangInstanceIdentifier.empty();
+ private static final YangInstanceIdentifier PATH = YangInstanceIdentifier.of();
@Mock
private DataTree dataTree;
@Test
public void testEnsureProxy() {
- final AbstractProxyTransaction expected = mock(AbstractProxyTransaction.class);
- final AbstractProxyTransaction proxy = handle.ensureProxy(PATH);
+ final var proxy = handle.ensureProxy(PATH);
assertEquals(0, proxy.getIdentifier().getTransactionId());
}
import org.opendaylight.controller.cluster.access.client.ClientActorContext;
import org.opendaylight.controller.cluster.access.client.ConnectedClientConnection;
import org.opendaylight.controller.cluster.access.concepts.LocalHistoryIdentifier;
+import org.opendaylight.controller.cluster.datastore.DatastoreContext;
import org.opendaylight.controller.cluster.datastore.messages.PrimaryShardInfo;
import org.opendaylight.controller.cluster.datastore.utils.ActorUtils;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
@Mock
private DataTree tree;
+ @Mock
+ private DatastoreContext datastoreContext;
protected abstract T object();
@Test
public void testResolveShardForPath() {
- final Long shardForPath = object().resolveShardForPath(YangInstanceIdentifier.empty());
+ final Long shardForPath = object().resolveShardForPath(YangInstanceIdentifier.of());
assertNotNull(shardForPath);
assertEquals(0L, (long) shardForPath);
}
assertNull(reconnectCohort);
}
- protected static ActorUtils createActorUtilsMock(final ActorSystem system, final ActorRef actor) {
+ protected final ActorUtils createActorUtilsMock(final ActorSystem system, final ActorRef actor) {
final ActorUtils mock = mock(ActorUtils.class);
final Promise<PrimaryShardInfo> promise = new DefaultPromise<>();
final ActorSelection selection = system.actorSelection(actor.path());
final PrimaryShardInfo shardInfo = new PrimaryShardInfo(selection, (short) 0);
promise.success(shardInfo);
doReturn(promise.future()).when(mock).findPrimaryShardAsync(any());
+ doReturn(1000).when(datastoreContext).getShardBatchedModificationCount();
+ doReturn(datastoreContext).when(mock).getDatastoreContext();
+
return mock;
}
}
\ No newline at end of file
import org.opendaylight.controller.cluster.access.client.InternalCommand;
import org.opendaylight.controller.cluster.access.commands.ConnectClientRequest;
import org.opendaylight.controller.cluster.access.commands.ConnectClientSuccess;
+import org.opendaylight.controller.cluster.datastore.DatastoreContext;
import org.opendaylight.controller.cluster.datastore.messages.PrimaryShardInfo;
import org.opendaylight.controller.cluster.datastore.utils.ActorUtils;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
private TestProbe clientActorProbe;
private TestProbe actorContextProbe;
private AbstractDataStoreClientBehavior behavior;
+ private ActorUtils util;
@Before
public void setUp() {
system = ActorSystem.apply();
clientActorProbe = new TestProbe(system, "client");
actorContextProbe = new TestProbe(system, "actor-context");
- final ActorUtils context = createActorContextMock(system, actorContextProbe.ref());
+ util = createActorContextMock(system, actorContextProbe.ref());
clientContext =
AccessClientUtil.createClientActorContext(system, clientActorProbe.ref(), CLIENT_ID, PERSISTENCE_ID);
- behavior = createBehavior(clientContext, context);
+ behavior = createBehavior(clientContext, util);
}
@SuppressWarnings("checkstyle:hiddenField")
@Test
public void testResolveShardForPath() {
- assertEquals(0L, behavior.resolveShardForPath(YangInstanceIdentifier.empty()).longValue());
+ assertEquals(0L, behavior.resolveShardForPath(YangInstanceIdentifier.of()).longValue());
}
@Test
@Test
public void testGetConnection() {
+ final var datastoreContext = mock(DatastoreContext.class);
+ doReturn(1000).when(datastoreContext).getShardBatchedModificationCount();
+ doReturn(datastoreContext).when(util).getDatastoreContext();
+
//set up data tree mock
final CursorAwareDataTreeModification modification = mock(CursorAwareDataTreeModification.class);
- doReturn(Optional.empty()).when(modification).readNode(YangInstanceIdentifier.empty());
+ doReturn(Optional.empty()).when(modification).readNode(YangInstanceIdentifier.of());
final DataTreeSnapshot snapshot = mock(DataTreeSnapshot.class);
doReturn(modification).when(snapshot).newModification();
final DataTree dataTree = mock(DataTree.class);
final TestProbe backendProbe = new TestProbe(system, "backend");
final long shard = 0L;
- behavior.createTransaction().read(YangInstanceIdentifier.empty());
+ behavior.createTransaction().read(YangInstanceIdentifier.of());
final AbstractClientConnection<ShardBackendInfo> connection = behavior.getConnection(shard);
//check cached connection for same shard
assertSame(connection, behavior.getConnection(shard));
final InternalCommand<ShardBackendInfo> command = clientActorProbe.expectMsgClass(InternalCommand.class);
command.execute(behavior);
//check, whether command was reaplayed
- verify(modification).readNode(YangInstanceIdentifier.empty());
+ verify(modification).readNode(YangInstanceIdentifier.of());
}
private static ActorUtils createActorContextMock(final ActorSystem system, final ActorRef actor) {
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
+import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import org.opendaylight.controller.cluster.access.concepts.RequestEnvelope;
import org.opendaylight.controller.cluster.access.concepts.Response;
import org.opendaylight.controller.cluster.access.concepts.TransactionIdentifier;
+import org.opendaylight.controller.cluster.datastore.DatastoreContext;
+import org.opendaylight.controller.cluster.datastore.utils.ActorUtils;
import org.opendaylight.yangtools.yang.common.Empty;
import org.opendaylight.yangtools.yang.common.QName;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
-import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
+import org.opendaylight.yangtools.yang.data.spi.node.ImmutableNodes;
import org.opendaylight.yangtools.yang.data.tree.api.CursorAwareDataTreeModification;
import org.opendaylight.yangtools.yang.data.tree.api.DataTreeSnapshot;
protected static final YangInstanceIdentifier PATH_3 = YangInstanceIdentifier.builder()
.node(QName.create("ns-1", "node-3"))
.build();
- protected static final ContainerNode DATA_1 = Builders.containerBuilder()
- .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(PATH_1.getLastPathArgument().getNodeType()))
+ protected static final ContainerNode DATA_1 = ImmutableNodes.newContainerBuilder()
+ .withNodeIdentifier(new NodeIdentifier(PATH_1.getLastPathArgument().getNodeType()))
.build();
- protected static final ContainerNode DATA_2 = Builders.containerBuilder()
- .withNodeIdentifier(new YangInstanceIdentifier.NodeIdentifier(PATH_2.getLastPathArgument().getNodeType()))
+ protected static final ContainerNode DATA_2 = ImmutableNodes.newContainerBuilder()
+ .withNodeIdentifier(new NodeIdentifier(PATH_2.getLastPathArgument().getNodeType()))
.build();
protected static final String PERSISTENCE_ID = "per-1";
private DataTreeSnapshot snapshot;
@Mock
private AbstractClientHistory history;
+ @Mock
+ private DatastoreContext datastoreContext;
+ @Mock
+ private ActorUtils actorUtils;
+
private ActorSystem system;
private TestProbe backendProbe;
private TestProbe clientContextProbe;
"default", UnsignedLong.ZERO, Optional.empty(), 3);
final AbstractClientConnection<ShardBackendInfo> connection =
AccessClientUtil.createConnectedConnection(context, 0L, backend);
+
final ProxyHistory parent = ProxyHistory.createClient(history, connection, HISTORY_ID);
transaction = createTransaction(parent, TestUtils.TRANSACTION_ID, snapshot);
tester = new TransactionTester<>(transaction, connection, backendProbe);
}
+ protected final void mockForRemote() {
+ doReturn(1000).when(datastoreContext).getShardBatchedModificationCount();
+ doReturn(datastoreContext).when(actorUtils).getDatastoreContext();
+ doReturn(actorUtils).when(history).actorUtils();
+ }
+
@SuppressWarnings("checkstyle:hiddenField")
protected abstract T createTransaction(ProxyHistory parent, TransactionIdentifier id, DataTreeSnapshot snapshot);
final ModifyTransactionRequest transformed = successor.expectTransactionRequest(ModifyTransactionRequest.class);
assertNotNull(transformed);
assertEquals(successful1.getSequence(), transformed.getSequence());
- assertTrue(transformed.getPersistenceProtocol().isPresent());
- assertEquals(PersistenceProtocol.ABORT, transformed.getPersistenceProtocol().get());
+ assertEquals(Optional.of(PersistenceProtocol.ABORT), transformed.getPersistenceProtocol());
ReadTransactionRequest tmpRead = successor.expectTransactionRequest(ReadTransactionRequest.class);
assertNotNull(tmpRead);
final TestProbe clientContextProbe = new TestProbe(system, "remoteClientContext");
final TestProbe backendProbe = new TestProbe(system, "remoteBackend");
final AbstractClientHistory history = mock(AbstractClientHistory.class);
+ doReturn(1000).when(datastoreContext).getShardBatchedModificationCount();
+ doReturn(datastoreContext).when(actorUtils).getDatastoreContext();
+ doReturn(actorUtils).when(history).actorUtils();
+
final ClientActorContext context =
AccessClientUtil.createClientActorContext(system, clientContextProbe.ref(), CLIENT_ID, PERSISTENCE_ID);
final ShardBackendInfo backend = new ShardBackendInfo(backendProbe.ref(), 0L, ABIVersion.current(),
final AbstractClientConnection<ShardBackendInfo> connection =
AccessClientUtil.createConnectedConnection(context, 0L, backend);
final ProxyHistory proxyHistory = ProxyHistory.createClient(history, connection, HISTORY_ID);
+
final RemoteProxyTransaction transaction =
new RemoteProxyTransaction(proxyHistory, TRANSACTION_ID, false, false, false);
return new TransactionTester<>(transaction, connection, backendProbe);
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
public class ClientSnapshotTest extends AbstractClientHandleTest<ClientSnapshot> {
- private static final YangInstanceIdentifier PATH = YangInstanceIdentifier.empty();
+ private static final YangInstanceIdentifier PATH = YangInstanceIdentifier.of();
@Before
@Override
package org.opendaylight.controller.cluster.databroker.actors.dds;
import static org.junit.Assert.assertEquals;
+import static org.mockito.Mockito.doReturn;
import static org.opendaylight.controller.cluster.databroker.actors.dds.TestUtils.CLIENT_ID;
import static org.opendaylight.controller.cluster.databroker.actors.dds.TestUtils.HISTORY_ID;
import static org.opendaylight.controller.cluster.databroker.actors.dds.TestUtils.TRANSACTION_ID;
import org.opendaylight.controller.cluster.access.commands.TransactionPreCommitSuccess;
import org.opendaylight.controller.cluster.access.concepts.RequestSuccess;
import org.opendaylight.controller.cluster.access.concepts.RuntimeRequestException;
+import org.opendaylight.controller.cluster.datastore.DatastoreContext;
+import org.opendaylight.controller.cluster.datastore.utils.ActorUtils;
import org.opendaylight.mdsal.common.api.CommitInfo;
import org.opendaylight.yangtools.yang.common.Empty;
@RunWith(MockitoJUnitRunner.StrictStubs.class)
public class ClientTransactionCommitCohortTest {
-
private static final String PERSISTENCE_ID = "per-1";
private static final int TRANSACTIONS = 3;
+ private final List<TransactionTester<RemoteProxyTransaction>> transactions = new ArrayList<>();
+
@Mock
private AbstractClientHistory history;
+ @Mock
+ private DatastoreContext datastoreContext;
+ @Mock
+ private ActorUtils actorUtils;
+
private ActorSystem system;
- private List<TransactionTester<RemoteProxyTransaction>> transactions;
private ClientTransactionCommitCohort cohort;
@Before
final TestProbe clientContextProbe = new TestProbe(system, "clientContext");
final ClientActorContext context =
AccessClientUtil.createClientActorContext(system, clientContextProbe.ref(), CLIENT_ID, PERSISTENCE_ID);
- transactions = new ArrayList<>();
+ doReturn(1000).when(datastoreContext).getShardBatchedModificationCount();
+ doReturn(datastoreContext).when(actorUtils).getDatastoreContext();
+ doReturn(actorUtils).when(history).actorUtils();
+
for (int i = 0; i < TRANSACTIONS; i++) {
transactions.add(createTransactionTester(new TestProbe(system, "backend" + i), context, history));
}
package org.opendaylight.controller.cluster.databroker.actors.dds;
import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.opendaylight.controller.cluster.databroker.actors.dds.TestUtils.TRANSACTION_ID;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
-import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
+import org.opendaylight.yangtools.yang.data.spi.node.ImmutableNodes;
import org.opendaylight.yangtools.yang.data.tree.api.CursorAwareDataTreeModification;
public class ClientTransactionTest extends AbstractClientHandleTest<ClientTransaction> {
-
- private static final YangInstanceIdentifier PATH = YangInstanceIdentifier.builder()
- .node(QName.create("ns-1", "node-1"))
- .build();
- private static final ContainerNode DATA = Builders.containerBuilder()
- .withNodeIdentifier(NodeIdentifier.create(PATH.getLastPathArgument().getNodeType()))
- .build();
+ private static final YangInstanceIdentifier PATH = YangInstanceIdentifier.of(QName.create("ns-1", "node-1"));
+ private static final ContainerNode DATA = ImmutableNodes.newContainerBuilder()
+ .withNodeIdentifier(NodeIdentifier.create(PATH.getLastPathArgument().getNodeType()))
+ .build();
@Mock
private CursorAwareDataTreeModification modification;
public void testRead() throws Exception {
final FluentFuture<Optional<NormalizedNode>> resultFuture = getHandle().read(PATH);
verify(modification).readNode(PATH);
- final Optional<NormalizedNode> result = getWithTimeout(resultFuture);
- assertTrue(result.isPresent());
- assertEquals(DATA, result.get());
+ assertEquals(Optional.of(DATA), getWithTimeout(resultFuture));
}
@Test
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
+import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.verify;
import static org.opendaylight.controller.cluster.databroker.actors.dds.TestUtils.CLIENT_ID;
import static org.opendaylight.controller.cluster.databroker.actors.dds.TestUtils.HISTORY_ID;
import org.opendaylight.controller.cluster.access.commands.PersistenceProtocol;
import org.opendaylight.controller.cluster.access.commands.TransactionCommitSuccess;
import org.opendaylight.controller.cluster.access.concepts.RequestSuccess;
+import org.opendaylight.controller.cluster.datastore.DatastoreContext;
+import org.opendaylight.controller.cluster.datastore.utils.ActorUtils;
@RunWith(MockitoJUnitRunner.StrictStubs.class)
public class DirectTransactionCommitCohortTest {
-
private static final String PERSISTENCE_ID = "per-1";
@Mock
private AbstractClientHistory history;
+ @Mock
+ private DatastoreContext datastoreContext;
+ @Mock
+ private ActorUtils actorUtils;
+
private ActorSystem system;
private TransactionTester<?> transaction;
private DirectTransactionCommitCohort cohort;
final TestProbe clientContextProbe = new TestProbe(system, "clientContext");
final ClientActorContext context =
AccessClientUtil.createClientActorContext(system, clientContextProbe.ref(), CLIENT_ID, PERSISTENCE_ID);
+ doReturn(1000).when(datastoreContext).getShardBatchedModificationCount();
+ doReturn(datastoreContext).when(actorUtils).getDatastoreContext();
+ doReturn(actorUtils).when(history).actorUtils();
+
transaction = createTransactionTester(new TestProbe(system, "backend"), context, history);
final AbstractProxyTransaction proxy = transaction.getTransaction();
proxy.seal();
public void testCanCommit() throws Exception {
final ListenableFuture<Boolean> canCommit = cohort.canCommit();
final ModifyTransactionRequest request = transaction.expectTransactionRequest(ModifyTransactionRequest.class);
- assertTrue(request.getPersistenceProtocol().isPresent());
- assertEquals(PersistenceProtocol.SIMPLE, request.getPersistenceProtocol().get());
+ assertEquals(Optional.of(PersistenceProtocol.SIMPLE), request.getPersistenceProtocol());
final RequestSuccess<?, ?> success = new TransactionCommitSuccess(transaction.getTransaction().getIdentifier(),
transaction.getLastReceivedMessage().getSequence());
transaction.replySuccess(success);
final Response<?, ?> value = captor.getValue();
assertTrue(value instanceof ReadTransactionSuccess);
final ReadTransactionSuccess success = (ReadTransactionSuccess) value;
- assertTrue(success.getData().isPresent());
- assertEquals(DATA_1, success.getData().get());
+ assertEquals(Optional.of(DATA_1), success.getData());
}
@Test
final TestProbe probe = createProbe();
final AbortLocalTransactionRequest request = new AbortLocalTransactionRequest(TRANSACTION_ID, probe.ref());
final ModifyTransactionRequest modifyRequest = testForwardToRemote(request, ModifyTransactionRequest.class);
- assertTrue(modifyRequest.getPersistenceProtocol().isPresent());
- assertEquals(PersistenceProtocol.ABORT, modifyRequest.getPersistenceProtocol().get());
+ assertEquals(Optional.of(PersistenceProtocol.ABORT), modifyRequest.getPersistenceProtocol());
}
@Override
doAnswer(LocalProxyTransactionTest::applyToCursorAnswer).when(modification).applyToCursor(any());
final ModifyTransactionRequest modifyRequest = testForwardToRemote(request, ModifyTransactionRequest.class);
verify(modification).applyToCursor(any());
- assertTrue(modifyRequest.getPersistenceProtocol().isPresent());
- assertEquals(PersistenceProtocol.THREE_PHASE, modifyRequest.getPersistenceProtocol().get());
+ assertEquals(Optional.of(PersistenceProtocol.THREE_PHASE), modifyRequest.getPersistenceProtocol());
checkModifications(modifyRequest);
}
final RemoteProxyTransaction successor = transactionTester.getTransaction();
doAnswer(LocalProxyTransactionTest::applyToCursorAnswer).when(modification).applyToCursor(any());
transaction.sealOnly();
- final TransactionRequest<?> request = transaction.flushState().get();
+ final TransactionRequest<?> request = transaction.flushState().orElseThrow();
transaction.forwardToSuccessor(successor, request, null);
verify(modification).applyToCursor(any());
transactionTester.getTransaction().seal();
moduleShardBackendResolver = new ModuleShardBackendResolver(CLIENT_ID, actorUtils);
doReturn(shardStrategyFactory).when(actorUtils).getShardStrategyFactory();
- doReturn(shardStrategy).when(shardStrategyFactory).getStrategy(YangInstanceIdentifier.empty());
+ doReturn(shardStrategy).when(shardStrategyFactory).getStrategy(YangInstanceIdentifier.of());
final PrimaryShardInfoFutureCache cache = new PrimaryShardInfoFutureCache();
doReturn(cache).when(actorUtils).getPrimaryShardInfoCache();
}
@Test
public void testResolveShardForPathNonNullCookie() {
- doReturn(DefaultShardStrategy.DEFAULT_SHARD).when(shardStrategy).findShard(YangInstanceIdentifier.empty());
- final Long cookie = moduleShardBackendResolver.resolveShardForPath(YangInstanceIdentifier.empty());
+ doReturn(DefaultShardStrategy.DEFAULT_SHARD).when(shardStrategy).findShard(YangInstanceIdentifier.of());
+ final Long cookie = moduleShardBackendResolver.resolveShardForPath(YangInstanceIdentifier.of());
assertEquals(0L, (long) cookie);
}
@Test
public void testResolveShardForPathNullCookie() {
- doReturn("foo").when(shardStrategy).findShard(YangInstanceIdentifier.empty());
- final Long cookie = moduleShardBackendResolver.resolveShardForPath(YangInstanceIdentifier.empty());
+ doReturn("foo").when(shardStrategy).findShard(YangInstanceIdentifier.of());
+ final Long cookie = moduleShardBackendResolver.resolveShardForPath(YangInstanceIdentifier.of());
assertEquals(1L, (long) cookie);
}
final CompletionStage<ShardBackendInfo> stage = moduleShardBackendResolver.getBackendInfo(0L);
final ShardBackendInfo shardBackendInfo = TestUtils.getWithTimeout(stage.toCompletableFuture());
assertEquals(0L, shardBackendInfo.getCookie().longValue());
- assertEquals(dataTree, shardBackendInfo.getDataTree().get());
+ assertEquals(dataTree, shardBackendInfo.getDataTree().orElseThrow());
assertEquals(DefaultShardStrategy.DEFAULT_SHARD, shardBackendInfo.getName());
}
import static org.hamcrest.CoreMatchers.isA;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
import static org.opendaylight.controller.cluster.databroker.actors.dds.TestUtils.assertFutureEquals;
import akka.testkit.TestProbe;
import org.opendaylight.yangtools.yang.data.tree.api.DataTreeSnapshot;
public class RemoteProxyTransactionTest extends AbstractProxyTransactionTest<RemoteProxyTransaction> {
-
@Override
protected RemoteProxyTransaction createTransaction(final ProxyHistory parent, final TransactionIdentifier id,
final DataTreeSnapshot snapshot) {
+ mockForRemote();
return new RemoteProxyTransaction(parent, TRANSACTION_ID, false, false, false);
}
final ListenableFuture<Boolean> result = transaction.directCommit();
final TransactionTester<RemoteProxyTransaction> tester = getTester();
final ModifyTransactionRequest req = tester.expectTransactionRequest(ModifyTransactionRequest.class);
- assertTrue(req.getPersistenceProtocol().isPresent());
- assertEquals(PersistenceProtocol.SIMPLE, req.getPersistenceProtocol().get());
+ assertEquals(Optional.of(PersistenceProtocol.SIMPLE), req.getPersistenceProtocol());
tester.replySuccess(new TransactionCommitSuccess(TRANSACTION_ID, req.getSequence()));
assertFutureEquals(true, result);
}
final ModifyTransactionRequest request = builder.build();
final ModifyTransactionRequest received = testForwardToRemote(request, ModifyTransactionRequest.class);
assertEquals(request.getTarget(), received.getTarget());
- assertTrue(received.getPersistenceProtocol().isPresent());
- assertEquals(PersistenceProtocol.ABORT, received.getPersistenceProtocol().get());
+ assertEquals(Optional.of(PersistenceProtocol.ABORT), received.getPersistenceProtocol());
}
@Test
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertThrows;
import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
import static org.mockito.ArgumentMatchers.any;
-import static org.mockito.ArgumentMatchers.eq;
+import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.timeout;
import static org.mockito.Mockito.verify;
import com.google.common.base.Throwables;
import com.google.common.collect.ImmutableMap;
import com.google.common.util.concurrent.FluentFuture;
+import com.google.common.util.concurrent.FutureCallback;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.MoreExecutors;
import com.google.common.util.concurrent.Uninterruptibles;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
+import org.junit.Ignore;
import org.junit.Test;
import org.junit.runners.Parameterized.Parameter;
-import org.mockito.Mockito;
import org.opendaylight.controller.cluster.access.client.RequestTimeoutException;
+import org.opendaylight.controller.cluster.databroker.ClientBackedDataStore;
import org.opendaylight.controller.cluster.databroker.ConcurrentDOMDataBroker;
import org.opendaylight.controller.cluster.datastore.TestShard.RequestFrontendMetadata;
-import org.opendaylight.controller.cluster.datastore.exceptions.NoShardLeaderException;
import org.opendaylight.controller.cluster.datastore.messages.FindLocalShard;
import org.opendaylight.controller.cluster.datastore.messages.LocalShardFound;
import org.opendaylight.controller.cluster.datastore.persisted.DatastoreSnapshot;
-import org.opendaylight.controller.cluster.datastore.persisted.FrontendClientMetadata;
import org.opendaylight.controller.cluster.datastore.persisted.FrontendShardDataTreeSnapshotMetadata;
import org.opendaylight.controller.cluster.datastore.persisted.MetadataShardDataTreeSnapshot;
import org.opendaylight.controller.cluster.datastore.persisted.ShardSnapshotState;
import org.opendaylight.mdsal.dom.api.DOMDataTreeWriteTransaction;
import org.opendaylight.mdsal.dom.api.DOMTransactionChain;
import org.opendaylight.mdsal.dom.api.DOMTransactionChainClosedException;
-import org.opendaylight.mdsal.dom.api.DOMTransactionChainListener;
import org.opendaylight.mdsal.dom.spi.store.DOMStore;
import org.opendaylight.mdsal.dom.spi.store.DOMStoreReadTransaction;
import org.opendaylight.mdsal.dom.spi.store.DOMStoreReadWriteTransaction;
import org.opendaylight.mdsal.dom.spi.store.DOMStoreThreePhaseCommitCohort;
import org.opendaylight.mdsal.dom.spi.store.DOMStoreTransactionChain;
import org.opendaylight.mdsal.dom.spi.store.DOMStoreWriteTransaction;
-import org.opendaylight.yangtools.concepts.ListenerRegistration;
import org.opendaylight.yangtools.yang.common.Uint64;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
public abstract class AbstractDistributedDataStoreIntegrationTest {
-
@Parameter
- public Class<? extends AbstractDataStore> testParameter;
+ public Class<? extends ClientBackedDataStore> testParameter;
protected ActorSystem system;
@Test
public void testWriteTransactionWithSingleShard() throws Exception {
final IntegrationTestKit testKit = new IntegrationTestKit(getSystem(), datastoreContextBuilder);
- try (AbstractDataStore dataStore = testKit.setupAbstractDataStore(
- testParameter, "transactionIntegrationTest", "test-1")) {
+ try (var dataStore = testKit.setupDataStore(testParameter, "transactionIntegrationTest", "test-1")) {
testKit.testWriteTransaction(dataStore, TestModel.TEST_PATH,
ImmutableNodes.containerNode(TestModel.TEST_QNAME));
@Test
public void testWriteTransactionWithMultipleShards() throws Exception {
final IntegrationTestKit testKit = new IntegrationTestKit(getSystem(), datastoreContextBuilder);
- try (AbstractDataStore dataStore = testKit.setupAbstractDataStore(
- testParameter, "testWriteTransactionWithMultipleShards", "cars-1", "people-1")) {
+ try (var dataStore = testKit.setupDataStore(testParameter, "testWriteTransactionWithMultipleShards",
+ "cars-1", "people-1")) {
DOMStoreWriteTransaction writeTx = dataStore.newWriteOnlyTransaction();
assertNotNull("newWriteOnlyTransaction returned null", writeTx);
// Verify the data in the store
final DOMStoreReadTransaction readTx = dataStore.newReadOnlyTransaction();
- Optional<NormalizedNode> optional = readTx.read(carPath).get(5, TimeUnit.SECONDS);
- assertTrue("isPresent", optional.isPresent());
- assertEquals("Data node", car, optional.get());
-
- optional = readTx.read(personPath).get(5, TimeUnit.SECONDS);
- assertTrue("isPresent", optional.isPresent());
- assertEquals("Data node", person, optional.get());
+ assertEquals(Optional.of(car), readTx.read(carPath).get(5, TimeUnit.SECONDS));
+ assertEquals(Optional.of(person), readTx.read(personPath).get(5, TimeUnit.SECONDS));
}
}
@Test
public void testReadWriteTransactionWithSingleShard() throws Exception {
final IntegrationTestKit testKit = new IntegrationTestKit(getSystem(), datastoreContextBuilder);
- try (AbstractDataStore dataStore = testKit.setupAbstractDataStore(
- testParameter, "testReadWriteTransactionWithSingleShard", "test-1")) {
+ try (var dataStore = testKit.setupDataStore(testParameter, "testReadWriteTransactionWithSingleShard",
+ "test-1")) {
// 1. Create a read-write Tx
final DOMStoreReadWriteTransaction readWriteTx = dataStore.newReadWriteTransaction();
final Boolean exists = readWriteTx.exists(nodePath).get(5, TimeUnit.SECONDS);
assertEquals("exists", Boolean.TRUE, exists);
- Optional<NormalizedNode> optional = readWriteTx.read(nodePath).get(5, TimeUnit.SECONDS);
- assertTrue("isPresent", optional.isPresent());
- assertEquals("Data node", nodeToWrite, optional.get());
+ assertEquals(Optional.of(nodeToWrite), readWriteTx.read(nodePath).get(5, TimeUnit.SECONDS));
// 4. Ready the Tx for commit
final DOMStoreThreePhaseCommitCohort cohort = readWriteTx.ready();
// 6. Verify the data in the store
final DOMStoreReadTransaction readTx = dataStore.newReadOnlyTransaction();
- optional = readTx.read(nodePath).get(5, TimeUnit.SECONDS);
- assertTrue("isPresent", optional.isPresent());
- assertEquals("Data node", nodeToWrite, optional.get());
+ assertEquals(Optional.of(nodeToWrite), readTx.read(nodePath).get(5, TimeUnit.SECONDS));
}
}
@Test
public void testReadWriteTransactionWithMultipleShards() throws Exception {
final IntegrationTestKit testKit = new IntegrationTestKit(getSystem(), datastoreContextBuilder);
- try (AbstractDataStore dataStore = testKit.setupAbstractDataStore(
- testParameter, "testReadWriteTransactionWithMultipleShards", "cars-1", "people-1")) {
+ try (var dataStore = testKit.setupDataStore(testParameter, "testReadWriteTransactionWithMultipleShards",
+ "cars-1", "people-1")) {
DOMStoreReadWriteTransaction readWriteTx = dataStore.newReadWriteTransaction();
assertNotNull("newReadWriteTransaction returned null", readWriteTx);
final Boolean exists = readWriteTx.exists(carPath).get(5, TimeUnit.SECONDS);
assertEquals("exists", Boolean.TRUE, exists);
- Optional<NormalizedNode> optional = readWriteTx.read(carPath).get(5, TimeUnit.SECONDS);
- assertTrue("isPresent", optional.isPresent());
- assertEquals("Data node", car, optional.get());
+ assertEquals("Data node", Optional.of(car), readWriteTx.read(carPath).get(5, TimeUnit.SECONDS));
testKit.doCommit(readWriteTx.ready());
// Verify the data in the store
DOMStoreReadTransaction readTx = dataStore.newReadOnlyTransaction();
- optional = readTx.read(carPath).get(5, TimeUnit.SECONDS);
- assertTrue("isPresent", optional.isPresent());
- assertEquals("Data node", car, optional.get());
-
- optional = readTx.read(personPath).get(5, TimeUnit.SECONDS);
- assertTrue("isPresent", optional.isPresent());
- assertEquals("Data node", person, optional.get());
+ assertEquals(Optional.of(car), readTx.read(carPath).get(5, TimeUnit.SECONDS));
+ assertEquals(Optional.of(person), readTx.read(personPath).get(5, TimeUnit.SECONDS));
}
}
@Test
public void testSingleTransactionsWritesInQuickSuccession() throws Exception {
- final IntegrationTestKit testKit = new IntegrationTestKit(getSystem(), datastoreContextBuilder);
- try (AbstractDataStore dataStore = testKit.setupAbstractDataStore(
- testParameter, "testSingleTransactionsWritesInQuickSuccession", "cars-1")) {
+ final var testKit = new IntegrationTestKit(getSystem(), datastoreContextBuilder);
+ try (var dataStore = testKit.setupDataStore(testParameter, "testSingleTransactionsWritesInQuickSuccession",
+ "cars-1")) {
- final DOMStoreTransactionChain txChain = dataStore.createTransactionChain();
+ final var txChain = dataStore.createTransactionChain();
- DOMStoreWriteTransaction writeTx = txChain.newWriteOnlyTransaction();
+ var writeTx = txChain.newWriteOnlyTransaction();
writeTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
writeTx.write(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode());
testKit.doCommit(writeTx.ready());
.untilAsserted(() -> {
// verify frontend metadata has no holes in purged transactions causing overtime memory leak
final var localShard = dataStore.getActorUtils().findLocalShard("cars-1") .orElseThrow();
- FrontendShardDataTreeSnapshotMetadata frontendMetadata =
- (FrontendShardDataTreeSnapshotMetadata) dataStore.getActorUtils()
+ final var frontendMetadata = (FrontendShardDataTreeSnapshotMetadata) dataStore.getActorUtils()
.executeOperation(localShard, new RequestFrontendMetadata());
final var clientMeta = frontendMetadata.getClients().get(0);
- if (dataStore.getActorUtils().getDatastoreContext().isUseTellBasedProtocol()) {
- assertTellMetadata(clientMeta);
- } else {
- assertAskMetadata(clientMeta);
+ final var iterator = clientMeta.getCurrentHistories().iterator();
+ var metadata = iterator.next();
+ while (iterator.hasNext() && metadata.getHistoryId() != 1) {
+ metadata = iterator.next();
}
+ assertEquals("[[0..10]]", metadata.getPurgedTransactions().ranges().toString());
});
final var body = txChain.newReadOnlyTransaction().read(CarsModel.CAR_LIST_PATH)
}
}
- private static void assertAskMetadata(final FrontendClientMetadata clientMeta) {
- // ask based should track no metadata
- assertEquals(List.of(), clientMeta.getCurrentHistories());
- }
-
- private static void assertTellMetadata(final FrontendClientMetadata clientMeta) {
- final var iterator = clientMeta.getCurrentHistories().iterator();
- var metadata = iterator.next();
- while (iterator.hasNext() && metadata.getHistoryId() != 1) {
- metadata = iterator.next();
- }
- assertEquals("[[0..10]]", metadata.getPurgedTransactions().ranges().toString());
- }
-
@SuppressWarnings("checkstyle:IllegalCatch")
private void testTransactionCommitFailureWithNoShardLeader(final boolean writeOnly, final String testName)
throws Exception {
datastoreContextBuilder.shardHeartbeatIntervalInMillis(100).shardElectionTimeoutFactor(1)
.shardInitializationTimeout(200, TimeUnit.MILLISECONDS).frontendRequestTimeoutInSeconds(2);
- try (AbstractDataStore dataStore = testKit.setupAbstractDataStore(testParameter, testName, false, shardName)) {
-
+ try (var dataStore = testKit.setupDataStore(testParameter, testName, false, shardName)) {
final Object result = dataStore.getActorUtils().executeOperation(
dataStore.getActorUtils().getShardManager(), new FindLocalShard(shardName, true));
assertTrue("Expected LocalShardFound. Actual: " + result, result instanceof LocalShardFound);
// leader was elected in time, the Tx
// should have timed out and throw an appropriate
// exception cause.
- try {
- txCohort.get().canCommit().get(10, TimeUnit.SECONDS);
- fail("Expected NoShardLeaderException");
- } catch (final ExecutionException e) {
- final String msg = "Unexpected exception: "
- + Throwables.getStackTraceAsString(e.getCause());
- if (DistributedDataStore.class.isAssignableFrom(testParameter)) {
- assertTrue(Throwables.getRootCause(e) instanceof NoShardLeaderException);
- } else {
- assertTrue(msg, Throwables.getRootCause(e) instanceof RequestTimeoutException);
- }
- }
+ final var ex = assertThrows(ExecutionException.class,
+ () -> txCohort.get().canCommit().get(10, TimeUnit.SECONDS));
+ assertTrue("Unexpected exception: " + Throwables.getStackTraceAsString(ex.getCause()),
+ Throwables.getRootCause(ex) instanceof RequestTimeoutException);
} finally {
try {
if (writeTxToClose != null) {
@Test
public void testTransactionAbort() throws Exception {
final IntegrationTestKit testKit = new IntegrationTestKit(getSystem(), datastoreContextBuilder);
- try (AbstractDataStore dataStore = testKit.setupAbstractDataStore(
- testParameter, "transactionAbortIntegrationTest", "test-1")) {
+ try (var dataStore = testKit.setupDataStore(testParameter, "transactionAbortIntegrationTest", "test-1")) {
final DOMStoreWriteTransaction writeTx = dataStore.newWriteOnlyTransaction();
assertNotNull("newWriteOnlyTransaction returned null", writeTx);
@SuppressWarnings("checkstyle:IllegalCatch")
public void testTransactionChainWithSingleShard() throws Exception {
final IntegrationTestKit testKit = new IntegrationTestKit(getSystem(), datastoreContextBuilder);
- try (AbstractDataStore dataStore = testKit.setupAbstractDataStore(
- testParameter, "testTransactionChainWithSingleShard", "test-1")) {
+ try (var dataStore = testKit.setupDataStore(testParameter, "testTransactionChainWithSingleShard", "test-1")) {
// 1. Create a Tx chain and write-only Tx
final DOMStoreTransactionChain txChain = dataStore.createTransactionChain();
// the data from the first
// Tx is visible after being readied.
DOMStoreReadTransaction readTx = txChain.newReadOnlyTransaction();
- Optional<NormalizedNode> optional = readTx.read(TestModel.TEST_PATH).get(5, TimeUnit.SECONDS);
- assertTrue("isPresent", optional.isPresent());
- assertEquals("Data node", testNode, optional.get());
+ assertEquals(Optional.of(testNode), readTx.read(TestModel.TEST_PATH).get(5, TimeUnit.SECONDS));
// 6. Create a new RW Tx from the chain, write more data,
// and ready it
// from the last RW Tx to
// verify it is visible.
readTx = txChain.newReadWriteTransaction();
- optional = readTx.read(TestModel.OUTER_LIST_PATH).get(5, TimeUnit.SECONDS);
- assertTrue("isPresent", optional.isPresent());
- assertEquals("Data node", outerNode, optional.get());
+ assertEquals(Optional.of(outerNode), readTx.read(TestModel.OUTER_LIST_PATH).get(5, TimeUnit.SECONDS));
// 8. Wait for the 2 commits to complete and close the
// chain.
// 9. Create a new read Tx from the data store and verify
// committed data.
readTx = dataStore.newReadOnlyTransaction();
- optional = readTx.read(TestModel.OUTER_LIST_PATH).get(5, TimeUnit.SECONDS);
- assertTrue("isPresent", optional.isPresent());
- assertEquals("Data node", outerNode, optional.get());
+ assertEquals(Optional.of(outerNode), readTx.read(TestModel.OUTER_LIST_PATH).get(5, TimeUnit.SECONDS));
}
}
@Test
public void testTransactionChainWithMultipleShards() throws Exception {
final IntegrationTestKit testKit = new IntegrationTestKit(getSystem(), datastoreContextBuilder);
- try (AbstractDataStore dataStore = testKit.setupAbstractDataStore(
- testParameter, "testTransactionChainWithMultipleShards", "cars-1", "people-1")) {
+ try (var dataStore = testKit.setupDataStore(testParameter, "testTransactionChainWithMultipleShards",
+ "cars-1", "people-1")) {
final DOMStoreTransactionChain txChain = dataStore.createTransactionChain();
final YangInstanceIdentifier personPath = PeopleModel.newPersonPath("jack");
readWriteTx.merge(personPath, person);
- Optional<NormalizedNode> optional = readWriteTx.read(carPath).get(5, TimeUnit.SECONDS);
- assertTrue("isPresent", optional.isPresent());
- assertEquals("Data node", car, optional.get());
-
- optional = readWriteTx.read(personPath).get(5, TimeUnit.SECONDS);
- assertTrue("isPresent", optional.isPresent());
- assertEquals("Data node", person, optional.get());
+ assertEquals(Optional.of(car), readWriteTx.read(carPath).get(5, TimeUnit.SECONDS));
+ assertEquals(Optional.of(person), readWriteTx.read(personPath).get(5, TimeUnit.SECONDS));
final DOMStoreThreePhaseCommitCohort cohort2 = readWriteTx.ready();
final DOMStoreReadTransaction readTx = dataStore.newReadOnlyTransaction();
- optional = readTx.read(carPath).get(5, TimeUnit.SECONDS);
- assertFalse("isPresent", optional.isPresent());
-
- optional = readTx.read(personPath).get(5, TimeUnit.SECONDS);
- assertTrue("isPresent", optional.isPresent());
- assertEquals("Data node", person, optional.get());
+ assertEquals(Optional.empty(), readTx.read(carPath).get(5, TimeUnit.SECONDS));
+ assertEquals(Optional.of(person), readTx.read(personPath).get(5, TimeUnit.SECONDS));
}
}
@Test
public void testCreateChainedTransactionsInQuickSuccession() throws Exception {
final IntegrationTestKit testKit = new IntegrationTestKit(getSystem(), datastoreContextBuilder);
- try (AbstractDataStore dataStore = testKit.setupAbstractDataStore(
- testParameter, "testCreateChainedTransactionsInQuickSuccession", "cars-1")) {
+ try (var dataStore = testKit.setupDataStore(testParameter, "testCreateChainedTransactionsInQuickSuccession",
+ "cars-1")) {
final ConcurrentDOMDataBroker broker = new ConcurrentDOMDataBroker(
ImmutableMap.<LogicalDatastoreType, DOMStore>builder()
.put(LogicalDatastoreType.CONFIGURATION, dataStore).build(),
MoreExecutors.directExecutor());
- final DOMTransactionChainListener listener = Mockito.mock(DOMTransactionChainListener.class);
- DOMTransactionChain txChain = broker.createTransactionChain(listener);
+ DOMTransactionChain txChain = broker.createTransactionChain();
final List<ListenableFuture<?>> futures = new ArrayList<>();
final Optional<NormalizedNode> optional = txChain.newReadOnlyTransaction()
.read(LogicalDatastoreType.CONFIGURATION, CarsModel.CAR_LIST_PATH).get(5, TimeUnit.SECONDS);
assertTrue("isPresent", optional.isPresent());
- assertEquals("# cars", numCars, ((Collection<?>) optional.get().body()).size());
+ assertEquals("# cars", numCars, ((Collection<?>) optional.orElseThrow().body()).size());
txChain.close();
@Test
public void testCreateChainedTransactionAfterEmptyTxReadied() throws Exception {
final IntegrationTestKit testKit = new IntegrationTestKit(getSystem(), datastoreContextBuilder);
- try (AbstractDataStore dataStore = testKit.setupAbstractDataStore(
- testParameter, "testCreateChainedTransactionAfterEmptyTxReadied", "test-1")) {
+ try (var dataStore = testKit.setupDataStore(testParameter, "testCreateChainedTransactionAfterEmptyTxReadied",
+ "test-1")) {
final DOMStoreTransactionChain txChain = dataStore.createTransactionChain();
@Test
public void testCreateChainedTransactionWhenPreviousNotReady() throws Exception {
final IntegrationTestKit testKit = new IntegrationTestKit(getSystem(), datastoreContextBuilder);
- try (AbstractDataStore dataStore = testKit.setupAbstractDataStore(
- testParameter, "testCreateChainedTransactionWhenPreviousNotReady", "test-1")) {
+ try (var dataStore = testKit.setupDataStore(testParameter, "testCreateChainedTransactionWhenPreviousNotReady",
+ "test-1")) {
final DOMStoreTransactionChain txChain = dataStore.createTransactionChain();
@Test
public void testCreateChainedTransactionAfterClose() throws Exception {
final IntegrationTestKit testKit = new IntegrationTestKit(getSystem(), datastoreContextBuilder);
- try (AbstractDataStore dataStore = testKit.setupAbstractDataStore(
- testParameter, "testCreateChainedTransactionAfterClose", "test-1")) {
+ try (var dataStore = testKit.setupDataStore(testParameter, "testCreateChainedTransactionAfterClose",
+ "test-1")) {
final DOMStoreTransactionChain txChain = dataStore.createTransactionChain();
txChain.close();
@Test
public void testChainWithReadOnlyTxAfterPreviousReady() throws Exception {
final IntegrationTestKit testKit = new IntegrationTestKit(getSystem(), datastoreContextBuilder);
- try (AbstractDataStore dataStore = testKit.setupAbstractDataStore(
- testParameter, "testChainWithReadOnlyTxAfterPreviousReady", "test-1")) {
+ try (var dataStore = testKit.setupDataStore(testParameter, "testChainWithReadOnlyTxAfterPreviousReady",
+ "test-1")) {
final DOMStoreTransactionChain txChain = dataStore.createTransactionChain();
@Test
public void testChainedTransactionFailureWithSingleShard() throws Exception {
- final IntegrationTestKit testKit = new IntegrationTestKit(getSystem(), datastoreContextBuilder);
- try (AbstractDataStore dataStore = testKit.setupAbstractDataStore(
- testParameter, "testChainedTransactionFailureWithSingleShard", "cars-1")) {
+ final var testKit = new IntegrationTestKit(getSystem(), datastoreContextBuilder);
+ try (var dataStore = testKit.setupDataStore(testParameter, "testChainedTransactionFailureWithSingleShard",
+ "cars-1")) {
- final ConcurrentDOMDataBroker broker = new ConcurrentDOMDataBroker(
+ final var broker = new ConcurrentDOMDataBroker(
ImmutableMap.<LogicalDatastoreType, DOMStore>builder()
.put(LogicalDatastoreType.CONFIGURATION, dataStore).build(),
MoreExecutors.directExecutor());
- final DOMTransactionChainListener listener = Mockito.mock(DOMTransactionChainListener.class);
- final DOMTransactionChain txChain = broker.createTransactionChain(listener);
+ final var listener = mock(FutureCallback.class);
+ final var txChain = broker.createTransactionChain();
+ txChain.addCallback(listener);
- final DOMDataTreeReadWriteTransaction writeTx = txChain.newReadWriteTransaction();
+ final var writeTx = txChain.newReadWriteTransaction();
writeTx.put(LogicalDatastoreType.CONFIGURATION, PeopleModel.BASE_PATH,
PeopleModel.emptyContainer());
- final ContainerNode invalidData = Builders.containerBuilder()
+ final var invalidData = Builders.containerBuilder()
.withNodeIdentifier(new NodeIdentifier(CarsModel.BASE_QNAME))
.withChild(ImmutableNodes.leafNode(TestModel.JUNK_QNAME, "junk"))
.build();
writeTx.merge(LogicalDatastoreType.CONFIGURATION, CarsModel.BASE_PATH, invalidData);
- try {
- writeTx.commit().get(5, TimeUnit.SECONDS);
- fail("Expected TransactionCommitFailedException");
- } catch (final ExecutionException e) {
- // Expected
- }
+ assertThrows(ExecutionException.class, () -> writeTx.commit().get(5, TimeUnit.SECONDS));
- verify(listener, timeout(5000)).onTransactionChainFailed(eq(txChain), eq(writeTx),
- any(Throwable.class));
+ verify(listener, timeout(5000)).onFailure(any());
txChain.close();
broker.close();
@Test
public void testChainedTransactionFailureWithMultipleShards() throws Exception {
final IntegrationTestKit testKit = new IntegrationTestKit(getSystem(), datastoreContextBuilder);
- try (AbstractDataStore dataStore = testKit.setupAbstractDataStore(
- testParameter, "testChainedTransactionFailureWithMultipleShards", "cars-1", "people-1")) {
+ try (var dataStore = testKit.setupDataStore(testParameter, "testChainedTransactionFailureWithMultipleShards",
+ "cars-1", "people-1")) {
final ConcurrentDOMDataBroker broker = new ConcurrentDOMDataBroker(
ImmutableMap.<LogicalDatastoreType, DOMStore>builder()
.put(LogicalDatastoreType.CONFIGURATION, dataStore).build(),
MoreExecutors.directExecutor());
- final DOMTransactionChainListener listener = Mockito.mock(DOMTransactionChainListener.class);
- final DOMTransactionChain txChain = broker.createTransactionChain(listener);
+ final var listener = mock(FutureCallback.class);
+ final DOMTransactionChain txChain = broker.createTransactionChain();
+ txChain.addCallback(listener);
final DOMDataTreeWriteTransaction writeTx = txChain.newReadWriteTransaction();
// Note that merge will validate the data and fail but put
// succeeds b/c deep validation is not
// done for put for performance reasons.
- try {
- writeTx.commit().get(5, TimeUnit.SECONDS);
- fail("Expected TransactionCommitFailedException");
- } catch (final ExecutionException e) {
- // Expected
- }
+ assertThrows(ExecutionException.class, () -> writeTx.commit().get(5, TimeUnit.SECONDS));
- verify(listener, timeout(5000)).onTransactionChainFailed(eq(txChain), eq(writeTx),
- any(Throwable.class));
+ verify(listener, timeout(5000)).onFailure(any());
txChain.close();
broker.close();
@Test
public void testDataTreeChangeListenerRegistration() throws Exception {
final IntegrationTestKit testKit = new IntegrationTestKit(getSystem(), datastoreContextBuilder);
- try (AbstractDataStore dataStore = testKit.setupAbstractDataStore(
- testParameter, "testDataTreeChangeListenerRegistration", "test-1")) {
+ try (var dataStore = testKit.setupDataStore(testParameter, "testDataTreeChangeListenerRegistration",
+ "test-1")) {
testKit.testWriteTransaction(dataStore, TestModel.TEST_PATH,
ImmutableNodes.containerNode(TestModel.TEST_QNAME));
final MockDataTreeChangeListener listener = new MockDataTreeChangeListener(1);
- ListenerRegistration<MockDataTreeChangeListener> listenerReg = dataStore
- .registerTreeChangeListener(TestModel.TEST_PATH, listener);
+ final var listenerReg = dataStore.registerTreeChangeListener(TestModel.TEST_PATH, listener);
assertNotNull("registerTreeChangeListener returned null", listenerReg);
DataTree dataTree = new InMemoryDataTreeFactory().create(
DataTreeConfiguration.DEFAULT_OPERATIONAL, SchemaContextHelper.full());
AbstractShardTest.writeToStore(dataTree, CarsModel.BASE_PATH, carsNode);
- NormalizedNode root = AbstractShardTest.readStore(dataTree, YangInstanceIdentifier.empty());
+ NormalizedNode root = AbstractShardTest.readStore(dataTree, YangInstanceIdentifier.of());
final Snapshot carsSnapshot = Snapshot.create(
new ShardSnapshotState(new MetadataShardDataTreeSnapshot(root)),
final NormalizedNode peopleNode = PeopleModel.create();
AbstractShardTest.writeToStore(dataTree, PeopleModel.BASE_PATH, peopleNode);
- root = AbstractShardTest.readStore(dataTree, YangInstanceIdentifier.empty());
+ root = AbstractShardTest.readStore(dataTree, YangInstanceIdentifier.of());
final Snapshot peopleSnapshot = Snapshot.create(
new ShardSnapshotState(new MetadataShardDataTreeSnapshot(root)),
new DatastoreSnapshot.ShardSnapshot("cars", carsSnapshot),
new DatastoreSnapshot.ShardSnapshot("people", peopleSnapshot)));
- try (AbstractDataStore dataStore = testKit.setupAbstractDataStore(
- testParameter, name, "module-shards-member1.conf", true, "cars", "people")) {
+ try (var dataStore = testKit.setupDataStore(testParameter, name, "module-shards-member1.conf", true,
+ "cars", "people")) {
final DOMStoreReadTransaction readTx = dataStore.newReadOnlyTransaction();
// two reads
- Optional<NormalizedNode> optional = readTx.read(CarsModel.BASE_PATH).get(5, TimeUnit.SECONDS);
- assertTrue("isPresent", optional.isPresent());
- assertEquals("Data node", carsNode, optional.get());
-
- optional = readTx.read(PeopleModel.BASE_PATH).get(5, TimeUnit.SECONDS);
- assertTrue("isPresent", optional.isPresent());
- assertEquals("Data node", peopleNode, optional.get());
+ assertEquals(Optional.of(carsNode), readTx.read(CarsModel.BASE_PATH).get(5, TimeUnit.SECONDS));
+ assertEquals(Optional.of(peopleNode), readTx.read(PeopleModel.BASE_PATH).get(5, TimeUnit.SECONDS));
}
}
@Test
+ @Ignore("ClientBackedDatastore does not have stable indexes/term, the snapshot index seems to fluctuate")
+ // FIXME: re-enable this test
public void testSnapshotOnRootOverwrite() throws Exception {
- if (!DistributedDataStore.class.isAssignableFrom(testParameter)) {
- // FIXME: ClientBackedDatastore does not have stable indexes/term, the snapshot index seems to fluctuate
- return;
- }
-
- final IntegrationTestKit testKit = new IntegrationTestKit(getSystem(),
- datastoreContextBuilder.snapshotOnRootOverwrite(true));
- try (AbstractDataStore dataStore = testKit.setupAbstractDataStore(
- testParameter, "testRootOverwrite", "module-shards-default-cars-member1.conf",
- true, "cars", "default")) {
+ final var testKit = new IntegrationTestKit(getSystem(), datastoreContextBuilder.snapshotOnRootOverwrite(true));
+ try (var dataStore = testKit.setupDataStore(testParameter, "testRootOverwrite",
+ "module-shards-default-cars-member1.conf", true, "cars", "default")) {
- ContainerNode rootNode = Builders.containerBuilder()
+ final var rootNode = Builders.containerBuilder()
.withNodeIdentifier(NodeIdentifier.create(SchemaContext.NAME))
.withChild(CarsModel.create())
.build();
- testKit.testWriteTransaction(dataStore, YangInstanceIdentifier.empty(), rootNode);
+ testKit.testWriteTransaction(dataStore, YangInstanceIdentifier.of(), rootNode);
IntegrationTestKit.verifyShardState(dataStore, "cars",
state -> assertEquals(1, state.getSnapshotIndex()));
verifySnapshot("member-1-shard-cars-testRootOverwrite", 1, 1);
// root overwrite so expect a snapshot
- testKit.testWriteTransaction(dataStore, YangInstanceIdentifier.empty(), rootNode);
+ testKit.testWriteTransaction(dataStore, YangInstanceIdentifier.of(), rootNode);
// this was a real snapshot so everything should be in it(1 + 10 + 1)
IntegrationTestKit.verifyShardState(dataStore, "cars",
final Optional<DataContainerChild> idLeaf =
mapEntry.findChildByArg(new YangInstanceIdentifier.NodeIdentifier(TestModel.ID_QNAME));
assertTrue("Missing leaf " + TestModel.ID_QNAME.getLocalName(), idLeaf.isPresent());
- final Object value = idLeaf.get().body();
+ final Object value = idLeaf.orElseThrow().body();
assertTrue("Unexpected value for leaf " + TestModel.ID_QNAME.getLocalName() + ": " + value,
listEntryKeys.remove(value));
}
writeToStore(testStore, TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME));
- final NormalizedNode root = readStore(testStore, YangInstanceIdentifier.empty());
+ final NormalizedNode root = readStore(testStore, YangInstanceIdentifier.of());
InMemorySnapshotStore.addSnapshot(shardID.toString(), Snapshot.create(
new ShardSnapshotState(new MetadataShardDataTreeSnapshot(root)),
final Optional<DataContainerChild> idLeaf =
mapEntry.findChildByArg(new YangInstanceIdentifier.NodeIdentifier(TestModel.ID_QNAME));
assertTrue("Missing leaf " + TestModel.ID_QNAME.getLocalName(), idLeaf.isPresent());
- assertEquals(TestModel.ID_QNAME.getLocalName() + " value", expIDValue, idLeaf.get().body());
+ assertEquals(TestModel.ID_QNAME.getLocalName() + " value", expIDValue, idLeaf.orElseThrow().body());
}
public static DataTreeCandidateTip mockCandidate(final String name) {
final DataTreeCandidateTip mockCandidate = mock(DataTreeCandidateTip.class, name);
final DataTreeCandidateNode mockCandidateNode = mock(DataTreeCandidateNode.class, name + "-node");
- doReturn(ModificationType.WRITE).when(mockCandidateNode).getModificationType();
- doReturn(Optional.of(ImmutableNodes.containerNode(CarsModel.CARS_QNAME)))
- .when(mockCandidateNode).getDataAfter();
+ doReturn(ModificationType.WRITE).when(mockCandidateNode).modificationType();
+ doReturn(ImmutableNodes.containerNode(CarsModel.CARS_QNAME)).when(mockCandidateNode).dataAfter();
doReturn(CarsModel.BASE_PATH).when(mockCandidate).getRootPath();
doReturn(mockCandidateNode).when(mockCandidate).getRootNode();
return mockCandidate;
static DataTreeCandidateTip mockUnmodifiedCandidate(final String name) {
final DataTreeCandidateTip mockCandidate = mock(DataTreeCandidateTip.class, name);
final DataTreeCandidateNode mockCandidateNode = mock(DataTreeCandidateNode.class, name + "-node");
- doReturn(ModificationType.UNMODIFIED).when(mockCandidateNode).getModificationType();
- doReturn(YangInstanceIdentifier.empty()).when(mockCandidate).getRootPath();
+ doReturn(ModificationType.UNMODIFIED).when(mockCandidateNode).modificationType();
+ doReturn(YangInstanceIdentifier.of()).when(mockCandidate).getRootPath();
doReturn(mockCandidateNode).when(mockCandidate).getRootNode();
return mockCandidate;
}
}
@Override
- public TransactionIdentifier getIdentifier() {
- return delegate.getIdentifier();
+ TransactionIdentifier transactionId() {
+ return delegate.transactionId();
}
@Override
+++ /dev/null
-/*
- * Copyright (c) 2015 Brocade Communications Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.cluster.datastore;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
-import static org.mockito.ArgumentMatchers.any;
-import static org.mockito.ArgumentMatchers.argThat;
-import static org.mockito.ArgumentMatchers.eq;
-import static org.mockito.ArgumentMatchers.isA;
-import static org.mockito.Mockito.doReturn;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.verify;
-
-import akka.actor.ActorRef;
-import akka.actor.ActorSelection;
-import akka.actor.ActorSystem;
-import akka.actor.Props;
-import akka.dispatch.Futures;
-import akka.testkit.javadsl.TestKit;
-import akka.util.Timeout;
-import com.codahale.metrics.MetricRegistry;
-import com.codahale.metrics.Timer;
-import com.google.common.base.Throwables;
-import com.google.common.collect.ImmutableMap;
-import com.google.common.util.concurrent.FluentFuture;
-import com.typesafe.config.Config;
-import com.typesafe.config.ConfigFactory;
-import java.util.ArrayList;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.Objects;
-import java.util.concurrent.ExecutionException;
-import java.util.concurrent.TimeUnit;
-import org.junit.AfterClass;
-import org.junit.Before;
-import org.junit.BeforeClass;
-import org.mockito.ArgumentCaptor;
-import org.mockito.ArgumentMatcher;
-import org.mockito.Mock;
-import org.mockito.Mockito;
-import org.mockito.MockitoAnnotations;
-import org.opendaylight.controller.cluster.access.concepts.ClientIdentifier;
-import org.opendaylight.controller.cluster.access.concepts.MemberName;
-import org.opendaylight.controller.cluster.datastore.DatastoreContext.Builder;
-import org.opendaylight.controller.cluster.datastore.TransactionProxyTest.TestException;
-import org.opendaylight.controller.cluster.datastore.config.Configuration;
-import org.opendaylight.controller.cluster.datastore.messages.BatchedModifications;
-import org.opendaylight.controller.cluster.datastore.messages.BatchedModificationsReply;
-import org.opendaylight.controller.cluster.datastore.messages.CommitTransactionReply;
-import org.opendaylight.controller.cluster.datastore.messages.CreateTransaction;
-import org.opendaylight.controller.cluster.datastore.messages.CreateTransactionReply;
-import org.opendaylight.controller.cluster.datastore.messages.DataExists;
-import org.opendaylight.controller.cluster.datastore.messages.DataExistsReply;
-import org.opendaylight.controller.cluster.datastore.messages.PrimaryShardInfo;
-import org.opendaylight.controller.cluster.datastore.messages.ReadData;
-import org.opendaylight.controller.cluster.datastore.messages.ReadDataReply;
-import org.opendaylight.controller.cluster.datastore.messages.ReadyLocalTransaction;
-import org.opendaylight.controller.cluster.datastore.messages.ReadyTransactionReply;
-import org.opendaylight.controller.cluster.datastore.modification.AbstractModification;
-import org.opendaylight.controller.cluster.datastore.modification.Modification;
-import org.opendaylight.controller.cluster.datastore.modification.WriteModification;
-import org.opendaylight.controller.cluster.datastore.shardstrategy.DefaultShardStrategy;
-import org.opendaylight.controller.cluster.datastore.shardstrategy.ShardStrategy;
-import org.opendaylight.controller.cluster.datastore.shardstrategy.ShardStrategyFactory;
-import org.opendaylight.controller.cluster.datastore.utils.ActorUtils;
-import org.opendaylight.controller.cluster.datastore.utils.MockConfiguration;
-import org.opendaylight.controller.cluster.raft.utils.DoNothingActor;
-import org.opendaylight.controller.md.cluster.datastore.model.CarsModel;
-import org.opendaylight.controller.md.cluster.datastore.model.TestModel;
-import org.opendaylight.mdsal.common.api.ReadFailedException;
-import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
-import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
-import org.opendaylight.yangtools.yang.model.api.SchemaContext;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import scala.concurrent.Await;
-import scala.concurrent.Future;
-import scala.concurrent.duration.FiniteDuration;
-
-/**
- * Abstract base class for TransactionProxy unit tests.
- *
- * @author Thomas Pantelis
- */
-public abstract class AbstractTransactionProxyTest extends AbstractTest {
- protected final Logger log = LoggerFactory.getLogger(getClass());
-
- private static ActorSystem system;
- private static SchemaContext SCHEMA_CONTEXT;
-
- private final Configuration configuration = new MockConfiguration() {
- Map<String, ShardStrategy> strategyMap = ImmutableMap.<String, ShardStrategy>builder().put(
- TestModel.JUNK_QNAME.getLocalName(), new ShardStrategy() {
- @Override
- public String findShard(final YangInstanceIdentifier path) {
- return TestModel.JUNK_QNAME.getLocalName();
- }
- }).put(
- CarsModel.BASE_QNAME.getLocalName(), new ShardStrategy() {
- @Override
- public String findShard(final YangInstanceIdentifier path) {
- return CarsModel.BASE_QNAME.getLocalName();
- }
- }).build();
-
- @Override
- public ShardStrategy getStrategyForModule(final String moduleName) {
- return strategyMap.get(moduleName);
- }
-
- @Override
- public String getModuleNameFromNameSpace(final String nameSpace) {
- if (TestModel.JUNK_QNAME.getNamespace().toString().equals(nameSpace)) {
- return TestModel.JUNK_QNAME.getLocalName();
- } else if (CarsModel.BASE_QNAME.getNamespace().toString().equals(nameSpace)) {
- return CarsModel.BASE_QNAME.getLocalName();
- }
- return null;
- }
- };
-
- @Mock
- protected ActorUtils mockActorContext;
-
- protected TransactionContextFactory mockComponentFactory;
-
- @Mock
- private ClusterWrapper mockClusterWrapper;
-
- protected final String memberName = "mock-member";
-
- private final int operationTimeoutInSeconds = 2;
- protected final Builder dataStoreContextBuilder = DatastoreContext.newBuilder()
- .operationTimeoutInSeconds(operationTimeoutInSeconds);
-
- @BeforeClass
- public static void setUpClass() {
-
- Config config = ConfigFactory.parseMap(ImmutableMap.<String, Object>builder()
- .put("akka.actor.default-dispatcher.type",
- "akka.testkit.CallingThreadDispatcherConfigurator").build())
- .withFallback(ConfigFactory.load());
- system = ActorSystem.create("test", config);
- SCHEMA_CONTEXT = TestModel.createTestContext();
- }
-
- @AfterClass
- public static void tearDownClass() {
- TestKit.shutdownActorSystem(system);
- system = null;
- SCHEMA_CONTEXT = null;
- }
-
- @Before
- public void setUp() {
- MockitoAnnotations.initMocks(this);
-
- doReturn(getSystem()).when(mockActorContext).getActorSystem();
- doReturn(getSystem().dispatchers().defaultGlobalDispatcher()).when(mockActorContext).getClientDispatcher();
- doReturn(MemberName.forName(memberName)).when(mockActorContext).getCurrentMemberName();
- doReturn(new ShardStrategyFactory(configuration)).when(mockActorContext).getShardStrategyFactory();
- doReturn(SCHEMA_CONTEXT).when(mockActorContext).getSchemaContext();
- doReturn(new Timeout(operationTimeoutInSeconds, TimeUnit.SECONDS)).when(mockActorContext).getOperationTimeout();
- doReturn(mockClusterWrapper).when(mockActorContext).getClusterWrapper();
- doReturn(mockClusterWrapper).when(mockActorContext).getClusterWrapper();
- doReturn(dataStoreContextBuilder.build()).when(mockActorContext).getDatastoreContext();
- doReturn(new Timeout(5, TimeUnit.SECONDS)).when(mockActorContext).getTransactionCommitOperationTimeout();
-
- final ClientIdentifier mockClientId = MockIdentifiers.clientIdentifier(getClass(), memberName);
- mockComponentFactory = new TransactionContextFactory(mockActorContext, mockClientId);
-
- Timer timer = new MetricRegistry().timer("test");
- doReturn(timer).when(mockActorContext).getOperationTimer(any(String.class));
- }
-
- protected ActorSystem getSystem() {
- return system;
- }
-
- protected CreateTransaction eqCreateTransaction(final String expMemberName,
- final TransactionType type) {
- class CreateTransactionArgumentMatcher implements ArgumentMatcher<CreateTransaction> {
- @Override
- public boolean matches(final CreateTransaction argument) {
- return argument.getTransactionId().getHistoryId().getClientId().getFrontendId().getMemberName()
- .getName().equals(expMemberName) && argument.getTransactionType() == type.ordinal();
- }
- }
-
- return argThat(new CreateTransactionArgumentMatcher());
- }
-
- protected DataExists eqDataExists() {
- class DataExistsArgumentMatcher implements ArgumentMatcher<DataExists> {
- @Override
- public boolean matches(final DataExists argument) {
- return argument.getPath().equals(TestModel.TEST_PATH);
- }
- }
-
- return argThat(new DataExistsArgumentMatcher());
- }
-
- protected ReadData eqReadData() {
- return eqReadData(TestModel.TEST_PATH);
- }
-
- protected ReadData eqReadData(final YangInstanceIdentifier path) {
- class ReadDataArgumentMatcher implements ArgumentMatcher<ReadData> {
- @Override
- public boolean matches(final ReadData argument) {
- return argument.getPath().equals(path);
- }
- }
-
- return argThat(new ReadDataArgumentMatcher());
- }
-
- protected Future<Object> readyTxReply(final String path) {
- return Futures.successful((Object)new ReadyTransactionReply(path));
- }
-
-
- protected Future<ReadDataReply> readDataReply(final NormalizedNode data) {
- return Futures.successful(new ReadDataReply(data, DataStoreVersions.CURRENT_VERSION));
- }
-
- protected Future<DataExistsReply> dataExistsReply(final boolean exists) {
- return Futures.successful(new DataExistsReply(exists, DataStoreVersions.CURRENT_VERSION));
- }
-
- protected Future<BatchedModificationsReply> batchedModificationsReply(final int count) {
- return Futures.successful(new BatchedModificationsReply(count));
- }
-
- @SuppressWarnings("unchecked")
- protected Future<Object> incompleteFuture() {
- return mock(Future.class);
- }
-
- protected ActorSelection actorSelection(final ActorRef actorRef) {
- return getSystem().actorSelection(actorRef.path());
- }
-
- protected void expectBatchedModifications(final ActorRef actorRef, final int count) {
- doReturn(batchedModificationsReply(count)).when(mockActorContext).executeOperationAsync(
- eq(actorSelection(actorRef)), isA(BatchedModifications.class), any(Timeout.class));
- }
-
- protected void expectBatchedModifications(final int count) {
- doReturn(batchedModificationsReply(count)).when(mockActorContext).executeOperationAsync(
- any(ActorSelection.class), isA(BatchedModifications.class), any(Timeout.class));
- }
-
- protected void expectBatchedModificationsReady(final ActorRef actorRef) {
- expectBatchedModificationsReady(actorRef, false);
- }
-
- protected void expectBatchedModificationsReady(final ActorRef actorRef, final boolean doCommitOnReady) {
- doReturn(doCommitOnReady ? Futures.successful(new CommitTransactionReply().toSerializable()) :
- readyTxReply(actorRef.path().toString())).when(mockActorContext).executeOperationAsync(
- eq(actorSelection(actorRef)), isA(BatchedModifications.class), any(Timeout.class));
- }
-
- protected void expectIncompleteBatchedModifications() {
- doReturn(incompleteFuture()).when(mockActorContext).executeOperationAsync(
- any(ActorSelection.class), isA(BatchedModifications.class), any(Timeout.class));
- }
-
- protected void expectFailedBatchedModifications(final ActorRef actorRef) {
- doReturn(Futures.failed(new TestException())).when(mockActorContext).executeOperationAsync(
- eq(actorSelection(actorRef)), isA(BatchedModifications.class), any(Timeout.class));
- }
-
- protected void expectReadyLocalTransaction(final ActorRef actorRef, final boolean doCommitOnReady) {
- doReturn(doCommitOnReady ? Futures.successful(new CommitTransactionReply().toSerializable()) :
- readyTxReply(actorRef.path().toString())).when(mockActorContext).executeOperationAsync(
- eq(actorSelection(actorRef)), isA(ReadyLocalTransaction.class), any(Timeout.class));
- }
-
- protected CreateTransactionReply createTransactionReply(final ActorRef actorRef, final short transactionVersion) {
- return new CreateTransactionReply(actorRef.path().toString(), nextTransactionId(), transactionVersion);
- }
-
- protected ActorRef setupActorContextWithoutInitialCreateTransaction(final ActorSystem actorSystem) {
- return setupActorContextWithoutInitialCreateTransaction(actorSystem, DefaultShardStrategy.DEFAULT_SHARD);
- }
-
- protected ActorRef setupActorContextWithoutInitialCreateTransaction(final ActorSystem actorSystem,
- final String shardName) {
- return setupActorContextWithoutInitialCreateTransaction(actorSystem, shardName,
- DataStoreVersions.CURRENT_VERSION);
- }
-
- protected ActorRef setupActorContextWithoutInitialCreateTransaction(final ActorSystem actorSystem,
- final String shardName, final short transactionVersion) {
- ActorRef actorRef = actorSystem.actorOf(Props.create(DoNothingActor.class));
- log.info("Created mock shard actor {}", actorRef);
-
- doReturn(actorSystem.actorSelection(actorRef.path()))
- .when(mockActorContext).actorSelection(actorRef.path().toString());
-
- doReturn(primaryShardInfoReply(actorSystem, actorRef, transactionVersion))
- .when(mockActorContext).findPrimaryShardAsync(eq(shardName));
-
- return actorRef;
- }
-
- protected Future<PrimaryShardInfo> primaryShardInfoReply(final ActorSystem actorSystem, final ActorRef actorRef) {
- return primaryShardInfoReply(actorSystem, actorRef, DataStoreVersions.CURRENT_VERSION);
- }
-
- protected Future<PrimaryShardInfo> primaryShardInfoReply(final ActorSystem actorSystem, final ActorRef actorRef,
- final short transactionVersion) {
- return Futures.successful(new PrimaryShardInfo(actorSystem.actorSelection(actorRef.path()),
- transactionVersion));
- }
-
- protected ActorRef setupActorContextWithInitialCreateTransaction(final ActorSystem actorSystem,
- final TransactionType type, final short transactionVersion, final String shardName) {
- ActorRef shardActorRef = setupActorContextWithoutInitialCreateTransaction(actorSystem, shardName,
- transactionVersion);
-
- return setupActorContextWithInitialCreateTransaction(actorSystem, type, transactionVersion,
- memberName, shardActorRef);
- }
-
- protected ActorRef setupActorContextWithInitialCreateTransaction(final ActorSystem actorSystem,
- final TransactionType type, final short transactionVersion, final String prefix,
- final ActorRef shardActorRef) {
-
- ActorRef txActorRef;
- if (type == TransactionType.WRITE_ONLY
- && dataStoreContextBuilder.build().isWriteOnlyTransactionOptimizationsEnabled()) {
- txActorRef = shardActorRef;
- } else {
- txActorRef = actorSystem.actorOf(Props.create(DoNothingActor.class));
- log.info("Created mock shard Tx actor {}", txActorRef);
-
- doReturn(actorSystem.actorSelection(txActorRef.path()))
- .when(mockActorContext).actorSelection(txActorRef.path().toString());
-
- doReturn(Futures.successful(createTransactionReply(txActorRef, transactionVersion))).when(mockActorContext)
- .executeOperationAsync(eq(actorSystem.actorSelection(shardActorRef.path())),
- eqCreateTransaction(prefix, type), any(Timeout.class));
- }
-
- return txActorRef;
- }
-
- protected ActorRef setupActorContextWithInitialCreateTransaction(final ActorSystem actorSystem,
- final TransactionType type) {
- return setupActorContextWithInitialCreateTransaction(actorSystem, type, DataStoreVersions.CURRENT_VERSION,
- DefaultShardStrategy.DEFAULT_SHARD);
- }
-
- protected ActorRef setupActorContextWithInitialCreateTransaction(final ActorSystem actorSystem,
- final TransactionType type,
- final String shardName) {
- return setupActorContextWithInitialCreateTransaction(actorSystem, type, DataStoreVersions.CURRENT_VERSION,
- shardName);
- }
-
- @SuppressWarnings({"checkstyle:avoidHidingCauseException", "checkstyle:IllegalThrows"})
- protected void propagateReadFailedExceptionCause(final FluentFuture<?> future) throws Throwable {
- try {
- future.get(5, TimeUnit.SECONDS);
- fail("Expected ReadFailedException");
- } catch (ExecutionException e) {
- final Throwable cause = e.getCause();
- assertTrue("Unexpected cause: " + cause.getClass(), cause instanceof ReadFailedException);
- throw Throwables.getRootCause(cause);
- }
- }
-
- protected List<BatchedModifications> captureBatchedModifications(final ActorRef actorRef) {
- ArgumentCaptor<BatchedModifications> batchedModificationsCaptor =
- ArgumentCaptor.forClass(BatchedModifications.class);
- verify(mockActorContext, Mockito.atLeastOnce()).executeOperationAsync(
- eq(actorSelection(actorRef)), batchedModificationsCaptor.capture(), any(Timeout.class));
-
- List<BatchedModifications> batchedModifications = filterCaptured(
- batchedModificationsCaptor, BatchedModifications.class);
- return batchedModifications;
- }
-
- protected <T> List<T> filterCaptured(final ArgumentCaptor<T> captor, final Class<T> type) {
- List<T> captured = new ArrayList<>();
- for (T c: captor.getAllValues()) {
- if (type.isInstance(c)) {
- captured.add(c);
- }
- }
-
- return captured;
- }
-
- protected void verifyOneBatchedModification(final ActorRef actorRef, final Modification expected,
- final boolean expIsReady) {
- List<BatchedModifications> batchedModifications = captureBatchedModifications(actorRef);
- assertEquals("Captured BatchedModifications count", 1, batchedModifications.size());
-
- verifyBatchedModifications(batchedModifications.get(0), expIsReady, expIsReady, expected);
- }
-
- protected void verifyBatchedModifications(final Object message, final boolean expIsReady,
- final Modification... expected) {
- verifyBatchedModifications(message, expIsReady, false, expected);
- }
-
- protected void verifyBatchedModifications(final Object message, final boolean expIsReady,
- final boolean expIsDoCommitOnReady, final Modification... expected) {
- assertEquals("Message type", BatchedModifications.class, message.getClass());
- BatchedModifications batchedModifications = (BatchedModifications)message;
- assertEquals("BatchedModifications size", expected.length, batchedModifications.getModifications().size());
- assertEquals("isReady", expIsReady, batchedModifications.isReady());
- assertEquals("isDoCommitOnReady", expIsDoCommitOnReady, batchedModifications.isDoCommitOnReady());
- for (int i = 0; i < batchedModifications.getModifications().size(); i++) {
- Modification actual = batchedModifications.getModifications().get(i);
- assertEquals("Modification type", expected[i].getClass(), actual.getClass());
- assertEquals("getPath", ((AbstractModification)expected[i]).getPath(),
- ((AbstractModification)actual).getPath());
- if (actual instanceof WriteModification) {
- assertEquals("getData", ((WriteModification)expected[i]).getData(),
- ((WriteModification)actual).getData());
- }
- }
- }
-
- @SuppressWarnings("checkstyle:IllegalCatch")
- protected void verifyCohortFutures(final AbstractThreePhaseCommitCohort<?> proxy,
- final Object... expReplies) {
- assertEquals("getReadyOperationFutures size", expReplies.length,
- proxy.getCohortFutures().size());
-
- List<Object> futureResults = new ArrayList<>();
- for (Future<?> future : proxy.getCohortFutures()) {
- assertNotNull("Ready operation Future is null", future);
- try {
- futureResults.add(Await.result(future, FiniteDuration.create(5, TimeUnit.SECONDS)));
- } catch (Exception e) {
- futureResults.add(e);
- }
- }
-
- for (Object expReply : expReplies) {
- boolean found = false;
- Iterator<?> iter = futureResults.iterator();
- while (iter.hasNext()) {
- Object actual = iter.next();
- if (CommitTransactionReply.isSerializedType(expReply)
- && CommitTransactionReply.isSerializedType(actual)
- || expReply instanceof ActorSelection && Objects.equals(expReply, actual)) {
- found = true;
- } else if (expReply instanceof Class && ((Class<?>) expReply).isInstance(actual)) {
- found = true;
- }
-
- if (found) {
- iter.remove();
- break;
- }
- }
-
- if (!found) {
- fail(String.format("No cohort Future response found for %s. Actual: %s", expReply, futureResults));
- }
- }
- }
-}
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.mockito.ArgumentMatchers.any;
-import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doAnswer;
+import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import com.google.common.util.concurrent.MoreExecutors;
import com.google.common.util.concurrent.Uninterruptibles;
import java.time.Duration;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.concurrent.Executor;
import java.util.concurrent.TimeUnit;
+import java.util.function.Consumer;
+import org.eclipse.jdt.annotation.NonNullByDefault;
import org.junit.Test;
-import org.mockito.stubbing.Answer;
+import org.mockito.ArgumentCaptor;
import org.opendaylight.controller.cluster.common.actor.Dispatchers;
import org.opendaylight.controller.cluster.datastore.config.Configuration;
import org.opendaylight.controller.cluster.datastore.exceptions.NotInitializedException;
import org.opendaylight.controller.cluster.datastore.utils.ActorUtils;
import org.opendaylight.controller.cluster.raft.utils.DoNothingActor;
import org.opendaylight.controller.md.cluster.datastore.model.TestModel;
-import org.opendaylight.mdsal.dom.api.ClusteredDOMDataTreeChangeListener;
import org.opendaylight.mdsal.dom.api.DOMDataTreeChangeListener;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
-import scala.concurrent.ExecutionContextExecutor;
-import scala.concurrent.Future;
public class DataTreeChangeListenerProxyTest extends AbstractActorTest {
private final DOMDataTreeChangeListener mockListener = mock(DOMDataTreeChangeListener.class);
@Test(timeout = 10000)
public void testSuccessfulRegistration() {
- final TestKit kit = new TestKit(getSystem());
- ActorUtils actorUtils = new ActorUtils(getSystem(), kit.getRef(), mock(ClusterWrapper.class),
+ final var kit = new TestKit(getSystem());
+ final var actorUtils = new ActorUtils(getSystem(), kit.getRef(), mock(ClusterWrapper.class),
mock(Configuration.class));
- final YangInstanceIdentifier path = YangInstanceIdentifier.of(TestModel.TEST_QNAME);
- final DataTreeChangeListenerProxy<DOMDataTreeChangeListener> proxy = new DataTreeChangeListenerProxy<>(
- actorUtils, mockListener, path);
+ final var path = YangInstanceIdentifier.of(TestModel.TEST_QNAME);
+ final var proxy = startProxyAsync(actorUtils, path, false);
- new Thread(() -> proxy.init("shard-1")).start();
-
- Duration timeout = Duration.ofSeconds(5);
- FindLocalShard findLocalShard = kit.expectMsgClass(timeout, FindLocalShard.class);
- assertEquals("getShardName", "shard-1", findLocalShard.getShardName());
+ final var timeout = Duration.ofSeconds(5);
+ final var findLocalShard = kit.expectMsgClass(timeout, FindLocalShard.class);
+ assertEquals("shard-1", findLocalShard.getShardName());
kit.reply(new LocalShardFound(kit.getRef()));
- RegisterDataTreeChangeListener registerMsg = kit.expectMsgClass(timeout,
- RegisterDataTreeChangeListener.class);
- assertEquals("getPath", path, registerMsg.getPath());
- assertFalse("isRegisterOnAllInstances", registerMsg.isRegisterOnAllInstances());
+ final var registerMsg = kit.expectMsgClass(timeout, RegisterDataTreeChangeListener.class);
+ assertEquals(path, registerMsg.getPath());
+ assertFalse(registerMsg.isRegisterOnAllInstances());
kit.reply(new RegisterDataTreeNotificationListenerReply(kit.getRef()));
Uninterruptibles.sleepUninterruptibly(50, TimeUnit.MILLISECONDS);
}
- assertEquals("getListenerRegistrationActor", getSystem().actorSelection(kit.getRef().path()),
- proxy.getListenerRegistrationActor());
+ assertEquals(getSystem().actorSelection(kit.getRef().path()), proxy.getListenerRegistrationActor());
kit.watch(proxy.getDataChangeListenerActor());
@Test(timeout = 10000)
public void testSuccessfulRegistrationForClusteredListener() {
- final TestKit kit = new TestKit(getSystem());
- ActorUtils actorUtils = new ActorUtils(getSystem(), kit.getRef(), mock(ClusterWrapper.class),
+ final var kit = new TestKit(getSystem());
+ final var actorUtils = new ActorUtils(getSystem(), kit.getRef(), mock(ClusterWrapper.class),
mock(Configuration.class));
- ClusteredDOMDataTreeChangeListener mockClusteredListener = mock(
- ClusteredDOMDataTreeChangeListener.class);
-
- final YangInstanceIdentifier path = YangInstanceIdentifier.of(TestModel.TEST_QNAME);
- final DataTreeChangeListenerProxy<ClusteredDOMDataTreeChangeListener> proxy =
- new DataTreeChangeListenerProxy<>(actorUtils, mockClusteredListener, path);
+ final var path = YangInstanceIdentifier.of(TestModel.TEST_QNAME);
+ final var proxy = startProxyAsync(actorUtils, path, true);
- new Thread(() -> proxy.init("shard-1")).start();
-
- Duration timeout = Duration.ofSeconds(5);
- FindLocalShard findLocalShard = kit.expectMsgClass(timeout, FindLocalShard.class);
- assertEquals("getShardName", "shard-1", findLocalShard.getShardName());
+ final var timeout = Duration.ofSeconds(5);
+ final var findLocalShard = kit.expectMsgClass(timeout, FindLocalShard.class);
+ assertEquals("shard-1", findLocalShard.getShardName());
kit.reply(new LocalShardFound(kit.getRef()));
- RegisterDataTreeChangeListener registerMsg = kit.expectMsgClass(timeout,
- RegisterDataTreeChangeListener.class);
- assertEquals("getPath", path, registerMsg.getPath());
- assertTrue("isRegisterOnAllInstances", registerMsg.isRegisterOnAllInstances());
+ final var registerMsg = kit.expectMsgClass(timeout, RegisterDataTreeChangeListener.class);
+ assertEquals(path, registerMsg.getPath());
+ assertTrue(registerMsg.isRegisterOnAllInstances());
proxy.close();
}
@Test(timeout = 10000)
public void testLocalShardNotFound() {
- final TestKit kit = new TestKit(getSystem());
- ActorUtils actorUtils = new ActorUtils(getSystem(), kit.getRef(), mock(ClusterWrapper.class),
+ final var kit = new TestKit(getSystem());
+ final var actorUtils = new ActorUtils(getSystem(), kit.getRef(), mock(ClusterWrapper.class),
mock(Configuration.class));
- final YangInstanceIdentifier path = YangInstanceIdentifier.of(TestModel.TEST_QNAME);
- final DataTreeChangeListenerProxy<DOMDataTreeChangeListener> proxy = new DataTreeChangeListenerProxy<>(
- actorUtils, mockListener, path);
-
- new Thread(() -> proxy.init("shard-1")).start();
+ final var path = YangInstanceIdentifier.of(TestModel.TEST_QNAME);
+ final var proxy = startProxyAsync(actorUtils, path, true);
- Duration timeout = Duration.ofSeconds(5);
- FindLocalShard findLocalShard = kit.expectMsgClass(timeout, FindLocalShard.class);
- assertEquals("getShardName", "shard-1", findLocalShard.getShardName());
+ final var timeout = Duration.ofSeconds(5);
+ final var findLocalShard = kit.expectMsgClass(timeout, FindLocalShard.class);
+ assertEquals("shard-1", findLocalShard.getShardName());
kit.reply(new LocalShardNotFound("shard-1"));
@Test(timeout = 10000)
public void testLocalShardNotInitialized() {
- final TestKit kit = new TestKit(getSystem());
- ActorUtils actorUtils = new ActorUtils(getSystem(), kit.getRef(), mock(ClusterWrapper.class),
+ final var kit = new TestKit(getSystem());
+ final var actorUtils = new ActorUtils(getSystem(), kit.getRef(), mock(ClusterWrapper.class),
mock(Configuration.class));
- final YangInstanceIdentifier path = YangInstanceIdentifier.of(TestModel.TEST_QNAME);
- final DataTreeChangeListenerProxy<DOMDataTreeChangeListener> proxy = new DataTreeChangeListenerProxy<>(
- actorUtils, mockListener, path);
+ final var path = YangInstanceIdentifier.of(TestModel.TEST_QNAME);
+ final var proxy = startProxyAsync(actorUtils, path, false);
- new Thread(() -> proxy.init("shard-1")).start();
-
- Duration timeout = Duration.ofSeconds(5);
- FindLocalShard findLocalShard = kit.expectMsgClass(timeout, FindLocalShard.class);
- assertEquals("getShardName", "shard-1", findLocalShard.getShardName());
+ final var timeout = Duration.ofSeconds(5);
+ final var findLocalShard = kit.expectMsgClass(timeout, FindLocalShard.class);
+ assertEquals("shard-1", findLocalShard.getShardName());
kit.reply(new NotInitializedException("not initialized"));
@Test
public void testFailedRegistration() {
- final TestKit kit = new TestKit(getSystem());
- ActorSystem mockActorSystem = mock(ActorSystem.class);
+ final var kit = new TestKit(getSystem());
+ final var mockActorSystem = mock(ActorSystem.class);
- ActorRef mockActor = getSystem().actorOf(Props.create(DoNothingActor.class), "testFailedRegistration");
+ final var mockActor = getSystem().actorOf(Props.create(DoNothingActor.class), "testFailedRegistration");
doReturn(mockActor).when(mockActorSystem).actorOf(any(Props.class));
- ExecutionContextExecutor executor = ExecutionContexts.fromExecutor(MoreExecutors.directExecutor());
+ final var executor = ExecutionContexts.fromExecutor(MoreExecutors.directExecutor());
- ActorUtils actorUtils = mock(ActorUtils.class);
- final YangInstanceIdentifier path = YangInstanceIdentifier.of(TestModel.TEST_QNAME);
+ final var actorUtils = mock(ActorUtils.class);
+ final var path = YangInstanceIdentifier.of(TestModel.TEST_QNAME);
doReturn(executor).when(actorUtils).getClientDispatcher();
doReturn(DatastoreContext.newBuilder().build()).when(actorUtils).getDatastoreContext();
doReturn(mockActorSystem).when(actorUtils).getActorSystem();
- String shardName = "shard-1";
- final DataTreeChangeListenerProxy<DOMDataTreeChangeListener> proxy = new DataTreeChangeListenerProxy<>(
- actorUtils, mockListener, path);
-
doReturn(kit.duration("5 seconds")).when(actorUtils).getOperationDuration();
- doReturn(Futures.successful(kit.getRef())).when(actorUtils).findLocalShardAsync(eq(shardName));
+ doReturn(Futures.successful(kit.getRef())).when(actorUtils).findLocalShardAsync("shard-1");
doReturn(Futures.failed(new RuntimeException("mock"))).when(actorUtils).executeOperationAsync(
any(ActorRef.class), any(Object.class), any(Timeout.class));
- doReturn(mock(DatastoreContext.class)).when(actorUtils).getDatastoreContext();
-
- proxy.init("shard-1");
- assertEquals("getListenerRegistrationActor", null, proxy.getListenerRegistrationActor());
+ final var proxy = DataTreeChangeListenerProxy.of(actorUtils, mockListener, path, true, "shard-1");
+ assertNull(proxy.getListenerRegistrationActor());
proxy.close();
}
@Test
public void testCloseBeforeRegistration() {
- final TestKit kit = new TestKit(getSystem());
- ActorUtils actorUtils = mock(ActorUtils.class);
-
- String shardName = "shard-1";
+ final var kit = new TestKit(getSystem());
+ final var actorUtils = mock(ActorUtils.class);
doReturn(DatastoreContext.newBuilder().build()).when(actorUtils).getDatastoreContext();
doReturn(getSystem().dispatchers().defaultGlobalDispatcher()).when(actorUtils).getClientDispatcher();
doReturn(getSystem().actorSelection(kit.getRef().path())).when(actorUtils).actorSelection(
kit.getRef().path());
doReturn(kit.duration("5 seconds")).when(actorUtils).getOperationDuration();
- doReturn(Futures.successful(kit.getRef())).when(actorUtils).findLocalShardAsync(eq(shardName));
+ doReturn(Futures.successful(kit.getRef())).when(actorUtils).findLocalShardAsync("shard-1");
- final DataTreeChangeListenerProxy<DOMDataTreeChangeListener> proxy = new DataTreeChangeListenerProxy<>(
- actorUtils, mockListener, YangInstanceIdentifier.of(TestModel.TEST_QNAME));
+ final var proxy = createProxy(actorUtils, YangInstanceIdentifier.of(TestModel.TEST_QNAME), true);
+ final var instance = proxy.getKey();
- Answer<Future<Object>> answer = invocation -> {
- proxy.close();
- return Futures.successful((Object) new RegisterDataTreeNotificationListenerReply(kit.getRef()));
- };
+ doAnswer(invocation -> {
+ instance.close();
+ return Futures.successful(new RegisterDataTreeNotificationListenerReply(kit.getRef()));
+ }).when(actorUtils).executeOperationAsync(any(ActorRef.class), any(Object.class), any(Timeout.class));
+ proxy.getValue().run();
- doAnswer(answer).when(actorUtils).executeOperationAsync(any(ActorRef.class), any(Object.class),
- any(Timeout.class));
+ kit.expectMsgClass(Duration.ofSeconds(5), CloseDataTreeNotificationListenerRegistration.class);
- proxy.init(shardName);
+ assertNull(instance.getListenerRegistrationActor());
+ }
- kit.expectMsgClass(Duration.ofSeconds(5), CloseDataTreeNotificationListenerRegistration.class);
+ @NonNullByDefault
+ private DataTreeChangeListenerProxy startProxyAsync(final ActorUtils actorUtils, final YangInstanceIdentifier path,
+ final boolean clustered) {
+ return startProxyAsync(actorUtils, path, clustered, Runnable::run);
+ }
+
+ @NonNullByDefault
+ private DataTreeChangeListenerProxy startProxyAsync(final ActorUtils actorUtils, final YangInstanceIdentifier path,
+ final boolean clustered, final Consumer<Runnable> execute) {
+ final var proxy = createProxy(actorUtils, path, clustered);
+ final var thread = new Thread(proxy.getValue());
+ thread.setDaemon(true);
+ thread.start();
+ return proxy.getKey();
+ }
- assertEquals("getListenerRegistrationActor", null, proxy.getListenerRegistrationActor());
+ @NonNullByDefault
+ private Entry<DataTreeChangeListenerProxy, Runnable> createProxy(final ActorUtils actorUtils,
+ final YangInstanceIdentifier path, final boolean clustered) {
+ final var executor = mock(Executor.class);
+ final var captor = ArgumentCaptor.forClass(Runnable.class);
+ doNothing().when(executor).execute(captor.capture());
+ final var proxy = DataTreeChangeListenerProxy.ofTesting(actorUtils, mockListener, path, clustered, "shard-1",
+ executor);
+ return Map.entry(proxy, captor.getValue());
}
}
import org.opendaylight.controller.cluster.datastore.utils.MockDataTreeChangeListener;
import org.opendaylight.controller.md.cluster.datastore.model.TestModel;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
-import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
+import org.opendaylight.yangtools.yang.data.spi.node.ImmutableNodes;
import org.opendaylight.yangtools.yang.data.tree.api.DataValidationFailedException;
import scala.concurrent.Await;
import scala.concurrent.duration.FiniteDuration;
@Test
public void testInitialChangeListenerEventWithContainerPath() throws DataValidationFailedException {
- writeToStore(shard.getDataStore(), TEST_PATH, ImmutableNodes.containerNode(TEST_QNAME));
+ writeToStore(shard.getDataStore(), TEST_PATH, ImmutableNodes.newContainerBuilder()
+ .withNodeIdentifier(new NodeIdentifier(TEST_QNAME))
+ .build());
Entry<MockDataTreeChangeListener, ActorSelection> entry = registerChangeListener(TEST_PATH, 1);
MockDataTreeChangeListener listener = entry.getKey();
listener.reset(1);
- writeToStore(shard.getDataStore(), TEST_PATH, ImmutableNodes.containerNode(TEST_QNAME));
+ writeToStore(shard.getDataStore(), TEST_PATH, ImmutableNodes.newContainerBuilder()
+ .withNodeIdentifier(new NodeIdentifier(TEST_QNAME))
+ .build());
listener.waitForChangeEvents();
listener.verifyNotifiedData(TEST_PATH);
entry.getValue().tell(CloseDataTreeNotificationListenerRegistration.getInstance(), kit.getRef());
kit.expectMsgClass(Duration.ofSeconds(5), CloseDataTreeNotificationListenerRegistrationReply.class);
- writeToStore(shard.getDataStore(), TEST_PATH, ImmutableNodes.containerNode(TEST_QNAME));
+ writeToStore(shard.getDataStore(), TEST_PATH, ImmutableNodes.newContainerBuilder()
+ .withNodeIdentifier(new NodeIdentifier(TEST_QNAME))
+ .build());
listener.verifyNoNotifiedData(TEST_PATH);
}
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyCollection;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.reset;
import org.opendaylight.yangtools.util.concurrent.FluentFutures;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
import org.opendaylight.yangtools.yang.data.tree.api.DataValidationFailedException;
-import org.opendaylight.yangtools.yang.model.api.SchemaContext;
+import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
import scala.concurrent.Await;
/**
*/
public class DataTreeCohortActorTest extends AbstractActorTest {
private static final Collection<DOMDataTreeCandidate> CANDIDATES = new ArrayList<>();
- private static final SchemaContext MOCK_SCHEMA = mock(SchemaContext.class);
+ private static final EffectiveModelContext MOCK_SCHEMA = mock(EffectiveModelContext.class);
private final TestActorFactory actorFactory = new TestActorFactory(getSystem());
private final DOMDataTreeCommitCohort mockCohort = mock(DOMDataTreeCommitCohort.class);
private final PostCanCommitStep mockPostCanCommit = mock(PostCanCommitStep.class);
askAndAwait(cohortActor, new Commit(txId2));
}
- @SuppressWarnings("unchecked")
@Test
public void testAsyncCohort() throws Exception {
ListeningExecutorService executor = MoreExecutors.listeningDecorator(Executors.newSingleThreadExecutor());
doReturn(executeWithDelay(executor, mockPostCanCommit))
- .when(mockCohort).canCommit(any(Object.class), any(SchemaContext.class), any(Collection.class));
+ .when(mockCohort).canCommit(any(Object.class), any(EffectiveModelContext.class), anyCollection());
doReturn(executor.submit(() -> mockPostPreCommit)).when(mockPostCanCommit).preCommit();
executor.shutdownNow();
}
- @SuppressWarnings("unchecked")
@Test
public void testFailureOnCanCommit() throws Exception {
- DataValidationFailedException failure = new DataValidationFailedException(YangInstanceIdentifier.empty(),
+ DataValidationFailedException failure = new DataValidationFailedException(YangInstanceIdentifier.of(),
"mock");
doReturn(FluentFutures.immediateFailedFluentFuture(failure)).when(mockCohort).canCommit(any(Object.class),
- any(SchemaContext.class), any(Collection.class));
+ any(EffectiveModelContext.class), anyCollection());
ActorRef cohortActor = newCohortActor("testFailureOnCanCommit");
}
private ActorRef newCohortActor(final String name) {
- return actorFactory.createActor(DataTreeCohortActor.props(mockCohort, YangInstanceIdentifier.empty()), name);
+ return actorFactory.createActor(DataTreeCohortActor.props(mockCohort, YangInstanceIdentifier.of()), name);
}
- @SuppressWarnings("unchecked")
private void resetMockCohort() {
reset(mockCohort);
doReturn(ThreePhaseCommitStep.NOOP_ABORT_FUTURE).when(mockPostCanCommit).abort();
doReturn(Futures.immediateFuture(mockPostPreCommit)).when(mockPostCanCommit).preCommit();
doReturn(FluentFutures.immediateFluentFuture(mockPostCanCommit)).when(mockCohort).canCommit(any(Object.class),
- any(SchemaContext.class), any(Collection.class));
+ any(EffectiveModelContext.class), anyCollection());
doReturn(ThreePhaseCommitStep.NOOP_ABORT_FUTURE).when(mockPostPreCommit).abort();
doReturn(Futures.immediateFuture(null)).when(mockPostPreCommit).commit();
import static org.junit.Assert.assertSame;
import static org.junit.Assert.fail;
import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyCollection;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.reset;
import com.google.common.util.concurrent.FluentFuture;
import com.typesafe.config.ConfigFactory;
import java.util.Collection;
-import java.util.Optional;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import org.junit.AfterClass;
import org.junit.Ignore;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
+import org.opendaylight.controller.cluster.databroker.ClientBackedDataStore;
import org.opendaylight.controller.md.cluster.datastore.model.CarsModel;
import org.opendaylight.controller.md.cluster.datastore.model.TestModel;
import org.opendaylight.mdsal.common.api.DataValidationFailedException;
import org.opendaylight.mdsal.dom.api.DOMDataTreeIdentifier;
import org.opendaylight.mdsal.dom.spi.store.DOMStoreThreePhaseCommitCohort;
import org.opendaylight.mdsal.dom.spi.store.DOMStoreWriteTransaction;
-import org.opendaylight.yangtools.concepts.ObjectRegistration;
import org.opendaylight.yangtools.util.concurrent.FluentFutures;
import org.opendaylight.yangtools.yang.common.Uint64;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
-import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
import org.opendaylight.yangtools.yang.data.tree.api.ModificationType;
-import org.opendaylight.yangtools.yang.model.api.SchemaContext;
+import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
public class DataTreeCohortIntegrationTest {
@SuppressWarnings({ "unchecked", "rawtypes" })
@Test
public void testSuccessfulCanCommitWithNoopPostStep() throws Exception {
- final DOMDataTreeCommitCohort cohort = mock(DOMDataTreeCommitCohort.class);
+ final var cohort = mock(DOMDataTreeCommitCohort.class);
doReturn(PostCanCommitStep.NOOP_SUCCESSFUL_FUTURE).when(cohort).canCommit(any(Object.class),
- any(SchemaContext.class), any(Collection.class));
+ any(EffectiveModelContext.class), anyCollection());
ArgumentCaptor<Collection> candidateCapt = ArgumentCaptor.forClass(Collection.class);
IntegrationTestKit kit = new IntegrationTestKit(getSystem(), datastoreContextBuilder);
- try (AbstractDataStore dataStore = kit.setupAbstractDataStore(
- DistributedDataStore.class, "testSuccessfulCanCommitWithNoopPostStep", "test-1")) {
- final ObjectRegistration<DOMDataTreeCommitCohort> cohortReg = dataStore.registerCommitCohort(TEST_ID,
- cohort);
+ try (var dataStore = kit.setupDataStore(ClientBackedDataStore.class, "testSuccessfulCanCommitWithNoopPostStep",
+ "test-1")) {
+
+ final var cohortReg = dataStore.registerCommitCohort(TEST_ID, cohort);
assertNotNull(cohortReg);
IntegrationTestKit.verifyShardState(dataStore, "test-1",
state -> assertEquals("Cohort registrations", 1, state.getCommitCohortActors().size()));
- final ContainerNode node = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
+ final var node = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
kit.testWriteTransaction(dataStore, TestModel.TEST_PATH, node);
- verify(cohort).canCommit(any(Object.class), any(SchemaContext.class), candidateCapt.capture());
+ verify(cohort).canCommit(any(Object.class), any(EffectiveModelContext.class), candidateCapt.capture());
assertDataTreeCandidate((DOMDataTreeCandidate) candidateCapt.getValue().iterator().next(), TEST_ID,
- ModificationType.WRITE, Optional.of(node), Optional.empty());
+ ModificationType.WRITE, node, null);
reset(cohort);
doReturn(PostCanCommitStep.NOOP_SUCCESSFUL_FUTURE).when(cohort).canCommit(any(Object.class),
- any(SchemaContext.class), any(Collection.class));
+ any(EffectiveModelContext.class), anyCollection());
kit.testWriteTransaction(dataStore, TestModel.OUTER_LIST_PATH,
ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME)
.withChild(ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, 42))
.build());
- verify(cohort).canCommit(any(Object.class), any(SchemaContext.class), any(Collection.class));
+ verify(cohort).canCommit(any(Object.class), any(EffectiveModelContext.class), anyCollection());
cohortReg.close();
}
}
- @SuppressWarnings("unchecked")
@Test
public void testFailedCanCommit() throws Exception {
- final DOMDataTreeCommitCohort failedCohort = mock(DOMDataTreeCommitCohort.class);
+ final var failedCohort = mock(DOMDataTreeCommitCohort.class);
doReturn(FAILED_CAN_COMMIT_FUTURE).when(failedCohort).canCommit(any(Object.class),
- any(SchemaContext.class), any(Collection.class));
+ any(EffectiveModelContext.class), anyCollection());
- IntegrationTestKit kit = new IntegrationTestKit(getSystem(), datastoreContextBuilder);
- try (AbstractDataStore dataStore = kit.setupAbstractDataStore(
- DistributedDataStore.class, "testFailedCanCommit", "test-1")) {
+ final var kit = new IntegrationTestKit(getSystem(), datastoreContextBuilder);
+ try (var dataStore = kit.setupDataStore(ClientBackedDataStore.class, "testFailedCanCommit", "test-1")) {
dataStore.registerCommitCohort(TEST_ID, failedCohort);
IntegrationTestKit.verifyShardState(dataStore, "test-1",
@SuppressWarnings({ "unchecked", "rawtypes" })
@Test
public void testCanCommitWithListEntries() throws Exception {
- final DOMDataTreeCommitCohort cohort = mock(DOMDataTreeCommitCohort.class);
+ final var cohort = mock(DOMDataTreeCommitCohort.class);
doReturn(PostCanCommitStep.NOOP_SUCCESSFUL_FUTURE).when(cohort).canCommit(any(Object.class),
- any(SchemaContext.class), any(Collection.class));
- IntegrationTestKit kit = new IntegrationTestKit(getSystem(), datastoreContextBuilder);
+ any(EffectiveModelContext.class), anyCollection());
+ final var kit = new IntegrationTestKit(getSystem(), datastoreContextBuilder);
- try (AbstractDataStore dataStore = kit.setupAbstractDataStore(
- DistributedDataStore.class, "testCanCommitWithMultipleListEntries", "cars-1")) {
- final ObjectRegistration<DOMDataTreeCommitCohort> cohortReg = dataStore.registerCommitCohort(
+ try (var dataStore = kit.setupDataStore(ClientBackedDataStore.class, "testCanCommitWithMultipleListEntries",
+ "cars-1")) {
+
+ final var cohortReg = dataStore.registerCommitCohort(
new DOMDataTreeIdentifier(LogicalDatastoreType.CONFIGURATION, CarsModel.CAR_LIST_PATH
.node(CarsModel.CAR_QNAME)), cohort);
assertNotNull(cohortReg);
kit.doCommit(writeTx.ready());
ArgumentCaptor<Collection> candidateCapture = ArgumentCaptor.forClass(Collection.class);
- verify(cohort).canCommit(any(Object.class), any(SchemaContext.class), candidateCapture.capture());
+ verify(cohort).canCommit(any(Object.class), any(EffectiveModelContext.class), candidateCapture.capture());
assertDataTreeCandidate((DOMDataTreeCandidate) candidateCapture.getValue().iterator().next(),
new DOMDataTreeIdentifier(LogicalDatastoreType.CONFIGURATION, optimaPath), ModificationType.WRITE,
- Optional.of(optimaNode), Optional.empty());
+ optimaNode, null);
// Write replace the cars container with 2 new car entries. The cohort should get invoked with 3
// DOMDataTreeCandidates: once for each of the 2 new car entries (WRITE mod) and once for the deleted prior
reset(cohort);
doReturn(PostCanCommitStep.NOOP_SUCCESSFUL_FUTURE).when(cohort).canCommit(any(Object.class),
- any(SchemaContext.class), any(Collection.class));
+ any(EffectiveModelContext.class), anyCollection());
writeTx = dataStore.newWriteOnlyTransaction();
final YangInstanceIdentifier sportagePath = CarsModel.newCarPath("sportage");
kit.doCommit(writeTx.ready());
candidateCapture = ArgumentCaptor.forClass(Collection.class);
- verify(cohort).canCommit(any(Object.class), any(SchemaContext.class), candidateCapture.capture());
+ verify(cohort).canCommit(any(Object.class), any(EffectiveModelContext.class), candidateCapture.capture());
assertDataTreeCandidate(findCandidate(candidateCapture, sportagePath), new DOMDataTreeIdentifier(
LogicalDatastoreType.CONFIGURATION, sportagePath), ModificationType.WRITE,
- Optional.of(sportageNode), Optional.empty());
+ sportageNode, null);
assertDataTreeCandidate(findCandidate(candidateCapture, soulPath), new DOMDataTreeIdentifier(
LogicalDatastoreType.CONFIGURATION, soulPath), ModificationType.WRITE,
- Optional.of(soulNode), Optional.empty());
+ soulNode, null);
assertDataTreeCandidate(findCandidate(candidateCapture, optimaPath), new DOMDataTreeIdentifier(
LogicalDatastoreType.CONFIGURATION, optimaPath), ModificationType.DELETE,
- Optional.empty(), Optional.of(optimaNode));
+ null, optimaNode);
// Delete the cars container - cohort should be invoked for the 2 deleted car entries.
reset(cohort);
doReturn(PostCanCommitStep.NOOP_SUCCESSFUL_FUTURE).when(cohort).canCommit(any(Object.class),
- any(SchemaContext.class), any(Collection.class));
+ any(EffectiveModelContext.class), anyCollection());
writeTx = dataStore.newWriteOnlyTransaction();
writeTx.delete(CarsModel.BASE_PATH);
kit.doCommit(writeTx.ready());
candidateCapture = ArgumentCaptor.forClass(Collection.class);
- verify(cohort).canCommit(any(Object.class), any(SchemaContext.class), candidateCapture.capture());
+ verify(cohort).canCommit(any(Object.class), any(EffectiveModelContext.class), candidateCapture.capture());
assertDataTreeCandidate(findCandidate(candidateCapture, sportagePath), new DOMDataTreeIdentifier(
LogicalDatastoreType.CONFIGURATION, sportagePath), ModificationType.DELETE,
- Optional.empty(), Optional.of(sportageNode));
+ null, sportageNode);
assertDataTreeCandidate(findCandidate(candidateCapture, soulPath), new DOMDataTreeIdentifier(
LogicalDatastoreType.CONFIGURATION, soulPath), ModificationType.DELETE,
- Optional.empty(), Optional.of(soulNode));
+ null, soulNode);
}
}
* DataTreeCandidate) and since currently preCommit is a noop in the Shard backend (it is combined with commit),
* we can't actually test abort after canCommit.
*/
- @SuppressWarnings("unchecked")
@Test
@Ignore
public void testAbortAfterCanCommit() throws Exception {
- final DOMDataTreeCommitCohort cohortToAbort = mock(DOMDataTreeCommitCohort.class);
- final PostCanCommitStep stepToAbort = mock(PostCanCommitStep.class);
+ final var cohortToAbort = mock(DOMDataTreeCommitCohort.class);
+ final var stepToAbort = mock(PostCanCommitStep.class);
doReturn(ThreePhaseCommitStep.NOOP_ABORT_FUTURE).when(stepToAbort).abort();
doReturn(PostPreCommitStep.NOOP_FUTURE).when(stepToAbort).preCommit();
doReturn(FluentFutures.immediateFluentFuture(stepToAbort)).when(cohortToAbort).canCommit(any(Object.class),
- any(SchemaContext.class), any(Collection.class));
+ any(EffectiveModelContext.class), anyCollection());
- IntegrationTestKit kit = new IntegrationTestKit(getSystem(), datastoreContextBuilder);
- try (AbstractDataStore dataStore = kit.setupAbstractDataStore(
- DistributedDataStore.class, "testAbortAfterCanCommit", "test-1", "cars-1")) {
+ var kit = new IntegrationTestKit(getSystem(), datastoreContextBuilder);
+ try (var dataStore = kit.setupDataStore(ClientBackedDataStore.class, "testAbortAfterCanCommit",
+ "test-1", "cars-1")) {
dataStore.registerCommitCohort(TEST_ID, cohortToAbort);
IntegrationTestKit.verifyShardState(dataStore, "test-1",
state -> assertEquals("Cohort registrations", 1, state.getCommitCohortActors().size()));
- DOMStoreWriteTransaction writeTx = dataStore.newWriteOnlyTransaction();
+ var writeTx = dataStore.newWriteOnlyTransaction();
writeTx.write(TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME));
writeTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
- DOMStoreThreePhaseCommitCohort dsCohort = writeTx.ready();
+ var dsCohort = writeTx.ready();
dsCohort.canCommit().get(5, TimeUnit.SECONDS);
dsCohort.preCommit().get(5, TimeUnit.SECONDS);
private static void assertDataTreeCandidate(final DOMDataTreeCandidate candidate,
final DOMDataTreeIdentifier expTreeId, final ModificationType expType,
- final Optional<NormalizedNode> expDataAfter, final Optional<NormalizedNode> expDataBefore) {
+ final NormalizedNode expDataAfter, final NormalizedNode expDataBefore) {
assertNotNull("Expected candidate for path " + expTreeId.getRootIdentifier(), candidate);
assertEquals("rootPath", expTreeId, candidate.getRootPath());
- assertEquals("modificationType", expType, candidate.getRootNode().getModificationType());
-
- assertEquals("dataAfter present", expDataAfter.isPresent(), candidate.getRootNode().getDataAfter().isPresent());
- if (expDataAfter.isPresent()) {
- assertEquals("dataAfter", expDataAfter.get(), candidate.getRootNode().getDataAfter().get());
- }
-
- assertEquals("dataBefore present", expDataBefore.isPresent(),
- candidate.getRootNode().getDataBefore().isPresent());
- if (expDataBefore.isPresent()) {
- assertEquals("dataBefore", expDataBefore.get(), candidate.getRootNode().getDataBefore().get());
- }
+ assertEquals("modificationType", expType, candidate.getRootNode().modificationType());
+ assertEquals("dataAfter", expDataAfter, candidate.getRootNode().dataAfter());
+ assertEquals("dataBefore", expDataBefore, candidate.getRootNode().dataBefore());
}
}
return currProps.get(obj);
}
- private class DummyListenerImpl implements Listener {
-
+ private static final class DummyListenerImpl implements Listener {
private DatastoreContextFactory contextFactory;
@Override
import org.junit.Test;
import org.opendaylight.mdsal.binding.dom.codec.impl.BindingCodecContext;
import org.opendaylight.mdsal.binding.runtime.spi.BindingRuntimeHelpers;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.distributed.datastore.provider.rev140612.DataStoreProperties.ExportOnRecovery;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.distributed.datastore.provider.rev140612.DataStorePropertiesContainer;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.distributed.datastore.provider.rev231229.DataStoreProperties.ExportOnRecovery;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.distributed.datastore.provider.rev231229.DataStorePropertiesContainer;
/**
* Unit tests for DatastoreContextIntrospector.
import java.util.concurrent.TimeUnit;
import org.junit.Assert;
import org.junit.Test;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.distributed.datastore.provider.rev140612.DataStoreProperties.ExportOnRecovery;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.distributed.datastore.provider.rev231229.DataStoreProperties.ExportOnRecovery;
public class DatastoreContextTest {
DataTree dataTree = new InMemoryDataTreeFactory().create(DataTreeConfiguration.DEFAULT_OPERATIONAL,
SchemaContextHelper.full());
AbstractShardTest.writeToStore(dataTree, path, node);
- NormalizedNode root = AbstractShardTest.readStore(dataTree, YangInstanceIdentifier.empty());
+ NormalizedNode root = AbstractShardTest.readStore(dataTree, YangInstanceIdentifier.of());
return Snapshot.create(new ShardSnapshotState(new MetadataShardDataTreeSnapshot(root)),
Collections.<ReplicatedLogEntry>emptyList(), 2, 1, 2, 1, 1, "member-1", null);
+++ /dev/null
-/*
- * Copyright (c) 2015 Brocade Communications Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.cluster.datastore;
-
-import static org.junit.Assert.assertSame;
-import static org.mockito.ArgumentMatchers.any;
-import static org.mockito.ArgumentMatchers.anyString;
-import static org.mockito.ArgumentMatchers.same;
-import static org.mockito.Mockito.doReturn;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.never;
-import static org.mockito.Mockito.reset;
-import static org.mockito.Mockito.verify;
-
-import com.google.common.util.concurrent.Futures;
-import com.google.common.util.concurrent.ListenableFuture;
-import java.util.ArrayList;
-import java.util.List;
-import org.junit.Test;
-import org.opendaylight.controller.cluster.access.concepts.TransactionIdentifier;
-import org.slf4j.Logger;
-import scala.concurrent.Future;
-
-/**
- * Unit tests for DebugThreePhaseCommitCohort.
- *
- * @author Thomas Pantelis
- */
-public class DebugThreePhaseCommitCohortTest {
- private final TransactionIdentifier transactionId = MockIdentifiers.transactionIdentifier(
- DebugThreePhaseCommitCohortTest.class, "mock");
-
- @Test
- public void test() {
- AbstractThreePhaseCommitCohort<?> mockDelegate = mock(AbstractThreePhaseCommitCohort.class);
- Exception failure = new Exception("mock failure");
- ListenableFuture<Object> expFailedFuture = Futures.immediateFailedFuture(failure);
- doReturn(expFailedFuture).when(mockDelegate).canCommit();
- doReturn(expFailedFuture).when(mockDelegate).preCommit();
- doReturn(expFailedFuture).when(mockDelegate).commit();
-
- ListenableFuture<Object> expAbortFuture = Futures.immediateFuture(null);
- doReturn(expAbortFuture).when(mockDelegate).abort();
-
- List<Future<Object>> expCohortFutures = new ArrayList<>();
- doReturn(expCohortFutures).when(mockDelegate).getCohortFutures();
-
- Throwable debugContext = new RuntimeException("mock");
- DebugThreePhaseCommitCohort cohort = new DebugThreePhaseCommitCohort(transactionId, mockDelegate, debugContext);
-
- Logger mockLogger = mock(Logger.class);
- cohort.setLogger(mockLogger);
-
- assertSame("canCommit", expFailedFuture, cohort.canCommit());
- verify(mockLogger).warn(anyString(), same(transactionId), same(failure), same(debugContext));
-
- reset(mockLogger);
- assertSame("preCommit", expFailedFuture, cohort.preCommit());
- verify(mockLogger).warn(anyString(), same(transactionId), same(failure), same(debugContext));
-
- reset(mockLogger);
- assertSame("commit", expFailedFuture, cohort.commit());
- verify(mockLogger).warn(anyString(), same(transactionId), same(failure), same(debugContext));
-
- assertSame("abort", expAbortFuture, cohort.abort());
-
- assertSame("getCohortFutures", expCohortFutures, cohort.getCohortFutures());
-
- reset(mockLogger);
- ListenableFuture<Boolean> expSuccessFuture = Futures.immediateFuture(Boolean.TRUE);
- doReturn(expSuccessFuture).when(mockDelegate).canCommit();
-
- assertSame("canCommit", expSuccessFuture, cohort.canCommit());
- verify(mockLogger, never()).warn(anyString(), any(TransactionIdentifier.class), any(Throwable.class),
- any(Throwable.class));
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2014, 2015 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.cluster.datastore;
-
-import static org.junit.Assert.assertEquals;
-import static org.mockito.Mockito.doReturn;
-import static org.mockito.Mockito.mock;
-
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.mockito.Mock;
-import org.mockito.junit.MockitoJUnitRunner;
-import org.opendaylight.controller.cluster.datastore.utils.ActorUtils;
-
-@RunWith(MockitoJUnitRunner.StrictStubs.class)
-public class DelayedTransactionContextWrapperTest {
- @Mock
- private ActorUtils actorUtils;
-
- @Mock
- private TransactionContext transactionContext;
-
- private DelayedTransactionContextWrapper transactionContextWrapper;
-
- @Before
- public void setUp() {
- doReturn(DatastoreContext.newBuilder().build()).when(actorUtils).getDatastoreContext();
- transactionContextWrapper = new DelayedTransactionContextWrapper(MockIdentifiers.transactionIdentifier(
- DelayedTransactionContextWrapperTest.class, "mock"), actorUtils, "mock");
- }
-
- @Test
- public void testExecutePriorTransactionOperations() {
- for (int i = 0; i < 100; i++) {
- transactionContextWrapper.maybeExecuteTransactionOperation(mock(TransactionOperation.class));
- }
- assertEquals(901, transactionContextWrapper.getLimiter().availablePermits());
-
- transactionContextWrapper.executePriorTransactionOperations(transactionContext);
-
- assertEquals(1001, transactionContextWrapper.getLimiter().availablePermits());
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2021 PANTHEON.tech, s.r.o. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.cluster.datastore;
-
-import static org.mockito.Mockito.doReturn;
-import static org.mockito.Mockito.times;
-import static org.mockito.Mockito.verify;
-
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.mockito.Mock;
-import org.mockito.junit.MockitoJUnitRunner;
-import org.opendaylight.controller.cluster.datastore.utils.ActorUtils;
-
-@RunWith(MockitoJUnitRunner.StrictStubs.class)
-public class DirectTransactionContextWrapperTest {
- @Mock
- private ActorUtils actorUtils;
-
- @Mock
- private TransactionContext transactionContext;
-
- @Mock
- private TransactionOperation transactionOperation;
-
- private DirectTransactionContextWrapper contextWrapper;
-
- @Before
- public void setUp() {
- doReturn(DatastoreContext.newBuilder().build()).when(actorUtils).getDatastoreContext();
- contextWrapper = new DirectTransactionContextWrapper(MockIdentifiers.transactionIdentifier(
- DirectTransactionContextWrapperTest.class, "mock"), actorUtils, "mock",
- transactionContext);
- }
-
- @Test
- public void testMaybeExecuteTransactionOperation() {
- contextWrapper.maybeExecuteTransactionOperation(transactionOperation);
- verify(transactionOperation, times(1)).invoke(transactionContext, null);
- }
-}
@Parameters(name = "{0}")
public static Collection<Object[]> data() {
return Arrays.asList(new Object[][] {
- { TestDistributedDataStore.class }, { TestClientBackedDataStore.class }
+ { TestClientBackedDataStore.class }
});
}
final CountDownLatch blockRecoveryLatch = new CountDownLatch(1);
InMemoryJournal.addBlockReadMessagesLatch(persistentID, blockRecoveryLatch);
- try (AbstractDataStore dataStore = testKit.setupAbstractDataStore(
- testParameter, testName, false, shardName)) {
-
+ try (var dataStore = testKit.setupDataStore(testParameter, testName, false, shardName)) {
// Create the write Tx
final DOMStoreWriteTransaction writeTx = writeOnly ? dataStore.newWriteOnlyTransaction()
: dataStore.newReadWriteTransaction();
final CountDownLatch blockRecoveryLatch = new CountDownLatch(1);
InMemoryJournal.addBlockReadMessagesLatch(persistentID, blockRecoveryLatch);
- try (AbstractDataStore dataStore = testKit.setupAbstractDataStore(
- testParameter, testName, false, shardName)) {
-
+ try (var dataStore = testKit.setupDataStore(testParameter, testName, false, shardName)) {
// Create the read-write Tx
final DOMStoreReadWriteTransaction readWriteTx = dataStore.newReadWriteTransaction();
assertNotNull("newReadWriteTransaction returned null", readWriteTx);
InMemoryJournal.addEntry(persistentID, 1, "Dummy data so akka will read from persistence");
- final AbstractDataStore dataStore = testKit.setupAbstractDataStore(testParameter, testName, false, shardName);
+ final var dataStore = testKit.setupDataStore(testParameter, testName, false, shardName);
// Create the write Tx
final DOMStoreWriteTransaction writeTx = dataStore.newWriteOnlyTransaction();
InMemoryJournal.addEntry(persistentID, 1, "Dummy data so akka will read from persistence");
- try (AbstractDataStore dataStore = testKit.setupAbstractDataStore(testParameter, testName, false, shardName)) {
-
+ try (var dataStore = testKit.setupDataStore(testParameter, testName, false, shardName)) {
// Create the read-write Tx
final DOMStoreReadWriteTransaction readWriteTx = dataStore.newReadWriteTransaction();
assertNotNull("newReadWriteTransaction returned null", readWriteTx);
package org.opendaylight.controller.cluster.datastore;
import static org.awaitility.Awaitility.await;
-import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertThrows;
import static org.junit.Assert.assertTrue;
import static org.junit.Assume.assumeTrue;
+import static org.junit.jupiter.api.Assertions.assertInstanceOf;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
-import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.timeout;
import com.google.common.base.Stopwatch;
import com.google.common.base.Throwables;
import com.google.common.collect.ImmutableMap;
+import com.google.common.util.concurrent.FutureCallback;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.MoreExecutors;
import com.google.common.util.concurrent.Uninterruptibles;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
+import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import org.opendaylight.controller.cluster.datastore.TestShard.RequestFrontendMetadata;
import org.opendaylight.controller.cluster.datastore.TestShard.StartDropMessages;
import org.opendaylight.controller.cluster.datastore.TestShard.StopDropMessages;
-import org.opendaylight.controller.cluster.datastore.exceptions.NoShardLeaderException;
-import org.opendaylight.controller.cluster.datastore.exceptions.ShardLeaderNotRespondingException;
import org.opendaylight.controller.cluster.datastore.messages.CommitTransactionReply;
import org.opendaylight.controller.cluster.datastore.messages.ForwardedReadyTransaction;
import org.opendaylight.controller.cluster.datastore.messages.GetShardDataTree;
import org.opendaylight.mdsal.common.api.TransactionCommitFailedException;
import org.opendaylight.mdsal.dom.api.DOMDataTreeWriteTransaction;
import org.opendaylight.mdsal.dom.api.DOMTransactionChain;
-import org.opendaylight.mdsal.dom.api.DOMTransactionChainListener;
import org.opendaylight.mdsal.dom.spi.store.DOMStore;
import org.opendaylight.mdsal.dom.spi.store.DOMStoreReadTransaction;
import org.opendaylight.mdsal.dom.spi.store.DOMStoreReadWriteTransaction;
import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
-import org.opendaylight.yangtools.yang.data.api.schema.SystemMapNode;
-import org.opendaylight.yangtools.yang.data.api.schema.builder.CollectionNodeBuilder;
import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
import org.opendaylight.yangtools.yang.data.tree.api.ConflictingModificationAppliedException;
@Parameters(name = "{0}")
public static Collection<Object[]> data() {
return Arrays.asList(new Object[][] {
- { TestDistributedDataStore.class, 7 }, { TestClientBackedDataStore.class, 12 }
+ { TestClientBackedDataStore.class, 12 }
});
}
@Parameter(0)
- public Class<? extends AbstractDataStore> testParameter;
+ public Class<? extends ClientBackedDataStore> testParameter;
@Parameter(1)
public int commitTimeout;
private final TransactionIdentifier tx1 = nextTransactionId();
private final TransactionIdentifier tx2 = nextTransactionId();
- private AbstractDataStore followerDistributedDataStore;
- private AbstractDataStore leaderDistributedDataStore;
+ private ClientBackedDataStore followerDistributedDataStore;
+ private ClientBackedDataStore leaderDistributedDataStore;
private IntegrationTestKit followerTestKit;
private IntegrationTestKit leaderTestKit;
@After
public void tearDown() {
if (followerDistributedDataStore != null) {
- leaderDistributedDataStore.close();
+ followerDistributedDataStore.close();
}
if (leaderDistributedDataStore != null) {
leaderDistributedDataStore.close();
throws Exception {
leaderTestKit = new IntegrationTestKit(leaderSystem, leaderBuilder, commitTimeout);
- leaderDistributedDataStore = leaderTestKit.setupAbstractDataStore(
- testParameter, type, moduleShardsConfig, false, shards);
+ leaderDistributedDataStore = leaderTestKit.setupDataStore(testParameter, type, moduleShardsConfig, false,
+ shards);
followerTestKit = new IntegrationTestKit(followerSystem, followerBuilder, commitTimeout);
- followerDistributedDataStore = followerTestKit.setupAbstractDataStore(
+ followerDistributedDataStore = followerTestKit.setupDataStore(
testParameter, type, moduleShardsConfig, false, shards);
leaderTestKit.waitUntilLeader(leaderDistributedDataStore.getActorUtils(), shards);
private static void verifyCars(final DOMStoreReadTransaction readTx, final MapEntryNode... entries)
throws Exception {
- final Optional<NormalizedNode> optional = readTx.read(CarsModel.CAR_LIST_PATH).get(5, TimeUnit.SECONDS);
- assertTrue("isPresent", optional.isPresent());
-
- final CollectionNodeBuilder<MapEntryNode, SystemMapNode> listBuilder = ImmutableNodes.mapNodeBuilder(
- CarsModel.CAR_QNAME);
- for (final NormalizedNode entry: entries) {
- listBuilder.withChild((MapEntryNode) entry);
- }
-
- assertEquals("Car list node", listBuilder.build(), optional.get());
+ assertEquals("Car list node",
+ Optional.of(ImmutableNodes.mapNodeBuilder(CarsModel.CAR_QNAME).withValue(Arrays.asList(entries)).build()),
+ readTx.read(CarsModel.CAR_LIST_PATH).get(5, TimeUnit.SECONDS));
}
private static void verifyNode(final DOMStoreReadTransaction readTx, final YangInstanceIdentifier path,
final ActorSystem newSystem = newActorSystem("reinstated-member2", "Member2");
- try (AbstractDataStore member2Datastore = new IntegrationTestKit(newSystem, leaderDatastoreContextBuilder,
- commitTimeout)
- .setupAbstractDataStore(testParameter, testName, "module-shards-member2", true, CARS)) {
+ try (var member2Datastore = new IntegrationTestKit(newSystem, leaderDatastoreContextBuilder, commitTimeout)
+ .setupDataStore(testParameter, testName, "module-shards-member2", true, CARS)) {
verifyCars(member2Datastore.newReadOnlyTransaction(), car2);
}
}
// wait to let the shard catch up with purged
await("Range set leak test").atMost(5, TimeUnit.SECONDS)
- .pollInterval(500, TimeUnit.MILLISECONDS)
- .untilAsserted(() -> {
- final var localShard = leaderDistributedDataStore.getActorUtils().findLocalShard("cars")
- .orElseThrow();
- final var frontendMetadata =
- (FrontendShardDataTreeSnapshotMetadata) leaderDistributedDataStore.getActorUtils()
- .executeOperation(localShard, new RequestFrontendMetadata());
-
- final var clientMeta = frontendMetadata.getClients().get(0);
- if (leaderDistributedDataStore.getActorUtils().getDatastoreContext().isUseTellBasedProtocol()) {
- assertTellClientMetadata(clientMeta, numCars * 2);
- } else {
- assertAskClientMetadata(clientMeta);
- }
- });
+ .pollInterval(500, TimeUnit.MILLISECONDS)
+ .untilAsserted(() -> {
+ final var localShard = leaderDistributedDataStore.getActorUtils().findLocalShard("cars").orElseThrow();
+ final var frontendMetadata =
+ (FrontendShardDataTreeSnapshotMetadata) leaderDistributedDataStore.getActorUtils()
+ .executeOperation(localShard, new RequestFrontendMetadata());
+
+ assertClientMetadata(frontendMetadata.getClients().get(0), numCars * 2);
+ });
try (var tx = txChain.newReadOnlyTransaction()) {
- final var body = tx.read(CarsModel.CAR_LIST_PATH).get(5, TimeUnit.SECONDS).orElseThrow().body();
- assertThat(body, instanceOf(Collection.class));
+ final var body = assertInstanceOf(Collection.class,
+ tx.read(CarsModel.CAR_LIST_PATH).get(5, TimeUnit.SECONDS).orElseThrow().body());
assertEquals(numCars, ((Collection<?>) body).size());
}
}
- private static void assertAskClientMetadata(final FrontendClientMetadata clientMeta) {
- // ask based should track no metadata
- assertEquals(List.of(), clientMeta.getCurrentHistories());
- }
-
- private static void assertTellClientMetadata(final FrontendClientMetadata clientMeta, final long lastPurged) {
+ private static void assertClientMetadata(final FrontendClientMetadata clientMeta, final long lastPurged) {
final var iterator = clientMeta.getCurrentHistories().iterator();
var metadata = iterator.next();
while (iterator.hasNext() && metadata.getHistoryId() != 1) {
@Test
public void testCloseTransactionMetadataLeak() throws Exception {
- // FIXME: CONTROLLER-2016: ask-based frontend triggers this:
- //
- // java.lang.IllegalStateException: Previous transaction
- // member-2-datastore-testCloseTransactionMetadataLeak-fe-0-chn-1-txn-1-0 is not ready yet
- // at org.opendaylight.controller.cluster.datastore.TransactionChainProxy$Allocated.checkReady()
- // at org.opendaylight.controller.cluster.datastore.TransactionChainProxy.newReadOnlyTransaction()
- assumeTrue(testParameter.isAssignableFrom(ClientBackedDataStore.class));
-
initDatastoresWithCars("testCloseTransactionMetadataLeak");
- final DOMStoreTransactionChain txChain = followerDistributedDataStore.createTransactionChain();
+ final var txChain = followerDistributedDataStore.createTransactionChain();
- DOMStoreWriteTransaction writeTx = txChain.newWriteOnlyTransaction();
+ var writeTx = txChain.newWriteOnlyTransaction();
writeTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
writeTx.write(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode());
followerTestKit.doCommit(writeTx.ready());
// wait to let the shard catch up with purged
await("wait for purges to settle").atMost(5, TimeUnit.SECONDS)
- .pollInterval(500, TimeUnit.MILLISECONDS)
- .untilAsserted(() -> {
- final var localShard = leaderDistributedDataStore.getActorUtils().findLocalShard("cars")
- .orElseThrow();
- final var frontendMetadata =
- (FrontendShardDataTreeSnapshotMetadata) leaderDistributedDataStore.getActorUtils()
- .executeOperation(localShard, new RequestFrontendMetadata());
-
- final var clientMeta = frontendMetadata.getClients().get(0);
- if (leaderDistributedDataStore.getActorUtils().getDatastoreContext().isUseTellBasedProtocol()) {
- assertTellClientMetadata(clientMeta, numCars * 2);
- } else {
- assertAskClientMetadata(clientMeta);
- }
- });
+ .pollInterval(500, TimeUnit.MILLISECONDS)
+ .untilAsserted(() -> {
+ final var localShard = leaderDistributedDataStore.getActorUtils().findLocalShard("cars").orElseThrow();
+ final var frontendMetadata =
+ (FrontendShardDataTreeSnapshotMetadata) leaderDistributedDataStore.getActorUtils()
+ .executeOperation(localShard, new RequestFrontendMetadata());
+
+ assertClientMetadata(frontendMetadata.getClients().get(0), numCars * 2);
+ });
}
@Test
LogicalDatastoreType.CONFIGURATION, followerDistributedDataStore).build(),
MoreExecutors.directExecutor());
- final DOMTransactionChainListener listener = mock(DOMTransactionChainListener.class);
- final DOMTransactionChain txChain = broker.createTransactionChain(listener);
+ final var listener = mock(FutureCallback.class);
+ final DOMTransactionChain txChain = broker.createTransactionChain();
+ txChain.addCallback(listener);
final DOMDataTreeWriteTransaction writeTx = txChain.newWriteOnlyTransaction();
.withChild(ImmutableNodes.leafNode(TestModel.JUNK_QNAME, "junk"))
.build());
- final var ex = assertThrows(ExecutionException.class, () -> writeTx.commit().get(5, TimeUnit.SECONDS))
- .getCause();
- assertThat(ex, instanceOf(TransactionCommitFailedException.class));
+ final var ex = assertThrows(ExecutionException.class, () -> writeTx.commit().get(5, TimeUnit.SECONDS));
+ assertInstanceOf(TransactionCommitFailedException.class, ex.getCause());
- verify(listener, timeout(5000)).onTransactionChainFailed(eq(txChain), eq(writeTx), any(Throwable.class));
+ verify(listener, timeout(5000)).onFailure(any());
txChain.close();
broker.close();
public void testChainedTransactionFailureWithMultipleShards() throws Exception {
initDatastoresWithCarsAndPeople("testChainedTransactionFailureWithMultipleShards");
- final ConcurrentDOMDataBroker broker = new ConcurrentDOMDataBroker(
- ImmutableMap.<LogicalDatastoreType, DOMStore>builder().put(
- LogicalDatastoreType.CONFIGURATION, followerDistributedDataStore).build(),
- MoreExecutors.directExecutor());
+ try (var broker = new ConcurrentDOMDataBroker(
+ Map.of(LogicalDatastoreType.CONFIGURATION, followerDistributedDataStore), MoreExecutors.directExecutor())) {
- final DOMTransactionChainListener listener = mock(DOMTransactionChainListener.class);
- final DOMTransactionChain txChain = broker.createTransactionChain(listener);
+ final var listener = mock(FutureCallback.class);
+ final DOMTransactionChain txChain = broker.createTransactionChain();
+ txChain.addCallback(listener);
- final DOMDataTreeWriteTransaction writeTx = txChain.newWriteOnlyTransaction();
+ final DOMDataTreeWriteTransaction writeTx = txChain.newWriteOnlyTransaction();
- writeTx.put(LogicalDatastoreType.CONFIGURATION, PeopleModel.BASE_PATH, PeopleModel.emptyContainer());
+ writeTx.put(LogicalDatastoreType.CONFIGURATION, PeopleModel.BASE_PATH, PeopleModel.emptyContainer());
- // Note that merge will validate the data and fail but put succeeds b/c deep validation is not
- // done for put for performance reasons.
- writeTx.merge(LogicalDatastoreType.CONFIGURATION, CarsModel.BASE_PATH, Builders.containerBuilder()
- .withNodeIdentifier(new NodeIdentifier(CarsModel.BASE_QNAME))
- .withChild(ImmutableNodes.leafNode(TestModel.JUNK_QNAME, "junk"))
- .build());
+ // Note that merge will validate the data and fail but put succeeds b/c deep validation is not
+ // done for put for performance reasons.
+ writeTx.merge(LogicalDatastoreType.CONFIGURATION, CarsModel.BASE_PATH, Builders.containerBuilder()
+ .withNodeIdentifier(new NodeIdentifier(CarsModel.BASE_QNAME))
+ .withChild(ImmutableNodes.leafNode(TestModel.JUNK_QNAME, "junk"))
+ .build());
- final var ex = assertThrows(ExecutionException.class, () -> writeTx.commit().get(5, TimeUnit.SECONDS))
- .getCause();
- assertThat(ex, instanceOf(TransactionCommitFailedException.class));
+ final var ex = assertThrows(ExecutionException.class, () -> writeTx.commit().get(5, TimeUnit.SECONDS))
+ .getCause();
+ assertThat(ex, instanceOf(TransactionCommitFailedException.class));
- verify(listener, timeout(5000)).onTransactionChainFailed(eq(txChain), eq(writeTx), any(Throwable.class));
+ verify(listener, timeout(5000)).onFailure(any());
- txChain.close();
- broker.close();
+ txChain.close();
+ }
}
@Test
.shardHeartbeatIntervalInMillis(100).shardElectionTimeoutFactor(5);
IntegrationTestKit newMember1TestKit = new IntegrationTestKit(leaderSystem, newMember1Builder, commitTimeout);
- try (AbstractDataStore ds =
- newMember1TestKit.setupAbstractDataStore(
- testParameter, testName, MODULE_SHARDS_CARS_ONLY_1_2, false, CARS)) {
+ try (var ds = newMember1TestKit.setupDataStore(testParameter, testName, MODULE_SHARDS_CARS_ONLY_1_2, false,
+ CARS)) {
followerTestKit.waitUntilLeader(followerDistributedDataStore.getActorUtils(), CARS);
ReadyLocalTransaction readyLocal = new ReadyLocalTransaction(tx1 , modification, true, Optional.empty());
- carsFollowerShard.get().tell(readyLocal, followerTestKit.getRef());
+ carsFollowerShard.orElseThrow().tell(readyLocal, followerTestKit.getRef());
Object resp = followerTestKit.expectMsgClass(Object.class);
if (resp instanceof akka.actor.Status.Failure) {
throw new AssertionError("Unexpected failure response", ((akka.actor.Status.Failure)resp).cause());
readyLocal = new ReadyLocalTransaction(tx2 , modification, false, Optional.empty());
- carsFollowerShard.get().tell(readyLocal, followerTestKit.getRef());
+ carsFollowerShard.orElseThrow().tell(readyLocal, followerTestKit.getRef());
resp = followerTestKit.expectMsgClass(Object.class);
if (resp instanceof akka.actor.Status.Failure) {
throw new AssertionError("Unexpected failure response", ((akka.actor.Status.Failure)resp).cause());
followerDistributedDataStore.getActorUtils().findLocalShard("cars");
assertTrue("Cars follower shard found", carsFollowerShard.isPresent());
- carsFollowerShard.get().tell(GetShardDataTree.INSTANCE, followerTestKit.getRef());
+ carsFollowerShard.orElseThrow().tell(GetShardDataTree.INSTANCE, followerTestKit.getRef());
final DataTree dataTree = followerTestKit.expectMsgClass(DataTree.class);
// Send a tx with immediate commit.
new ReadWriteShardDataTreeTransaction(mock(ShardDataTreeTransactionParent.class), tx1, modification),
true, Optional.empty());
- carsFollowerShard.get().tell(forwardedReady, followerTestKit.getRef());
+ carsFollowerShard.orElseThrow().tell(forwardedReady, followerTestKit.getRef());
Object resp = followerTestKit.expectMsgClass(Object.class);
if (resp instanceof akka.actor.Status.Failure) {
throw new AssertionError("Unexpected failure response", ((akka.actor.Status.Failure)resp).cause());
new ReadWriteShardDataTreeTransaction(mock(ShardDataTreeTransactionParent.class), tx2, modification),
false, Optional.empty());
- carsFollowerShard.get().tell(forwardedReady, followerTestKit.getRef());
+ carsFollowerShard.orElseThrow().tell(forwardedReady, followerTestKit.getRef());
resp = followerTestKit.expectMsgClass(Object.class);
if (resp instanceof akka.actor.Status.Failure) {
throw new AssertionError("Unexpected failure response", ((akka.actor.Status.Failure)resp).cause());
leaderDatastoreContextBuilder.shardBatchedModificationCount(2);
initDatastoresWithCarsAndPeople("testTransactionForwardedToLeaderAfterRetry");
+ // Verify backend statistics on start
+ verifyCarsReadWriteTransactions(leaderDistributedDataStore, 0);
+ verifyCarsReadWriteTransactions(followerDistributedDataStore, 0);
+
// Do an initial write to get the primary shard info cached.
final DOMStoreWriteTransaction initialWriteTx = followerDistributedDataStore.newWriteOnlyTransaction();
writeTx2.write(PeopleModel.PERSON_LIST_PATH, people);
final DOMStoreThreePhaseCommitCohort writeTx2Cohort = writeTx2.ready();
+ // At this point only leader should see the transactions
+ verifyCarsReadWriteTransactions(leaderDistributedDataStore, 2);
+ verifyCarsReadWriteTransactions(followerDistributedDataStore, 0);
+
// Prepare another WO that writes to a single shard and thus will be directly committed on ready. This
- // tx writes 5 cars so 2 BatchedModidifications messages will be sent initially and cached in the
- // leader shard (with shardBatchedModificationCount set to 2). The 3rd BatchedModidifications will be
- // sent on ready.
+ // tx writes 5 cars so 2 BatchedModifications messages will be sent initially and cached in the leader shard
+ // (with shardBatchedModificationCount set to 2). The 3rd BatchedModifications will be sent on ready.
final DOMStoreWriteTransaction writeTx3 = followerDistributedDataStore.newWriteOnlyTransaction();
for (int i = 1; i <= 5; i++, carIndex++) {
writeTx3.write(CarsModel.newCarPath("car" + carIndex), cars.getLast());
}
- // Prepare another WO that writes to a single shard. This will send a single BatchedModidifications
- // message on ready.
+ // Prepare another WO that writes to a single shard. This will send a single BatchedModifications message
+ // on ready.
final DOMStoreWriteTransaction writeTx4 = followerDistributedDataStore.newWriteOnlyTransaction();
cars.add(CarsModel.newCarEntry("car" + carIndex, Uint64.valueOf(carIndex)));
writeTx4.write(CarsModel.newCarPath("car" + carIndex), cars.getLast());
carIndex++;
- // Prepare a RW tx that will create a tx actor and send a ForwardedReadyTransaciton message to the
- // leader shard on ready.
+ // Prepare a RW tx that will create a tx actor and send a ForwardedReadyTransaction message to the leader shard
+ // on ready.
final DOMStoreReadWriteTransaction readWriteTx = followerDistributedDataStore.newReadWriteTransaction();
cars.add(CarsModel.newCarEntry("car" + carIndex, Uint64.valueOf(carIndex)));
- readWriteTx.write(CarsModel.newCarPath("car" + carIndex), cars.getLast());
+ final YangInstanceIdentifier carPath = CarsModel.newCarPath("car" + carIndex);
+ readWriteTx.write(carPath, cars.getLast());
- // FIXME: CONTROLLER-2017: ClientBackedDataStore reports only 4 transactions
- assumeTrue(DistributedDataStore.class.isAssignableFrom(testParameter));
- IntegrationTestKit.verifyShardStats(leaderDistributedDataStore, "cars",
- stats -> assertEquals("getReadWriteTransactionCount", 5, stats.getReadWriteTransactionCount()));
+ // There is a difference here between implementations: tell-based protocol enforces batching on per-transaction
+ // level whereas ask-based protocol has a global limit towards a shard -- and hence flushes out last two
+ // transactions eagerly.
+ verifyCarsReadWriteTransactions(leaderDistributedDataStore, 3);
+ verifyCarsReadWriteTransactions(followerDistributedDataStore, 0);
// Disable elections on the leader so it switches to follower.
followerTestKit.doCommit(writeTx4Cohort);
followerTestKit.doCommit(rwTxCohort);
+ // At this point everything is committed and the follower datastore should see 5 transactions, but leader should
+ // only see the initial transactions
+ verifyCarsReadWriteTransactions(leaderDistributedDataStore, 3);
+ verifyCarsReadWriteTransactions(followerDistributedDataStore, 5);
+
DOMStoreReadTransaction readTx = leaderDistributedDataStore.newReadOnlyTransaction();
verifyCars(readTx, cars.toArray(new MapEntryNode[cars.size()]));
verifyNode(readTx, PeopleModel.PERSON_LIST_PATH, people);
}
+ private static void verifyCarsReadWriteTransactions(final ClientBackedDataStore datastore, final int expected)
+ throws Exception {
+ IntegrationTestKit.verifyShardStats(datastore, "cars",
+ stats -> assertEquals("getReadWriteTransactionCount", expected, stats.getReadWriteTransactionCount()));
+ }
+
@Test
public void testLeadershipTransferOnShutdown() throws Exception {
leaderDatastoreContextBuilder.shardBatchedModificationCount(1);
final IntegrationTestKit follower2TestKit = new IntegrationTestKit(follower2System,
DatastoreContext.newBuilderFrom(followerDatastoreContextBuilder.build()).operationTimeoutInMillis(500),
commitTimeout);
- try (AbstractDataStore follower2DistributedDataStore = follower2TestKit.setupAbstractDataStore(
- testParameter, testName, MODULE_SHARDS_CARS_PEOPLE_1_2_3, false)) {
+ try (var follower2DistributedDataStore = follower2TestKit.setupDataStore(testParameter, testName,
+ MODULE_SHARDS_CARS_PEOPLE_1_2_3, false)) {
followerTestKit.waitForMembersUp("member-3");
follower2TestKit.waitForMembersUp("member-1", "member-2");
writeTx.write(PeopleModel.BASE_PATH, PeopleModel.emptyContainer());
final DOMStoreThreePhaseCommitCohort cohort1 = writeTx.ready();
- final var usesCohorts = DistributedDataStore.class.isAssignableFrom(testParameter);
- if (usesCohorts) {
- IntegrationTestKit.verifyShardStats(leaderDistributedDataStore, "cars",
- stats -> assertEquals("getTxCohortCacheSize", 1, stats.getTxCohortCacheSize()));
- }
+ // FIXME: this assertion should be made in an explicit Shard test
+ // IntegrationTestKit.verifyShardStats(leaderDistributedDataStore, "cars",
+ // stats -> assertEquals("getTxCohortCacheSize", 1, stats.getTxCohortCacheSize()));
writeTx = followerDistributedDataStore.newWriteOnlyTransaction();
final MapEntryNode car = CarsModel.newCarEntry("optima", Uint64.valueOf(20000));
writeTx.write(CarsModel.newCarPath("optima"), car);
final DOMStoreThreePhaseCommitCohort cohort2 = writeTx.ready();
- if (usesCohorts) {
- IntegrationTestKit.verifyShardStats(leaderDistributedDataStore, "cars",
- stats -> assertEquals("getTxCohortCacheSize", 2, stats.getTxCohortCacheSize()));
- }
+ // FIXME: this assertion should be made in an explicit Shard test
+ // IntegrationTestKit.verifyShardStats(leaderDistributedDataStore, "cars",
+ // stats -> assertEquals("getTxCohortCacheSize", 2, stats.getTxCohortCacheSize()));
// Gracefully stop the leader via a Shutdown message.
raftState -> assertEquals("getRaftState", "IsolatedLeader", raftState.getRaftState()));
final var noShardLeaderCohort = noShardLeaderWriteTx.ready();
- final ListenableFuture<Boolean> canCommit;
-
- // There is difference in behavior here:
- if (!leaderDistributedDataStore.getActorUtils().getDatastoreContext().isUseTellBasedProtocol()) {
- // ask-based canCommit() times out and aborts
- final var ex = assertThrows(ExecutionException.class,
- () -> leaderTestKit.doCommit(noShardLeaderCohort)).getCause();
- assertThat(ex, instanceOf(NoShardLeaderException.class));
- assertThat(ex.getMessage(), containsString(
- "Shard member-1-shard-cars-testTransactionWithIsolatedLeader currently has no leader."));
- canCommit = null;
- } else {
- // tell-based canCommit() does not have a real timeout and hence continues
- canCommit = noShardLeaderCohort.canCommit();
- Uninterruptibles.sleepUninterruptibly(commitTimeout, TimeUnit.SECONDS);
- assertFalse(canCommit.isDone());
- }
+ // tell-based canCommit() does not have a real timeout and hence continues
+ final var canCommit = noShardLeaderCohort.canCommit();
+ Uninterruptibles.sleepUninterruptibly(commitTimeout, TimeUnit.SECONDS);
+ assertFalse(canCommit.isDone());
sendDatastoreContextUpdate(leaderDistributedDataStore, leaderDatastoreContextBuilder
.shardElectionTimeoutFactor(100));
final DOMStoreThreePhaseCommitCohort successTxCohort = successWriteTx.ready();
- followerDistributedDataStore = followerTestKit.setupAbstractDataStore(
- testParameter, testName, MODULE_SHARDS_CARS_ONLY_1_2, false, CARS);
+ followerDistributedDataStore = followerTestKit.setupDataStore(testParameter, testName,
+ MODULE_SHARDS_CARS_ONLY_1_2, false, CARS);
leaderTestKit.doCommit(preIsolatedLeaderTxCohort);
leaderTestKit.doCommit(successTxCohort);
- // continuation of tell-based protocol: readied transaction will complete commit, but will report an OLFE
- if (canCommit != null) {
- final var ex = assertThrows(ExecutionException.class,
- () -> canCommit.get(commitTimeout, TimeUnit.SECONDS)).getCause();
- assertThat(ex, instanceOf(OptimisticLockFailedException.class));
- assertEquals("Optimistic lock failed for path " + CarsModel.BASE_PATH, ex.getMessage());
- final var cause = ex.getCause();
- assertThat(cause, instanceOf(ConflictingModificationAppliedException.class));
- final var cmae = (ConflictingModificationAppliedException) cause;
- assertEquals("Node was created by other transaction.", cmae.getMessage());
- assertEquals(CarsModel.BASE_PATH, cmae.getPath());
- }
+ // continuation of canCommit(): readied transaction will complete commit, but will report an OLFE
+ final var ex = assertThrows(ExecutionException.class,
+ () -> canCommit.get(commitTimeout, TimeUnit.SECONDS)).getCause();
+ assertThat(ex, instanceOf(OptimisticLockFailedException.class));
+ assertEquals("Optimistic lock failed for path " + CarsModel.BASE_PATH, ex.getMessage());
+ final var cause = ex.getCause();
+ assertThat(cause, instanceOf(ConflictingModificationAppliedException.class));
+ final var cmae = (ConflictingModificationAppliedException) cause;
+ assertEquals("Node was created by other transaction.", cmae.getMessage());
+ assertEquals(CarsModel.BASE_PATH, cmae.getPath());
}
@Test
rwTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
final var ex = assertThrows(ExecutionException.class, () -> followerTestKit.doCommit(rwTx.ready()));
- final String msg = "Unexpected exception: " + Throwables.getStackTraceAsString(ex.getCause());
- if (DistributedDataStore.class.isAssignableFrom(testParameter)) {
- assertTrue(msg, Throwables.getRootCause(ex) instanceof NoShardLeaderException
- || ex.getCause() instanceof ShardLeaderNotRespondingException);
- } else {
- assertThat(msg, Throwables.getRootCause(ex), instanceOf(RequestTimeoutException.class));
- }
+ assertThat("Unexpected exception: " + Throwables.getStackTraceAsString(ex.getCause()),
+ Throwables.getRootCause(ex), instanceOf(RequestTimeoutException.class));
}
@Test
rwTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
final var ex = assertThrows(ExecutionException.class, () -> followerTestKit.doCommit(rwTx.ready()));
- final String msg = "Unexpected exception: " + Throwables.getStackTraceAsString(ex.getCause());
- if (DistributedDataStore.class.isAssignableFrom(testParameter)) {
- assertThat(msg, Throwables.getRootCause(ex), instanceOf(NoShardLeaderException.class));
- } else {
- assertThat(msg, Throwables.getRootCause(ex), instanceOf(RequestTimeoutException.class));
- }
+ assertThat("Unexpected exception: " + Throwables.getStackTraceAsString(ex.getCause()),
+ Throwables.getRootCause(ex), instanceOf(RequestTimeoutException.class));
}
@Test
final IntegrationTestKit follower2TestKit = new IntegrationTestKit(
follower2System, follower2DatastoreContextBuilder, commitTimeout);
- try (AbstractDataStore ds =
- follower2TestKit.setupAbstractDataStore(
- testParameter, testName, MODULE_SHARDS_CARS_1_2_3, false, CARS)) {
+ try (var ds = follower2TestKit.setupDataStore(testParameter, testName, MODULE_SHARDS_CARS_1_2_3, false, CARS)) {
followerTestKit.waitForMembersUp("member-1", "member-3");
follower2TestKit.waitForMembersUp("member-1", "member-2");
final IntegrationTestKit follower2TestKit = new IntegrationTestKit(
follower2System, follower2DatastoreContextBuilder, commitTimeout);
- final AbstractDataStore ds2 =
- follower2TestKit.setupAbstractDataStore(
- testParameter, testName, MODULE_SHARDS_CARS_1_2_3, false, CARS);
+ final var ds2 = follower2TestKit.setupDataStore(testParameter, testName, MODULE_SHARDS_CARS_1_2_3, false, CARS);
followerTestKit.waitForMembersUp("member-1", "member-3");
follower2TestKit.waitForMembersUp("member-1", "member-2");
// behavior is controlled by akka.coordinated-shutdown.run-by-actor-system-terminate configuration option
TestKit.shutdownActorSystem(follower2System, true);
- ActorRef cars = leaderDistributedDataStore.getActorUtils().findLocalShard("cars").get();
+ ActorRef cars = leaderDistributedDataStore.getActorUtils().findLocalShard("cars").orElseThrow();
final OnDemandRaftState initialState = (OnDemandRaftState) leaderDistributedDataStore.getActorUtils()
.executeOperation(cars, GetOnDemandRaftState.INSTANCE);
await().atMost(10, TimeUnit.SECONDS)
.until(() -> containsUnreachable(followerCluster, follower2Member));
- ActorRef followerCars = followerDistributedDataStore.getActorUtils().findLocalShard("cars").get();
+ ActorRef followerCars = followerDistributedDataStore.getActorUtils().findLocalShard("cars").orElseThrow();
// to simulate a follower not being able to receive messages, but still being able to send messages and becoming
// candidate, we can just send a couple of RequestVotes to both leader and follower.
CarsModel.newCarsMapNode(CarsModel.newCarEntry("optima", Uint64.valueOf(20000))));
AbstractShardTest.writeToStore(tree, CarsModel.BASE_PATH, carsNode);
- final NormalizedNode snapshotRoot = AbstractShardTest.readStore(tree, YangInstanceIdentifier.empty());
+ final NormalizedNode snapshotRoot = AbstractShardTest.readStore(tree, YangInstanceIdentifier.of());
final Snapshot initialSnapshot = Snapshot.create(
new ShardSnapshotState(new MetadataShardDataTreeSnapshot(snapshotRoot)),
Collections.emptyList(), 5, 1, 5, 1, 1, null, null);
@Test
public void testReadWriteMessageSlicing() throws Exception {
- // The slicing is only implemented for tell-based protocol
- assumeTrue(ClientBackedDataStore.class.isAssignableFrom(testParameter));
-
leaderDatastoreContextBuilder.maximumMessageSliceSize(100);
followerDatastoreContextBuilder.maximumMessageSliceSize(100);
initDatastoresWithCars("testLargeReadReplySlicing");
initialWriteTx.write(CarsModel.BASE_PATH, CarsModel.emptyContainer());
leaderTestKit.doCommit(initialWriteTx.ready());
- try (AbstractDataStore follower2DistributedDataStore = follower2TestKit.setupAbstractDataStore(
- testParameter, testName, MODULE_SHARDS_CARS_1_2_3, false)) {
+ try (var follower2DistributedDataStore = follower2TestKit.setupDataStore(testParameter, testName,
+ MODULE_SHARDS_CARS_1_2_3, false)) {
final ActorRef member3Cars = ((LocalShardStore) follower2DistributedDataStore).getLocalShards()
.getLocalShards().get("cars").getActor();
final ActorRef member2Cars = ((LocalShardStore)followerDistributedDataStore).getLocalShards()
.getLocalShards().get("cars").getActor();
- member2Cars.tell(new StartDropMessages(AppendEntries.class), null);
- member3Cars.tell(new StartDropMessages(AppendEntries.class), null);
+ member2Cars.tell(new StartDropMessages<>(AppendEntries.class), null);
+ member3Cars.tell(new StartDropMessages<>(AppendEntries.class), null);
final DOMStoreWriteTransaction newTx = leaderDistributedDataStore.newWriteOnlyTransaction();
newTx.write(CarsModel.CAR_LIST_PATH, CarsModel.newCarMapNode());
"member-3-shard-cars-testRaftCallbackDuringLeadershipDrop", -1,
-1), member3Cars);
- member2Cars.tell(new StopDropMessages(AppendEntries.class), null);
- member3Cars.tell(new StopDropMessages(AppendEntries.class), null);
+ member2Cars.tell(new StopDropMessages<>(AppendEntries.class), null);
+ member3Cars.tell(new StopDropMessages<>(AppendEntries.class), null);
await("Is tx stuck in COMMIT_PENDING")
.atMost(10, TimeUnit.SECONDS).untilAtomic(submitDone, equalTo(true));
.withChild(CarsModel.create())
.build();
- leaderTestKit.testWriteTransaction(leaderDistributedDataStore, YangInstanceIdentifier.empty(), rootNode);
+ leaderTestKit.testWriteTransaction(leaderDistributedDataStore, YangInstanceIdentifier.of(), rootNode);
// FIXME: CONTROLLER-2020: ClientBackedDatastore does not have stable indexes/term,
// the snapshot index seems to fluctuate
- assumeTrue(DistributedDataStore.class.isAssignableFrom(testParameter));
+ assumeTrue(false);
IntegrationTestKit.verifyShardState(leaderDistributedDataStore, "cars",
state -> assertEquals(1, state.getSnapshotIndex()));
verifySnapshot("member-2-shard-cars-testSnapshotOnRootOverwrite", 1);
// root overwrite so expect a snapshot
- leaderTestKit.testWriteTransaction(leaderDistributedDataStore, YangInstanceIdentifier.empty(), rootNode);
+ leaderTestKit.testWriteTransaction(leaderDistributedDataStore, YangInstanceIdentifier.of(), rootNode);
// this was a real snapshot so everything should be in it(1(DisableTrackingPayload) + 1 + 10 + 1)
IntegrationTestKit.verifyShardState(leaderDistributedDataStore, "cars",
assertEquals("Snapshot state type", ShardSnapshotState.class, actual.getState().getClass());
MetadataShardDataTreeSnapshot shardSnapshot =
(MetadataShardDataTreeSnapshot) ((ShardSnapshotState)actual.getState()).getSnapshot();
- assertEquals("Snapshot root node", expRoot, shardSnapshot.getRootNode().get());
+ assertEquals("Snapshot root node", expRoot, shardSnapshot.getRootNode().orElseThrow());
}
- private static void sendDatastoreContextUpdate(final AbstractDataStore dataStore, final Builder builder) {
+ private static void sendDatastoreContextUpdate(final ClientBackedDataStore dataStore, final Builder builder) {
final Builder newBuilder = DatastoreContext.newBuilderFrom(builder.build());
final DatastoreContextFactory mockContextFactory = mock(DatastoreContextFactory.class);
final Answer<DatastoreContext> answer = invocation -> newBuilder.build();
+++ /dev/null
-/*
- * Copyright (c) 2014, 2015 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.cluster.datastore;
-
-import static org.junit.Assert.assertTrue;
-import static org.mockito.Mockito.doReturn;
-import static org.mockito.Mockito.times;
-import static org.mockito.Mockito.verify;
-
-import akka.util.Timeout;
-import com.google.common.util.concurrent.Uninterruptibles;
-import java.util.concurrent.Executors;
-import java.util.concurrent.TimeUnit;
-import org.junit.AfterClass;
-import org.junit.Before;
-import org.junit.BeforeClass;
-import org.junit.Test;
-import org.mockito.Mock;
-import org.mockito.MockitoAnnotations;
-import org.opendaylight.controller.cluster.access.concepts.ClientIdentifier;
-import org.opendaylight.controller.cluster.access.concepts.FrontendIdentifier;
-import org.opendaylight.controller.cluster.access.concepts.FrontendType;
-import org.opendaylight.controller.cluster.access.concepts.MemberName;
-import org.opendaylight.controller.cluster.datastore.utils.ActorUtils;
-import org.opendaylight.controller.md.cluster.datastore.model.TestModel;
-import org.opendaylight.yangtools.yang.common.Empty;
-import org.opendaylight.yangtools.yang.model.api.SchemaContext;
-import scala.concurrent.duration.FiniteDuration;
-
-public class DistributedDataStoreTest extends AbstractActorTest {
- private static final ClientIdentifier UNKNOWN_ID = ClientIdentifier.create(
- FrontendIdentifier.create(MemberName.forName("local"), FrontendType.forName("unknown")), 0);
-
- private static SchemaContext SCHEMA_CONTEXT;
-
- @Mock
- private ActorUtils actorUtils;
-
- @Mock
- private DatastoreContext datastoreContext;
-
- @Mock
- private Timeout shardElectionTimeout;
-
- @BeforeClass
- public static void beforeClass() {
- SCHEMA_CONTEXT = TestModel.createTestContext();
- }
-
- @AfterClass
- public static void afterClass() {
- SCHEMA_CONTEXT = null;
- }
-
- @Before
- public void setUp() {
- MockitoAnnotations.initMocks(this);
-
- doReturn(SCHEMA_CONTEXT).when(actorUtils).getSchemaContext();
- doReturn(DatastoreContext.newBuilder().build()).when(actorUtils).getDatastoreContext();
- }
-
- @Test
- public void testRateLimitingUsedInReadWriteTxCreation() {
- try (DistributedDataStore distributedDataStore = new DistributedDataStore(actorUtils, UNKNOWN_ID)) {
-
- distributedDataStore.newReadWriteTransaction();
-
- verify(actorUtils, times(1)).acquireTxCreationPermit();
- }
- }
-
- @Test
- public void testRateLimitingUsedInWriteOnlyTxCreation() {
- try (DistributedDataStore distributedDataStore = new DistributedDataStore(actorUtils, UNKNOWN_ID)) {
-
- distributedDataStore.newWriteOnlyTransaction();
-
- verify(actorUtils, times(1)).acquireTxCreationPermit();
- }
- }
-
- @Test
- public void testRateLimitingNotUsedInReadOnlyTxCreation() {
- try (DistributedDataStore distributedDataStore = new DistributedDataStore(actorUtils, UNKNOWN_ID)) {
-
- distributedDataStore.newReadOnlyTransaction();
- distributedDataStore.newReadOnlyTransaction();
- distributedDataStore.newReadOnlyTransaction();
-
- verify(actorUtils, times(0)).acquireTxCreationPermit();
- }
- }
-
- @Test
- public void testWaitTillReadyBlocking() {
- doReturn(datastoreContext).when(actorUtils).getDatastoreContext();
- doReturn(shardElectionTimeout).when(datastoreContext).getShardLeaderElectionTimeout();
- doReturn(1).when(datastoreContext).getInitialSettleTimeoutMultiplier();
- doReturn(FiniteDuration.apply(50, TimeUnit.MILLISECONDS)).when(shardElectionTimeout).duration();
- try (DistributedDataStore distributedDataStore = new DistributedDataStore(actorUtils, UNKNOWN_ID)) {
-
- long start = System.currentTimeMillis();
-
- distributedDataStore.waitTillReady();
-
- long end = System.currentTimeMillis();
-
- assertTrue("Expected to be blocked for 50 millis", end - start >= 50);
- }
- }
-
- @Test
- public void testWaitTillReadyCountDown() {
- try (DistributedDataStore distributedDataStore = new DistributedDataStore(actorUtils, UNKNOWN_ID)) {
- doReturn(datastoreContext).when(actorUtils).getDatastoreContext();
- doReturn(shardElectionTimeout).when(datastoreContext).getShardLeaderElectionTimeout();
- doReturn(FiniteDuration.apply(5000, TimeUnit.MILLISECONDS)).when(shardElectionTimeout).duration();
-
- Executors.newSingleThreadExecutor().submit(() -> {
- Uninterruptibles.sleepUninterruptibly(500, TimeUnit.MILLISECONDS);
- distributedDataStore.readinessFuture().set(Empty.value());
- });
-
- long start = System.currentTimeMillis();
-
- distributedDataStore.waitTillReady();
-
- long end = System.currentTimeMillis();
-
- assertTrue("Expected to be released in 500 millis", end - start < 5000);
- }
- }
-}
@Parameters(name = "{0}")
public static Collection<Object[]> data() {
return Arrays.asList(new Object[][] {
- { TestDistributedDataStore.class }, { TestClientBackedDataStore.class }
+ { TestClientBackedDataStore.class }
});
}
final IntegrationTestKit testKit = new IntegrationTestKit(getSystem(), datastoreContextBuilder);
CollectionNodeBuilder<MapEntryNode, SystemMapNode> carMapBuilder = ImmutableNodes.mapNodeBuilder(CAR_QNAME);
- try (AbstractDataStore dataStore = testKit.setupAbstractDataStore(
- testParameter, "testManyWritesDeletes", "module-shards-cars-member-1.conf", true, "cars")) {
+ try (var dataStore = testKit.setupDataStore(testParameter, "testManyWritesDeletes",
+ "module-shards-cars-member-1.conf", true, "cars")) {
DOMStoreTransactionChain txChain = dataStore.createTransactionChain();
MapNode cars = carMapBuilder.build();
- assertEquals("cars not matching result", cars, optional.get());
+ assertEquals("cars not matching result", cars, optional.orElseThrow());
txChain.close();
}
// test restoration from journal and verify data matches
- try (AbstractDataStore dataStore = testKit.setupAbstractDataStore(
- testParameter, "testManyWritesDeletes", "module-shards-cars-member-1.conf", true, "cars")) {
+ try (var dataStore = testKit.setupDataStore(testParameter, "testManyWritesDeletes",
+ "module-shards-cars-member-1.conf", true, "cars")) {
DOMStoreTransactionChain txChain = dataStore.createTransactionChain();
MapNode cars = carMapBuilder.build();
final Optional<NormalizedNode> optional = txChain.newReadOnlyTransaction()
.read(CarsModel.CAR_LIST_PATH).get(5, TimeUnit.SECONDS);
- assertTrue("isPresent", optional.isPresent());
- assertEquals("restored cars do not match snapshot", cars, optional.get());
+ assertEquals("restored cars do not match snapshot", Optional.of(cars), optional);
txChain.close();
}
assertNotNull(handleRequest(readyReq));
verify(mockParent).finishTransaction(same(shardTransaction), eq(Optional.empty()));
- handleRequest(new ReadTransactionRequest(TX_ID, 0, mock(ActorRef.class), YangInstanceIdentifier.empty(), true));
+ handleRequest(new ReadTransactionRequest(TX_ID, 0, mock(ActorRef.class), YangInstanceIdentifier.of(), true));
}
@Test(expected = IllegalStateException.class)
assertNull(handleRequest(abortReq));
verify(mockParent).abortTransaction(same(shardTransaction), any(Runnable.class));
- handleRequest(new ReadTransactionRequest(TX_ID, 0, mock(ActorRef.class), YangInstanceIdentifier.empty(), true));
+ handleRequest(new ReadTransactionRequest(TX_ID, 0, mock(ActorRef.class), YangInstanceIdentifier.of(), true));
}
}
import com.google.common.collect.Sets;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.Uninterruptibles;
-import java.lang.reflect.Constructor;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.opendaylight.controller.cluster.datastore.DatastoreContext.Builder;
import org.opendaylight.controller.cluster.datastore.config.Configuration;
import org.opendaylight.controller.cluster.datastore.config.ConfigurationImpl;
-import org.opendaylight.controller.cluster.datastore.config.EmptyModuleShardConfigProvider;
import org.opendaylight.controller.cluster.datastore.messages.OnDemandShardState;
import org.opendaylight.controller.cluster.datastore.persisted.DatastoreSnapshot;
import org.opendaylight.controller.cluster.datastore.utils.ActorUtils;
return datastoreContextBuilder;
}
- @Deprecated(since = "7.0.0", forRemoval = true)
- public DistributedDataStore setupDistributedDataStore(final String typeName, final String moduleShardsConfig,
- final boolean waitUntilLeader,
- final EffectiveModelContext schemaContext) throws Exception {
- return setupDistributedDataStore(typeName, moduleShardsConfig, "modules.conf", waitUntilLeader, schemaContext);
+ public ClientBackedDataStore setupDataStore(final Class<? extends ClientBackedDataStore> implementation,
+ final String typeName, final String... shardNames) throws Exception {
+ return setupDataStore(implementation, typeName, "module-shards.conf", true, SchemaContextHelper.full(),
+ shardNames);
}
- @Deprecated(since = "7.0.0", forRemoval = true)
- public DistributedDataStore setupDistributedDataStore(final String typeName, final String moduleShardsConfig,
- final String modulesConfig,
- final boolean waitUntilLeader,
- final EffectiveModelContext schemaContext,
- final String... shardNames) throws Exception {
- return (DistributedDataStore) setupAbstractDataStore(DistributedDataStore.class, typeName, moduleShardsConfig,
- modulesConfig, waitUntilLeader, schemaContext, shardNames);
+ public ClientBackedDataStore setupDataStore(final Class<? extends ClientBackedDataStore> implementation,
+ final String typeName, final boolean waitUntilLeader, final String... shardNames) throws Exception {
+ return setupDataStore(implementation, typeName, "module-shards.conf", waitUntilLeader,
+ SchemaContextHelper.full(), shardNames);
}
- public AbstractDataStore setupAbstractDataStore(final Class<? extends AbstractDataStore> implementation,
- final String typeName, final String... shardNames)
- throws Exception {
- return setupAbstractDataStore(implementation, typeName, "module-shards.conf", true,
- SchemaContextHelper.full(), shardNames);
- }
-
- public AbstractDataStore setupAbstractDataStore(final Class<? extends AbstractDataStore> implementation,
- final String typeName, final boolean waitUntilLeader,
- final String... shardNames) throws Exception {
- return setupAbstractDataStore(implementation, typeName, "module-shards.conf", waitUntilLeader,
- SchemaContextHelper.full(), shardNames);
- }
-
- public AbstractDataStore setupAbstractDataStore(final Class<? extends AbstractDataStore> implementation,
- final String typeName, final String moduleShardsConfig,
- final boolean waitUntilLeader, final String... shardNames)
- throws Exception {
- return setupAbstractDataStore(implementation, typeName, moduleShardsConfig, waitUntilLeader,
- SchemaContextHelper.full(), shardNames);
+ public ClientBackedDataStore setupDataStore(final Class<? extends ClientBackedDataStore> implementation,
+ final String typeName, final String moduleShardsConfig, final boolean waitUntilLeader,
+ final String... shardNames) throws Exception {
+ return setupDataStore(implementation, typeName, moduleShardsConfig, waitUntilLeader,
+ SchemaContextHelper.full(), shardNames);
}
- public AbstractDataStore setupAbstractDataStore(final Class<? extends AbstractDataStore> implementation,
- final String typeName, final String moduleShardsConfig,
- final boolean waitUntilLeader,
- final EffectiveModelContext schemaContext,
- final String... shardNames) throws Exception {
- return setupAbstractDataStore(implementation, typeName, moduleShardsConfig, "modules.conf", waitUntilLeader,
- schemaContext, shardNames);
+ public ClientBackedDataStore setupDataStore(final Class<? extends ClientBackedDataStore> implementation,
+ final String typeName, final String moduleShardsConfig, final boolean waitUntilLeader,
+ final EffectiveModelContext schemaContext, final String... shardNames) throws Exception {
+ return setupDataStore(implementation, typeName, moduleShardsConfig, "modules.conf", waitUntilLeader,
+ schemaContext, shardNames);
}
- private AbstractDataStore setupAbstractDataStore(final Class<? extends AbstractDataStore> implementation,
- final String typeName, final String moduleShardsConfig,
- final String modulesConfig, final boolean waitUntilLeader,
- final EffectiveModelContext schemaContext,
- final String... shardNames)
- throws Exception {
+ private ClientBackedDataStore setupDataStore(final Class<? extends ClientBackedDataStore> implementation,
+ final String typeName, final String moduleShardsConfig, final String modulesConfig,
+ final boolean waitUntilLeader, final EffectiveModelContext schemaContext, final String... shardNames)
+ throws Exception {
final ClusterWrapper cluster = new ClusterWrapperImpl(getSystem());
final Configuration config = new ConfigurationImpl(moduleShardsConfig, modulesConfig);
setDataStoreName(typeName);
- // Make sure we set up datastore context correctly
- datastoreContextBuilder.useTellBasedProtocol(ClientBackedDataStore.class.isAssignableFrom(implementation));
-
final DatastoreContext datastoreContext = datastoreContextBuilder.build();
final DatastoreContextFactory mockContextFactory = mock(DatastoreContextFactory.class);
doReturn(datastoreContext).when(mockContextFactory).getBaseDatastoreContext();
doReturn(datastoreContext).when(mockContextFactory).getShardDatastoreContext(anyString());
- final Constructor<? extends AbstractDataStore> constructor = implementation.getDeclaredConstructor(
- ActorSystem.class, ClusterWrapper.class, Configuration.class,
- DatastoreContextFactory.class, DatastoreSnapshot.class);
+ final var constructor = implementation.getDeclaredConstructor(ActorSystem.class, ClusterWrapper.class,
+ Configuration.class, DatastoreContextFactory.class, DatastoreSnapshot.class);
- final AbstractDataStore dataStore = constructor.newInstance(getSystem(), cluster, config, mockContextFactory,
+ final var dataStore = constructor.newInstance(getSystem(), cluster, config, mockContextFactory,
restoreFromSnapshot);
dataStore.onModelContextUpdated(schemaContext);
}
}
- @Deprecated(since = "7.0.0", forRemoval = true)
- public DistributedDataStore setupDistributedDataStoreWithoutConfig(final String typeName,
- final EffectiveModelContext schemaContext) {
- final ClusterWrapper cluster = new ClusterWrapperImpl(getSystem());
- final ConfigurationImpl configuration = new ConfigurationImpl(new EmptyModuleShardConfigProvider());
-
- setDataStoreName(typeName);
-
- final DatastoreContext datastoreContext = getDatastoreContextBuilder().build();
-
- final DatastoreContextFactory mockContextFactory = mock(DatastoreContextFactory.class);
- doReturn(datastoreContext).when(mockContextFactory).getBaseDatastoreContext();
- doReturn(datastoreContext).when(mockContextFactory).getShardDatastoreContext(anyString());
-
- final DistributedDataStore dataStore = new DistributedDataStore(getSystem(), cluster,
- configuration, mockContextFactory, restoreFromSnapshot);
-
- dataStore.onModelContextUpdated(schemaContext);
-
- datastoreContextBuilder = DatastoreContext.newBuilderFrom(datastoreContext);
- return dataStore;
- }
-
- @Deprecated(since = "7.0.0", forRemoval = true)
- public DistributedDataStore setupDistributedDataStoreWithoutConfig(final String typeName,
- final EffectiveModelContext schemaContext,
- final LogicalDatastoreType storeType) {
- final ClusterWrapper cluster = new ClusterWrapperImpl(getSystem());
- final ConfigurationImpl configuration = new ConfigurationImpl(new EmptyModuleShardConfigProvider());
-
- setDataStoreName(typeName);
-
- final DatastoreContext datastoreContext =
- getDatastoreContextBuilder().logicalStoreType(storeType).build();
-
- final DatastoreContextFactory mockContextFactory = mock(DatastoreContextFactory.class);
- doReturn(datastoreContext).when(mockContextFactory).getBaseDatastoreContext();
- doReturn(datastoreContext).when(mockContextFactory).getShardDatastoreContext(anyString());
-
- final DistributedDataStore dataStore = new DistributedDataStore(getSystem(), cluster,
- configuration, mockContextFactory, restoreFromSnapshot);
-
- dataStore.onModelContextUpdated(schemaContext);
-
- datastoreContextBuilder = DatastoreContext.newBuilderFrom(datastoreContext);
- return dataStore;
- }
-
public void waitUntilLeader(final ActorUtils actorUtils, final String... shardNames) {
for (String shardName: shardNames) {
ActorRef shard = findLocalShard(actorUtils, shardName);
}
public static ActorRef findLocalShard(final ActorUtils actorUtils, final String shardName) {
- ActorRef shard = null;
- for (int i = 0; i < 20 * 5 && shard == null; i++) {
+ for (int i = 0; i < 20 * 5; i++) {
Uninterruptibles.sleepUninterruptibly(50, TimeUnit.MILLISECONDS);
Optional<ActorRef> shardReply = actorUtils.findLocalShard(shardName);
if (shardReply.isPresent()) {
- shard = shardReply.get();
+ return shardReply.orElseThrow();
}
}
- return shard;
+ return null;
}
public static void waitUntilShardIsDown(final ActorUtils actorUtils, final String shardName) {
throw new IllegalStateException("Shard[" + shardName + " did not shutdown in time");
}
- public static void verifyShardStats(final AbstractDataStore datastore, final String shardName,
+ public static void verifyShardStats(final ClientBackedDataStore datastore, final String shardName,
final ShardStatsVerifier verifier) throws Exception {
ActorUtils actorUtils = datastore.getActorUtils();
throw lastError;
}
- public static void verifyShardState(final AbstractDataStore datastore, final String shardName,
+ public static void verifyShardState(final ClientBackedDataStore datastore, final String shardName,
final Consumer<OnDemandShardState> verifier) throws Exception {
ActorUtils actorUtils = datastore.getActorUtils();
throw lastError;
}
- void testWriteTransaction(final AbstractDataStore dataStore, final YangInstanceIdentifier nodePath,
+ void testWriteTransaction(final ClientBackedDataStore dataStore, final YangInstanceIdentifier nodePath,
final NormalizedNode nodeToWrite) throws Exception {
// 1. Create a write-only Tx
import org.opendaylight.controller.cluster.raft.persisted.SimpleReplicatedLogEntry;
import org.opendaylight.controller.cluster.raft.utils.InMemoryJournal;
import org.opendaylight.controller.md.cluster.datastore.model.TestModel;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.distributed.datastore.provider.rev140612.DataStoreProperties.ExportOnRecovery;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.distributed.datastore.provider.rev231229.DataStoreProperties.ExportOnRecovery;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
-import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
-import org.opendaylight.yangtools.yang.data.tree.api.DataTree;
-import org.opendaylight.yangtools.yang.data.tree.api.DataTreeModification;
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
+import org.opendaylight.yangtools.yang.data.spi.node.ImmutableNodes;
public class JsonExportTest extends AbstractShardTest {
private static final String DUMMY_DATA = "Dummy data as snapshot sequence number is set to 0 in "
@Before
public void setUp() throws Exception {
super.setUp();
- final File exportTmpFolder = temporaryFolder.newFolder("persistence-export");
+ final var exportTmpFolder = temporaryFolder.newFolder("persistence-export");
actualJournalFilePath = exportTmpFolder.getAbsolutePath() + "/journals/"
+ "member-1-shard-inventory-config" + nextShardNum + "-journal.json";
actualSnapshotFilePath = exportTmpFolder.getAbsolutePath() + "/snapshots/"
@Test
public void testJsonExport() throws Exception {
// Set up the InMemorySnapshotStore.
- final DataTree source = setupInMemorySnapshotStore();
+ final var source = setupInMemorySnapshotStore();
- final DataTreeModification writeMod = source.takeSnapshot().newModification();
- writeMod.write(TestModel.OUTER_LIST_PATH, ImmutableNodes.mapNodeBuilder(TestModel.OUTER_LIST_QNAME).build());
+ final var writeMod = source.takeSnapshot().newModification();
+ writeMod.write(TestModel.OUTER_LIST_PATH, ImmutableNodes.newSystemMapBuilder()
+ .withNodeIdentifier(new NodeIdentifier(TestModel.OUTER_LIST_QNAME))
+ .build());
writeMod.ready();
InMemoryJournal.addEntry(shardID.toString(), 0, DUMMY_DATA);
// Add some ModificationPayload entries
for (int i = 1; i <= nListEntries; i++) {
- listEntryKeys.add(i);
-
- final YangInstanceIdentifier path = YangInstanceIdentifier.builder(TestModel.OUTER_LIST_PATH)
- .nodeWithKey(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, i).build();
-
- final DataTreeModification mod = source.takeSnapshot().newModification();
- mod.merge(path, ImmutableNodes.mapEntry(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, i));
+ final Integer value = i;
+ listEntryKeys.add(value);
+
+ final var path = YangInstanceIdentifier.builder(TestModel.OUTER_LIST_PATH)
+ .nodeWithKey(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, value).build();
+
+ final var mod = source.takeSnapshot().newModification();
+ mod.merge(path, ImmutableNodes.newMapEntryBuilder()
+ .withNodeIdentifier(
+ NodeIdentifierWithPredicates.of(TestModel.OUTER_LIST_QNAME, TestModel.ID_QNAME, value))
+ .withChild(ImmutableNodes.leafNode(TestModel.ID_QNAME, value))
+ .build());
mod.ready();
InMemoryJournal.addEntry(shardID.toString(), i + 1, new SimpleReplicatedLogEntry(i, 1,
+++ /dev/null
-/*
- * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.cluster.datastore;
-
-import static org.junit.Assert.assertTrue;
-import static org.mockito.Mockito.doReturn;
-import static org.mockito.Mockito.doThrow;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.verify;
-
-import akka.actor.ActorSelection;
-import com.google.common.util.concurrent.SettableFuture;
-import java.util.Optional;
-import org.junit.Before;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.mockito.Mock;
-import org.mockito.junit.MockitoJUnitRunner;
-import org.opendaylight.controller.cluster.access.concepts.ClientIdentifier;
-import org.opendaylight.controller.cluster.access.concepts.FrontendIdentifier;
-import org.opendaylight.controller.cluster.access.concepts.FrontendType;
-import org.opendaylight.controller.cluster.access.concepts.LocalHistoryIdentifier;
-import org.opendaylight.controller.cluster.access.concepts.MemberName;
-import org.opendaylight.controller.cluster.access.concepts.TransactionIdentifier;
-import org.opendaylight.controller.cluster.datastore.messages.DataExists;
-import org.opendaylight.controller.cluster.datastore.messages.ReadData;
-import org.opendaylight.mdsal.dom.spi.store.DOMStoreReadTransaction;
-import org.opendaylight.mdsal.dom.spi.store.DOMStoreReadWriteTransaction;
-import org.opendaylight.mdsal.dom.spi.store.DOMStoreWriteTransaction;
-import org.opendaylight.yangtools.util.concurrent.FluentFutures;
-import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
-import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
-import scala.concurrent.Future;
-
-@RunWith(MockitoJUnitRunner.StrictStubs.class)
-public class LocalTransactionContextTest {
- @Mock
- private DOMStoreReadWriteTransaction readWriteTransaction;
- @Mock
- private LocalTransactionReadySupport mockReadySupport;
-
- private LocalTransactionContext localTransactionContext;
-
- @Before
- public void setUp() {
- final TransactionIdentifier txId = new TransactionIdentifier(new LocalHistoryIdentifier(ClientIdentifier.create(
- FrontendIdentifier.create(MemberName.forName("member"), FrontendType.forName("type")), 0), 0), 0);
-
- localTransactionContext = new LocalTransactionContext(readWriteTransaction, txId, mockReadySupport) {
- @Override
- DOMStoreWriteTransaction getWriteDelegate() {
- return readWriteTransaction;
- }
-
- @Override
- DOMStoreReadTransaction getReadDelegate() {
- return readWriteTransaction;
- }
- };
- }
-
- @Test
- public void testWrite() {
- YangInstanceIdentifier yangInstanceIdentifier = YangInstanceIdentifier.empty();
- NormalizedNode normalizedNode = mock(NormalizedNode.class);
- localTransactionContext.executeWrite(yangInstanceIdentifier, normalizedNode, null);
- verify(readWriteTransaction).write(yangInstanceIdentifier, normalizedNode);
- }
-
- @Test
- public void testMerge() {
- YangInstanceIdentifier yangInstanceIdentifier = YangInstanceIdentifier.empty();
- NormalizedNode normalizedNode = mock(NormalizedNode.class);
- localTransactionContext.executeMerge(yangInstanceIdentifier, normalizedNode, null);
- verify(readWriteTransaction).merge(yangInstanceIdentifier, normalizedNode);
- }
-
- @Test
- public void testDelete() {
- YangInstanceIdentifier yangInstanceIdentifier = YangInstanceIdentifier.empty();
- localTransactionContext.executeDelete(yangInstanceIdentifier, null);
- verify(readWriteTransaction).delete(yangInstanceIdentifier);
- }
-
- @Test
- public void testRead() {
- YangInstanceIdentifier yangInstanceIdentifier = YangInstanceIdentifier.empty();
- NormalizedNode normalizedNode = mock(NormalizedNode.class);
- doReturn(FluentFutures.immediateFluentFuture(Optional.of(normalizedNode))).when(readWriteTransaction)
- .read(yangInstanceIdentifier);
- localTransactionContext.executeRead(new ReadData(yangInstanceIdentifier, DataStoreVersions.CURRENT_VERSION),
- SettableFuture.create(), null);
- verify(readWriteTransaction).read(yangInstanceIdentifier);
- }
-
- @Test
- public void testExists() {
- YangInstanceIdentifier yangInstanceIdentifier = YangInstanceIdentifier.empty();
- doReturn(FluentFutures.immediateTrueFluentFuture()).when(readWriteTransaction).exists(yangInstanceIdentifier);
- localTransactionContext.executeRead(new DataExists(yangInstanceIdentifier, DataStoreVersions.CURRENT_VERSION),
- SettableFuture.create(), null);
- verify(readWriteTransaction).exists(yangInstanceIdentifier);
- }
-
- @Test
- public void testReady() {
- final LocalThreePhaseCommitCohort mockCohort = mock(LocalThreePhaseCommitCohort.class);
- doReturn(akka.dispatch.Futures.successful(null)).when(mockCohort).initiateCoordinatedCommit(Optional.empty());
- doReturn(mockCohort).when(mockReadySupport).onTransactionReady(readWriteTransaction, null);
-
- Future<ActorSelection> future = localTransactionContext.readyTransaction(null, Optional.empty());
- assertTrue(future.isCompleted());
-
- verify(mockReadySupport).onTransactionReady(readWriteTransaction, null);
- }
-
- @Test
- public void testReadyWithWriteError() {
- YangInstanceIdentifier yangInstanceIdentifier = YangInstanceIdentifier.empty();
- NormalizedNode normalizedNode = mock(NormalizedNode.class);
- RuntimeException error = new RuntimeException("mock");
- doThrow(error).when(readWriteTransaction).write(yangInstanceIdentifier, normalizedNode);
-
- localTransactionContext.executeWrite(yangInstanceIdentifier, normalizedNode, null);
- localTransactionContext.executeWrite(yangInstanceIdentifier, normalizedNode, null);
-
- verify(readWriteTransaction).write(yangInstanceIdentifier, normalizedNode);
-
- doReadyWithExpectedError(error);
- }
-
- @Test
- public void testReadyWithMergeError() {
- YangInstanceIdentifier yangInstanceIdentifier = YangInstanceIdentifier.empty();
- NormalizedNode normalizedNode = mock(NormalizedNode.class);
- RuntimeException error = new RuntimeException("mock");
- doThrow(error).when(readWriteTransaction).merge(yangInstanceIdentifier, normalizedNode);
-
- localTransactionContext.executeMerge(yangInstanceIdentifier, normalizedNode, null);
- localTransactionContext.executeMerge(yangInstanceIdentifier, normalizedNode, null);
-
- verify(readWriteTransaction).merge(yangInstanceIdentifier, normalizedNode);
-
- doReadyWithExpectedError(error);
- }
-
- @Test
- public void testReadyWithDeleteError() {
- YangInstanceIdentifier yangInstanceIdentifier = YangInstanceIdentifier.empty();
- RuntimeException error = new RuntimeException("mock");
- doThrow(error).when(readWriteTransaction).delete(yangInstanceIdentifier);
-
- localTransactionContext.executeDelete(yangInstanceIdentifier, null);
- localTransactionContext.executeDelete(yangInstanceIdentifier, null);
-
- verify(readWriteTransaction).delete(yangInstanceIdentifier);
-
- doReadyWithExpectedError(error);
- }
-
- private void doReadyWithExpectedError(final RuntimeException expError) {
- LocalThreePhaseCommitCohort mockCohort = mock(LocalThreePhaseCommitCohort.class);
- doReturn(akka.dispatch.Futures.successful(null)).when(mockCohort).initiateCoordinatedCommit(Optional.empty());
- doReturn(mockCohort).when(mockReadySupport).onTransactionReady(readWriteTransaction, expError);
-
- localTransactionContext.readyTransaction(null, Optional.empty());
- }
-}
import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.opendaylight.controller.cluster.access.concepts.MemberName;
+import org.opendaylight.controller.cluster.databroker.ClientBackedDataStore;
import org.opendaylight.controller.cluster.datastore.identifiers.ShardIdentifier;
import org.opendaylight.controller.cluster.datastore.utils.ActorUtils;
import org.opendaylight.controller.cluster.raft.client.messages.GetOnDemandRaftState;
private static final String MEMBER_1_ADDRESS = "akka://cluster-test@127.0.0.1:2558";
private IntegrationTestKit kit;
- private AbstractDataStore configDataStore;
- private AbstractDataStore operDataStore;
+ private ClientBackedDataStore configDataStore;
+ private ClientBackedDataStore operDataStore;
private DatastoreContext.Builder datastoreContextBuilder;
private boolean cleanedUp;
}
- public AbstractDataStore configDataStore() {
+ public ClientBackedDataStore configDataStore() {
return configDataStore;
}
- public AbstractDataStore operDataStore() {
+ public ClientBackedDataStore operDataStore() {
return operDataStore;
}
}
try {
- IntegrationTestKit.shutdownActorSystem(kit.getSystem(), Boolean.TRUE);
+ IntegrationTestKit.shutdownActorSystem(kit.getSystem(), true);
} catch (RuntimeException e) {
LoggerFactory.getLogger(MemberNode.class).warn("Failed to shutdown actor system", e);
}
}
}
- public static void verifyRaftState(final AbstractDataStore datastore, final String shardName,
+ public static void verifyRaftState(final ClientBackedDataStore datastore, final String shardName,
final RaftStateVerifier verifier) throws Exception {
ActorUtils actorUtils = datastore.getActorUtils();
throw lastError;
}
- public static void verifyRaftPeersPresent(final AbstractDataStore datastore, final String shardName,
+ public static void verifyRaftPeersPresent(final ClientBackedDataStore datastore, final String shardName,
final String... peerMemberNames) throws Exception {
final Set<String> peerIds = new HashSet<>();
for (String p: peerMemberNames) {
raftState.getPeerAddresses().keySet()));
}
- public static void verifyNoShardPresent(final AbstractDataStore datastore, final String shardName) {
+ public static void verifyNoShardPresent(final ClientBackedDataStore datastore, final String shardName) {
Stopwatch sw = Stopwatch.createStarted();
while (sw.elapsed(TimeUnit.SECONDS) <= 5) {
Optional<ActorRef> shardReply = datastore.getActorUtils().findLocalShard(shardName);
* @return this Builder
*/
public Builder moduleShardsConfig(final String newModuleShardsConfig) {
- this.moduleShardsConfig = newModuleShardsConfig;
+ moduleShardsConfig = newModuleShardsConfig;
return this;
}
* @return this Builder
*/
public Builder akkaConfig(final String newAkkaConfig) {
- this.akkaConfig = newAkkaConfig;
+ akkaConfig = newAkkaConfig;
return this;
}
* @return this Builder
*/
public Builder useAkkaArtery(final boolean newUseAkkaArtery) {
- this.useAkkaArtery = newUseAkkaArtery;
+ useAkkaArtery = newUseAkkaArtery;
return this;
}
* @return this Builder
*/
public Builder testName(final String newTestName) {
- this.testName = newTestName;
+ testName = newTestName;
return this;
}
* @return this Builder
*/
public Builder waitForShardLeader(final String... shardNames) {
- this.waitForshardLeader = shardNames;
+ waitForshardLeader = shardNames;
return this;
}
* @return this Builder
*/
public Builder createOperDatastore(final boolean value) {
- this.createOperDatastore = value;
+ createOperDatastore = value;
return this;
}
* @return this Builder
*/
public Builder schemaContext(final EffectiveModelContext newSchemaContext) {
- this.schemaContext = newSchemaContext;
+ schemaContext = newSchemaContext;
return this;
}
String memberName = new ClusterWrapperImpl(system).getCurrentMemberName().getName();
node.kit.getDatastoreContextBuilder().shardManagerPersistenceId("shard-manager-config-" + memberName);
- node.configDataStore = node.kit.setupAbstractDataStore(DistributedDataStore.class,
- "config_" + testName, moduleShardsConfig, true, schemaContext, waitForshardLeader);
+ node.configDataStore = node.kit.setupDataStore(ClientBackedDataStore.class, "config_" + testName,
+ moduleShardsConfig, true, schemaContext, waitForshardLeader);
if (createOperDatastore) {
node.kit.getDatastoreContextBuilder().shardManagerPersistenceId("shard-manager-oper-" + memberName);
- node.operDataStore = node.kit.setupAbstractDataStore(DistributedDataStore.class,
+ node.operDataStore = node.kit.setupDataStore(ClientBackedDataStore.class,
"oper_" + testName, moduleShardsConfig, true, schemaContext, waitForshardLeader);
}
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
-
package org.opendaylight.controller.cluster.datastore;
import java.util.concurrent.atomic.AtomicReference;
+@Deprecated(since = "9.0.0", forRemoval = true)
interface OperationCallback {
- OperationCallback NO_OP_CALLBACK = new OperationCallback() {
- @Override
- public void run() {
- }
-
- @Override
- public void success() {
- }
-
- @Override
- public void failure() {
- }
-
- @Override
- public void pause() {
- }
-
- @Override
- public void resume() {
- }
- };
-
class Reference extends AtomicReference<OperationCallback> {
private static final long serialVersionUID = 1L;
- Reference(OperationCallback initialValue) {
+ Reference(final OperationCallback initialValue) {
super(initialValue);
}
}
+++ /dev/null
-/*
- * Copyright (c) 2017 Pantheon Technologies, s.r.o. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.cluster.datastore;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
-import static org.mockito.Mockito.mock;
-
-import akka.actor.ActorRef;
-import akka.actor.Status.Failure;
-import akka.dispatch.ExecutionContexts;
-import akka.dispatch.OnComplete;
-import akka.testkit.javadsl.TestKit;
-import com.google.common.util.concurrent.MoreExecutors;
-import com.google.common.util.concurrent.SettableFuture;
-import java.util.concurrent.ExecutionException;
-import java.util.concurrent.TimeUnit;
-import java.util.concurrent.TimeoutException;
-import org.junit.Before;
-import org.junit.Test;
-import org.mockito.Mockito;
-import org.opendaylight.controller.cluster.access.concepts.ClientIdentifier;
-import org.opendaylight.controller.cluster.access.concepts.FrontendIdentifier;
-import org.opendaylight.controller.cluster.access.concepts.FrontendType;
-import org.opendaylight.controller.cluster.access.concepts.LocalHistoryIdentifier;
-import org.opendaylight.controller.cluster.access.concepts.MemberName;
-import org.opendaylight.controller.cluster.access.concepts.TransactionIdentifier;
-import org.opendaylight.controller.cluster.datastore.config.Configuration;
-import org.opendaylight.controller.cluster.datastore.messages.BatchedModifications;
-import org.opendaylight.controller.cluster.datastore.messages.DataExists;
-import org.opendaylight.controller.cluster.datastore.utils.ActorUtils;
-import scala.concurrent.Await;
-import scala.concurrent.Future;
-import scala.concurrent.duration.FiniteDuration;
-
-/**
- * Test whether RmoteTransactionContext operates correctly.
- */
-public class RemoteTransactionContextTest extends AbstractActorTest {
- private static final TransactionIdentifier TX_ID = new TransactionIdentifier(new LocalHistoryIdentifier(
- ClientIdentifier.create(FrontendIdentifier.create(MemberName.forName("test"), FrontendType.forName("test")), 0),
- 0), 0);
-
- private OperationLimiter limiter;
- private RemoteTransactionContext txContext;
- private ActorUtils actorUtils;
- private TestKit kit;
-
- @Before
- public void before() {
- kit = new TestKit(getSystem());
- actorUtils = Mockito.spy(new ActorUtils(getSystem(), kit.getRef(), mock(ClusterWrapper.class),
- mock(Configuration.class)));
- limiter = new OperationLimiter(TX_ID, 4, 0);
- txContext = new RemoteTransactionContext(TX_ID, actorUtils.actorSelection(kit.getRef().path()), actorUtils,
- DataStoreVersions.CURRENT_VERSION, limiter);
- txContext.operationHandOffComplete();
- }
-
- /**
- * OperationLimiter should be correctly released when a failure, like AskTimeoutException occurs. Future reads
- * need to complete immediately with the failure and modifications should not be throttled and thrown away
- * immediately.
- */
- @Test
- public void testLimiterOnFailure() throws TimeoutException, InterruptedException {
- txContext.executeDelete(null, null);
- txContext.executeDelete(null, null);
- assertEquals(2, limiter.availablePermits());
-
- final Future<Object> sendFuture = txContext.sendBatchedModifications();
- assertEquals(2, limiter.availablePermits());
-
- BatchedModifications msg = kit.expectMsgClass(BatchedModifications.class);
- assertEquals(2, msg.getModifications().size());
- assertEquals(1, msg.getTotalMessagesSent());
- sendReply(new Failure(new NullPointerException()));
- assertFuture(sendFuture, new OnComplete<>() {
- @Override
- public void onComplete(final Throwable failure, final Object success) {
- assertTrue(failure instanceof NullPointerException);
- assertEquals(4, limiter.availablePermits());
-
- // The transaction has failed, no throttling should occur
- txContext.executeDelete(null, null);
- assertEquals(4, limiter.availablePermits());
-
- // Executing a read should result in immediate failure
- final SettableFuture<Boolean> readFuture = SettableFuture.create();
- txContext.executeRead(new DataExists(), readFuture, null);
- assertTrue(readFuture.isDone());
- try {
- readFuture.get();
- fail("Read future did not fail");
- } catch (ExecutionException | InterruptedException e) {
- assertTrue(e.getCause() instanceof NullPointerException);
- }
- }
- });
-
- final Future<Object> commitFuture = txContext.directCommit(null);
-
- msg = kit.expectMsgClass(BatchedModifications.class);
- // Modification should have been thrown away by the dropped transmit induced by executeRead()
- assertEquals(0, msg.getModifications().size());
- assertTrue(msg.isDoCommitOnReady());
- assertTrue(msg.isReady());
- assertEquals(2, msg.getTotalMessagesSent());
- sendReply(new Failure(new IllegalStateException()));
- assertFuture(commitFuture, new OnComplete<>() {
- @Override
- public void onComplete(final Throwable failure, final Object success) {
- assertTrue(failure instanceof IllegalStateException);
- }
- });
-
- kit.expectNoMessage();
- }
-
- /**
- * OperationLimiter gives up throttling at some point -- {@link RemoteTransactionContext} needs to deal with that
- * case, too.
- */
- @Test
- public void testLimiterOnOverflowFailure() throws TimeoutException, InterruptedException {
- txContext.executeDelete(null, null);
- txContext.executeDelete(null, null);
- txContext.executeDelete(null, null);
- txContext.executeDelete(null, null);
- assertEquals(0, limiter.availablePermits());
- txContext.executeDelete(null, null);
- // Last acquire should have failed ...
- assertEquals(0, limiter.availablePermits());
-
- final Future<Object> future = txContext.sendBatchedModifications();
- assertEquals(0, limiter.availablePermits());
-
- BatchedModifications msg = kit.expectMsgClass(BatchedModifications.class);
- // ... so we are sending 5 modifications ...
- assertEquals(5, msg.getModifications().size());
- assertEquals(1, msg.getTotalMessagesSent());
- sendReply(new Failure(new NullPointerException()));
-
- assertFuture(future, new OnComplete<>() {
- @Override
- public void onComplete(final Throwable failure, final Object success) {
- assertTrue(failure instanceof NullPointerException);
- // ... but they account for only 4 permits.
- assertEquals(4, limiter.availablePermits());
- }
- });
-
- kit.expectNoMessage();
- }
-
- private void sendReply(final Object message) {
- final ActorRef askActor = kit.getLastSender();
- kit.watch(askActor);
- kit.reply(new Failure(new IllegalStateException()));
- kit.expectTerminated(askActor);
- }
-
- private static void assertFuture(final Future<Object> future, final OnComplete<Object> complete)
- throws TimeoutException, InterruptedException {
- Await.ready(future, FiniteDuration.apply(3, TimeUnit.SECONDS));
- future.onComplete(complete, ExecutionContexts.fromExecutor(MoreExecutors.directExecutor()));
- }
-}
ClusteredDOMDataTreeChangeListener mockClusteredListener = mock(
ClusteredDOMDataTreeChangeListener.class);
- final YangInstanceIdentifier path = YangInstanceIdentifier.empty();
+ final YangInstanceIdentifier path = YangInstanceIdentifier.of();
final RootDataTreeChangeListenerProxy<ClusteredDOMDataTreeChangeListener> rootListenerProxy =
new RootDataTreeChangeListenerProxy<>(actorUtils, mockClusteredListener,
Set.of("shard-1", "shard-2"));
final TestKit kit2 = new TestKit(getSystem());
final ActorSelection rootListenerActor = getSystem().actorSelection(registerForShard1.getListenerActorPath());
rootListenerActor.tell(new EnableNotification(true, "test"), kit.getRef());
- final DataTreeCandidate peopleCandidate = DataTreeCandidates.fromNormalizedNode(YangInstanceIdentifier.empty(),
+ final DataTreeCandidate peopleCandidate = DataTreeCandidates.fromNormalizedNode(YangInstanceIdentifier.of(),
PeopleModel.create());
rootListenerActor.tell(new DataTreeChanged(ImmutableList.of(peopleCandidate)), kit.getRef());
rootListenerActor.tell(new DataTreeChanged(ImmutableList.of(peopleCandidate)), kit2.getRef());
*
* @author Thomas Pantelis
*/
+@Deprecated(since = "9.0.0", forRemoval = true)
public class ShardCommitCoordinationTest extends AbstractShardTest {
private static final Logger LOG = LoggerFactory.getLogger(ShardCommitCoordinationTest.class);
LOG.info("{} ending", testName);
}
- static void verifyInnerListEntry(TestActorRef<Shard> shard, int outerID, String innerID) {
+ static void verifyInnerListEntry(final TestActorRef<Shard> shard, final int outerID, final String innerID) {
final YangInstanceIdentifier path = innerEntryPath(outerID, innerID);
final NormalizedNode innerListEntry = readStore(shard, path);
assertNotNull(path + " not found", innerListEntry);
import com.google.common.primitives.UnsignedLong;
import com.google.common.util.concurrent.FutureCallback;
import java.io.IOException;
-import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
addCar(shardDataTree, "optima");
verifyOnDataTreeChanged(listener, dtc -> {
- assertEquals("getModificationType", ModificationType.WRITE, dtc.getRootNode().getModificationType());
+ assertEquals("getModificationType", ModificationType.WRITE, dtc.getRootNode().modificationType());
assertEquals("getRootPath", CarsModel.newCarPath("optima"), dtc.getRootPath());
});
addCar(shardDataTree, "sportage");
verifyOnDataTreeChanged(listener, dtc -> {
- assertEquals("getModificationType", ModificationType.WRITE, dtc.getRootNode().getModificationType());
+ assertEquals("getModificationType", ModificationType.WRITE, dtc.getRootNode().modificationType());
assertEquals("getRootPath", CarsModel.newCarPath("sportage"), dtc.getRootPath());
});
verifyOnDataTreeChanged(listener, dtc -> {
ModificationType expType = expChanges.remove(dtc.getRootPath());
assertNotNull("Got unexpected change for " + dtc.getRootPath(), expType);
- assertEquals("getModificationType", expType, dtc.getRootNode().getModificationType());
+ assertEquals("getModificationType", expType, dtc.getRootNode().modificationType());
});
if (!expChanges.isEmpty()) {
verify(preCommitCallback4).onSuccess(cohort4.getCandidate());
final FutureCallback<UnsignedLong> commitCallback2 = coordinatedCommit(cohort2);
- verify(mockShard, never()).persistPayload(eq(cohort1.getIdentifier()), any(CommitTransactionPayload.class),
+ verify(mockShard, never()).persistPayload(eq(cohort1.transactionId()), any(CommitTransactionPayload.class),
anyBoolean());
verifyNoMoreInteractions(commitCallback2);
final FutureCallback<UnsignedLong> commitCallback4 = coordinatedCommit(cohort4);
- verify(mockShard, never()).persistPayload(eq(cohort4.getIdentifier()), any(CommitTransactionPayload.class),
+ verify(mockShard, never()).persistPayload(eq(cohort4.transactionId()), any(CommitTransactionPayload.class),
anyBoolean());
verifyNoMoreInteractions(commitCallback4);
final FutureCallback<UnsignedLong> commitCallback1 = coordinatedCommit(cohort1);
InOrder inOrder = inOrder(mockShard);
- inOrder.verify(mockShard).persistPayload(eq(cohort1.getIdentifier()), any(CommitTransactionPayload.class),
+ inOrder.verify(mockShard).persistPayload(eq(cohort1.transactionId()), any(CommitTransactionPayload.class),
eq(true));
- inOrder.verify(mockShard).persistPayload(eq(cohort2.getIdentifier()), any(CommitTransactionPayload.class),
+ inOrder.verify(mockShard).persistPayload(eq(cohort2.transactionId()), any(CommitTransactionPayload.class),
eq(false));
verifyNoMoreInteractions(commitCallback1);
verifyNoMoreInteractions(commitCallback2);
final FutureCallback<UnsignedLong> commitCallback3 = coordinatedCommit(cohort3);
inOrder = inOrder(mockShard);
- inOrder.verify(mockShard).persistPayload(eq(cohort3.getIdentifier()), any(CommitTransactionPayload.class),
+ inOrder.verify(mockShard).persistPayload(eq(cohort3.transactionId()), any(CommitTransactionPayload.class),
eq(true));
- inOrder.verify(mockShard).persistPayload(eq(cohort4.getIdentifier()), any(CommitTransactionPayload.class),
+ inOrder.verify(mockShard).persistPayload(eq(cohort4.transactionId()), any(CommitTransactionPayload.class),
eq(false));
verifyNoMoreInteractions(commitCallback3);
verifyNoMoreInteractions(commitCallback4);
// The payload instance doesn't matter - it just needs to be of type CommitTransactionPayload.
CommitTransactionPayload mockPayload = CommitTransactionPayload.create(nextTransactionId(),
cohort1.getCandidate());
- shardDataTree.applyReplicatedPayload(cohort1.getIdentifier(), mockPayload);
- shardDataTree.applyReplicatedPayload(cohort2.getIdentifier(), mockPayload);
- shardDataTree.applyReplicatedPayload(cohort3.getIdentifier(), mockPayload);
- shardDataTree.applyReplicatedPayload(cohort4.getIdentifier(), mockPayload);
+ shardDataTree.applyReplicatedPayload(cohort1.transactionId(), mockPayload);
+ shardDataTree.applyReplicatedPayload(cohort2.transactionId(), mockPayload);
+ shardDataTree.applyReplicatedPayload(cohort3.transactionId(), mockPayload);
+ shardDataTree.applyReplicatedPayload(cohort4.transactionId(), mockPayload);
inOrder = inOrder(commitCallback1, commitCallback2, commitCallback3, commitCallback4);
inOrder.verify(commitCallback1).onSuccess(any(UnsignedLong.class));
final DataTreeSnapshot snapshot =
shardDataTree.newReadOnlyTransaction(nextTransactionId()).getSnapshot();
- Optional<NormalizedNode> optional = snapshot.readNode(carPath);
- assertTrue("Car node present", optional.isPresent());
- assertEquals("Car node", carNode, optional.get());
-
- optional = snapshot.readNode(PeopleModel.BASE_PATH);
- assertTrue("People node present", optional.isPresent());
- assertEquals("People node", peopleNode, optional.get());
+ assertEquals("Car node", Optional.of(carNode), snapshot.readNode(carPath));
+ assertEquals("People node", Optional.of(peopleNode), snapshot.readNode(PeopleModel.BASE_PATH));
}
@Test
final FutureCallback<UnsignedLong> commitCallback1 = immediate3PhaseCommit(cohort1);
InOrder inOrder = inOrder(mockShard);
- inOrder.verify(mockShard).persistPayload(eq(cohort1.getIdentifier()), any(CommitTransactionPayload.class),
+ inOrder.verify(mockShard).persistPayload(eq(cohort1.transactionId()), any(CommitTransactionPayload.class),
eq(true));
- inOrder.verify(mockShard).persistPayload(eq(cohort2.getIdentifier()), any(CommitTransactionPayload.class),
+ inOrder.verify(mockShard).persistPayload(eq(cohort2.transactionId()), any(CommitTransactionPayload.class),
eq(true));
- inOrder.verify(mockShard).persistPayload(eq(cohort3.getIdentifier()), any(CommitTransactionPayload.class),
+ inOrder.verify(mockShard).persistPayload(eq(cohort3.transactionId()), any(CommitTransactionPayload.class),
eq(false));
// The payload instance doesn't matter - it just needs to be of type CommitTransactionPayload.
CommitTransactionPayload mockPayload = CommitTransactionPayload.create(nextTransactionId(),
cohort1.getCandidate());
- shardDataTree.applyReplicatedPayload(cohort1.getIdentifier(), mockPayload);
- shardDataTree.applyReplicatedPayload(cohort2.getIdentifier(), mockPayload);
- shardDataTree.applyReplicatedPayload(cohort3.getIdentifier(), mockPayload);
+ shardDataTree.applyReplicatedPayload(cohort1.transactionId(), mockPayload);
+ shardDataTree.applyReplicatedPayload(cohort2.transactionId(), mockPayload);
+ shardDataTree.applyReplicatedPayload(cohort3.transactionId(), mockPayload);
inOrder = inOrder(commitCallback1, commitCallback2, commitCallback3);
inOrder.verify(commitCallback1).onSuccess(any(UnsignedLong.class));
final DataTreeSnapshot snapshot =
shardDataTree.newReadOnlyTransaction(nextTransactionId()).getSnapshot();
- Optional<NormalizedNode> optional = snapshot.readNode(carPath);
- assertTrue("Car node present", optional.isPresent());
- assertEquals("Car node", carNode, optional.get());
+ assertEquals("Car node", Optional.of(carNode), snapshot.readNode(carPath));
}
@Test
coordinatedCommit(cohort4);
InOrder inOrder = inOrder(mockShard);
- inOrder.verify(mockShard).persistPayload(eq(cohort1.getIdentifier()), any(CommitTransactionPayload.class),
+ inOrder.verify(mockShard).persistPayload(eq(cohort1.transactionId()), any(CommitTransactionPayload.class),
eq(false));
- inOrder.verify(mockShard).persistPayload(eq(cohort3.getIdentifier()), any(CommitTransactionPayload.class),
+ inOrder.verify(mockShard).persistPayload(eq(cohort3.transactionId()), any(CommitTransactionPayload.class),
eq(false));
- inOrder.verify(mockShard).persistPayload(eq(cohort4.getIdentifier()), any(CommitTransactionPayload.class),
+ inOrder.verify(mockShard).persistPayload(eq(cohort4.transactionId()), any(CommitTransactionPayload.class),
eq(false));
// The payload instance doesn't matter - it just needs to be of type CommitTransactionPayload.
CommitTransactionPayload mockPayload = CommitTransactionPayload.create(nextTransactionId(),
cohort1.getCandidate());
- shardDataTree.applyReplicatedPayload(cohort1.getIdentifier(), mockPayload);
- shardDataTree.applyReplicatedPayload(cohort3.getIdentifier(), mockPayload);
- shardDataTree.applyReplicatedPayload(cohort4.getIdentifier(), mockPayload);
+ shardDataTree.applyReplicatedPayload(cohort1.transactionId(), mockPayload);
+ shardDataTree.applyReplicatedPayload(cohort3.transactionId(), mockPayload);
+ shardDataTree.applyReplicatedPayload(cohort4.transactionId(), mockPayload);
final DataTreeSnapshot snapshot =
shardDataTree.newReadOnlyTransaction(nextTransactionId()).getSnapshot();
Optional<NormalizedNode> optional = snapshot.readNode(carPath);
- assertTrue("Car node present", optional.isPresent());
- assertEquals("Car node", carNode, optional.get());
+ assertEquals("Car node", Optional.of(carNode), optional);
}
@SuppressWarnings("unchecked")
final DataTreeSnapshot snapshot =
shardDataTree.newReadOnlyTransaction(nextTransactionId()).getSnapshot();
Optional<NormalizedNode> optional = snapshot.readNode(PeopleModel.BASE_PATH);
- assertTrue("People node present", optional.isPresent());
- assertEquals("People node", peopleNode, optional.get());
+ assertEquals("People node", Optional.of(peopleNode), optional);
}
@Test
public void testUintCommitPayload() throws IOException {
shardDataTree.applyRecoveryPayload(CommitTransactionPayload.create(nextTransactionId(),
- DataTreeCandidates.fromNormalizedNode(YangInstanceIdentifier.empty(), bigIntegerRoot()),
- PayloadVersion.SODIUM_SR1));
+ DataTreeCandidates.fromNormalizedNode(YangInstanceIdentifier.of(), bigIntegerRoot()),
+ PayloadVersion.POTASSIUM));
assertCarsUint64();
}
.withNodeIdentifier(new NodeIdentifier(CarsModel.BASE_QNAME))
.withChild(Builders.mapBuilder()
.withNodeIdentifier(new NodeIdentifier(CarsModel.CAR_QNAME))
- .withChild(createCar("one", BigInteger.ONE))
+ .withChild(createCar("one", Uint64.ONE))
.build())
.build());
mod.ready();
dataTree.commit(first);
mod = dataTree.takeSnapshot().newModification();
- mod.write(CarsModel.newCarPath("two"), createCar("two", BigInteger.TWO));
+ mod.write(CarsModel.newCarPath("two"), createCar("two", Uint64.TWO));
mod.ready();
dataTree.validate(mod);
final DataTreeCandidate second = dataTree.prepare(mod);
mod = dataTree.takeSnapshot().newModification();
mod.merge(CarsModel.CAR_LIST_PATH, Builders.mapBuilder()
.withNodeIdentifier(new NodeIdentifier(CarsModel.CAR_QNAME))
- .withChild(createCar("three", BigInteger.TEN))
+ .withChild(createCar("three", Uint64.TEN))
.build());
mod.ready();
dataTree.validate(mod);
dataTree.commit(third);
// Apply first candidate as a snapshot
- shardDataTree.applyRecoverySnapshot(
- new ShardSnapshotState(new MetadataShardDataTreeSnapshot(first.getRootNode().getDataAfter().get()), true));
+ shardDataTree.applyRecoverySnapshot(new ShardSnapshotState(
+ new MetadataShardDataTreeSnapshot(first.getRootNode().getDataAfter()), true));
// Apply the other two snapshots as transactions
shardDataTree.applyRecoveryPayload(CommitTransactionPayload.create(nextTransactionId(), second,
- PayloadVersion.SODIUM_SR1));
+ PayloadVersion.POTASSIUM));
shardDataTree.applyRecoveryPayload(CommitTransactionPayload.create(nextTransactionId(), third,
- PayloadVersion.SODIUM_SR1));
+ PayloadVersion.POTASSIUM));
// Verify uint translation
final DataTreeSnapshot snapshot = shardDataTree.newReadOnlyTransaction(nextTransactionId()).getSnapshot();
- final NormalizedNode cars = snapshot.readNode(CarsModel.CAR_LIST_PATH).get();
assertEquals(Builders.mapBuilder()
.withNodeIdentifier(new NodeIdentifier(CarsModel.CAR_QNAME))
.withChild(createCar("one", Uint64.ONE))
.withChild(createCar("two", Uint64.TWO))
.withChild(createCar("three", Uint64.TEN))
- .build(), cars);
+ .build(), snapshot.readNode(CarsModel.CAR_LIST_PATH).orElseThrow());
}
private void assertCarsUint64() {
final DataTreeSnapshot snapshot = shardDataTree.newReadOnlyTransaction(nextTransactionId()).getSnapshot();
- final NormalizedNode cars = snapshot.readNode(CarsModel.CAR_LIST_PATH).get();
+ final NormalizedNode cars = snapshot.readNode(CarsModel.CAR_LIST_PATH).orElseThrow();
assertEquals(Builders.mapBuilder()
.withNodeIdentifier(new NodeIdentifier(CarsModel.CAR_QNAME))
private static ContainerNode bigIntegerRoot() {
return Builders.containerBuilder()
- .withNodeIdentifier(new NodeIdentifier(SchemaContext.NAME))
- .withChild(Builders.containerBuilder()
- .withNodeIdentifier(new NodeIdentifier(CarsModel.CARS_QNAME))
- .withChild(Builders.mapBuilder()
- .withNodeIdentifier(new NodeIdentifier(CarsModel.CAR_QNAME))
- // Note: BigInteger
- .withChild(createCar("foo", BigInteger.ONE))
- .build())
+ .withNodeIdentifier(new NodeIdentifier(SchemaContext.NAME))
+ .withChild(Builders.containerBuilder()
+ .withNodeIdentifier(new NodeIdentifier(CarsModel.CARS_QNAME))
+ .withChild(Builders.mapBuilder()
+ .withNodeIdentifier(new NodeIdentifier(CarsModel.CAR_QNAME))
+ .withChild(createCar("foo", Uint64.ONE))
.build())
- .build();
+ .build())
+ .build();
}
private static MapEntryNode createCar(final String name, final Object value) {
return Builders.mapEntryBuilder()
- .withNodeIdentifier(NodeIdentifierWithPredicates.of(CarsModel.CAR_QNAME,CarsModel.CAR_NAME_QNAME, name))
- .withChild(ImmutableNodes.leafNode(CarsModel.CAR_NAME_QNAME, name))
- // Note: old BigInteger
- .withChild(ImmutableNodes.leafNode(CarsModel.CAR_PRICE_QNAME, value))
- .build();
+ .withNodeIdentifier(NodeIdentifierWithPredicates.of(CarsModel.CAR_QNAME, CarsModel.CAR_NAME_QNAME, name))
+ .withChild(ImmutableNodes.leafNode(CarsModel.CAR_NAME_QNAME, name))
+ // Note: old BigInteger
+ .withChild(ImmutableNodes.leafNode(CarsModel.CAR_PRICE_QNAME, value))
+ .build();
}
private ShardDataTreeCohort newShardDataTreeCohort(final DataTreeOperation operation) {
assertTrue(optional.isPresent());
- return optional.get();
+ return optional.orElseThrow();
}
private static DataTreeCandidate addCar(final ShardDataTree shardDataTree) {
dataTree.commit(dataTree.prepare(modification));
return new ShardSnapshotState(new MetadataShardDataTreeSnapshot(dataTree.takeSnapshot().readNode(
- YangInstanceIdentifier.empty()).get()));
+ YangInstanceIdentifier.of()).orElseThrow()));
}
}
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
writeToStore(store, TestModel.TEST_PATH, container);
- final YangInstanceIdentifier root = YangInstanceIdentifier.empty();
+ final YangInstanceIdentifier root = YangInstanceIdentifier.of();
final NormalizedNode expected = readStore(store, root);
final Snapshot snapshot = Snapshot.create(new ShardSnapshotState(new MetadataShardDataTreeSnapshot(expected)),
verifyOuterListEntry(shard, 1);
}
+ @Deprecated(since = "9.0.0", forRemoval = true)
@Test(expected = IllegalStateException.class)
public void testBatchedModificationsReadyWithIncorrectTotalMessageCount() throws Exception {
final ShardTestKit testKit = new ShardTestKit(getSystem());
}
@Test
+ @Deprecated(since = "9.0.0", forRemoval = true)
public void testBatchedModificationsWithOperationFailure() {
final ShardTestKit testKit = new ShardTestKit(getSystem());
final TestActorRef<Shard> shard = actorFactory.createTestActor(
}
@Test
+ @Deprecated(since = "9.0.0", forRemoval = true)
public void testOnBatchedModificationsWhenNotLeader() {
final AtomicBoolean overrideLeaderCalls = new AtomicBoolean();
final ShardTestKit testKit = new ShardTestKit(getSystem());
}
@Test
+ @Deprecated(since = "9.0.0", forRemoval = true)
public void testTransactionMessagesWithNoLeader() {
final ShardTestKit testKit = new ShardTestKit(getSystem());
dataStoreContextBuilder.customRaftPolicyImplementation(DisableElectionsRaftPolicy.class.getName())
final Duration duration = Duration.ofSeconds(5);
final TransactionIdentifier transactionID1 = nextTransactionId();
- doThrow(new DataValidationFailedException(YangInstanceIdentifier.empty(), "mock canCommit failure"))
+ doThrow(new DataValidationFailedException(YangInstanceIdentifier.of(), "mock canCommit failure"))
.doNothing().when(dataTree).validate(any(DataTreeModification.class));
shard.tell(newBatchedModifications(transactionID1, TestModel.TEST_PATH,
ShardTestKit.waitUntilLeader(shard);
- doThrow(new DataValidationFailedException(YangInstanceIdentifier.empty(), "mock canCommit failure"))
+ doThrow(new DataValidationFailedException(YangInstanceIdentifier.of(), "mock canCommit failure"))
.doNothing().when(dataTree).validate(any(DataTreeModification.class));
final Duration duration = Duration.ofSeconds(5);
ShardTestKit.waitUntilLeader(shard);
writeToStore(shard, TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME));
- final NormalizedNode expectedRoot = readStore(shard, YangInstanceIdentifier.empty());
+ final NormalizedNode expectedRoot = readStore(shard, YangInstanceIdentifier.of());
// Trigger creation of a snapshot by ensuring
final RaftActorContext raftActorContext = ((TestShard) shard.underlyingActor()).getRaftActorContext();
}
private static void verifySnapshot(final Snapshot snapshot, final NormalizedNode expectedRoot) {
- final NormalizedNode actual = ((ShardSnapshotState)snapshot.getState()).getSnapshot().getRootNode().get();
- assertEquals("Root node", expectedRoot, actual);
+ assertEquals("Root node", expectedRoot,
+ ((ShardSnapshotState)snapshot.getState()).getSnapshot().getRootNode().orElseThrow());
}
/**
commitTransaction(store, putTransaction);
- final NormalizedNode expected = readStore(store, YangInstanceIdentifier.empty());
+ final NormalizedNode expected = readStore(store, YangInstanceIdentifier.of());
final DataTreeModification writeTransaction = store.takeSnapshot().newModification();
- writeTransaction.delete(YangInstanceIdentifier.empty());
- writeTransaction.write(YangInstanceIdentifier.empty(), expected);
+ writeTransaction.delete(YangInstanceIdentifier.of());
+ writeTransaction.write(YangInstanceIdentifier.of(), expected);
commitTransaction(store, writeTransaction);
- final NormalizedNode actual = readStore(store, YangInstanceIdentifier.empty());
+ final NormalizedNode actual = readStore(store, YangInstanceIdentifier.of());
assertEquals(expected, actual);
}
ShardLeaderStateChanged leaderStateChanged = MessageCollectorActor.expectFirstMatching(listener,
ShardLeaderStateChanged.class);
- assertTrue("getLocalShardDataTree present", leaderStateChanged.getLocalShardDataTree().isPresent());
- assertSame("getLocalShardDataTree", shard.underlyingActor().getDataStore().getDataTree(),
- leaderStateChanged.getLocalShardDataTree().get());
+ final var dataTree = leaderStateChanged.localShardDataTree();
+ assertNotNull("getLocalShardDataTree present", dataTree);
+ assertSame("getLocalShardDataTree", shard.underlyingActor().getDataStore().getDataTree(), dataTree);
MessageCollectorActor.clearMessages(listener);
shard.tell(new RequestVote(10000, "member2", 50, 50), testKit.getRef());
leaderStateChanged = MessageCollectorActor.expectFirstMatching(listener, ShardLeaderStateChanged.class);
- assertFalse("getLocalShardDataTree present", leaderStateChanged.getLocalShardDataTree().isPresent());
+ assertNull("getLocalShardDataTree present", leaderStateChanged.localShardDataTree());
}
@Test
import akka.testkit.javadsl.TestKit;
import akka.util.Timeout;
import com.google.common.util.concurrent.Uninterruptibles;
-import java.util.Optional;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import org.opendaylight.controller.cluster.raft.client.messages.FindLeader;
for (int i = 0; i < 20 * 5; i++) {
Future<Object> future = Patterns.ask(shard, FindLeader.INSTANCE, new Timeout(duration));
try {
- final Optional<String> maybeLeader = ((FindLeaderReply) Await.result(future, duration))
- .getLeaderActor();
+ final var maybeLeader = ((FindLeaderReply) Await.result(future, duration)).getLeaderActor();
if (maybeLeader.isPresent()) {
- return maybeLeader.get();
+ return maybeLeader.orElseThrow();
}
} catch (TimeoutException e) {
LOG.trace("FindLeader timed out", e);
for (int i = 0; i < 20 * 5; i++) {
Future<Object> future = Patterns.ask(shard, FindLeader.INSTANCE, new Timeout(duration));
try {
- final Optional<String> maybeLeader = ((FindLeaderReply) Await.result(future, duration))
- .getLeaderActor();
+ final var maybeLeader = ((FindLeaderReply) Await.result(future, duration)).getLeaderActor();
if (!maybeLeader.isPresent()) {
return;
}
- lastResponse = maybeLeader.get();
+ lastResponse = maybeLeader.orElseThrow();
} catch (TimeoutException e) {
lastResponse = e;
} catch (Exception e) {
*
* @author Basheeruddin Ahmed
*/
+@Deprecated(since = "9.0.0", forRemoval = true)
public class ShardTransactionFailureTest extends AbstractActorTest {
private static final EffectiveModelContext TEST_SCHEMA_CONTEXT = TestModel.createTestContext();
private static final TransactionType RO = TransactionType.READ_ONLY;
"testNegativeReadWithReadOnlyTransactionClosed");
Future<Object> future = akka.pattern.Patterns.ask(subject,
- new ReadData(YangInstanceIdentifier.empty(), DataStoreVersions.CURRENT_VERSION), 3000);
+ new ReadData(YangInstanceIdentifier.of(), DataStoreVersions.CURRENT_VERSION), 3000);
Await.result(future, FiniteDuration.create(3, TimeUnit.SECONDS));
subject.underlyingActor().getDOMStoreTransaction().abortFromTransactionActor();
- future = akka.pattern.Patterns.ask(subject, new ReadData(YangInstanceIdentifier.empty(),
+ future = akka.pattern.Patterns.ask(subject, new ReadData(YangInstanceIdentifier.of(),
DataStoreVersions.CURRENT_VERSION), 3000);
Await.result(future, FiniteDuration.create(3, TimeUnit.SECONDS));
}
"testNegativeReadWithReadWriteTransactionClosed");
Future<Object> future = akka.pattern.Patterns.ask(subject,
- new ReadData(YangInstanceIdentifier.empty(), DataStoreVersions.CURRENT_VERSION), 3000);
+ new ReadData(YangInstanceIdentifier.of(), DataStoreVersions.CURRENT_VERSION), 3000);
Await.result(future, FiniteDuration.create(3, TimeUnit.SECONDS));
subject.underlyingActor().getDOMStoreTransaction().abortFromTransactionActor();
- future = akka.pattern.Patterns.ask(subject, new ReadData(YangInstanceIdentifier.empty(),
+ future = akka.pattern.Patterns.ask(subject, new ReadData(YangInstanceIdentifier.of(),
DataStoreVersions.CURRENT_VERSION), 3000);
Await.result(future, FiniteDuration.create(3, TimeUnit.SECONDS));
}
"testNegativeExistsWithReadWriteTransactionClosed");
Future<Object> future = akka.pattern.Patterns.ask(subject,
- new DataExists(YangInstanceIdentifier.empty(), DataStoreVersions.CURRENT_VERSION), 3000);
+ new DataExists(YangInstanceIdentifier.of(), DataStoreVersions.CURRENT_VERSION), 3000);
Await.result(future, FiniteDuration.create(3, TimeUnit.SECONDS));
subject.underlyingActor().getDOMStoreTransaction().abortFromTransactionActor();
future = akka.pattern.Patterns.ask(subject,
- new DataExists(YangInstanceIdentifier.empty(), DataStoreVersions.CURRENT_VERSION), 3000);
+ new DataExists(YangInstanceIdentifier.of(), DataStoreVersions.CURRENT_VERSION), 3000);
Await.result(future, FiniteDuration.create(3, TimeUnit.SECONDS));
}
}
import org.opendaylight.yangtools.yang.data.tree.api.DataTreeModification;
import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
+@Deprecated(since = "9.0.0", forRemoval = true)
public class ShardTransactionTest extends AbstractActorTest {
private static final TransactionType RO = TransactionType.READ_ONLY;
}
private void testOnReceiveReadData(final ActorRef transaction) {
- transaction.tell(new ReadData(YangInstanceIdentifier.empty(), DataStoreVersions.CURRENT_VERSION),
+ transaction.tell(new ReadData(YangInstanceIdentifier.of(), DataStoreVersions.CURRENT_VERSION),
testKit.getRef());
ReadDataReply reply = testKit.expectMsgClass(Duration.ofSeconds(5), ReadDataReply.class);
}
private void testOnReceiveDataExistsPositive(final ActorRef transaction) {
- transaction.tell(new DataExists(YangInstanceIdentifier.empty(), DataStoreVersions.CURRENT_VERSION),
+ transaction.tell(new DataExists(YangInstanceIdentifier.of(), DataStoreVersions.CURRENT_VERSION),
testKit.getRef());
DataExistsReply reply = testKit.expectMsgClass(Duration.ofSeconds(5), DataExistsReply.class);
@Test
public void testCanCommitWithConflictingModEx() {
- testValidatationPropagates(new ConflictingModificationAppliedException(YangInstanceIdentifier.empty(), "mock"));
+ testValidatationPropagates(new ConflictingModificationAppliedException(YangInstanceIdentifier.of(), "mock"));
}
@Test
public void testCanCommitWithDataValidationEx() {
- testValidatationPropagates(new DataValidationFailedException(YangInstanceIdentifier.empty(), "mock"));
+ testValidatationPropagates(new DataValidationFailedException(YangInstanceIdentifier.of(), "mock"));
}
@Test
+++ /dev/null
-/*
- * Copyright (c) 2019 PANTHEON.tech, s.r.o. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.cluster.datastore;
-
-import akka.actor.ActorSystem;
-import org.opendaylight.controller.cluster.access.concepts.ClientIdentifier;
-import org.opendaylight.controller.cluster.datastore.config.Configuration;
-import org.opendaylight.controller.cluster.datastore.persisted.DatastoreSnapshot;
-import org.opendaylight.controller.cluster.datastore.shardmanager.AbstractShardManagerCreator;
-import org.opendaylight.controller.cluster.datastore.shardmanager.TestShardManager;
-import org.opendaylight.controller.cluster.datastore.utils.ActorUtils;
-
-@Deprecated(since = "7.0.0", forRemoval = true)
-public class TestDistributedDataStore extends DistributedDataStore implements LocalShardStore {
-
- public TestDistributedDataStore(final ActorSystem actorSystem, final ClusterWrapper cluster,
- final Configuration configuration,
- final DatastoreContextFactory datastoreContextFactory,
- final DatastoreSnapshot restoreFromSnapshot) {
- super(actorSystem, cluster, configuration, datastoreContextFactory, restoreFromSnapshot);
- }
-
- TestDistributedDataStore(final ActorUtils actorUtils, final ClientIdentifier identifier) {
- super(actorUtils, identifier);
- }
-
- @Override
- protected AbstractShardManagerCreator<?> getShardManagerCreator() {
- return new TestShardManager.TestShardManagerCreator();
- }
-
- @Override
- public TestShardManager.GetLocalShardsReply getLocalShards() {
- TestShardManager.GetLocalShardsReply reply =
- (TestShardManager.GetLocalShardsReply) getActorUtils()
- .executeOperation(getActorUtils().getShardManager(), TestShardManager.GetLocalShards.INSTANCE);
-
- return reply;
- }
-}
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Supplier;
+import org.eclipse.jdt.annotation.NonNull;
import org.opendaylight.controller.cluster.access.concepts.TransactionIdentifier;
import org.opendaylight.controller.cluster.datastore.messages.AbortTransaction;
import org.opendaylight.controller.cluster.datastore.messages.AbortTransactionReply;
import org.opendaylight.controller.cluster.datastore.messages.CommitTransactionReply;
import org.opendaylight.controller.cluster.datastore.utils.ActorUtils;
import org.opendaylight.mdsal.common.api.CommitInfo;
+import org.opendaylight.mdsal.dom.spi.store.DOMStoreThreePhaseCommitCohort;
import org.opendaylight.yangtools.yang.common.Empty;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* ThreePhaseCommitCohortProxy represents a set of remote cohort proxies.
*/
-public class ThreePhaseCommitCohortProxy extends AbstractThreePhaseCommitCohort<ActorSelection> {
-
+@Deprecated(since = "9.0.0", forRemoval = true)
+final class ThreePhaseCommitCohortProxy implements DOMStoreThreePhaseCommitCohort {
private static final Logger LOG = LoggerFactory.getLogger(ThreePhaseCommitCohortProxy.class);
+ private static final @NonNull ListenableFuture<Empty> IMMEDIATE_EMPTY_SUCCESS =
+ Futures.immediateFuture(Empty.value());
private static final MessageSupplier COMMIT_MESSAGE_SUPPLIER = new MessageSupplier() {
@Override
}
};
+ private static final OperationCallback NO_OP_CALLBACK = new OperationCallback() {
+ @Override
+ public void run() {
+ }
+
+ @Override
+ public void success() {
+ }
+
+ @Override
+ public void failure() {
+ }
+
+ @Override
+ public void pause() {
+ }
+
+ @Override
+ public void resume() {
+ }
+ };
+
+
private final ActorUtils actorUtils;
private final List<CohortInfo> cohorts;
private final SettableFuture<Empty> cohortsResolvedFuture = SettableFuture.create();
private final TransactionIdentifier transactionId;
private volatile OperationCallback commitOperationCallback;
- public ThreePhaseCommitCohortProxy(final ActorUtils actorUtils, final List<CohortInfo> cohorts,
+ ThreePhaseCommitCohortProxy(final ActorUtils actorUtils, final List<CohortInfo> cohorts,
final TransactionIdentifier transactionId) {
this.actorUtils = actorUtils;
this.cohorts = cohorts;
// it's the original exception that is the root cause and of more interest to the client.
return operation("abort", Empty.value(), ABORT_MESSAGE_SUPPLIER, AbortTransactionReply.class, false,
- OperationCallback.NO_OP_CALLBACK);
+ NO_OP_CALLBACK);
}
@Override
public ListenableFuture<? extends CommitInfo> commit() {
OperationCallback operationCallback = commitOperationCallback != null ? commitOperationCallback :
- OperationCallback.NO_OP_CALLBACK;
+ NO_OP_CALLBACK;
return operation("commit", CommitInfo.empty(), COMMIT_MESSAGE_SUPPLIER, CommitTransactionReply.class, true,
operationCallback);
}, actorUtils.getClientDispatcher());
}
- @Override
- List<Future<ActorSelection>> getCohortFutures() {
- List<Future<ActorSelection>> cohortFutures = new ArrayList<>(cohorts.size());
- for (CohortInfo info: cohorts) {
- cohortFutures.add(info.getActorFuture());
- }
-
- return cohortFutures;
- }
-
static class CohortInfo {
private final Future<ActorSelection> actorFuture;
private final Supplier<Short> actorVersionSupplier;
import org.opendaylight.controller.cluster.raft.TestActorFactory;
import org.opendaylight.controller.cluster.raft.utils.DoNothingActor;
+@Deprecated(since = "9.0.0", forRemoval = true)
@RunWith(MockitoJUnitRunner.StrictStubs.class)
public class ThreePhaseCommitCohortProxyTest extends AbstractActorTest {
static class TestException extends RuntimeException {
+++ /dev/null
-/*
- * Copyright (c) 2014, 2015 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-
-package org.opendaylight.controller.cluster.datastore;
-
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.fail;
-import static org.mockito.ArgumentMatchers.any;
-import static org.mockito.ArgumentMatchers.eq;
-import static org.mockito.ArgumentMatchers.isA;
-import static org.mockito.Mockito.doReturn;
-import static org.mockito.Mockito.never;
-import static org.mockito.Mockito.timeout;
-import static org.mockito.Mockito.times;
-import static org.mockito.Mockito.verify;
-import static org.opendaylight.controller.cluster.datastore.TransactionType.READ_WRITE;
-import static org.opendaylight.controller.cluster.datastore.TransactionType.WRITE_ONLY;
-
-import akka.actor.ActorRef;
-import akka.util.Timeout;
-import java.util.concurrent.CountDownLatch;
-import java.util.concurrent.TimeUnit;
-import java.util.concurrent.atomic.AtomicReference;
-import java.util.function.Function;
-import org.junit.Assert;
-import org.junit.Test;
-import org.opendaylight.controller.cluster.access.concepts.LocalHistoryIdentifier;
-import org.opendaylight.controller.cluster.datastore.messages.BatchedModifications;
-import org.opendaylight.controller.cluster.datastore.modification.WriteModification;
-import org.opendaylight.controller.cluster.datastore.shardstrategy.DefaultShardStrategy;
-import org.opendaylight.controller.md.cluster.datastore.model.TestModel;
-import org.opendaylight.mdsal.dom.spi.store.DOMStoreReadTransaction;
-import org.opendaylight.mdsal.dom.spi.store.DOMStoreReadWriteTransaction;
-import org.opendaylight.mdsal.dom.spi.store.DOMStoreTransaction;
-import org.opendaylight.mdsal.dom.spi.store.DOMStoreWriteTransaction;
-import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
-import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
-import scala.concurrent.Promise;
-
-public class TransactionChainProxyTest extends AbstractTransactionProxyTest {
- private LocalHistoryIdentifier historyId;
-
- @Override
- public void setUp() {
- super.setUp();
- historyId = MockIdentifiers.historyIdentifier(TransactionChainProxyTest.class, memberName);
- }
-
- @SuppressWarnings("resource")
- @Test
- public void testNewReadOnlyTransaction() {
-
- DOMStoreTransaction dst = new TransactionChainProxy(mockComponentFactory, historyId).newReadOnlyTransaction();
- Assert.assertTrue(dst instanceof DOMStoreReadTransaction);
-
- }
-
- @SuppressWarnings("resource")
- @Test
- public void testNewReadWriteTransaction() {
- DOMStoreTransaction dst = new TransactionChainProxy(mockComponentFactory, historyId).newReadWriteTransaction();
- Assert.assertTrue(dst instanceof DOMStoreReadWriteTransaction);
-
- }
-
- @SuppressWarnings("resource")
- @Test
- public void testNewWriteOnlyTransaction() {
- DOMStoreTransaction dst = new TransactionChainProxy(mockComponentFactory, historyId).newWriteOnlyTransaction();
- Assert.assertTrue(dst instanceof DOMStoreWriteTransaction);
-
- }
-
- @SuppressWarnings("unchecked")
- @Test
- public void testClose() {
- new TransactionChainProxy(mockComponentFactory, historyId).close();
-
- verify(mockActorContext, times(1)).broadcast(any(Function.class), any(Class.class));
- }
-
- @Test
- public void testRateLimitingUsedInReadWriteTxCreation() {
- try (TransactionChainProxy txChainProxy = new TransactionChainProxy(mockComponentFactory, historyId)) {
-
- txChainProxy.newReadWriteTransaction();
-
- verify(mockActorContext, times(1)).acquireTxCreationPermit();
- }
- }
-
- @Test
- public void testRateLimitingUsedInWriteOnlyTxCreation() {
- try (TransactionChainProxy txChainProxy = new TransactionChainProxy(mockComponentFactory, historyId)) {
-
- txChainProxy.newWriteOnlyTransaction();
-
- verify(mockActorContext, times(1)).acquireTxCreationPermit();
- }
- }
-
- @Test
- public void testRateLimitingNotUsedInReadOnlyTxCreation() {
- try (TransactionChainProxy txChainProxy = new TransactionChainProxy(mockComponentFactory, historyId)) {
-
- txChainProxy.newReadOnlyTransaction();
-
- verify(mockActorContext, times(0)).acquireTxCreationPermit();
- }
- }
-
- /**
- * Tests 2 successive chained write-only transactions and verifies the second transaction isn't
- * initiated until the first one completes its read future.
- */
- @Test
- @SuppressWarnings("checkstyle:IllegalCatch")
- public void testChainedWriteOnlyTransactions() throws Exception {
- dataStoreContextBuilder.writeOnlyTransactionOptimizationsEnabled(true);
-
- try (TransactionChainProxy txChainProxy = new TransactionChainProxy(mockComponentFactory, historyId)) {
-
- ActorRef txActorRef1 = setupActorContextWithoutInitialCreateTransaction(getSystem());
-
- Promise<Object> batchedReplyPromise1 = akka.dispatch.Futures.promise();
- doReturn(batchedReplyPromise1.future()).when(mockActorContext).executeOperationAsync(
- eq(actorSelection(txActorRef1)), isA(BatchedModifications.class), any(Timeout.class));
-
- DOMStoreWriteTransaction writeTx1 = txChainProxy.newWriteOnlyTransaction();
-
- NormalizedNode writeNode1 = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
- writeTx1.write(TestModel.TEST_PATH, writeNode1);
-
- writeTx1.ready();
-
- verify(mockActorContext, times(1)).findPrimaryShardAsync(eq(DefaultShardStrategy.DEFAULT_SHARD));
-
- verifyOneBatchedModification(txActorRef1, new WriteModification(TestModel.TEST_PATH, writeNode1), true);
-
- ActorRef txActorRef2 = setupActorContextWithoutInitialCreateTransaction(getSystem());
-
- expectBatchedModifications(txActorRef2, 1);
-
- final NormalizedNode writeNode2 = ImmutableNodes.containerNode(TestModel.OUTER_LIST_QNAME);
-
- final DOMStoreWriteTransaction writeTx2 = txChainProxy.newWriteOnlyTransaction();
-
- final AtomicReference<Exception> caughtEx = new AtomicReference<>();
- final CountDownLatch write2Complete = new CountDownLatch(1);
- new Thread(() -> {
- try {
- writeTx2.write(TestModel.OUTER_LIST_PATH, writeNode2);
- } catch (Exception e) {
- caughtEx.set(e);
- } finally {
- write2Complete.countDown();
- }
- }).start();
-
- assertTrue("Tx 2 write should've completed", write2Complete.await(5, TimeUnit.SECONDS));
-
- if (caughtEx.get() != null) {
- throw caughtEx.get();
- }
-
- try {
- verify(mockActorContext, times(1)).findPrimaryShardAsync(eq(DefaultShardStrategy.DEFAULT_SHARD));
- } catch (AssertionError e) {
- fail("Tx 2 should not have initiated until the Tx 1's ready future completed");
- }
-
- batchedReplyPromise1.success(readyTxReply(txActorRef1.path().toString()).value().get().get());
-
- // Tx 2 should've proceeded to find the primary shard.
- verify(mockActorContext, timeout(5000).times(2)).findPrimaryShardAsync(
- eq(DefaultShardStrategy.DEFAULT_SHARD));
- }
- }
-
- /**
- * Tests 2 successive chained read-write transactions and verifies the second transaction isn't
- * initiated until the first one completes its read future.
- */
- @Test
- @SuppressWarnings("checkstyle:IllegalCatch")
- public void testChainedReadWriteTransactions() throws Exception {
- try (TransactionChainProxy txChainProxy = new TransactionChainProxy(mockComponentFactory, historyId)) {
-
- ActorRef txActorRef1 = setupActorContextWithInitialCreateTransaction(getSystem(), READ_WRITE);
-
- expectBatchedModifications(txActorRef1, 1);
-
- Promise<Object> readyReplyPromise1 = akka.dispatch.Futures.promise();
- doReturn(readyReplyPromise1.future()).when(mockActorContext).executeOperationAsync(
- eq(actorSelection(txActorRef1)), isA(BatchedModifications.class), any(Timeout.class));
-
- DOMStoreWriteTransaction writeTx1 = txChainProxy.newReadWriteTransaction();
-
- NormalizedNode writeNode1 = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
- writeTx1.write(TestModel.TEST_PATH, writeNode1);
-
- writeTx1.ready();
-
- verifyOneBatchedModification(txActorRef1, new WriteModification(TestModel.TEST_PATH, writeNode1), true);
-
- String tx2MemberName = "mock-member";
- ActorRef shardActorRef2 = setupActorContextWithoutInitialCreateTransaction(getSystem());
- ActorRef txActorRef2 = setupActorContextWithInitialCreateTransaction(getSystem(), READ_WRITE,
- DataStoreVersions.CURRENT_VERSION, tx2MemberName, shardActorRef2);
-
- expectBatchedModifications(txActorRef2, 1);
-
- final NormalizedNode writeNode2 = ImmutableNodes.containerNode(TestModel.OUTER_LIST_QNAME);
-
- final DOMStoreWriteTransaction writeTx2 = txChainProxy.newReadWriteTransaction();
-
- final AtomicReference<Exception> caughtEx = new AtomicReference<>();
- final CountDownLatch write2Complete = new CountDownLatch(1);
- new Thread(() -> {
- try {
- writeTx2.write(TestModel.OUTER_LIST_PATH, writeNode2);
- } catch (Exception e) {
- caughtEx.set(e);
- } finally {
- write2Complete.countDown();
- }
- }).start();
-
- assertTrue("Tx 2 write should've completed", write2Complete.await(5, TimeUnit.SECONDS));
-
- if (caughtEx.get() != null) {
- throw caughtEx.get();
- }
-
- try {
- verify(mockActorContext, never()).executeOperationAsync(
- eq(getSystem().actorSelection(shardActorRef2.path())),
- eqCreateTransaction(tx2MemberName, READ_WRITE));
- } catch (AssertionError e) {
- fail("Tx 2 should not have initiated until the Tx 1's ready future completed");
- }
-
- readyReplyPromise1.success(readyTxReply(txActorRef1.path().toString()).value().get().get());
-
- verify(mockActorContext, timeout(5000)).executeOperationAsync(
- eq(getSystem().actorSelection(shardActorRef2.path())),
- eqCreateTransaction(tx2MemberName, READ_WRITE), any(Timeout.class));
- }
- }
-
- @Test(expected = IllegalStateException.class)
- public void testChainedWriteTransactionsWithPreviousTxNotReady() {
- ActorRef actorRef = setupActorContextWithInitialCreateTransaction(getSystem(), WRITE_ONLY);
-
- expectBatchedModifications(actorRef, 1);
-
- try (TransactionChainProxy txChainProxy = new TransactionChainProxy(mockComponentFactory, historyId)) {
-
- DOMStoreWriteTransaction writeTx1 = txChainProxy.newWriteOnlyTransaction();
-
- NormalizedNode writeNode1 = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
- writeTx1.write(TestModel.TEST_PATH, writeNode1);
-
- txChainProxy.newWriteOnlyTransaction();
- }
- }
-}
+++ /dev/null
-/*
- * Copyright (c) 2014, 2015 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.cluster.datastore;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
-import static org.mockito.ArgumentMatchers.any;
-import static org.mockito.ArgumentMatchers.anyString;
-import static org.mockito.ArgumentMatchers.eq;
-import static org.mockito.ArgumentMatchers.isA;
-import static org.mockito.Mockito.doReturn;
-import static org.mockito.Mockito.doThrow;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.verify;
-import static org.opendaylight.controller.cluster.datastore.TransactionType.READ_ONLY;
-import static org.opendaylight.controller.cluster.datastore.TransactionType.READ_WRITE;
-import static org.opendaylight.controller.cluster.datastore.TransactionType.WRITE_ONLY;
-
-import akka.actor.ActorRef;
-import akka.actor.ActorSelection;
-import akka.actor.ActorSystem;
-import akka.actor.Props;
-import akka.dispatch.Futures;
-import akka.util.Timeout;
-import com.google.common.base.Throwables;
-import com.google.common.collect.ImmutableSortedSet;
-import com.google.common.collect.Sets;
-import com.google.common.util.concurrent.FluentFuture;
-import com.google.common.util.concurrent.FutureCallback;
-import com.google.common.util.concurrent.MoreExecutors;
-import com.google.common.util.concurrent.Uninterruptibles;
-import java.util.Collection;
-import java.util.List;
-import java.util.Optional;
-import java.util.SortedSet;
-import java.util.concurrent.CountDownLatch;
-import java.util.concurrent.ExecutionException;
-import java.util.concurrent.TimeUnit;
-import java.util.concurrent.atomic.AtomicReference;
-import org.junit.Assert;
-import org.junit.Test;
-import org.mockito.ArgumentCaptor;
-import org.mockito.InOrder;
-import org.mockito.Mockito;
-import org.opendaylight.controller.cluster.access.concepts.MemberName;
-import org.opendaylight.controller.cluster.datastore.config.Configuration;
-import org.opendaylight.controller.cluster.datastore.exceptions.NoShardLeaderException;
-import org.opendaylight.controller.cluster.datastore.exceptions.NotInitializedException;
-import org.opendaylight.controller.cluster.datastore.exceptions.PrimaryNotFoundException;
-import org.opendaylight.controller.cluster.datastore.exceptions.TimeoutException;
-import org.opendaylight.controller.cluster.datastore.messages.BatchedModifications;
-import org.opendaylight.controller.cluster.datastore.messages.CloseTransaction;
-import org.opendaylight.controller.cluster.datastore.messages.CommitTransactionReply;
-import org.opendaylight.controller.cluster.datastore.messages.CreateTransactionReply;
-import org.opendaylight.controller.cluster.datastore.messages.PrimaryShardInfo;
-import org.opendaylight.controller.cluster.datastore.messages.ReadyLocalTransaction;
-import org.opendaylight.controller.cluster.datastore.modification.DeleteModification;
-import org.opendaylight.controller.cluster.datastore.modification.MergeModification;
-import org.opendaylight.controller.cluster.datastore.modification.WriteModification;
-import org.opendaylight.controller.cluster.datastore.shardstrategy.DefaultShardStrategy;
-import org.opendaylight.controller.cluster.datastore.utils.NormalizedNodeAggregatorTest;
-import org.opendaylight.controller.cluster.raft.utils.DoNothingActor;
-import org.opendaylight.controller.md.cluster.datastore.model.CarsModel;
-import org.opendaylight.controller.md.cluster.datastore.model.SchemaContextHelper;
-import org.opendaylight.controller.md.cluster.datastore.model.TestModel;
-import org.opendaylight.mdsal.common.api.ReadFailedException;
-import org.opendaylight.mdsal.dom.spi.store.DOMStoreThreePhaseCommitCohort;
-import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
-import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
-import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
-import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
-import org.opendaylight.yangtools.yang.data.tree.api.DataTree;
-import org.opendaylight.yangtools.yang.data.tree.api.DataTreeModification;
-import org.opendaylight.yangtools.yang.data.tree.api.DataTreeSnapshot;
-import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
-import scala.concurrent.Promise;
-
-@SuppressWarnings({"resource", "checkstyle:IllegalThrows", "checkstyle:AvoidHidingCauseException"})
-public class TransactionProxyTest extends AbstractTransactionProxyTest {
-
- @SuppressWarnings("serial")
- static class TestException extends RuntimeException {
- }
-
- interface Invoker {
- FluentFuture<?> invoke(TransactionProxy proxy);
- }
-
- @Test
- public void testRead() throws Exception {
- ActorRef actorRef = setupActorContextWithInitialCreateTransaction(getSystem(), READ_ONLY);
-
- TransactionProxy transactionProxy = new TransactionProxy(mockComponentFactory, READ_ONLY);
-
- doReturn(readDataReply(null)).when(mockActorContext).executeOperationAsync(
- eq(actorSelection(actorRef)), eqReadData(), any(Timeout.class));
-
- Optional<NormalizedNode> readOptional = transactionProxy.read(
- TestModel.TEST_PATH).get(5, TimeUnit.SECONDS);
-
- assertFalse("NormalizedNode isPresent", readOptional.isPresent());
-
- NormalizedNode expectedNode = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
-
- doReturn(readDataReply(expectedNode)).when(mockActorContext).executeOperationAsync(
- eq(actorSelection(actorRef)), eqReadData(), any(Timeout.class));
-
- readOptional = transactionProxy.read(TestModel.TEST_PATH).get(5, TimeUnit.SECONDS);
-
- assertTrue("NormalizedNode isPresent", readOptional.isPresent());
-
- assertEquals("Response NormalizedNode", expectedNode, readOptional.get());
- }
-
- @Test(expected = ReadFailedException.class)
- public void testReadWithInvalidReplyMessageType() throws Throwable {
- ActorRef actorRef = setupActorContextWithInitialCreateTransaction(getSystem(), READ_ONLY);
-
- doReturn(Futures.successful(new Object())).when(mockActorContext)
- .executeOperationAsync(eq(actorSelection(actorRef)), eqReadData(), any(Timeout.class));
-
- TransactionProxy transactionProxy = new TransactionProxy(mockComponentFactory, READ_ONLY);
-
- try {
- transactionProxy.read(TestModel.TEST_PATH).get(5, TimeUnit.SECONDS);
- } catch (ExecutionException e) {
- throw e.getCause();
- }
- }
-
- @Test(expected = TestException.class)
- public void testReadWithAsyncRemoteOperatonFailure() throws Throwable {
- ActorRef actorRef = setupActorContextWithInitialCreateTransaction(getSystem(), READ_ONLY);
-
- doReturn(Futures.failed(new TestException())).when(mockActorContext)
- .executeOperationAsync(eq(actorSelection(actorRef)), eqReadData(), any(Timeout.class));
-
- TransactionProxy transactionProxy = new TransactionProxy(mockComponentFactory, READ_ONLY);
-
- propagateReadFailedExceptionCause(transactionProxy.read(TestModel.TEST_PATH));
- }
-
- private void testExceptionOnInitialCreateTransaction(final Exception exToThrow, final Invoker invoker)
- throws Throwable {
- ActorRef actorRef = getSystem().actorOf(Props.create(DoNothingActor.class));
-
- if (exToThrow instanceof PrimaryNotFoundException) {
- doReturn(Futures.failed(exToThrow)).when(mockActorContext).findPrimaryShardAsync(anyString());
- } else {
- doReturn(primaryShardInfoReply(getSystem(), actorRef)).when(mockActorContext)
- .findPrimaryShardAsync(anyString());
- }
-
- doReturn(Futures.failed(exToThrow)).when(mockActorContext).executeOperationAsync(
- any(ActorSelection.class), any(), any(Timeout.class));
-
- TransactionProxy transactionProxy = new TransactionProxy(mockComponentFactory, READ_ONLY);
-
- propagateReadFailedExceptionCause(invoker.invoke(transactionProxy));
- }
-
- private void testReadWithExceptionOnInitialCreateTransaction(final Exception exToThrow) throws Throwable {
- testExceptionOnInitialCreateTransaction(exToThrow, proxy -> proxy.read(TestModel.TEST_PATH));
- }
-
- @Test(expected = PrimaryNotFoundException.class)
- public void testReadWhenAPrimaryNotFoundExceptionIsThrown() throws Throwable {
- testReadWithExceptionOnInitialCreateTransaction(new PrimaryNotFoundException("test"));
- }
-
- @Test(expected = TestException.class)
- public void testReadWhenATimeoutExceptionIsThrown() throws Throwable {
- testReadWithExceptionOnInitialCreateTransaction(new TimeoutException("test",
- new TestException()));
- }
-
- @Test(expected = TestException.class)
- public void testReadWhenAnyOtherExceptionIsThrown() throws Throwable {
- testReadWithExceptionOnInitialCreateTransaction(new TestException());
- }
-
- @Test
- public void testReadWithPriorRecordingOperationSuccessful() throws Exception {
- ActorRef actorRef = setupActorContextWithInitialCreateTransaction(getSystem(), READ_WRITE);
-
- NormalizedNode expectedNode = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
-
- expectBatchedModifications(actorRef, 1);
-
- doReturn(readDataReply(expectedNode)).when(mockActorContext).executeOperationAsync(
- eq(actorSelection(actorRef)), eqReadData(), any(Timeout.class));
-
- TransactionProxy transactionProxy = new TransactionProxy(mockComponentFactory, READ_WRITE);
-
- transactionProxy.write(TestModel.TEST_PATH, expectedNode);
-
- Optional<NormalizedNode> readOptional = transactionProxy.read(
- TestModel.TEST_PATH).get(5, TimeUnit.SECONDS);
-
- assertTrue("NormalizedNode isPresent", readOptional.isPresent());
- assertEquals("Response NormalizedNode", expectedNode, readOptional.get());
-
- InOrder inOrder = Mockito.inOrder(mockActorContext);
- inOrder.verify(mockActorContext).executeOperationAsync(
- eq(actorSelection(actorRef)), isA(BatchedModifications.class), any(Timeout.class));
-
- inOrder.verify(mockActorContext).executeOperationAsync(
- eq(actorSelection(actorRef)), eqReadData(), any(Timeout.class));
- }
-
- @Test(expected = IllegalStateException.class)
- public void testReadPreConditionCheck() {
- TransactionProxy transactionProxy = new TransactionProxy(mockComponentFactory, WRITE_ONLY);
- transactionProxy.read(TestModel.TEST_PATH);
- }
-
- @Test(expected = IllegalArgumentException.class)
- public void testInvalidCreateTransactionReply() throws Throwable {
- ActorRef actorRef = getSystem().actorOf(Props.create(DoNothingActor.class));
-
- doReturn(getSystem().actorSelection(actorRef.path())).when(mockActorContext)
- .actorSelection(actorRef.path().toString());
-
- doReturn(primaryShardInfoReply(getSystem(), actorRef)).when(mockActorContext)
- .findPrimaryShardAsync(eq(DefaultShardStrategy.DEFAULT_SHARD));
-
- doReturn(Futures.successful(new Object())).when(mockActorContext).executeOperationAsync(
- eq(getSystem().actorSelection(actorRef.path())), eqCreateTransaction(memberName, READ_ONLY),
- any(Timeout.class));
-
- TransactionProxy transactionProxy = new TransactionProxy(mockComponentFactory, READ_ONLY);
-
- propagateReadFailedExceptionCause(transactionProxy.read(TestModel.TEST_PATH));
- }
-
- @Test
- public void testExists() throws Exception {
- ActorRef actorRef = setupActorContextWithInitialCreateTransaction(getSystem(), READ_ONLY);
-
- TransactionProxy transactionProxy = new TransactionProxy(mockComponentFactory, READ_ONLY);
-
- doReturn(dataExistsReply(false)).when(mockActorContext).executeOperationAsync(
- eq(actorSelection(actorRef)), eqDataExists(), any(Timeout.class));
-
- Boolean exists = transactionProxy.exists(TestModel.TEST_PATH).get();
-
- assertEquals("Exists response", Boolean.FALSE, exists);
-
- doReturn(dataExistsReply(true)).when(mockActorContext).executeOperationAsync(
- eq(actorSelection(actorRef)), eqDataExists(), any(Timeout.class));
-
- exists = transactionProxy.exists(TestModel.TEST_PATH).get();
-
- assertEquals("Exists response", Boolean.TRUE, exists);
- }
-
- @Test(expected = PrimaryNotFoundException.class)
- public void testExistsWhenAPrimaryNotFoundExceptionIsThrown() throws Throwable {
- testExceptionOnInitialCreateTransaction(new PrimaryNotFoundException("test"),
- proxy -> proxy.exists(TestModel.TEST_PATH));
- }
-
- @Test(expected = ReadFailedException.class)
- public void testExistsWithInvalidReplyMessageType() throws Throwable {
- ActorRef actorRef = setupActorContextWithInitialCreateTransaction(getSystem(), READ_ONLY);
-
- doReturn(Futures.successful(new Object())).when(mockActorContext)
- .executeOperationAsync(eq(actorSelection(actorRef)), eqDataExists(), any(Timeout.class));
-
- TransactionProxy transactionProxy = new TransactionProxy(mockComponentFactory, READ_ONLY);
-
- try {
- transactionProxy.exists(TestModel.TEST_PATH).get(5, TimeUnit.SECONDS);
- } catch (ExecutionException e) {
- throw e.getCause();
- }
- }
-
- @Test(expected = TestException.class)
- public void testExistsWithAsyncRemoteOperatonFailure() throws Throwable {
- ActorRef actorRef = setupActorContextWithInitialCreateTransaction(getSystem(), READ_ONLY);
-
- doReturn(Futures.failed(new TestException())).when(mockActorContext)
- .executeOperationAsync(eq(actorSelection(actorRef)), eqDataExists(), any(Timeout.class));
-
- TransactionProxy transactionProxy = new TransactionProxy(mockComponentFactory, READ_ONLY);
-
- propagateReadFailedExceptionCause(transactionProxy.exists(TestModel.TEST_PATH));
- }
-
- @Test
- public void testExistsWithPriorRecordingOperationSuccessful() throws Exception {
- ActorRef actorRef = setupActorContextWithInitialCreateTransaction(getSystem(), READ_WRITE);
-
- NormalizedNode nodeToWrite = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
-
- expectBatchedModifications(actorRef, 1);
-
- doReturn(dataExistsReply(true)).when(mockActorContext).executeOperationAsync(
- eq(actorSelection(actorRef)), eqDataExists(), any(Timeout.class));
-
- TransactionProxy transactionProxy = new TransactionProxy(mockComponentFactory, READ_WRITE);
-
- transactionProxy.write(TestModel.TEST_PATH, nodeToWrite);
-
- Boolean exists = transactionProxy.exists(TestModel.TEST_PATH).get();
-
- assertEquals("Exists response", Boolean.TRUE, exists);
-
- InOrder inOrder = Mockito.inOrder(mockActorContext);
- inOrder.verify(mockActorContext).executeOperationAsync(
- eq(actorSelection(actorRef)), isA(BatchedModifications.class), any(Timeout.class));
-
- inOrder.verify(mockActorContext).executeOperationAsync(
- eq(actorSelection(actorRef)), eqDataExists(), any(Timeout.class));
- }
-
- @Test(expected = IllegalStateException.class)
- public void testExistsPreConditionCheck() {
- TransactionProxy transactionProxy = new TransactionProxy(mockComponentFactory, WRITE_ONLY);
- transactionProxy.exists(TestModel.TEST_PATH);
- }
-
- @Test
- public void testWrite() {
- dataStoreContextBuilder.shardBatchedModificationCount(1);
- ActorRef actorRef = setupActorContextWithInitialCreateTransaction(getSystem(), WRITE_ONLY);
-
- NormalizedNode nodeToWrite = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
-
- expectBatchedModifications(actorRef, 1);
-
- TransactionProxy transactionProxy = new TransactionProxy(mockComponentFactory, WRITE_ONLY);
-
- transactionProxy.write(TestModel.TEST_PATH, nodeToWrite);
-
- verifyOneBatchedModification(actorRef, new WriteModification(TestModel.TEST_PATH, nodeToWrite), false);
- }
-
- @Test
- @SuppressWarnings("checkstyle:IllegalCatch")
- public void testWriteAfterAsyncRead() throws Exception {
- ActorRef actorRef = setupActorContextWithoutInitialCreateTransaction(getSystem(),
- DefaultShardStrategy.DEFAULT_SHARD);
-
- Promise<Object> createTxPromise = akka.dispatch.Futures.promise();
- doReturn(createTxPromise).when(mockActorContext).executeOperationAsync(
- eq(getSystem().actorSelection(actorRef.path())),
- eqCreateTransaction(memberName, READ_WRITE), any(Timeout.class));
-
- doReturn(readDataReply(null)).when(mockActorContext).executeOperationAsync(
- eq(actorSelection(actorRef)), eqReadData(), any(Timeout.class));
-
- expectBatchedModificationsReady(actorRef);
-
- final NormalizedNode nodeToWrite = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
-
- final TransactionProxy transactionProxy = new TransactionProxy(mockComponentFactory, READ_WRITE);
-
- final CountDownLatch readComplete = new CountDownLatch(1);
- final AtomicReference<Throwable> caughtEx = new AtomicReference<>();
- com.google.common.util.concurrent.Futures.addCallback(transactionProxy.read(TestModel.TEST_PATH),
- new FutureCallback<Optional<NormalizedNode>>() {
- @Override
- public void onSuccess(final Optional<NormalizedNode> result) {
- try {
- transactionProxy.write(TestModel.TEST_PATH, nodeToWrite);
- } catch (Exception e) {
- caughtEx.set(e);
- } finally {
- readComplete.countDown();
- }
- }
-
- @Override
- public void onFailure(final Throwable failure) {
- caughtEx.set(failure);
- readComplete.countDown();
- }
- }, MoreExecutors.directExecutor());
-
- createTxPromise.success(createTransactionReply(actorRef, DataStoreVersions.CURRENT_VERSION));
-
- Uninterruptibles.awaitUninterruptibly(readComplete, 5, TimeUnit.SECONDS);
-
- final Throwable t = caughtEx.get();
- if (t != null) {
- Throwables.propagateIfPossible(t, Exception.class);
- throw new RuntimeException(t);
- }
-
- // This sends the batched modification.
- transactionProxy.ready();
-
- verifyOneBatchedModification(actorRef, new WriteModification(TestModel.TEST_PATH, nodeToWrite), true);
- }
-
- @Test(expected = IllegalStateException.class)
- public void testWritePreConditionCheck() {
- TransactionProxy transactionProxy = new TransactionProxy(mockComponentFactory, READ_ONLY);
- transactionProxy.write(TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME));
- }
-
- @Test(expected = IllegalStateException.class)
- public void testWriteAfterReadyPreConditionCheck() {
- TransactionProxy transactionProxy = new TransactionProxy(mockComponentFactory, WRITE_ONLY);
-
- transactionProxy.ready();
-
- transactionProxy.write(TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME));
- }
-
- @Test
- public void testMerge() {
- dataStoreContextBuilder.shardBatchedModificationCount(1);
- ActorRef actorRef = setupActorContextWithInitialCreateTransaction(getSystem(), WRITE_ONLY);
-
- NormalizedNode nodeToWrite = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
-
- expectBatchedModifications(actorRef, 1);
-
- TransactionProxy transactionProxy = new TransactionProxy(mockComponentFactory, WRITE_ONLY);
-
- transactionProxy.merge(TestModel.TEST_PATH, nodeToWrite);
-
- verifyOneBatchedModification(actorRef, new MergeModification(TestModel.TEST_PATH, nodeToWrite), false);
- }
-
- @Test
- public void testDelete() {
- dataStoreContextBuilder.shardBatchedModificationCount(1);
- ActorRef actorRef = setupActorContextWithInitialCreateTransaction(getSystem(), WRITE_ONLY);
-
- expectBatchedModifications(actorRef, 1);
-
- TransactionProxy transactionProxy = new TransactionProxy(mockComponentFactory, WRITE_ONLY);
-
- transactionProxy.delete(TestModel.TEST_PATH);
-
- verifyOneBatchedModification(actorRef, new DeleteModification(TestModel.TEST_PATH), false);
- }
-
- @Test
- public void testReadWrite() {
- ActorRef actorRef = setupActorContextWithInitialCreateTransaction(getSystem(), READ_WRITE);
-
- final NormalizedNode nodeToWrite = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
-
- doReturn(readDataReply(null)).when(mockActorContext).executeOperationAsync(
- eq(actorSelection(actorRef)), eqReadData(), any(Timeout.class));
-
- expectBatchedModifications(actorRef, 1);
-
- TransactionProxy transactionProxy = new TransactionProxy(mockComponentFactory, READ_WRITE);
-
- transactionProxy.read(TestModel.TEST_PATH);
-
- transactionProxy.write(TestModel.TEST_PATH, nodeToWrite);
-
- transactionProxy.read(TestModel.TEST_PATH);
-
- transactionProxy.read(TestModel.TEST_PATH);
-
- List<BatchedModifications> batchedModifications = captureBatchedModifications(actorRef);
- assertEquals("Captured BatchedModifications count", 1, batchedModifications.size());
-
- verifyBatchedModifications(batchedModifications.get(0), false,
- new WriteModification(TestModel.TEST_PATH, nodeToWrite));
- }
-
- @Test
- public void testReadyWithReadWrite() {
- ActorRef actorRef = setupActorContextWithInitialCreateTransaction(getSystem(), READ_WRITE);
-
- final NormalizedNode nodeToWrite = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
-
- doReturn(readDataReply(null)).when(mockActorContext).executeOperationAsync(
- eq(actorSelection(actorRef)), eqReadData(), any(Timeout.class));
-
- expectBatchedModificationsReady(actorRef, true);
-
- TransactionProxy transactionProxy = new TransactionProxy(mockComponentFactory, READ_WRITE);
-
- transactionProxy.read(TestModel.TEST_PATH);
-
- transactionProxy.write(TestModel.TEST_PATH, nodeToWrite);
-
- DOMStoreThreePhaseCommitCohort ready = transactionProxy.ready();
-
- assertTrue(ready instanceof SingleCommitCohortProxy);
-
- verifyCohortFutures((SingleCommitCohortProxy)ready, new CommitTransactionReply().toSerializable());
-
- List<BatchedModifications> batchedModifications = captureBatchedModifications(actorRef);
- assertEquals("Captured BatchedModifications count", 1, batchedModifications.size());
-
- verifyBatchedModifications(batchedModifications.get(0), true, true,
- new WriteModification(TestModel.TEST_PATH, nodeToWrite));
-
- assertEquals("getTotalMessageCount", 1, batchedModifications.get(0).getTotalMessagesSent());
- }
-
- @Test
- public void testReadyWithNoModifications() {
- ActorRef actorRef = setupActorContextWithInitialCreateTransaction(getSystem(), READ_WRITE);
-
- doReturn(readDataReply(null)).when(mockActorContext).executeOperationAsync(
- eq(actorSelection(actorRef)), eqReadData(), any(Timeout.class));
-
- expectBatchedModificationsReady(actorRef, true);
-
- TransactionProxy transactionProxy = new TransactionProxy(mockComponentFactory, READ_WRITE);
-
- transactionProxy.read(TestModel.TEST_PATH);
-
- DOMStoreThreePhaseCommitCohort ready = transactionProxy.ready();
-
- assertTrue(ready instanceof SingleCommitCohortProxy);
-
- verifyCohortFutures((SingleCommitCohortProxy)ready, new CommitTransactionReply().toSerializable());
-
- List<BatchedModifications> batchedModifications = captureBatchedModifications(actorRef);
- assertEquals("Captured BatchedModifications count", 1, batchedModifications.size());
-
- verifyBatchedModifications(batchedModifications.get(0), true, true);
- }
-
- @Test
- public void testReadyWithMultipleShardWrites() {
- ActorRef actorRef1 = setupActorContextWithInitialCreateTransaction(getSystem(), WRITE_ONLY);
-
- ActorRef actorRef2 = setupActorContextWithInitialCreateTransaction(getSystem(), WRITE_ONLY,
- TestModel.JUNK_QNAME.getLocalName());
-
- expectBatchedModificationsReady(actorRef1);
- expectBatchedModificationsReady(actorRef2);
-
- ActorRef actorRef3 = getSystem().actorOf(Props.create(DoNothingActor.class));
-
- doReturn(getSystem().actorSelection(actorRef3.path())).when(mockActorContext)
- .actorSelection(actorRef3.path().toString());
-
- doReturn(Futures.successful(newPrimaryShardInfo(actorRef3, createDataTree()))).when(mockActorContext)
- .findPrimaryShardAsync(eq(CarsModel.BASE_QNAME.getLocalName()));
-
- expectReadyLocalTransaction(actorRef3, false);
-
- TransactionProxy transactionProxy = new TransactionProxy(mockComponentFactory, WRITE_ONLY);
-
- transactionProxy.write(TestModel.JUNK_PATH, ImmutableNodes.containerNode(TestModel.JUNK_QNAME));
- transactionProxy.write(TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME));
- transactionProxy.write(CarsModel.BASE_PATH, ImmutableNodes.containerNode(CarsModel.BASE_QNAME));
-
- DOMStoreThreePhaseCommitCohort ready = transactionProxy.ready();
-
- assertTrue(ready instanceof ThreePhaseCommitCohortProxy);
-
- verifyCohortFutures((ThreePhaseCommitCohortProxy)ready, actorSelection(actorRef1),
- actorSelection(actorRef2), actorSelection(actorRef3));
-
- SortedSet<String> expShardNames =
- ImmutableSortedSet.of(DefaultShardStrategy.DEFAULT_SHARD,
- TestModel.JUNK_QNAME.getLocalName(), CarsModel.BASE_QNAME.getLocalName());
-
- ArgumentCaptor<BatchedModifications> batchedMods = ArgumentCaptor.forClass(BatchedModifications.class);
- verify(mockActorContext).executeOperationAsync(
- eq(actorSelection(actorRef1)), batchedMods.capture(), any(Timeout.class));
- assertTrue("Participating shards present", batchedMods.getValue().getParticipatingShardNames().isPresent());
- assertEquals("Participating shards", expShardNames, batchedMods.getValue().getParticipatingShardNames().get());
-
- batchedMods = ArgumentCaptor.forClass(BatchedModifications.class);
- verify(mockActorContext).executeOperationAsync(
- eq(actorSelection(actorRef2)), batchedMods.capture(), any(Timeout.class));
- assertTrue("Participating shards present", batchedMods.getValue().getParticipatingShardNames().isPresent());
- assertEquals("Participating shards", expShardNames, batchedMods.getValue().getParticipatingShardNames().get());
-
- ArgumentCaptor<ReadyLocalTransaction> readyLocalTx = ArgumentCaptor.forClass(ReadyLocalTransaction.class);
- verify(mockActorContext).executeOperationAsync(
- eq(actorSelection(actorRef3)), readyLocalTx.capture(), any(Timeout.class));
- assertTrue("Participating shards present", readyLocalTx.getValue().getParticipatingShardNames().isPresent());
- assertEquals("Participating shards", expShardNames, readyLocalTx.getValue().getParticipatingShardNames().get());
- }
-
- @Test
- public void testReadyWithWriteOnlyAndLastBatchPending() {
- dataStoreContextBuilder.writeOnlyTransactionOptimizationsEnabled(true);
-
- ActorRef actorRef = setupActorContextWithInitialCreateTransaction(getSystem(), WRITE_ONLY);
-
- NormalizedNode nodeToWrite = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
-
- expectBatchedModificationsReady(actorRef, true);
-
- TransactionProxy transactionProxy = new TransactionProxy(mockComponentFactory, WRITE_ONLY);
-
- transactionProxy.write(TestModel.TEST_PATH, nodeToWrite);
-
- DOMStoreThreePhaseCommitCohort ready = transactionProxy.ready();
-
- assertTrue(ready instanceof SingleCommitCohortProxy);
-
- verifyCohortFutures((SingleCommitCohortProxy)ready, new CommitTransactionReply().toSerializable());
-
- List<BatchedModifications> batchedModifications = captureBatchedModifications(actorRef);
- assertEquals("Captured BatchedModifications count", 1, batchedModifications.size());
-
- verifyBatchedModifications(batchedModifications.get(0), true, true,
- new WriteModification(TestModel.TEST_PATH, nodeToWrite));
- }
-
- @Test
- public void testReadyWithWriteOnlyAndLastBatchEmpty() {
- dataStoreContextBuilder.shardBatchedModificationCount(1).writeOnlyTransactionOptimizationsEnabled(true);
- ActorRef actorRef = setupActorContextWithInitialCreateTransaction(getSystem(), WRITE_ONLY);
-
- NormalizedNode nodeToWrite = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
-
- expectBatchedModificationsReady(actorRef, true);
-
- TransactionProxy transactionProxy = new TransactionProxy(mockComponentFactory, WRITE_ONLY);
-
- transactionProxy.write(TestModel.TEST_PATH, nodeToWrite);
-
- DOMStoreThreePhaseCommitCohort ready = transactionProxy.ready();
-
- assertTrue(ready instanceof SingleCommitCohortProxy);
-
- verifyCohortFutures((SingleCommitCohortProxy)ready, new CommitTransactionReply().toSerializable());
-
- List<BatchedModifications> batchedModifications = captureBatchedModifications(actorRef);
- assertEquals("Captured BatchedModifications count", 2, batchedModifications.size());
-
- verifyBatchedModifications(batchedModifications.get(0), false,
- new WriteModification(TestModel.TEST_PATH, nodeToWrite));
-
- verifyBatchedModifications(batchedModifications.get(1), true, true);
- }
-
- @Test
- public void testReadyWithReplyFailure() {
- dataStoreContextBuilder.writeOnlyTransactionOptimizationsEnabled(true);
-
- ActorRef actorRef = setupActorContextWithInitialCreateTransaction(getSystem(), WRITE_ONLY);
-
- NormalizedNode nodeToWrite = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
-
- expectFailedBatchedModifications(actorRef);
-
- TransactionProxy transactionProxy = new TransactionProxy(mockComponentFactory, WRITE_ONLY);
-
- transactionProxy.merge(TestModel.TEST_PATH, nodeToWrite);
-
- DOMStoreThreePhaseCommitCohort ready = transactionProxy.ready();
-
- assertTrue(ready instanceof SingleCommitCohortProxy);
-
- verifyCohortFutures((SingleCommitCohortProxy)ready, TestException.class);
- }
-
- @Test
- public void testReadyWithDebugContextEnabled() {
- dataStoreContextBuilder.transactionDebugContextEnabled(true);
-
- ActorRef actorRef = setupActorContextWithInitialCreateTransaction(getSystem(), READ_WRITE);
-
- expectBatchedModificationsReady(actorRef, true);
-
- TransactionProxy transactionProxy = new TransactionProxy(mockComponentFactory, READ_WRITE);
-
- transactionProxy.merge(TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME));
-
- DOMStoreThreePhaseCommitCohort ready = transactionProxy.ready();
-
- assertTrue(ready instanceof DebugThreePhaseCommitCohort);
-
- verifyCohortFutures((DebugThreePhaseCommitCohort)ready, new CommitTransactionReply().toSerializable());
- }
-
- @Test
- public void testReadyWithLocalTransaction() {
- ActorRef shardActorRef = getSystem().actorOf(Props.create(DoNothingActor.class));
-
- doReturn(getSystem().actorSelection(shardActorRef.path())).when(mockActorContext)
- .actorSelection(shardActorRef.path().toString());
-
- doReturn(Futures.successful(newPrimaryShardInfo(shardActorRef, createDataTree()))).when(mockActorContext)
- .findPrimaryShardAsync(eq(DefaultShardStrategy.DEFAULT_SHARD));
-
- TransactionProxy transactionProxy = new TransactionProxy(mockComponentFactory, WRITE_ONLY);
-
- expectReadyLocalTransaction(shardActorRef, true);
-
- NormalizedNode nodeToWrite = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
- transactionProxy.write(TestModel.TEST_PATH, nodeToWrite);
-
- DOMStoreThreePhaseCommitCohort ready = transactionProxy.ready();
- assertTrue(ready instanceof SingleCommitCohortProxy);
- verifyCohortFutures((SingleCommitCohortProxy)ready, new CommitTransactionReply().toSerializable());
-
- ArgumentCaptor<ReadyLocalTransaction> readyLocalTx = ArgumentCaptor.forClass(ReadyLocalTransaction.class);
- verify(mockActorContext).executeOperationAsync(
- eq(actorSelection(shardActorRef)), readyLocalTx.capture(), any(Timeout.class));
- assertFalse("Participating shards present", readyLocalTx.getValue().getParticipatingShardNames().isPresent());
- }
-
- @Test
- public void testReadyWithLocalTransactionWithFailure() {
- ActorRef shardActorRef = getSystem().actorOf(Props.create(DoNothingActor.class));
-
- doReturn(getSystem().actorSelection(shardActorRef.path())).when(mockActorContext)
- .actorSelection(shardActorRef.path().toString());
-
- DataTree mockDataTree = createDataTree();
- DataTreeModification mockModification = mockDataTree.takeSnapshot().newModification();
- doThrow(new RuntimeException("mock")).when(mockModification).ready();
-
- doReturn(Futures.successful(newPrimaryShardInfo(shardActorRef, mockDataTree))).when(mockActorContext)
- .findPrimaryShardAsync(eq(DefaultShardStrategy.DEFAULT_SHARD));
-
- TransactionProxy transactionProxy = new TransactionProxy(mockComponentFactory, WRITE_ONLY);
-
- expectReadyLocalTransaction(shardActorRef, true);
-
- NormalizedNode nodeToWrite = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
- transactionProxy.write(TestModel.TEST_PATH, nodeToWrite);
-
- DOMStoreThreePhaseCommitCohort ready = transactionProxy.ready();
- assertTrue(ready instanceof SingleCommitCohortProxy);
- verifyCohortFutures((SingleCommitCohortProxy)ready, RuntimeException.class);
- }
-
- private void testWriteOnlyTxWithFindPrimaryShardFailure(final Exception toThrow) {
- doReturn(Futures.failed(toThrow)).when(mockActorContext).findPrimaryShardAsync(anyString());
-
- TransactionProxy transactionProxy = new TransactionProxy(mockComponentFactory, WRITE_ONLY);
-
- NormalizedNode nodeToWrite = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
-
- transactionProxy.merge(TestModel.TEST_PATH, nodeToWrite);
-
- transactionProxy.write(TestModel.TEST_PATH, nodeToWrite);
-
- transactionProxy.delete(TestModel.TEST_PATH);
-
- DOMStoreThreePhaseCommitCohort ready = transactionProxy.ready();
-
- assertTrue(ready instanceof SingleCommitCohortProxy);
-
- verifyCohortFutures((SingleCommitCohortProxy)ready, toThrow.getClass());
- }
-
- @Test
- public void testWriteOnlyTxWithPrimaryNotFoundException() {
- testWriteOnlyTxWithFindPrimaryShardFailure(new PrimaryNotFoundException("mock"));
- }
-
- @Test
- public void testWriteOnlyTxWithNotInitializedException() {
- testWriteOnlyTxWithFindPrimaryShardFailure(new NotInitializedException("mock"));
- }
-
- @Test
- public void testWriteOnlyTxWithNoShardLeaderException() {
- testWriteOnlyTxWithFindPrimaryShardFailure(new NoShardLeaderException("mock"));
- }
-
- @Test
- public void testReadyWithInvalidReplyMessageType() {
- dataStoreContextBuilder.writeOnlyTransactionOptimizationsEnabled(true);
- ActorRef actorRef1 = setupActorContextWithInitialCreateTransaction(getSystem(), WRITE_ONLY);
-
- ActorRef actorRef2 = setupActorContextWithInitialCreateTransaction(getSystem(), WRITE_ONLY,
- TestModel.JUNK_QNAME.getLocalName());
-
- doReturn(Futures.successful(new Object())).when(mockActorContext).executeOperationAsync(
- eq(actorSelection(actorRef1)), isA(BatchedModifications.class), any(Timeout.class));
-
- expectBatchedModificationsReady(actorRef2);
-
- TransactionProxy transactionProxy = new TransactionProxy(mockComponentFactory, WRITE_ONLY);
-
- transactionProxy.write(TestModel.JUNK_PATH, ImmutableNodes.containerNode(TestModel.JUNK_QNAME));
- transactionProxy.write(TestModel.TEST_PATH, ImmutableNodes.containerNode(TestModel.TEST_QNAME));
-
- DOMStoreThreePhaseCommitCohort ready = transactionProxy.ready();
-
- assertTrue(ready instanceof ThreePhaseCommitCohortProxy);
-
- verifyCohortFutures((ThreePhaseCommitCohortProxy)ready, actorSelection(actorRef2),
- IllegalArgumentException.class);
- }
-
- @Test
- public void testGetIdentifier() {
- setupActorContextWithInitialCreateTransaction(getSystem(), READ_ONLY);
- TransactionProxy transactionProxy = new TransactionProxy(mockComponentFactory, READ_ONLY);
-
- Object id = transactionProxy.getIdentifier();
- assertNotNull("getIdentifier returned null", id);
- assertTrue("Invalid identifier: " + id, id.toString().contains(memberName));
- }
-
- @Test
- public void testClose() {
- ActorRef actorRef = setupActorContextWithInitialCreateTransaction(getSystem(), READ_WRITE);
-
- doReturn(readDataReply(null)).when(mockActorContext).executeOperationAsync(
- eq(actorSelection(actorRef)), eqReadData(), any(Timeout.class));
-
- TransactionProxy transactionProxy = new TransactionProxy(mockComponentFactory, READ_WRITE);
-
- transactionProxy.read(TestModel.TEST_PATH);
-
- transactionProxy.close();
-
- verify(mockActorContext).sendOperationAsync(
- eq(actorSelection(actorRef)), isA(CloseTransaction.class));
- }
-
- private interface TransactionProxyOperation {
- void run(TransactionProxy transactionProxy);
- }
-
- private PrimaryShardInfo newPrimaryShardInfo(final ActorRef actorRef) {
- return new PrimaryShardInfo(getSystem().actorSelection(actorRef.path()), DataStoreVersions.CURRENT_VERSION);
- }
-
- private PrimaryShardInfo newPrimaryShardInfo(final ActorRef actorRef, final DataTree dataTree) {
- return new PrimaryShardInfo(getSystem().actorSelection(actorRef.path()), DataStoreVersions.CURRENT_VERSION,
- dataTree);
- }
-
- private void throttleOperation(final TransactionProxyOperation operation) {
- throttleOperation(operation, 1, true);
- }
-
- private void throttleOperation(final TransactionProxyOperation operation, final int outstandingOpsLimit,
- final boolean shardFound) {
- throttleOperation(operation, outstandingOpsLimit, shardFound, TimeUnit.MILLISECONDS.toNanos(
- mockActorContext.getDatastoreContext().getOperationTimeoutInMillis()));
- }
-
- private void throttleOperation(final TransactionProxyOperation operation, final int outstandingOpsLimit,
- final boolean shardFound, final long expectedCompletionTime) {
- ActorSystem actorSystem = getSystem();
- ActorRef shardActorRef = actorSystem.actorOf(Props.create(DoNothingActor.class));
-
- // Note that we setting batchedModificationCount to one less than what we need because in TransactionProxy
- // we now allow one extra permit to be allowed for ready
- doReturn(dataStoreContextBuilder.operationTimeoutInSeconds(2)
- .shardBatchedModificationCount(outstandingOpsLimit - 1).build()).when(mockActorContext)
- .getDatastoreContext();
-
- doReturn(actorSystem.actorSelection(shardActorRef.path())).when(mockActorContext)
- .actorSelection(shardActorRef.path().toString());
-
- if (shardFound) {
- doReturn(Futures.successful(newPrimaryShardInfo(shardActorRef))).when(mockActorContext)
- .findPrimaryShardAsync(eq(DefaultShardStrategy.DEFAULT_SHARD));
- doReturn(Futures.successful(newPrimaryShardInfo(shardActorRef))).when(mockActorContext)
- .findPrimaryShardAsync(eq("cars"));
-
- } else {
- doReturn(Futures.failed(new Exception("not found")))
- .when(mockActorContext).findPrimaryShardAsync(eq(DefaultShardStrategy.DEFAULT_SHARD));
- }
-
- doReturn(incompleteFuture()).when(mockActorContext).executeOperationAsync(
- eq(actorSystem.actorSelection(shardActorRef.path())), eqCreateTransaction(memberName, READ_WRITE),
- any(Timeout.class));
-
- TransactionProxy transactionProxy = new TransactionProxy(mockComponentFactory, READ_WRITE);
-
- long start = System.nanoTime();
-
- operation.run(transactionProxy);
-
- long end = System.nanoTime();
-
- Assert.assertTrue(String.format("Expected elapsed time: %s. Actual: %s",
- expectedCompletionTime, end - start),
- end - start > expectedCompletionTime && end - start < expectedCompletionTime * 2);
-
- }
-
- private void completeOperation(final TransactionProxyOperation operation) {
- completeOperation(operation, true);
- }
-
- private void completeOperation(final TransactionProxyOperation operation, final boolean shardFound) {
- ActorSystem actorSystem = getSystem();
- ActorRef shardActorRef = actorSystem.actorOf(Props.create(DoNothingActor.class));
-
- doReturn(actorSystem.actorSelection(shardActorRef.path())).when(mockActorContext)
- .actorSelection(shardActorRef.path().toString());
-
- if (shardFound) {
- doReturn(Futures.successful(newPrimaryShardInfo(shardActorRef))).when(mockActorContext)
- .findPrimaryShardAsync(eq(DefaultShardStrategy.DEFAULT_SHARD));
- } else {
- doReturn(Futures.failed(new PrimaryNotFoundException("test"))).when(mockActorContext)
- .findPrimaryShardAsync(eq(DefaultShardStrategy.DEFAULT_SHARD));
- }
-
- ActorRef txActorRef = actorSystem.actorOf(Props.create(DoNothingActor.class));
- String actorPath = txActorRef.path().toString();
- CreateTransactionReply createTransactionReply = new CreateTransactionReply(actorPath, nextTransactionId(),
- DataStoreVersions.CURRENT_VERSION);
-
- doReturn(actorSystem.actorSelection(actorPath)).when(mockActorContext).actorSelection(actorPath);
-
- doReturn(Futures.successful(createTransactionReply)).when(mockActorContext).executeOperationAsync(
- eq(actorSystem.actorSelection(shardActorRef.path())), eqCreateTransaction(memberName, READ_WRITE),
- any(Timeout.class));
-
- TransactionProxy transactionProxy = new TransactionProxy(mockComponentFactory, READ_WRITE);
-
- long start = System.nanoTime();
-
- operation.run(transactionProxy);
-
- long end = System.nanoTime();
-
- long expected = TimeUnit.MILLISECONDS.toNanos(mockActorContext.getDatastoreContext()
- .getOperationTimeoutInMillis());
- Assert.assertTrue(String.format("Expected elapsed time: %s. Actual: %s",
- expected, end - start), end - start <= expected);
- }
-
- private void completeOperationLocal(final TransactionProxyOperation operation, final DataTree dataTree) {
- ActorSystem actorSystem = getSystem();
- ActorRef shardActorRef = actorSystem.actorOf(Props.create(DoNothingActor.class));
-
- doReturn(actorSystem.actorSelection(shardActorRef.path())).when(mockActorContext)
- .actorSelection(shardActorRef.path().toString());
-
- doReturn(Futures.successful(newPrimaryShardInfo(shardActorRef, dataTree))).when(mockActorContext)
- .findPrimaryShardAsync(eq(DefaultShardStrategy.DEFAULT_SHARD));
-
- TransactionProxy transactionProxy = new TransactionProxy(mockComponentFactory, READ_WRITE);
-
- long start = System.nanoTime();
-
- operation.run(transactionProxy);
-
- long end = System.nanoTime();
-
- long expected = TimeUnit.MILLISECONDS.toNanos(mockActorContext.getDatastoreContext()
- .getOperationTimeoutInMillis());
- Assert.assertTrue(String.format("Expected elapsed time: %s. Actual: %s", expected, end - start),
- end - start <= expected);
- }
-
- private static DataTree createDataTree() {
- DataTree dataTree = mock(DataTree.class);
- DataTreeSnapshot dataTreeSnapshot = mock(DataTreeSnapshot.class);
- DataTreeModification dataTreeModification = mock(DataTreeModification.class);
-
- doReturn(dataTreeSnapshot).when(dataTree).takeSnapshot();
- doReturn(dataTreeModification).when(dataTreeSnapshot).newModification();
-
- return dataTree;
- }
-
- private static DataTree createDataTree(final NormalizedNode readResponse) {
- DataTree dataTree = mock(DataTree.class);
- DataTreeSnapshot dataTreeSnapshot = mock(DataTreeSnapshot.class);
- DataTreeModification dataTreeModification = mock(DataTreeModification.class);
-
- doReturn(dataTreeSnapshot).when(dataTree).takeSnapshot();
- doReturn(dataTreeModification).when(dataTreeSnapshot).newModification();
- doReturn(Optional.of(readResponse)).when(dataTreeModification).readNode(any(YangInstanceIdentifier.class));
-
- return dataTree;
- }
-
-
- @Test
- public void testWriteCompletionForLocalShard() {
- completeOperationLocal(transactionProxy -> {
- NormalizedNode nodeToWrite = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
-
- transactionProxy.write(TestModel.TEST_PATH, nodeToWrite);
-
- transactionProxy.write(TestModel.TEST_PATH, nodeToWrite);
-
- }, createDataTree());
- }
-
- @Test
- public void testWriteThrottlingWhenShardFound() {
- throttleOperation(transactionProxy -> {
- NormalizedNode nodeToWrite = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
-
- expectIncompleteBatchedModifications();
-
- transactionProxy.write(TestModel.TEST_PATH, nodeToWrite);
-
- transactionProxy.write(TestModel.TEST_PATH, nodeToWrite);
- });
- }
-
- @Test
- public void testWriteThrottlingWhenShardNotFound() {
- // Confirm that there is no throttling when the Shard is not found
- completeOperation(transactionProxy -> {
- NormalizedNode nodeToWrite = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
-
- expectBatchedModifications(2);
-
- transactionProxy.write(TestModel.TEST_PATH, nodeToWrite);
-
- transactionProxy.write(TestModel.TEST_PATH, nodeToWrite);
- }, false);
-
- }
-
-
- @Test
- public void testWriteCompletion() {
- completeOperation(transactionProxy -> {
- NormalizedNode nodeToWrite = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
-
- expectBatchedModifications(2);
-
- transactionProxy.write(TestModel.TEST_PATH, nodeToWrite);
-
- transactionProxy.write(TestModel.TEST_PATH, nodeToWrite);
- });
- }
-
- @Test
- public void testMergeThrottlingWhenShardFound() {
- throttleOperation(transactionProxy -> {
- NormalizedNode nodeToMerge = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
-
- expectIncompleteBatchedModifications();
-
- transactionProxy.merge(TestModel.TEST_PATH, nodeToMerge);
-
- transactionProxy.merge(TestModel.TEST_PATH, nodeToMerge);
- });
- }
-
- @Test
- public void testMergeThrottlingWhenShardNotFound() {
- completeOperation(transactionProxy -> {
- NormalizedNode nodeToMerge = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
-
- expectBatchedModifications(2);
-
- transactionProxy.merge(TestModel.TEST_PATH, nodeToMerge);
-
- transactionProxy.merge(TestModel.TEST_PATH, nodeToMerge);
- }, false);
- }
-
- @Test
- public void testMergeCompletion() {
- completeOperation(transactionProxy -> {
- NormalizedNode nodeToMerge = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
-
- expectBatchedModifications(2);
-
- transactionProxy.merge(TestModel.TEST_PATH, nodeToMerge);
-
- transactionProxy.merge(TestModel.TEST_PATH, nodeToMerge);
- });
-
- }
-
- @Test
- public void testMergeCompletionForLocalShard() {
- completeOperationLocal(transactionProxy -> {
- NormalizedNode nodeToWrite = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
-
- transactionProxy.merge(TestModel.TEST_PATH, nodeToWrite);
-
- transactionProxy.merge(TestModel.TEST_PATH, nodeToWrite);
-
- }, createDataTree());
- }
-
-
- @Test
- public void testDeleteThrottlingWhenShardFound() {
-
- throttleOperation(transactionProxy -> {
- expectIncompleteBatchedModifications();
-
- transactionProxy.delete(TestModel.TEST_PATH);
-
- transactionProxy.delete(TestModel.TEST_PATH);
- });
- }
-
-
- @Test
- public void testDeleteThrottlingWhenShardNotFound() {
-
- completeOperation(transactionProxy -> {
- expectBatchedModifications(2);
-
- transactionProxy.delete(TestModel.TEST_PATH);
-
- transactionProxy.delete(TestModel.TEST_PATH);
- }, false);
- }
-
- @Test
- public void testDeleteCompletionForLocalShard() {
- completeOperationLocal(transactionProxy -> {
-
- transactionProxy.delete(TestModel.TEST_PATH);
-
- transactionProxy.delete(TestModel.TEST_PATH);
- }, createDataTree());
-
- }
-
- @Test
- public void testDeleteCompletion() {
- completeOperation(transactionProxy -> {
- expectBatchedModifications(2);
-
- transactionProxy.delete(TestModel.TEST_PATH);
-
- transactionProxy.delete(TestModel.TEST_PATH);
- });
-
- }
-
- @Test
- public void testReadThrottlingWhenShardFound() {
-
- throttleOperation(transactionProxy -> {
- doReturn(incompleteFuture()).when(mockActorContext).executeOperationAsync(
- any(ActorSelection.class), eqReadData());
-
- transactionProxy.read(TestModel.TEST_PATH);
-
- transactionProxy.read(TestModel.TEST_PATH);
- });
- }
-
- @Test
- public void testReadThrottlingWhenShardNotFound() {
-
- completeOperation(transactionProxy -> {
- doReturn(incompleteFuture()).when(mockActorContext).executeOperationAsync(
- any(ActorSelection.class), eqReadData());
-
- transactionProxy.read(TestModel.TEST_PATH);
-
- transactionProxy.read(TestModel.TEST_PATH);
- }, false);
- }
-
-
- @Test
- public void testReadCompletion() {
- completeOperation(transactionProxy -> {
- NormalizedNode nodeToRead = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
-
- doReturn(readDataReply(nodeToRead)).when(mockActorContext).executeOperationAsync(
- any(ActorSelection.class), eqReadData(), any(Timeout.class));
-
- transactionProxy.read(TestModel.TEST_PATH);
-
- transactionProxy.read(TestModel.TEST_PATH);
- });
-
- }
-
- @Test
- public void testReadCompletionForLocalShard() {
- final NormalizedNode nodeToRead = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
- completeOperationLocal(transactionProxy -> {
- transactionProxy.read(TestModel.TEST_PATH);
-
- transactionProxy.read(TestModel.TEST_PATH);
- }, createDataTree(nodeToRead));
-
- }
-
- @Test
- public void testReadCompletionForLocalShardWhenExceptionOccurs() {
- completeOperationLocal(transactionProxy -> {
- transactionProxy.read(TestModel.TEST_PATH);
-
- transactionProxy.read(TestModel.TEST_PATH);
- }, createDataTree());
-
- }
-
- @Test
- public void testExistsThrottlingWhenShardFound() {
-
- throttleOperation(transactionProxy -> {
- doReturn(incompleteFuture()).when(mockActorContext).executeOperationAsync(
- any(ActorSelection.class), eqDataExists());
-
- transactionProxy.exists(TestModel.TEST_PATH);
-
- transactionProxy.exists(TestModel.TEST_PATH);
- });
- }
-
- @Test
- public void testExistsThrottlingWhenShardNotFound() {
-
- completeOperation(transactionProxy -> {
- doReturn(incompleteFuture()).when(mockActorContext).executeOperationAsync(
- any(ActorSelection.class), eqDataExists());
-
- transactionProxy.exists(TestModel.TEST_PATH);
-
- transactionProxy.exists(TestModel.TEST_PATH);
- }, false);
- }
-
-
- @Test
- public void testExistsCompletion() {
- completeOperation(transactionProxy -> {
- doReturn(dataExistsReply(true)).when(mockActorContext).executeOperationAsync(
- any(ActorSelection.class), eqDataExists(), any(Timeout.class));
-
- transactionProxy.exists(TestModel.TEST_PATH);
-
- transactionProxy.exists(TestModel.TEST_PATH);
- });
-
- }
-
- @Test
- public void testExistsCompletionForLocalShard() {
- final NormalizedNode nodeToRead = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
- completeOperationLocal(transactionProxy -> {
- transactionProxy.exists(TestModel.TEST_PATH);
-
- transactionProxy.exists(TestModel.TEST_PATH);
- }, createDataTree(nodeToRead));
-
- }
-
- @Test
- public void testExistsCompletionForLocalShardWhenExceptionOccurs() {
- completeOperationLocal(transactionProxy -> {
- transactionProxy.exists(TestModel.TEST_PATH);
-
- transactionProxy.exists(TestModel.TEST_PATH);
- }, createDataTree());
-
- }
-
- @Test
- public void testReadyThrottling() {
-
- throttleOperation(transactionProxy -> {
- NormalizedNode nodeToWrite = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
-
- expectBatchedModifications(1);
-
- transactionProxy.write(TestModel.TEST_PATH, nodeToWrite);
-
- transactionProxy.ready();
- });
- }
-
- @Test
- public void testReadyThrottlingWithTwoTransactionContexts() {
- throttleOperation(transactionProxy -> {
- NormalizedNode nodeToWrite = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
- NormalizedNode carsNode = ImmutableNodes.containerNode(CarsModel.BASE_QNAME);
-
- expectBatchedModifications(2);
-
- transactionProxy.write(TestModel.TEST_PATH, nodeToWrite);
-
- // Trying to write to Cars will cause another transaction context to get created
- transactionProxy.write(CarsModel.BASE_PATH, carsNode);
-
- // Now ready should block for both transaction contexts
- transactionProxy.ready();
- }, 1, true, TimeUnit.MILLISECONDS.toNanos(mockActorContext.getDatastoreContext()
- .getOperationTimeoutInMillis()) * 2);
- }
-
- private void testModificationOperationBatching(final TransactionType type) {
- int shardBatchedModificationCount = 3;
- dataStoreContextBuilder.shardBatchedModificationCount(shardBatchedModificationCount);
-
- ActorRef actorRef = setupActorContextWithInitialCreateTransaction(getSystem(), type);
-
- expectBatchedModifications(actorRef, shardBatchedModificationCount);
-
- YangInstanceIdentifier writePath1 = TestModel.TEST_PATH;
- NormalizedNode writeNode1 = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
-
- YangInstanceIdentifier writePath2 = TestModel.OUTER_LIST_PATH;
- NormalizedNode writeNode2 = ImmutableNodes.containerNode(TestModel.OUTER_LIST_QNAME);
-
- YangInstanceIdentifier writePath3 = TestModel.INNER_LIST_PATH;
- NormalizedNode writeNode3 = ImmutableNodes.containerNode(TestModel.INNER_LIST_QNAME);
-
- YangInstanceIdentifier mergePath1 = TestModel.TEST_PATH;
- NormalizedNode mergeNode1 = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
-
- YangInstanceIdentifier mergePath2 = TestModel.OUTER_LIST_PATH;
- NormalizedNode mergeNode2 = ImmutableNodes.containerNode(TestModel.OUTER_LIST_QNAME);
-
- YangInstanceIdentifier mergePath3 = TestModel.INNER_LIST_PATH;
- NormalizedNode mergeNode3 = ImmutableNodes.containerNode(TestModel.INNER_LIST_QNAME);
-
- YangInstanceIdentifier deletePath1 = TestModel.TEST_PATH;
- YangInstanceIdentifier deletePath2 = TestModel.OUTER_LIST_PATH;
-
- TransactionProxy transactionProxy = new TransactionProxy(mockComponentFactory, type);
-
- transactionProxy.write(writePath1, writeNode1);
- transactionProxy.write(writePath2, writeNode2);
- transactionProxy.delete(deletePath1);
- transactionProxy.merge(mergePath1, mergeNode1);
- transactionProxy.merge(mergePath2, mergeNode2);
- transactionProxy.write(writePath3, writeNode3);
- transactionProxy.merge(mergePath3, mergeNode3);
- transactionProxy.delete(deletePath2);
-
- // This sends the last batch.
- transactionProxy.ready();
-
- List<BatchedModifications> batchedModifications = captureBatchedModifications(actorRef);
- assertEquals("Captured BatchedModifications count", 3, batchedModifications.size());
-
- verifyBatchedModifications(batchedModifications.get(0), false, new WriteModification(writePath1, writeNode1),
- new WriteModification(writePath2, writeNode2), new DeleteModification(deletePath1));
-
- verifyBatchedModifications(batchedModifications.get(1), false, new MergeModification(mergePath1, mergeNode1),
- new MergeModification(mergePath2, mergeNode2), new WriteModification(writePath3, writeNode3));
-
- verifyBatchedModifications(batchedModifications.get(2), true, true,
- new MergeModification(mergePath3, mergeNode3), new DeleteModification(deletePath2));
-
- assertEquals("getTotalMessageCount", 3, batchedModifications.get(2).getTotalMessagesSent());
- }
-
- @Test
- public void testReadWriteModificationOperationBatching() {
- testModificationOperationBatching(READ_WRITE);
- }
-
- @Test
- public void testWriteOnlyModificationOperationBatching() {
- testModificationOperationBatching(WRITE_ONLY);
- }
-
- @Test
- public void testOptimizedWriteOnlyModificationOperationBatching() {
- dataStoreContextBuilder.writeOnlyTransactionOptimizationsEnabled(true);
- testModificationOperationBatching(WRITE_ONLY);
- }
-
- @Test
- public void testModificationOperationBatchingWithInterleavedReads() throws Exception {
-
- int shardBatchedModificationCount = 10;
- dataStoreContextBuilder.shardBatchedModificationCount(shardBatchedModificationCount);
-
- ActorRef actorRef = setupActorContextWithInitialCreateTransaction(getSystem(), READ_WRITE);
-
- expectBatchedModifications(actorRef, shardBatchedModificationCount);
-
- final YangInstanceIdentifier writePath1 = TestModel.TEST_PATH;
- final NormalizedNode writeNode1 = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
-
- YangInstanceIdentifier writePath2 = TestModel.OUTER_LIST_PATH;
- NormalizedNode writeNode2 = ImmutableNodes.containerNode(TestModel.OUTER_LIST_QNAME);
-
- final YangInstanceIdentifier mergePath1 = TestModel.TEST_PATH;
- final NormalizedNode mergeNode1 = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
-
- YangInstanceIdentifier mergePath2 = TestModel.INNER_LIST_PATH;
- NormalizedNode mergeNode2 = ImmutableNodes.containerNode(TestModel.INNER_LIST_QNAME);
-
- final YangInstanceIdentifier deletePath = TestModel.OUTER_LIST_PATH;
-
- doReturn(readDataReply(writeNode2)).when(mockActorContext).executeOperationAsync(
- eq(actorSelection(actorRef)), eqReadData(writePath2), any(Timeout.class));
-
- doReturn(readDataReply(mergeNode2)).when(mockActorContext).executeOperationAsync(
- eq(actorSelection(actorRef)), eqReadData(mergePath2), any(Timeout.class));
-
- doReturn(dataExistsReply(true)).when(mockActorContext).executeOperationAsync(
- eq(actorSelection(actorRef)), eqDataExists(), any(Timeout.class));
-
- TransactionProxy transactionProxy = new TransactionProxy(mockComponentFactory, READ_WRITE);
-
- transactionProxy.write(writePath1, writeNode1);
- transactionProxy.write(writePath2, writeNode2);
-
- Optional<NormalizedNode> readOptional = transactionProxy.read(writePath2).get(5, TimeUnit.SECONDS);
-
- assertTrue("NormalizedNode isPresent", readOptional.isPresent());
- assertEquals("Response NormalizedNode", writeNode2, readOptional.get());
-
- transactionProxy.merge(mergePath1, mergeNode1);
- transactionProxy.merge(mergePath2, mergeNode2);
-
- readOptional = transactionProxy.read(mergePath2).get(5, TimeUnit.SECONDS);
-
- transactionProxy.delete(deletePath);
-
- Boolean exists = transactionProxy.exists(TestModel.TEST_PATH).get();
- assertEquals("Exists response", Boolean.TRUE, exists);
-
- assertTrue("NormalizedNode isPresent", readOptional.isPresent());
- assertEquals("Response NormalizedNode", mergeNode2, readOptional.get());
-
- List<BatchedModifications> batchedModifications = captureBatchedModifications(actorRef);
- assertEquals("Captured BatchedModifications count", 3, batchedModifications.size());
-
- verifyBatchedModifications(batchedModifications.get(0), false, new WriteModification(writePath1, writeNode1),
- new WriteModification(writePath2, writeNode2));
-
- verifyBatchedModifications(batchedModifications.get(1), false, new MergeModification(mergePath1, mergeNode1),
- new MergeModification(mergePath2, mergeNode2));
-
- verifyBatchedModifications(batchedModifications.get(2), false, new DeleteModification(deletePath));
-
- InOrder inOrder = Mockito.inOrder(mockActorContext);
- inOrder.verify(mockActorContext).executeOperationAsync(
- eq(actorSelection(actorRef)), isA(BatchedModifications.class), any(Timeout.class));
-
- inOrder.verify(mockActorContext).executeOperationAsync(
- eq(actorSelection(actorRef)), eqReadData(writePath2), any(Timeout.class));
-
- inOrder.verify(mockActorContext).executeOperationAsync(
- eq(actorSelection(actorRef)), isA(BatchedModifications.class), any(Timeout.class));
-
- inOrder.verify(mockActorContext).executeOperationAsync(
- eq(actorSelection(actorRef)), eqReadData(mergePath2), any(Timeout.class));
-
- inOrder.verify(mockActorContext).executeOperationAsync(
- eq(actorSelection(actorRef)), isA(BatchedModifications.class), any(Timeout.class));
-
- inOrder.verify(mockActorContext).executeOperationAsync(
- eq(actorSelection(actorRef)), eqDataExists(), any(Timeout.class));
- }
-
- @Test
- public void testReadRoot() throws InterruptedException, ExecutionException, java.util.concurrent.TimeoutException {
- EffectiveModelContext schemaContext = SchemaContextHelper.full();
- Configuration configuration = mock(Configuration.class);
- doReturn(configuration).when(mockActorContext).getConfiguration();
- doReturn(schemaContext).when(mockActorContext).getSchemaContext();
- doReturn(Sets.newHashSet("test", "cars")).when(configuration).getAllShardNames();
-
- NormalizedNode expectedNode1 = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
- NormalizedNode expectedNode2 = ImmutableNodes.containerNode(CarsModel.CARS_QNAME);
-
- setUpReadData("test", NormalizedNodeAggregatorTest.getRootNode(expectedNode1, schemaContext));
- setUpReadData("cars", NormalizedNodeAggregatorTest.getRootNode(expectedNode2, schemaContext));
-
- doReturn(MemberName.forName(memberName)).when(mockActorContext).getCurrentMemberName();
-
- doReturn(getSystem().dispatchers().defaultGlobalDispatcher()).when(mockActorContext).getClientDispatcher();
-
- TransactionProxy transactionProxy = new TransactionProxy(mockComponentFactory, READ_ONLY);
-
- Optional<NormalizedNode> readOptional = transactionProxy.read(
- YangInstanceIdentifier.empty()).get(5, TimeUnit.SECONDS);
-
- assertTrue("NormalizedNode isPresent", readOptional.isPresent());
-
- NormalizedNode normalizedNode = readOptional.get();
-
- assertTrue("Expect value to be a Collection", normalizedNode.body() instanceof Collection);
-
- @SuppressWarnings("unchecked")
- Collection<NormalizedNode> collection = (Collection<NormalizedNode>) normalizedNode.body();
-
- for (NormalizedNode node : collection) {
- assertTrue("Expected " + node + " to be a ContainerNode", node instanceof ContainerNode);
- }
-
- assertTrue("Child with QName = " + TestModel.TEST_QNAME + " not found",
- NormalizedNodeAggregatorTest.findChildWithQName(collection, TestModel.TEST_QNAME) != null);
-
- assertEquals(expectedNode1, NormalizedNodeAggregatorTest.findChildWithQName(collection, TestModel.TEST_QNAME));
-
- assertTrue("Child with QName = " + CarsModel.BASE_QNAME + " not found",
- NormalizedNodeAggregatorTest.findChildWithQName(collection, CarsModel.BASE_QNAME) != null);
-
- assertEquals(expectedNode2, NormalizedNodeAggregatorTest.findChildWithQName(collection, CarsModel.BASE_QNAME));
- }
-
-
- private void setUpReadData(final String shardName, final NormalizedNode expectedNode) {
- ActorSystem actorSystem = getSystem();
- ActorRef shardActorRef = getSystem().actorOf(Props.create(DoNothingActor.class));
-
- doReturn(getSystem().actorSelection(shardActorRef.path())).when(mockActorContext)
- .actorSelection(shardActorRef.path().toString());
-
- doReturn(primaryShardInfoReply(getSystem(), shardActorRef)).when(mockActorContext)
- .findPrimaryShardAsync(eq(shardName));
-
- ActorRef txActorRef = actorSystem.actorOf(Props.create(DoNothingActor.class));
-
- doReturn(actorSystem.actorSelection(txActorRef.path())).when(mockActorContext)
- .actorSelection(txActorRef.path().toString());
-
- doReturn(Futures.successful(createTransactionReply(txActorRef, DataStoreVersions.CURRENT_VERSION)))
- .when(mockActorContext).executeOperationAsync(eq(actorSystem.actorSelection(shardActorRef.path())),
- eqCreateTransaction(memberName, TransactionType.READ_ONLY), any(Timeout.class));
-
- doReturn(readDataReply(expectedNode)).when(mockActorContext).executeOperationAsync(
- eq(actorSelection(txActorRef)), eqReadData(YangInstanceIdentifier.empty()), any(Timeout.class));
- }
-}
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
-
package org.opendaylight.controller.cluster.datastore;
import com.codahale.metrics.Timer;
* TransactionRateLimitingCallback computes the new transaction rate limit on the successful completion of a
* transaction.
*/
-public class TransactionRateLimitingCallback implements OperationCallback {
+@Deprecated(since = "9.0.0", forRemoval = true)
+final class TransactionRateLimitingCallback implements OperationCallback {
private static Ticker TICKER = Ticker.systemTicker();
private enum State {
private long elapsedTime;
private volatile State state = State.STOPPED;
- TransactionRateLimitingCallback(ActorUtils actorUtils) {
+ TransactionRateLimitingCallback(final ActorUtils actorUtils) {
commitTimer = actorUtils.getOperationTimer(ActorUtils.COMMIT);
}
}
@VisibleForTesting
- static void setTicker(Ticker ticker) {
+ static void setTicker(final Ticker ticker) {
TICKER = ticker;
}
}
*
* @author Thomas Pantelis
*/
+@Deprecated(since = "9.0.0", forRemoval = true)
@RunWith(MockitoJUnitRunner.StrictStubs.class)
public class TransactionRateLimitingCallbackTest {
@Mock
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
import akka.actor.ActorRef;
import akka.testkit.javadsl.TestKit;
final ActorRef snapshotActor = getSystem().actorOf(ShardSnapshotActor.props(STREAM_FACTORY), testName);
kit.watch(snapshotActor);
- final NormalizedNode expectedRoot = snapshot.getRootNode().get();
+ final NormalizedNode expectedRoot = snapshot.getRootNode().orElseThrow();
ByteArrayOutputStream installSnapshotStream = withInstallSnapshot ? new ByteArrayOutputStream() : null;
ShardSnapshotActor.requestSnapshot(snapshotActor, snapshot,
}
assertEquals("Deserialized snapshot type", snapshot.getClass(), deserialized.getClass());
-
- final Optional<NormalizedNode> maybeNode = deserialized.getRootNode();
- assertTrue("isPresent", maybeNode.isPresent());
- assertEquals("Root node", expectedRoot, maybeNode.get());
+ assertEquals("Root node", Optional.of(expectedRoot), deserialized.getRootNode());
}
}
import static org.junit.Assert.assertTrue;
import java.io.Serializable;
-import org.apache.commons.lang.SerializationUtils;
+import org.apache.commons.lang3.SerializationUtils;
import org.junit.Test;
import org.opendaylight.controller.cluster.datastore.DataStoreVersions;
*
* @author Thomas Pantelis
*/
+@Deprecated(since = "9.0.0", forRemoval = true)
public class AbortTransactionReplyTest {
-
@Test
public void testSerialization() {
AbortTransactionReply expected = AbortTransactionReply.instance(DataStoreVersions.CURRENT_VERSION);
import static org.junit.Assert.assertTrue;
import java.io.Serializable;
-import org.apache.commons.lang.SerializationUtils;
+import org.apache.commons.lang3.SerializationUtils;
import org.junit.Test;
import org.opendaylight.controller.cluster.datastore.DataStoreVersions;
import org.opendaylight.controller.cluster.datastore.MockIdentifiers;
*
* @author Thomas Pantelis
*/
+@Deprecated(since = "9.0.0", forRemoval = true)
public class AbortTransactionTest {
-
@Test
public void testSerialization() {
AbortTransaction expected = new AbortTransaction(
import java.io.Serializable;
import java.util.Optional;
import java.util.SortedSet;
-import org.apache.commons.lang.SerializationUtils;
+import org.apache.commons.lang3.SerializationUtils;
import org.junit.Test;
import org.opendaylight.controller.cluster.access.concepts.TransactionIdentifier;
import org.opendaylight.controller.cluster.datastore.AbstractTest;
*
* @author Thomas Pantelis
*/
+@Deprecated(since = "9.0.0", forRemoval = true)
public class BatchedModificationsTest extends AbstractTest {
@Test
public void testSerialization() {
import static org.junit.Assert.assertTrue;
import java.io.Serializable;
-import org.apache.commons.lang.SerializationUtils;
+import org.apache.commons.lang3.SerializationUtils;
import org.junit.Test;
import org.opendaylight.controller.cluster.datastore.DataStoreVersions;
*
* @author Thomas Pantelis
*/
+@Deprecated(since = "9.0.0", forRemoval = true)
public class CanCommitTransactionReplyTest {
-
@Test
public void testSerialization() {
testSerialization(CanCommitTransactionReply.yes(DataStoreVersions.CURRENT_VERSION),
CanCommitTransactionReply.class);
}
- private static void testSerialization(CanCommitTransactionReply expected, Class<?> expSerialized) {
+ private static void testSerialization(final CanCommitTransactionReply expected, final Class<?> expSerialized) {
Object serialized = expected.toSerializable();
assertEquals("Serialized type", expSerialized, serialized.getClass());
import static org.junit.Assert.assertTrue;
import java.io.Serializable;
-import org.apache.commons.lang.SerializationUtils;
+import org.apache.commons.lang3.SerializationUtils;
import org.junit.Test;
import org.opendaylight.controller.cluster.datastore.AbstractTest;
import org.opendaylight.controller.cluster.datastore.DataStoreVersions;
*
* @author Thomas Pantelis
*/
+@Deprecated(since = "9.0.0", forRemoval = true)
public class CanCommitTransactionTest extends AbstractTest {
-
@Test
public void testSerialization() {
CanCommitTransaction expected = new CanCommitTransaction(nextTransactionId(),
import static org.junit.Assert.assertTrue;
import java.io.Serializable;
-import org.apache.commons.lang.SerializationUtils;
+import org.apache.commons.lang3.SerializationUtils;
import org.junit.Test;
import org.opendaylight.controller.cluster.datastore.AbstractTest;
import org.opendaylight.controller.cluster.datastore.DataStoreVersions;
*
* @author Thomas Pantelis
*/
+@Deprecated(since = "9.0.0", forRemoval = true)
public class CloseTransactionChainTest extends AbstractTest {
@Test
public void testSerialization() {
import static org.junit.Assert.assertEquals;
import java.io.Serializable;
-import org.apache.commons.lang.SerializationUtils;
+import org.apache.commons.lang3.SerializationUtils;
import org.junit.Test;
import org.opendaylight.controller.cluster.datastore.DataStoreVersions;
*
* @author Thomas Pantelis
*/
+@Deprecated(since = "9.0.0", forRemoval = true)
public class CloseTransactionTest {
@Test
public void testCloseTransactionSerialization() {
import static org.junit.Assert.assertTrue;
import java.io.Serializable;
-import org.apache.commons.lang.SerializationUtils;
+import org.apache.commons.lang3.SerializationUtils;
import org.junit.Test;
import org.opendaylight.controller.cluster.datastore.DataStoreVersions;
*
* @author Thomas Pantelis
*/
+@Deprecated(since = "9.0.0", forRemoval = true)
public class CommitTransactionReplyTest {
-
@Test
public void testSerialization() {
CommitTransactionReply expected = CommitTransactionReply.instance(DataStoreVersions.CURRENT_VERSION);
import static org.junit.Assert.assertTrue;
import java.io.Serializable;
-import org.apache.commons.lang.SerializationUtils;
+import org.apache.commons.lang3.SerializationUtils;
import org.junit.Test;
import org.opendaylight.controller.cluster.datastore.AbstractTest;
import org.opendaylight.controller.cluster.datastore.DataStoreVersions;
*
* @author Thomas Pantelis
*/
+@Deprecated(since = "9.0.0", forRemoval = true)
public class CommitTransactionTest extends AbstractTest {
@Test
import static org.junit.Assert.assertTrue;
import java.io.Serializable;
-import org.apache.commons.lang.SerializationUtils;
+import org.apache.commons.lang3.SerializationUtils;
import org.junit.Test;
import org.opendaylight.controller.cluster.datastore.AbstractTest;
import org.opendaylight.controller.cluster.datastore.DataStoreVersions;
*
* @author Thomas Pantelis
*/
+@Deprecated(since = "9.0.0", forRemoval = true)
public class CreateTransactionReplyTest extends AbstractTest {
-
@Test
public void testSerialization() {
CreateTransactionReply expected = new CreateTransactionReply("txPath", nextTransactionId(),
import static org.junit.Assert.assertTrue;
import java.io.Serializable;
-import org.apache.commons.lang.SerializationUtils;
+import org.apache.commons.lang3.SerializationUtils;
import org.junit.Test;
import org.opendaylight.controller.cluster.datastore.AbstractTest;
import org.opendaylight.controller.cluster.datastore.DataStoreVersions;
*
* @author Thomas Pantelis
*/
+@Deprecated(since = "9.0.0", forRemoval = true)
public class CreateTransactionTest extends AbstractTest {
-
@Test
public void testSerialization() {
CreateTransaction expected = new CreateTransaction(nextTransactionId(), 2, DataStoreVersions.CURRENT_VERSION);
import static org.junit.Assert.assertTrue;
import java.io.Serializable;
-import org.apache.commons.lang.SerializationUtils;
+import org.apache.commons.lang3.SerializationUtils;
import org.junit.Test;
import org.opendaylight.controller.cluster.datastore.DataStoreVersions;
*
* @author Thomas Pantelis
*/
+@Deprecated(since = "9.0.0", forRemoval = true)
public class DataExistsReplyTest {
-
@Test
public void testSerialization() {
DataExistsReply expected = new DataExistsReply(true, DataStoreVersions.CURRENT_VERSION);
import static org.junit.Assert.assertTrue;
import java.io.Serializable;
-import org.apache.commons.lang.SerializationUtils;
+import org.apache.commons.lang3.SerializationUtils;
import org.junit.Test;
import org.opendaylight.controller.cluster.datastore.DataStoreVersions;
import org.opendaylight.controller.md.cluster.datastore.model.TestModel;
*
* @author Thomas Pantelis
*/
+@Deprecated(since = "9.0.0", forRemoval = true)
public class DataExistsTest {
-
@Test
public void testSerialization() {
DataExists expected = new DataExists(TestModel.TEST_PATH, DataStoreVersions.CURRENT_VERSION);
import static org.junit.Assert.assertTrue;
import java.io.Serializable;
-import org.apache.commons.lang.SerializationUtils;
+import org.apache.commons.lang3.SerializationUtils;
import org.junit.Test;
import org.opendaylight.controller.cluster.datastore.DataStoreVersions;
import org.opendaylight.controller.md.cluster.datastore.model.TestModel;
*
* @author Thomas Pantelis
*/
+@Deprecated(since = "9.0.0", forRemoval = true)
public class ReadDataReplyTest {
@Test
import static org.junit.Assert.assertTrue;
import java.io.Serializable;
-import org.apache.commons.lang.SerializationUtils;
+import org.apache.commons.lang3.SerializationUtils;
import org.junit.Test;
import org.opendaylight.controller.cluster.datastore.DataStoreVersions;
import org.opendaylight.controller.md.cluster.datastore.model.TestModel;
*
* @author Thomas Pantelis
*/
+@Deprecated(since = "9.0.0", forRemoval = true)
public class ReadDataTest {
-
@Test
public void testSerialization() {
ReadData expected = new ReadData(TestModel.TEST_PATH, DataStoreVersions.CURRENT_VERSION);
*
* @author Thomas Pantelis
*/
+@Deprecated(since = "9.0.0", forRemoval = true)
public class ReadyLocalTransactionSerializerTest extends AbstractTest {
-
@Test
public void testToAndFromBinary() throws NotSerializableException {
DataTree dataTree = new InMemoryDataTreeFactory().create(
assertEquals("getVersion", DataStoreVersions.CURRENT_VERSION, batched.getVersion());
assertTrue("isReady", batched.isReady());
assertTrue("isDoCommitOnReady", batched.isDoCommitOnReady());
- assertTrue("participatingShardNames present", batched.getParticipatingShardNames().isPresent());
- assertEquals("participatingShardNames", shardNames, batched.getParticipatingShardNames().get());
+ assertEquals("participatingShardNames", Optional.of(shardNames), batched.getParticipatingShardNames());
List<Modification> batchedMods = batched.getModifications();
assertEquals("getModifications size", 2, batchedMods.size());
import static org.junit.Assert.assertEquals;
import java.io.Serializable;
-import org.apache.commons.lang.SerializationUtils;
+import org.apache.commons.lang3.SerializationUtils;
import org.junit.Test;
import org.opendaylight.controller.cluster.datastore.DataStoreVersions;
*
* @author Thomas Pantelis
*/
+@Deprecated(since = "9.0.0", forRemoval = true)
public class ReadyTransactionReplyTest {
@Test
import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
+@Deprecated(since = "9.0.0", forRemoval = true)
public abstract class AbstractModificationTest {
private static EffectiveModelContext TEST_SCHEMA_CONTEXT;
import static org.junit.Assert.assertEquals;
import java.util.Optional;
-import org.apache.commons.lang.SerializationUtils;
+import org.apache.commons.lang3.SerializationUtils;
import org.junit.Test;
import org.opendaylight.controller.md.cluster.datastore.model.TestModel;
import org.opendaylight.mdsal.dom.spi.store.DOMStoreReadWriteTransaction;
import org.opendaylight.mdsal.dom.spi.store.DOMStoreWriteTransaction;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
+@Deprecated(since = "9.0.0", forRemoval = true)
public class DeleteModificationTest extends AbstractModificationTest {
@Test
public void testApply() throws Exception {
DeleteModification expected = new DeleteModification(path);
- DeleteModification clone = (DeleteModification) SerializationUtils.clone(expected);
+ DeleteModification clone = SerializationUtils.clone(expected);
assertEquals("getPath", expected.getPath(), clone.getPath());
}
}
import static org.junit.Assert.assertEquals;
import java.util.Optional;
-import org.apache.commons.lang.SerializationUtils;
+import org.apache.commons.lang3.SerializationUtils;
import org.junit.Test;
import org.opendaylight.controller.md.cluster.datastore.model.TestModel;
import org.opendaylight.mdsal.dom.spi.store.DOMStoreReadWriteTransaction;
import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
+@Deprecated(since = "9.0.0", forRemoval = true)
public class MergeModificationTest extends AbstractModificationTest {
@Test
public void testApply() throws Exception {
.withChild(ImmutableNodes.leafNode(TestModel.DESC_QNAME, "foo"))
.build());
- MergeModification clone = (MergeModification) SerializationUtils.clone(expected);
+ MergeModification clone = SerializationUtils.clone(expected);
assertEquals("getPath", expected.getPath(), clone.getPath());
assertEquals("getData", expected.getData(), clone.getData());
}
import static org.junit.Assert.assertEquals;
-import org.apache.commons.lang.SerializationUtils;
+import org.apache.commons.lang3.SerializationUtils;
import org.junit.Test;
import org.opendaylight.controller.cluster.datastore.DataStoreVersions;
import org.opendaylight.controller.md.cluster.datastore.model.TestModel;
import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
+@Deprecated(since = "9.0.0", forRemoval = true)
public class MutableCompositeModificationTest extends AbstractModificationTest {
@Test
public void testApply() throws Exception {
compositeModification.apply(transaction);
commitTransaction(transaction);
- assertEquals(TestModel.TEST_QNAME, readData(TestModel.TEST_PATH).get().getIdentifier().getNodeType());
+ assertEquals(TestModel.TEST_QNAME, readData(TestModel.TEST_PATH).orElseThrow().name().getNodeType());
}
@Test
YangInstanceIdentifier deletePath = TestModel.TEST_PATH;
MutableCompositeModification compositeModification =
- new MutableCompositeModification(DataStoreVersions.SODIUM_SR1_VERSION);
+ new MutableCompositeModification(DataStoreVersions.POTASSIUM_VERSION);
compositeModification.addModification(new WriteModification(writePath, writeData));
compositeModification.addModification(new MergeModification(mergePath, mergeData));
compositeModification.addModification(new DeleteModification(deletePath));
assertEquals(360, bytes.length);
MutableCompositeModification clone = (MutableCompositeModification) SerializationUtils.deserialize(bytes);
- assertEquals("getVersion", DataStoreVersions.SODIUM_SR1_VERSION, clone.getVersion());
+ assertEquals("getVersion", DataStoreVersions.POTASSIUM_VERSION, clone.getVersion());
assertEquals("getModifications size", 3, clone.getModifications().size());
WriteModification write = (WriteModification)clone.getModifications().get(0);
- assertEquals("getVersion", DataStoreVersions.SODIUM_SR1_VERSION, write.getVersion());
+ assertEquals("getVersion", DataStoreVersions.POTASSIUM_VERSION, write.getVersion());
assertEquals("getPath", writePath, write.getPath());
assertEquals("getData", writeData, write.getData());
MergeModification merge = (MergeModification)clone.getModifications().get(1);
- assertEquals("getVersion", DataStoreVersions.SODIUM_SR1_VERSION, merge.getVersion());
+ assertEquals("getVersion", DataStoreVersions.POTASSIUM_VERSION, merge.getVersion());
assertEquals("getPath", mergePath, merge.getPath());
assertEquals("getData", mergeData, merge.getData());
DeleteModification delete = (DeleteModification)clone.getModifications().get(2);
- assertEquals("getVersion", DataStoreVersions.SODIUM_SR1_VERSION, delete.getVersion());
+ assertEquals("getVersion", DataStoreVersions.POTASSIUM_VERSION, delete.getVersion());
assertEquals("getPath", deletePath, delete.getPath());
}
import static org.junit.Assert.assertEquals;
import java.util.Optional;
-import org.apache.commons.lang.SerializationUtils;
+import org.apache.commons.lang3.SerializationUtils;
import org.junit.Test;
import org.opendaylight.controller.md.cluster.datastore.model.TestModel;
import org.opendaylight.mdsal.dom.spi.store.DOMStoreReadWriteTransaction;
import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
+@Deprecated(since = "9.0.0", forRemoval = true)
public class WriteModificationTest extends AbstractModificationTest {
@Test
public void testApply() throws Exception {
.withChild(ImmutableNodes.leafNode(TestModel.DESC_QNAME, "foo"))
.build());
- WriteModification clone = (WriteModification) SerializationUtils.clone(expected);
+ WriteModification clone = SerializationUtils.clone(expected);
assertEquals("getPath", expected.getPath(), clone.getPath());
assertEquals("getData", expected.getData(), clone.getData());
}
import org.junit.Before;
import org.junit.Test;
import org.opendaylight.controller.cluster.datastore.AbstractTest;
-import org.opendaylight.controller.cluster.datastore.persisted.DataTreeCandidateInputOutput.DataTreeCandidateWithVersion;
+import org.opendaylight.controller.cluster.datastore.persisted.CommitTransactionPayload.CandidateTransaction;
import org.opendaylight.controller.md.cluster.datastore.model.SchemaContextHelper;
import org.opendaylight.controller.md.cluster.datastore.model.TestModel;
import org.opendaylight.yangtools.yang.common.QName;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeWithValue;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
-import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
-import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
+import org.opendaylight.yangtools.yang.data.spi.node.ImmutableNodes;
import org.opendaylight.yangtools.yang.data.tree.api.DataTree;
import org.opendaylight.yangtools.yang.data.tree.api.DataTreeCandidate;
import org.opendaylight.yangtools.yang.data.tree.api.DataTreeCandidateNode;
private static DataTreeCandidateNode findNode(final Collection<DataTreeCandidateNode> nodes,
final PathArgument arg) {
for (DataTreeCandidateNode node : nodes) {
- if (arg.equals(node.getIdentifier())) {
+ if (arg.equals(node.name())) {
return node;
}
}
final Collection<DataTreeCandidateNode> actual) {
// Make sure all expected nodes are there
for (DataTreeCandidateNode exp : expected) {
- final DataTreeCandidateNode act = findNode(actual, exp.getIdentifier());
+ final DataTreeCandidateNode act = findNode(actual, exp.name());
assertNotNull("missing expected child", act);
assertCandidateNodeEquals(exp, act);
}
// Make sure no nodes are present which are not in the expected set
for (DataTreeCandidateNode act : actual) {
- final DataTreeCandidateNode exp = findNode(expected, act.getIdentifier());
+ final DataTreeCandidateNode exp = findNode(expected, act.name());
assertNull("unexpected child", exp);
}
}
- private static void assertCandidateEquals(final DataTreeCandidate expected,
- final DataTreeCandidateWithVersion actual) {
- final DataTreeCandidate candidate = actual.getCandidate();
+ private static void assertCandidateEquals(final DataTreeCandidate expected, final CandidateTransaction actual) {
+ final var candidate = actual.candidate();
assertEquals("root path", expected.getRootPath(), candidate.getRootPath());
assertCandidateNodeEquals(expected.getRootNode(), candidate.getRootNode());
}
private static void assertCandidateNodeEquals(final DataTreeCandidateNode expected,
final DataTreeCandidateNode actual) {
- assertEquals("child type", expected.getModificationType(), actual.getModificationType());
+ assertEquals("child type", expected.modificationType(), actual.modificationType());
- switch (actual.getModificationType()) {
+ switch (actual.modificationType()) {
case DELETE:
case WRITE:
- assertEquals("child identifier", expected.getIdentifier(), actual.getIdentifier());
- assertEquals("child data", expected.getDataAfter(), actual.getDataAfter());
+ assertEquals("child identifier", expected.name(), actual.name());
+ assertEquals("child data", expected.dataAfter(), actual.dataAfter());
break;
case SUBTREE_MODIFIED:
- assertEquals("child identifier", expected.getIdentifier(), actual.getIdentifier());
- assertChildrenEquals(expected.getChildNodes(), actual.getChildNodes());
+ assertEquals("child identifier", expected.name(), actual.name());
+ assertChildrenEquals(expected.childNodes(), actual.childNodes());
break;
case UNMODIFIED:
break;
default:
- fail("Unexpect root type " + actual.getModificationType());
+ fail("Unexpect root type " + actual.modificationType());
break;
}
}
@Before
public void setUp() {
setUpStatic();
- candidate = DataTreeCandidates.fromNormalizedNode(TestModel.TEST_PATH, Builders.containerBuilder()
+ candidate = DataTreeCandidates.fromNormalizedNode(TestModel.TEST_PATH, ImmutableNodes.newContainerBuilder()
.withNodeIdentifier(new NodeIdentifier(TestModel.TEST_QNAME))
.withChild(ImmutableNodes.leafNode(TestModel.DESC_QNAME, "foo"))
.build());
@Test
public void testCandidateSerDes() throws IOException {
final CommitTransactionPayload payload = CommitTransactionPayload.create(nextTransactionId(), candidate);
- assertCandidateEquals(candidate, payload.getCandidate().getValue());
+ assertCandidateEquals(candidate, payload.getCandidate());
}
@Test
public void testPayloadSerDes() throws IOException {
final CommitTransactionPayload payload = CommitTransactionPayload.create(nextTransactionId(), candidate);
- assertCandidateEquals(candidate, SerializationUtils.clone(payload).getCandidate().getValue());
+ assertCandidateEquals(candidate, SerializationUtils.clone(payload).getCandidate());
}
@Test
YangInstanceIdentifier leafSetEntryPath = YangInstanceIdentifier.builder(TestModel.TEST_PATH).node(LEAF_SET)
.node(entryPathArg).build();
- candidate = DataTreeCandidates.fromNormalizedNode(leafSetEntryPath, Builders.leafSetEntryBuilder()
- .withNodeIdentifier(entryPathArg)
- .withValue("one")
- .build());
+ candidate = DataTreeCandidates.fromNormalizedNode(leafSetEntryPath, ImmutableNodes.leafSetEntry(entryPathArg));
CommitTransactionPayload payload = CommitTransactionPayload.create(nextTransactionId(), candidate);
- assertCandidateEquals(candidate, payload.getCandidate().getValue());
+ assertCandidateEquals(candidate, payload.getCandidate());
}
@Test
public void testLeafSetNodeCandidate() throws Exception {
YangInstanceIdentifier leafSetPath = YangInstanceIdentifier.builder(TestModel.TEST_PATH).node(LEAF_SET).build();
- candidate = DataTreeCandidates.fromNormalizedNode(leafSetPath, Builders.leafSetBuilder()
+ candidate = DataTreeCandidates.fromNormalizedNode(leafSetPath, ImmutableNodes.newSystemLeafSetBuilder()
.withNodeIdentifier(new NodeIdentifier(LEAF_SET))
- .withChild(Builders.leafSetEntryBuilder()
- .withNodeIdentifier(new NodeWithValue<>(LEAF_SET, "one"))
- .withValue("one")
- .build())
+ .withChild(ImmutableNodes.leafSetEntry(LEAF_SET, "one"))
.build());
CommitTransactionPayload payload = CommitTransactionPayload.create(nextTransactionId(), candidate);
- assertCandidateEquals(candidate, payload.getCandidate().getValue());
+ assertCandidateEquals(candidate, payload.getCandidate());
}
@Test
public void testOrderedLeafSetNodeCandidate() throws Exception {
YangInstanceIdentifier leafSetPath = YangInstanceIdentifier.builder(TestModel.TEST_PATH).node(LEAF_SET).build();
- candidate = DataTreeCandidates.fromNormalizedNode(leafSetPath, Builders.orderedLeafSetBuilder()
+ candidate = DataTreeCandidates.fromNormalizedNode(leafSetPath, ImmutableNodes.newUserLeafSetBuilder()
.withNodeIdentifier(new NodeIdentifier(LEAF_SET))
- .withChild(Builders.leafSetEntryBuilder()
- .withNodeIdentifier(new NodeWithValue<>(LEAF_SET, "one"))
- .withValue("one")
- .build())
+ .withChild(ImmutableNodes.leafSetEntry(LEAF_SET, "one"))
.build());
CommitTransactionPayload payload = CommitTransactionPayload.create(nextTransactionId(), candidate);
- assertCandidateEquals(candidate, payload.getCandidate().getValue());
+ assertCandidateEquals(candidate, payload.getCandidate());
}
@Test
candidate = DataTreeCandidates.fromNormalizedNode(leafPath,
ImmutableNodes.leafNode(TestModel.DESC_QNAME, "test"));
CommitTransactionPayload payload = CommitTransactionPayload.create(nextTransactionId(), candidate);
- assertCandidateEquals(candidate, payload.getCandidate().getValue());
+ assertCandidateEquals(candidate, payload.getCandidate());
}
@Test
candidate = dataTree.prepare(modification);
CommitTransactionPayload payload = CommitTransactionPayload.create(nextTransactionId(), candidate);
- assertCandidateEquals(candidate, payload.getCandidate().getValue());
+ assertCandidateEquals(candidate, payload.getCandidate());
}
}
@Test
public void testCreateMetadataSnapshotEmptyInput() throws Exception {
final FrontendShardDataTreeSnapshotMetadata emptyOrigSnapshot = createEmptyMetadataSnapshot();
- final FrontendShardDataTreeSnapshotMetadata emptyCopySnapshot = copy(emptyOrigSnapshot, 127);
+ final FrontendShardDataTreeSnapshotMetadata emptyCopySnapshot = copy(emptyOrigSnapshot, 86);
testMetadataSnapshotEqual(emptyOrigSnapshot, emptyCopySnapshot);
}
@Test
public void testSerializeMetadataSnapshotWithOneClient() throws Exception {
final FrontendShardDataTreeSnapshotMetadata origSnapshot = createMetadataSnapshot(1);
- final FrontendShardDataTreeSnapshotMetadata copySnapshot = copy(origSnapshot, 162);
+ final FrontendShardDataTreeSnapshotMetadata copySnapshot = copy(origSnapshot, 121);
testMetadataSnapshotEqual(origSnapshot, copySnapshot);
}
@Test
public void testSerializeMetadataSnapshotWithMoreClients() throws Exception {
final FrontendShardDataTreeSnapshotMetadata origSnapshot = createMetadataSnapshot(5);
- final FrontendShardDataTreeSnapshotMetadata copySnapshot = copy(origSnapshot, 314);
+ final FrontendShardDataTreeSnapshotMetadata copySnapshot = copy(origSnapshot, 273);
testMetadataSnapshotEqual(origSnapshot, copySnapshot);
}
final Map<ClientIdentifier, FrontendClientMetadata> origIdent = new HashMap<>();
final Map<ClientIdentifier, FrontendClientMetadata> copyIdent = new HashMap<>();
- origClientList.forEach(client -> origIdent.put(client.getIdentifier(), client));
- origClientList.forEach(client -> copyIdent.put(client.getIdentifier(), client));
+ origClientList.forEach(client -> origIdent.put(client.clientId(), client));
+ origClientList.forEach(client -> copyIdent.put(client.clientId(), client));
assertTrue(origIdent.keySet().containsAll(copyIdent.keySet()));
assertTrue(copyIdent.keySet().containsAll(origIdent.keySet()));
origIdent.values().forEach(client -> {
- final FrontendClientMetadata copyClient = copyIdent.get(client.getIdentifier());
- testObject(client.getIdentifier(), copyClient.getIdentifier());
+ final var copyClient = copyIdent.get(client.clientId());
+ testObject(client.clientId(), copyClient.clientId());
assertEquals(client.getPurgedHistories(), copyClient.getPurgedHistories());
assertEquals(client.getCurrentHistories(), copyClient.getCurrentHistories());
});
package org.opendaylight.controller.cluster.datastore.persisted;
import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import org.opendaylight.controller.md.cluster.datastore.model.TestModel;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
-import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
-import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
-import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
+import org.opendaylight.yangtools.yang.data.spi.node.ImmutableNodes;
/**
* Unit tests for ShardDataTreeSnapshot.
* @author Thomas Pantelis
*/
public class ShardDataTreeSnapshotTest {
-
@Test
public void testShardDataTreeSnapshotWithNoMetadata() throws Exception {
- ContainerNode expectedNode = Builders.containerBuilder()
+ ContainerNode expectedNode = ImmutableNodes.newContainerBuilder()
.withNodeIdentifier(new NodeIdentifier(TestModel.TEST_QNAME))
.withChild(ImmutableNodes.leafNode(TestModel.DESC_QNAME, "foo")).build();
}
final byte[] bytes = bos.toByteArray();
- assertEquals(236, bytes.length);
+ assertEquals(202, bytes.length);
ShardDataTreeSnapshot deserialized;
try (ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(bytes))) {
deserialized = ShardDataTreeSnapshot.deserialize(in).getSnapshot();
}
- Optional<NormalizedNode> actualNode = deserialized.getRootNode();
- assertTrue("rootNode present", actualNode.isPresent());
- assertEquals("rootNode", expectedNode, actualNode.get());
+ assertEquals("rootNode", Optional.of(expectedNode), deserialized.getRootNode());
assertEquals("Deserialized type", MetadataShardDataTreeSnapshot.class, deserialized.getClass());
assertEquals("Metadata size", 0, ((MetadataShardDataTreeSnapshot)deserialized).getMetadata().size());
}
@Test
public void testShardDataTreeSnapshotWithMetadata() throws Exception {
- ContainerNode expectedNode = Builders.containerBuilder()
+ ContainerNode expectedNode = ImmutableNodes.newContainerBuilder()
.withNodeIdentifier(new NodeIdentifier(TestModel.TEST_QNAME))
.withChild(ImmutableNodes.leafNode(TestModel.DESC_QNAME, "foo")).build();
}
final byte[] bytes = bos.toByteArray();
- assertEquals(384, bytes.length);
+ assertEquals(350, bytes.length);
ShardDataTreeSnapshot deserialized;
try (ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(bytes))) {
deserialized = ShardDataTreeSnapshot.deserialize(in).getSnapshot();
}
- Optional<NormalizedNode> actualNode = deserialized.getRootNode();
- assertTrue("rootNode present", actualNode.isPresent());
- assertEquals("rootNode", expectedNode, actualNode.get());
+ assertEquals("rootNode", Optional.of(expectedNode), deserialized.getRootNode());
assertEquals("Deserialized type", MetadataShardDataTreeSnapshot.class, deserialized.getClass());
assertEquals("Metadata", expMetadata, ((MetadataShardDataTreeSnapshot)deserialized).getMetadata());
}
static class TestShardDataTreeSnapshotMetadata
extends ShardDataTreeSnapshotMetadata<TestShardDataTreeSnapshotMetadata> {
+ @java.io.Serial
private static final long serialVersionUID = 1L;
private final String data;
@Override
public boolean equals(final Object obj) {
- return obj instanceof TestShardDataTreeSnapshotMetadata
- && data.equals(((TestShardDataTreeSnapshotMetadata)obj).data);
+ return obj instanceof TestShardDataTreeSnapshotMetadata other && data.equals(other.data);
}
private static class Proxy implements Externalizable {
import static org.junit.Assert.assertEquals;
import java.util.Arrays;
-import org.apache.commons.lang.SerializationUtils;
+import org.apache.commons.lang3.SerializationUtils;
import org.junit.Test;
/**
public void testSerialization() {
ShardManagerSnapshot expected =
new ShardManagerSnapshot(Arrays.asList("shard1", "shard2"));
- ShardManagerSnapshot cloned = (ShardManagerSnapshot) SerializationUtils.clone(expected);
+ ShardManagerSnapshot cloned = SerializationUtils.clone(expected);
assertEquals("getShardList", expected.getShardList(), cloned.getShardList());
}
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
-import org.apache.commons.lang.SerializationUtils;
+import java.util.Optional;
+import org.apache.commons.lang3.SerializationUtils;
import org.junit.Test;
import org.opendaylight.controller.md.cluster.datastore.model.TestModel;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
.build();
ShardSnapshotState expected = new ShardSnapshotState(new MetadataShardDataTreeSnapshot(expectedNode));
- ShardSnapshotState cloned = (ShardSnapshotState) SerializationUtils.clone(expected);
+ ShardSnapshotState cloned = SerializationUtils.clone(expected);
assertNotNull("getSnapshot is null", cloned.getSnapshot());
assertEquals("getSnapshot type", MetadataShardDataTreeSnapshot.class, cloned.getSnapshot().getClass());
- assertEquals("getRootNode", expectedNode,
- ((MetadataShardDataTreeSnapshot)cloned.getSnapshot()).getRootNode().get());
+ assertEquals("getRootNode", Optional.of(expectedNode),
+ ((MetadataShardDataTreeSnapshot)cloned.getSnapshot()).getRootNode());
}
}
import org.junit.runner.RunWith;
import org.mockito.junit.MockitoJUnitRunner;
import org.opendaylight.controller.cluster.access.concepts.MemberName;
+import org.opendaylight.controller.cluster.databroker.ClientBackedDataStore;
import org.opendaylight.controller.cluster.datastore.AbstractClusterRefActorTest;
-import org.opendaylight.controller.cluster.datastore.AbstractDataStore;
import org.opendaylight.controller.cluster.datastore.ClusterWrapperImpl;
import org.opendaylight.controller.cluster.datastore.DataStoreVersions;
import org.opendaylight.controller.cluster.datastore.DatastoreContext;
}
private TestShardManager.Builder newTestShardMgrBuilder() {
- return TestShardManager.builder(datastoreContextBuilder).distributedDataStore(mock(AbstractDataStore.class));
+ return TestShardManager.builder(datastoreContextBuilder)
+ .distributedDataStore(mock(ClientBackedDataStore.class));
}
private TestShardManager.Builder newTestShardMgrBuilder(final Configuration config) {
- return TestShardManager.builder(datastoreContextBuilder).configuration(config)
- .distributedDataStore(mock(AbstractDataStore.class));
+ return newTestShardMgrBuilder().configuration(config);
}
private Props newShardMgrProps() {
}
private TestShardManager.Builder newTestShardMgrBuilderWithMockShardActor(final ActorRef shardActor) {
- return TestShardManager.builder(datastoreContextBuilder).shardActor(shardActor)
- .distributedDataStore(mock(AbstractDataStore.class));
+ return TestShardManager.builder(datastoreContextBuilder)
+ .shardActor(shardActor)
+ .distributedDataStore(mock(ClientBackedDataStore.class));
}
final ActorRef shardManager = actorFactory.createActor(newPropsShardMgrWithMockShardActor());
shardManager.tell(new UpdateSchemaContext(TEST_SCHEMA_CONTEXT), kit.getRef());
- shardManager.tell(new ActorInitialized(), mockShardActor);
+ shardManager.tell(new ActorInitialized(mockShardActor), ActorRef.noSender());
DataTree mockDataTree = mock(DataTree.class);
shardManager.tell(new ShardLeaderStateChanged(memberId, memberId, mockDataTree,
final ActorRef shardManager = actorFactory.createActor(newPropsShardMgrWithMockShardActor());
shardManager.tell(new UpdateSchemaContext(TEST_SCHEMA_CONTEXT), kit.getRef());
- shardManager.tell(new ActorInitialized(), mockShardActor);
+ shardManager.tell(new ActorInitialized(mockShardActor), ActorRef.noSender());
String memberId2 = "member-2-shard-default-" + shardMrgIDSuffix;
String memberId1 = "member-1-shard-default-" + shardMrgIDSuffix;
final ActorRef shardManager = actorFactory.createActor(newPropsShardMgrWithMockShardActor());
shardManager.tell(new UpdateSchemaContext(TEST_SCHEMA_CONTEXT), kit.getRef());
- shardManager.tell(new ActorInitialized(), mockShardActor);
+ shardManager.tell(new ActorInitialized(mockShardActor), ActorRef.noSender());
String memberId2 = "member-2-shard-default-" + shardMrgIDSuffix;
MockClusterWrapper.sendMemberUp(shardManager, "member-2", kit.getRef().path().toString());
final ActorRef shardManager = actorFactory.createActor(newPropsShardMgrWithMockShardActor());
shardManager.tell(new UpdateSchemaContext(TEST_SCHEMA_CONTEXT), kit.getRef());
- shardManager.tell(new ActorInitialized(), mockShardActor);
+ shardManager.tell(new ActorInitialized(mockShardActor), ActorRef.noSender());
shardManager.tell(new FindPrimary(Shard.DEFAULT_NAME, false), kit.getRef());
final ActorRef shardManager = actorFactory.createActor(newPropsShardMgrWithMockShardActor());
shardManager.tell(new UpdateSchemaContext(TEST_SCHEMA_CONTEXT), kit.getRef());
- shardManager.tell(new ActorInitialized(), mockShardActor);
+ shardManager.tell(new ActorInitialized(mockShardActor), ActorRef.noSender());
String memberId = "member-1-shard-default-" + shardMrgIDSuffix;
shardManager.tell(
kit.expectNoMessage(Duration.ofMillis(150));
- shardManager.tell(new ActorInitialized(), mockShardActor);
+ shardManager.tell(new ActorInitialized(mockShardActor), ActorRef.noSender());
kit.expectNoMessage(Duration.ofMillis(150));
kit.expectMsgClass(Duration.ofSeconds(2), NotInitializedException.class);
- shardManager.tell(new ActorInitialized(), mockShardActor);
+ shardManager.tell(new ActorInitialized(mockShardActor), ActorRef.noSender());
kit.expectNoMessage(Duration.ofMillis(200));
final ActorRef shardManager = actorFactory.createActor(newPropsShardMgrWithMockShardActor());
shardManager.tell(new UpdateSchemaContext(TEST_SCHEMA_CONTEXT), kit.getRef());
- shardManager.tell(new ActorInitialized(), mockShardActor);
+ shardManager.tell(new ActorInitialized(mockShardActor), ActorRef.noSender());
shardManager.tell(new RoleChangeNotification("member-1-shard-default-" + shardMrgIDSuffix, null,
RaftState.Candidate.name()), mockShardActor);
final ActorRef shardManager = actorFactory.createActor(newPropsShardMgrWithMockShardActor());
shardManager.tell(new UpdateSchemaContext(TEST_SCHEMA_CONTEXT), kit.getRef());
- shardManager.tell(new ActorInitialized(), mockShardActor);
+ shardManager.tell(new ActorInitialized(mockShardActor), ActorRef.noSender());
shardManager.tell(new RoleChangeNotification("member-1-shard-default-" + shardMrgIDSuffix, null,
RaftState.IsolatedLeader.name()), mockShardActor);
final ActorRef shardManager = actorFactory.createActor(newPropsShardMgrWithMockShardActor());
shardManager.tell(new UpdateSchemaContext(TEST_SCHEMA_CONTEXT), kit.getRef());
- shardManager.tell(new ActorInitialized(), mockShardActor);
+ shardManager.tell(new ActorInitialized(mockShardActor), ActorRef.noSender());
shardManager.tell(new FindPrimary(Shard.DEFAULT_NAME, true), kit.getRef());
shardManager1.tell(new UpdateSchemaContext(TEST_SCHEMA_CONTEXT), kit.getRef());
shardManager2.tell(new UpdateSchemaContext(TEST_SCHEMA_CONTEXT), kit.getRef());
- shardManager2.tell(new ActorInitialized(), mockShardActor2);
+ shardManager2.tell(new ActorInitialized(mockShardActor2), ActorRef.noSender());
String memberId2 = "member-2-shard-astronauts-" + shardMrgIDSuffix;
short leaderVersion = DataStoreVersions.CURRENT_VERSION - 1;
final TestKit kit = new TestKit(system1);
shardManager1.tell(new UpdateSchemaContext(TEST_SCHEMA_CONTEXT), kit.getRef());
shardManager2.tell(new UpdateSchemaContext(TEST_SCHEMA_CONTEXT), kit.getRef());
- shardManager1.tell(new ActorInitialized(), mockShardActor1);
- shardManager2.tell(new ActorInitialized(), mockShardActor2);
+ shardManager1.tell(new ActorInitialized(mockShardActor1), ActorRef.noSender());
+ shardManager2.tell(new ActorInitialized(mockShardActor1), ActorRef.noSender());
String memberId2 = "member-2-shard-default-" + shardMrgIDSuffix;
String memberId1 = "member-1-shard-default-" + shardMrgIDSuffix;
final TestKit kit = new TestKit(system1);
shardManager1.tell(new UpdateSchemaContext(TEST_SCHEMA_CONTEXT), kit.getRef());
shardManager2.tell(new UpdateSchemaContext(TEST_SCHEMA_CONTEXT), kit.getRef());
- shardManager1.tell(new ActorInitialized(), mockShardActor1);
- shardManager2.tell(new ActorInitialized(), mockShardActor2);
+ shardManager1.tell(new ActorInitialized(mockShardActor1), ActorRef.noSender());
+ shardManager2.tell(new ActorInitialized(mockShardActor2), ActorRef.noSender());
String memberId2 = "member-2-shard-default-" + shardMrgIDSuffix;
String memberId1 = "member-1-shard-default-" + shardMrgIDSuffix;
final TestKit kit256 = new TestKit(system256);
shardManager256.tell(new UpdateSchemaContext(TEST_SCHEMA_CONTEXT), kit256.getRef());
shardManager2.tell(new UpdateSchemaContext(TEST_SCHEMA_CONTEXT), kit256.getRef());
- shardManager256.tell(new ActorInitialized(), mockShardActor256);
- shardManager2.tell(new ActorInitialized(), mockShardActor2);
+ shardManager256.tell(new ActorInitialized(mockShardActor256), ActorRef.noSender());
+ shardManager2.tell(new ActorInitialized(mockShardActor2), ActorRef.noSender());
String memberId256 = "member-256-shard-default-" + shardMrgIDSuffix;
String memberId2 = "member-2-shard-default-" + shardMrgIDSuffix;
final ActorRef shardManager = actorFactory.createActor(newPropsShardMgrWithMockShardActor());
shardManager.tell(new UpdateSchemaContext(TEST_SCHEMA_CONTEXT), kit.getRef());
- shardManager.tell(new ActorInitialized(), mockShardActor);
+ shardManager.tell(new ActorInitialized(mockShardActor), ActorRef.noSender());
shardManager.tell(new FindLocalShard(Shard.DEFAULT_NAME, false), kit.getRef());
Future<Object> future = Patterns.ask(shardManager, new FindLocalShard(Shard.DEFAULT_NAME, true),
new Timeout(5, TimeUnit.SECONDS));
- shardManager.tell(new ActorInitialized(), mockShardActor);
+ shardManager.tell(new ActorInitialized(mockShardActor), ActorRef.noSender());
Object resp = Await.result(future, kit.duration("5 seconds"));
assertTrue("Expected: LocalShardFound, Actual: " + resp, resp instanceof LocalShardFound);
final ActorRef shardManager = actorFactory.createActor(newPropsShardMgrWithMockShardActor());
shardManager.tell(new UpdateSchemaContext(TEST_SCHEMA_CONTEXT), kit.getRef());
- shardManager.tell(new ActorInitialized(), mockShardActor);
+ shardManager.tell(new ActorInitialized(mockShardActor), ActorRef.noSender());
shardManager.tell(new SwitchShardBehavior(mockShardName, RaftState.Leader, 1000), kit.getRef());
newReplicaShardManager.tell(new UpdateSchemaContext(TEST_SCHEMA_CONTEXT), kit.getRef());
leaderShardManager.tell(new UpdateSchemaContext(TEST_SCHEMA_CONTEXT), kit.getRef());
- leaderShardManager.tell(new ActorInitialized(), mockShardLeaderActor);
+ leaderShardManager.tell(new ActorInitialized(mockShardLeaderActor), ActorRef.noSender());
short leaderVersion = DataStoreVersions.CURRENT_VERSION - 1;
leaderShardManager.tell(
.createTestActor(newPropsShardMgrWithMockShardActor(), shardMgrID);
shardManager.tell(new UpdateSchemaContext(TEST_SCHEMA_CONTEXT), kit.getRef());
- shardManager.tell(new ActorInitialized(), mockShardActor);
+ shardManager.tell(new ActorInitialized(mockShardActor), ActorRef.noSender());
String leaderId = "leader-member-shard-default-" + shardMrgIDSuffix;
AddServerReply addServerReply = new AddServerReply(ServerChangeStatus.ALREADY_EXISTS, null);
ActorRef shardManager = actorFactory.createActor(newPropsShardMgrWithMockShardActor());
shardManager.tell(new UpdateSchemaContext(TEST_SCHEMA_CONTEXT), kit.getRef());
- shardManager.tell(new ActorInitialized(), mockShardActor);
+ shardManager.tell(new ActorInitialized(mockShardActor), ActorRef.noSender());
shardManager.tell(new ShardLeaderStateChanged(memberId, memberId, mock(DataTree.class),
DataStoreVersions.CURRENT_VERSION), kit.getRef());
shardManager.tell(
ActorRef shardManager = getSystem().actorOf(newPropsShardMgrWithMockShardActor(respondActor));
shardManager.tell(new UpdateSchemaContext(TEST_SCHEMA_CONTEXT), kit.getRef());
- shardManager.tell(new ActorInitialized(), respondActor);
+ shardManager.tell(new ActorInitialized(respondActor), ActorRef.noSender());
shardManager.tell(new ShardLeaderStateChanged(memberId, memberId, mock(DataTree.class),
DataStoreVersions.CURRENT_VERSION), kit.getRef());
shardManager.tell(
newReplicaShardManager.tell(new UpdateSchemaContext(TEST_SCHEMA_CONTEXT), kit.getRef());
leaderShardManager.tell(new UpdateSchemaContext(TEST_SCHEMA_CONTEXT), kit.getRef());
- leaderShardManager.tell(new ActorInitialized(), mockShardLeaderActor);
- newReplicaShardManager.tell(new ActorInitialized(), mockShardLeaderActor);
+ leaderShardManager.tell(new ActorInitialized(mockShardLeaderActor), ActorRef.noSender());
+ newReplicaShardManager.tell(new ActorInitialized(mockShardLeaderActor), ActorRef.noSender());
short leaderVersion = DataStoreVersions.CURRENT_VERSION - 1;
leaderShardManager.tell(
shardManager.underlyingActor().waitForRecoveryComplete();
shardManager.tell(new UpdateSchemaContext(TEST_SCHEMA_CONTEXT), kit.getRef());
- shardManager.tell(new ActorInitialized(), shard);
+ shardManager.tell(new ActorInitialized(shard), ActorRef.noSender());
waitForShardInitialized(shardManager, "people", kit);
waitForShardInitialized(shardManager, "default", kit);
.addShardActor("shard1", shard1).addShardActor("shard2", shard2).props());
shardManager.tell(new UpdateSchemaContext(TEST_SCHEMA_CONTEXT), kit.getRef());
- shardManager.tell(new ActorInitialized(), shard1);
- shardManager.tell(new ActorInitialized(), shard2);
+ shardManager.tell(new ActorInitialized(shard1), ActorRef.noSender());
+ shardManager.tell(new ActorInitialized(shard2), ActorRef.noSender());
FiniteDuration duration = FiniteDuration.create(5, TimeUnit.SECONDS);
Future<Boolean> stopFuture = Patterns.gracefulStop(shardManager, duration, Shutdown.INSTANCE);
ActorRef shardManager = getSystem().actorOf(newPropsShardMgrWithMockShardActor(respondActor));
shardManager.tell(new UpdateSchemaContext(TEST_SCHEMA_CONTEXT), kit.getRef());
- shardManager.tell(new ActorInitialized(), respondActor);
+ shardManager.tell(new ActorInitialized(respondActor), ActorRef.noSender());
shardManager.tell(new ShardLeaderStateChanged(memberId, memberId, mock(DataTree.class),
DataStoreVersions.CURRENT_VERSION), kit.getRef());
shardManager.tell(
ActorRef shardManager = getSystem().actorOf(newPropsShardMgrWithMockShardActor(respondActor));
shardManager.tell(new UpdateSchemaContext(TEST_SCHEMA_CONTEXT), kit.getRef());
- shardManager.tell(new ActorInitialized(), respondActor);
+ shardManager.tell(new ActorInitialized(respondActor), ActorRef.noSender());
shardManager.tell(new RoleChangeNotification(memberId, null, RaftState.Follower.name()), respondActor);
shardManager.tell(
final ActorRef shardManager = actorFactory.createActor(newPropsShardMgrWithMockShardActor());
shardManager.tell(new UpdateSchemaContext(TEST_SCHEMA_CONTEXT), kit.getRef());
- shardManager.tell(new ActorInitialized(), mockShardActor);
+ shardManager.tell(new ActorInitialized(mockShardActor), ActorRef.noSender());
final Consumer<String> mockCallback = mock(Consumer.class);
shardManager.tell(new RegisterForShardAvailabilityChanges(mockCallback), kit.getRef());
import scala.concurrent.duration.FiniteDuration;
public class ActorUtilsTest extends AbstractActorTest {
-
static final Logger LOG = LoggerFactory.getLogger(ActorUtilsTest.class);
- private static class TestMessage {
+ private static final class TestMessage {
+
}
private static final class MockShardManager extends UntypedAbstractActor {
}
@Override public void onReceive(final Object message) {
- if (message instanceof FindPrimary) {
- FindPrimary fp = (FindPrimary)message;
+ if (message instanceof FindPrimary fp) {
Object resp = findPrimaryResponses.get(fp.getShardName());
if (resp == null) {
LOG.error("No expected FindPrimary response found for shard name {}", fp.getShardName());
ActorUtils actorUtils = new ActorUtils(getSystem(), shardManagerActorRef,
mock(ClusterWrapper.class), mock(Configuration.class));
- Optional<ActorRef> out = actorUtils.findLocalShard("default");
-
- assertEquals(shardActorRef, out.get());
+ assertEquals(Optional.of(shardActorRef), actorUtils.findLocalShard("default"));
testKit.expectNoMessage();
return null;
assertNotNull(actual);
assertTrue("LocalShardDataTree present", actual.getLocalShardDataTree().isPresent());
- assertSame("LocalShardDataTree", mockDataTree, actual.getLocalShardDataTree().get());
+ assertSame("LocalShardDataTree", mockDataTree, actual.getLocalShardDataTree().orElseThrow());
assertTrue("Unexpected PrimaryShardActor path " + actual.getPrimaryShardActor().path(),
expPrimaryPath.endsWith(actual.getPrimaryShardActor().pathString()));
assertEquals("getPrimaryShardVersion", DataStoreVersions.CURRENT_VERSION, actual.getPrimaryShardVersion());
for (int i = 0; i < expPaths.length; i++) {
final DataTreeCandidate candidate = changeList.get(i);
- final Optional<NormalizedNode> maybeDataAfter = candidate.getRootNode().getDataAfter();
- if (!maybeDataAfter.isPresent()) {
+ final NormalizedNode dataAfter = candidate.getRootNode().dataAfter();
+ if (dataAfter == null) {
fail(String.format("Change %d does not contain data after. Actual: %s", i + 1,
- candidate.getRootNode()));
+ candidate.getRootNode()));
}
- final NormalizedNode dataAfter = maybeDataAfter.get();
final Optional<YangInstanceIdentifier> relativePath = expPaths[i].relativeTo(candidate.getRootPath());
if (!relativePath.isPresent()) {
assertEquals(String.format("Change %d does not contain %s. Actual: %s", i + 1, expPaths[i],
- dataAfter), expPaths[i].getLastPathArgument(), dataAfter.getIdentifier());
+ dataAfter), expPaths[i].getLastPathArgument(), dataAfter.name());
} else {
NormalizedNode nextChild = dataAfter;
- for (PathArgument pathArg: relativePath.get().getPathArguments()) {
+ for (PathArgument pathArg: relativePath.orElseThrow().getPathArguments()) {
boolean found = false;
if (nextChild instanceof DistinctNodeContainer) {
Optional<NormalizedNode> maybeChild = ((DistinctNodeContainer)nextChild)
.findChildByArg(pathArg);
if (maybeChild.isPresent()) {
found = true;
- nextChild = maybeChild.get();
+ nextChild = maybeChild.orElseThrow();
}
}
import static org.junit.Assert.assertTrue;
import com.google.common.collect.ImmutableList;
-import com.google.common.util.concurrent.FluentFuture;
import java.util.Collection;
import java.util.Optional;
import java.util.concurrent.ExecutionException;
import org.opendaylight.mdsal.dom.store.inmemory.InMemoryDOMDataStore;
import org.opendaylight.yangtools.yang.common.QName;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
-import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
+import org.opendaylight.yangtools.yang.data.spi.node.ImmutableNodes;
import org.opendaylight.yangtools.yang.data.tree.api.DataValidationFailedException;
import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
@Test
public void testAggregate() throws InterruptedException, ExecutionException, DataValidationFailedException {
EffectiveModelContext schemaContext = SchemaContextHelper.full();
- NormalizedNode expectedNode1 = ImmutableNodes.containerNode(TestModel.TEST_QNAME);
- NormalizedNode expectedNode2 = ImmutableNodes.containerNode(CarsModel.CARS_QNAME);
-
- Optional<NormalizedNode> optional = NormalizedNodeAggregator.aggregate(YangInstanceIdentifier.empty(),
+ NormalizedNode expectedNode1 = ImmutableNodes.newContainerBuilder()
+ .withNodeIdentifier(new NodeIdentifier(TestModel.TEST_QNAME))
+ .build();
+ NormalizedNode expectedNode2 = ImmutableNodes.newContainerBuilder()
+ .withNodeIdentifier(new NodeIdentifier(CarsModel.CARS_QNAME))
+ .build();
+
+ Optional<NormalizedNode> optional = NormalizedNodeAggregator.aggregate(YangInstanceIdentifier.of(),
ImmutableList.of(
Optional.<NormalizedNode>of(getRootNode(expectedNode1, schemaContext)),
Optional.<NormalizedNode>of(getRootNode(expectedNode2, schemaContext))),
schemaContext, LogicalDatastoreType.CONFIGURATION);
- NormalizedNode normalizedNode = optional.get();
+ NormalizedNode normalizedNode = optional.orElseThrow();
assertTrue("Expect value to be a Collection", normalizedNode.body() instanceof Collection);
DOMStoreWriteTransaction writeTransaction = store.newWriteOnlyTransaction();
- writeTransaction.merge(YangInstanceIdentifier.of(moduleNode.getIdentifier().getNodeType()), moduleNode);
+ writeTransaction.merge(YangInstanceIdentifier.of(moduleNode.name().getNodeType()), moduleNode);
DOMStoreThreePhaseCommitCohort ready = writeTransaction.ready();
DOMStoreReadTransaction readTransaction = store.newReadOnlyTransaction();
- FluentFuture<Optional<NormalizedNode>> read = readTransaction.read(YangInstanceIdentifier.empty());
-
- Optional<NormalizedNode> nodeOptional = read.get();
-
- return nodeOptional.get();
+ return readTransaction.read(YangInstanceIdentifier.of()).get().orElseThrow();
}
}
public static NormalizedNode findChildWithQName(final Collection<NormalizedNode> collection,
final QName qname) {
for (NormalizedNode node : collection) {
- if (node.getIdentifier().getNodeType().equals(qname)) {
+ if (node.name().getNodeType().equals(qname)) {
return node;
}
}
verify(mockModification, times(1)).merge(path, normalizedNode);
DataTreeCandidate candidate = getCandidate();
- assertEquals("getModificationType", ModificationType.UNMODIFIED, candidate.getRootNode().getModificationType());
+ assertEquals("getModificationType", ModificationType.UNMODIFIED, candidate.getRootNode().modificationType());
}
@Test
.withChild(outerNode)
.build();
- Optional<NormalizedNode> actual = dataTree.takeSnapshot().readNode(path);
- assertTrue("After pruning present", actual.isPresent());
- assertEquals("After pruning", prunedNode, actual.get());
+ assertEquals("After pruning", Optional.of(prunedNode), dataTree.takeSnapshot().readNode(path));
}
@Test
verify(mockModification, times(1)).merge(path, normalizedNode);
DataTreeCandidate candidate = getCandidate();
- assertEquals("getModificationType", ModificationType.UNMODIFIED, candidate.getRootNode().getModificationType());
+ assertEquals("getModificationType", ModificationType.UNMODIFIED, candidate.getRootNode().modificationType());
}
@Test
localDataTree.validate(mod);
localDataTree.commit(localDataTree.prepare(mod));
- NormalizedNode normalizedNode = dataTree.takeSnapshot().readNode(YangInstanceIdentifier.empty()).get();
- pruningDataTreeModification.write(YangInstanceIdentifier.empty(), normalizedNode);
+ NormalizedNode normalizedNode = dataTree.takeSnapshot().readNode(YangInstanceIdentifier.of()).orElseThrow();
+ pruningDataTreeModification.write(YangInstanceIdentifier.of(), normalizedNode);
dataTree.commit(getCandidate());
- Optional<NormalizedNode> actual = dataTree.takeSnapshot().readNode(YangInstanceIdentifier.empty());
- assertTrue("Root present", actual.isPresent());
- assertEquals("Root node", normalizedNode, actual.get());
+ assertEquals(Optional.of(normalizedNode), dataTree.takeSnapshot().readNode(YangInstanceIdentifier.of()));
}
@Test
final Shard mockShard = Mockito.mock(Shard.class);
ShardDataTree shardDataTree = new ShardDataTree(mockShard, SCHEMA_CONTEXT, TreeType.CONFIGURATION);
- NormalizedNode root = shardDataTree.readNode(YangInstanceIdentifier.empty()).get();
+ NormalizedNode root = shardDataTree.readNode(YangInstanceIdentifier.of()).orElseThrow();
NormalizedNode normalizedNode = Builders.containerBuilder()
- .withNodeIdentifier(new NodeIdentifier(root.getIdentifier().getNodeType()))
+ .withNodeIdentifier(new NodeIdentifier(root.name().getNodeType()))
.withChild(ImmutableNodes.containerNode(AUG_CONTAINER))
.build();
- pruningDataTreeModification.write(YangInstanceIdentifier.empty(), normalizedNode);
+ pruningDataTreeModification.write(YangInstanceIdentifier.of(), normalizedNode);
dataTree.commit(getCandidate());
- Optional<NormalizedNode> actual = dataTree.takeSnapshot().readNode(YangInstanceIdentifier.empty());
- assertEquals("Root present", true, actual.isPresent());
- assertEquals("Root node", root, actual.get());
+ assertEquals(Optional.of(root), dataTree.takeSnapshot().readNode(YangInstanceIdentifier.of()));
}
verify(mockModification, times(1)).write(path, normalizedNode);
DataTreeCandidate candidate = getCandidate();
- assertEquals("getModificationType", ModificationType.UNMODIFIED, candidate.getRootNode().getModificationType());
+ assertEquals("getModificationType", ModificationType.UNMODIFIED, candidate.getRootNode().modificationType());
}
@Test
.withChild(ImmutableNodes.leafNode(NAME_QNAME, "name"))
.build();
- Optional<NormalizedNode> actual = dataTree.takeSnapshot().readNode(path);
- assertTrue("After pruning present", actual.isPresent());
- assertEquals("After pruning", prunedNode, actual.get());
+ assertEquals(Optional.of(prunedNode), dataTree.takeSnapshot().readNode(path));
}
@Test
*/
package org.opendaylight.controller.md.cluster.datastore.model;
-import static org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes.leafNode;
import static org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes.mapEntry;
import static org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes.mapEntryBuilder;
import static org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes.mapNodeBuilder;
+import static org.opendaylight.yangtools.yang.data.spi.node.ImmutableNodes.leafNode;
-import java.util.Set;
import org.opendaylight.yangtools.yang.common.QName;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
-import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
-import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeWithValue;
import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
-import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
+import org.opendaylight.yangtools.yang.data.spi.node.ImmutableNodes;
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
import org.opendaylight.yangtools.yang.test.util.YangParserTestUtils;
}
public static ContainerNode createTestContainer() {
- return Builders.containerBuilder()
+ return ImmutableNodes.newContainerBuilder()
.withNodeIdentifier(new NodeIdentifier(TEST_QNAME))
.withChild(leafNode(DESC_QNAME, DESC))
- .withChild(Builders.augmentationBuilder()
- .withNodeIdentifier(new AugmentationIdentifier(Set.of(AUG_QNAME)))
- .withChild(leafNode(AUG_QNAME, "First Test"))
- .build())
- .withChild(Builders.leafSetBuilder()
+ .withChild(leafNode(AUG_QNAME, "First Test"))
+ .withChild(ImmutableNodes.<String>newSystemLeafSetBuilder()
.withNodeIdentifier(new NodeIdentifier(QName.create(TEST_QNAME, "shoe")))
- .withChild(Builders.leafSetEntryBuilder()
- .withNodeIdentifier(new NodeWithValue<>(QName.create(TEST_QNAME, "shoe"), "nike"))
- .withValue("nike")
- .build())
- .withChild(Builders.leafSetEntryBuilder()
- .withNodeIdentifier(new NodeWithValue<>(QName.create(TEST_QNAME, "shoe"), "puma"))
- .withValue("puma")
- .build())
+ .withChildValue("nike")
+ .withChildValue("puma")
.build())
- .withChild(Builders.leafSetBuilder()
+ .withChild(ImmutableNodes.<Integer>newSystemLeafSetBuilder()
.withNodeIdentifier(new NodeIdentifier(QName.create(TEST_QNAME, "number")))
- .withChild(Builders.leafSetEntryBuilder()
- .withNodeIdentifier(new NodeWithValue<>(QName.create(TEST_QNAME, "number"), 5))
- .withValue(5)
- .build())
- .withChild(Builders.leafSetEntryBuilder()
- .withNodeIdentifier(new NodeWithValue<>(QName.create(TEST_QNAME, "number"), 15))
- .withValue(15)
- .build())
+ .withChildValue(5)
+ .withChildValue(15)
.build())
.withChild(mapNodeBuilder(OUTER_LIST_QNAME)
.withChild(mapEntry(OUTER_LIST_QNAME, ID_QNAME, ONE_ID))
.withChild(leafNode(GRAND_CHILD_NAME_QNAME, FIRST_GRAND_CHILD_NAME))
.build();
- return Builders.containerBuilder()
+ return ImmutableNodes.newContainerBuilder()
.withNodeIdentifier(new NodeIdentifier(FAMILY_QNAME))
.withChild(mapNodeBuilder(CHILDREN_QNAME)
.withChild(mapEntryBuilder(CHILDREN_QNAME, CHILD_NUMBER_QNAME, FIRST_CHILD_ID)
*/
package org.opendaylight.controller.md.cluster.datastore.model;
+import static org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes.mapEntryBuilder;
+
import org.opendaylight.yangtools.yang.common.QName;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
import org.opendaylight.yangtools.yang.data.api.schema.SystemMapNode;
-import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
-import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
+import org.opendaylight.yangtools.yang.data.spi.node.ImmutableNodes;
public final class PeopleModel {
public static final QName BASE_QNAME = QName.create(
}
public static ContainerNode create() {
- return Builders.containerBuilder()
+ return ImmutableNodes.newContainerBuilder()
.withNodeIdentifier(new NodeIdentifier(BASE_QNAME))
- .withChild(Builders.mapBuilder()
+ .withChild(ImmutableNodes.newSystemMapBuilder()
.withNodeIdentifier(new NodeIdentifier(PERSON_QNAME))
// Create an entry for the person jack
- .withChild(ImmutableNodes.mapEntryBuilder(PERSON_QNAME, PERSON_NAME_QNAME, "jack")
+ .withChild(mapEntryBuilder(PERSON_QNAME, PERSON_NAME_QNAME, "jack")
.withChild(ImmutableNodes.leafNode(PERSON_NAME_QNAME, "jack"))
.withChild(ImmutableNodes.leafNode(PERSON_AGE_QNAME, 100L))
.build())
// Create an entry for the person jill
- .withChild(ImmutableNodes.mapEntryBuilder(PERSON_QNAME, PERSON_NAME_QNAME, "jill")
+ .withChild(mapEntryBuilder(PERSON_QNAME, PERSON_NAME_QNAME, "jill")
.withChild(ImmutableNodes.leafNode(PERSON_NAME_QNAME, "jill"))
.withChild(ImmutableNodes.leafNode(PERSON_AGE_QNAME, 200L))
.build())
}
public static ContainerNode emptyContainer() {
- return Builders.containerBuilder()
- .withNodeIdentifier(new NodeIdentifier(BASE_QNAME))
- .build();
+ return ImmutableNodes.newContainerBuilder().withNodeIdentifier(new NodeIdentifier(BASE_QNAME)).build();
}
public static SystemMapNode newPersonMapNode() {
- return ImmutableNodes.mapNodeBuilder(PERSON_QNAME).build();
+ return ImmutableNodes.newSystemMapBuilder().withNodeIdentifier(new NodeIdentifier(PERSON_QNAME)).build();
}
public static MapEntryNode newPersonEntry(final String name) {
- return ImmutableNodes.mapEntryBuilder(PERSON_QNAME, PERSON_NAME_QNAME, name)
+ return mapEntryBuilder(PERSON_QNAME, PERSON_NAME_QNAME, name)
.withChild(ImmutableNodes.leafNode(PERSON_NAME_QNAME, name))
.build();
}
-{"Entries":[{"Entry":[{"Node":[{"Path":"/"},{"ModificationType":"UNMODIFIED"}]}]},{"Entry":[{"Node":[{"Path":"/(urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:test?revision=2014-03-13)test/outer-list"},{"ModificationType":"WRITE"},{"Data":"[ImmutableLeafNode{identifier=(urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:test?revision=2014-03-13)id, body=1}]"}]}]},{"Entry":[{"Node":[{"Path":"/(urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:test?revision=2014-03-13)test/outer-list"},{"ModificationType":"WRITE"},{"Data":"[ImmutableLeafNode{identifier=(urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:test?revision=2014-03-13)id, body=2}]"}]}]},{"Entry":[{"Node":[{"Path":"/(urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:test?revision=2014-03-13)test/outer-list"},{"ModificationType":"WRITE"},{"Data":"[ImmutableLeafNode{identifier=(urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:test?revision=2014-03-13)id, body=3}]"}]}]},{"Entry":[{"Node":[{"Path":"/(urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:test?revision=2014-03-13)test/outer-list"},{"ModificationType":"WRITE"},{"Data":"[ImmutableLeafNode{identifier=(urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:test?revision=2014-03-13)id, body=4}]"}]}]},{"Entry":[{"Node":[{"Path":"/(urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:test?revision=2014-03-13)test/outer-list"},{"ModificationType":"WRITE"},{"Data":"[ImmutableLeafNode{identifier=(urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:test?revision=2014-03-13)id, body=5}]"}]}]},{"Entry":[{"Node":[{"Path":"/(urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:test?revision=2014-03-13)test/outer-list"},{"ModificationType":"WRITE"},{"Data":"[ImmutableLeafNode{identifier=(urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:test?revision=2014-03-13)id, body=6}]"}]}]},{"Entry":[{"Node":[{"Path":"/(urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:test?revision=2014-03-13)test/outer-list"},{"ModificationType":"WRITE"},{"Data":"[ImmutableLeafNode{identifier=(urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:test?revision=2014-03-13)id, body=7}]"}]}]},{"Entry":[{"Node":[{"Path":"/(urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:test?revision=2014-03-13)test/outer-list"},{"ModificationType":"WRITE"},{"Data":"[ImmutableLeafNode{identifier=(urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:test?revision=2014-03-13)id, body=8}]"}]}]},{"Entry":[{"Node":[{"Path":"/(urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:test?revision=2014-03-13)test/outer-list"},{"ModificationType":"WRITE"},{"Data":"[ImmutableLeafNode{identifier=(urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:test?revision=2014-03-13)id, body=9}]"}]}]},{"Entry":[{"Node":[{"Path":"/(urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:test?revision=2014-03-13)test/outer-list"},{"ModificationType":"WRITE"},{"Data":"[ImmutableLeafNode{identifier=(urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:test?revision=2014-03-13)id, body=10}]"}]}]},{"Entry":[{"Node":[{"Path":"/(urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:test?revision=2014-03-13)test/outer-list"},{"ModificationType":"WRITE"},{"Data":"[ImmutableLeafNode{identifier=(urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:test?revision=2014-03-13)id, body=11}]"}]}]},{"Entry":[{"Node":[{"Path":"/(urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:test?revision=2014-03-13)test/outer-list"},{"ModificationType":"WRITE"},{"Data":"[ImmutableLeafNode{identifier=(urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:test?revision=2014-03-13)id, body=12}]"}]}]},{"Entry":[{"Node":[{"Path":"/(urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:test?revision=2014-03-13)test/outer-list"},{"ModificationType":"WRITE"},{"Data":"[ImmutableLeafNode{identifier=(urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:test?revision=2014-03-13)id, body=13}]"}]}]},{"Entry":[{"Node":[{"Path":"/(urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:test?revision=2014-03-13)test/outer-list"},{"ModificationType":"WRITE"},{"Data":"[ImmutableLeafNode{identifier=(urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:test?revision=2014-03-13)id, body=14}]"}]}]},{"Entry":[{"Node":[{"Path":"/(urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:test?revision=2014-03-13)test/outer-list"},{"ModificationType":"WRITE"},{"Data":"[ImmutableLeafNode{identifier=(urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:test?revision=2014-03-13)id, body=15}]"}]}]},{"Entry":[{"Node":[{"Path":"/(urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:test?revision=2014-03-13)test/outer-list"},{"ModificationType":"WRITE"},{"Data":"[ImmutableLeafNode{identifier=(urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:test?revision=2014-03-13)id, body=16}]"}]}]}]}
\ No newline at end of file
+{"Entries":[{"Entry":[{"Node":[{"Path":"/"},{"ModificationType":"UNMODIFIED"}]}]},{"Entry":[{"Node":[{"Path":"/(urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:test?revision=2014-03-13)test/outer-list"},{"ModificationType":"WRITE"},{"Data":"[ImmutableLeafNode{name=(urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:test?revision=2014-03-13)id, body=1}]"}]}]},{"Entry":[{"Node":[{"Path":"/(urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:test?revision=2014-03-13)test/outer-list"},{"ModificationType":"WRITE"},{"Data":"[ImmutableLeafNode{name=(urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:test?revision=2014-03-13)id, body=2}]"}]}]},{"Entry":[{"Node":[{"Path":"/(urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:test?revision=2014-03-13)test/outer-list"},{"ModificationType":"WRITE"},{"Data":"[ImmutableLeafNode{name=(urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:test?revision=2014-03-13)id, body=3}]"}]}]},{"Entry":[{"Node":[{"Path":"/(urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:test?revision=2014-03-13)test/outer-list"},{"ModificationType":"WRITE"},{"Data":"[ImmutableLeafNode{name=(urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:test?revision=2014-03-13)id, body=4}]"}]}]},{"Entry":[{"Node":[{"Path":"/(urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:test?revision=2014-03-13)test/outer-list"},{"ModificationType":"WRITE"},{"Data":"[ImmutableLeafNode{name=(urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:test?revision=2014-03-13)id, body=5}]"}]}]},{"Entry":[{"Node":[{"Path":"/(urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:test?revision=2014-03-13)test/outer-list"},{"ModificationType":"WRITE"},{"Data":"[ImmutableLeafNode{name=(urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:test?revision=2014-03-13)id, body=6}]"}]}]},{"Entry":[{"Node":[{"Path":"/(urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:test?revision=2014-03-13)test/outer-list"},{"ModificationType":"WRITE"},{"Data":"[ImmutableLeafNode{name=(urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:test?revision=2014-03-13)id, body=7}]"}]}]},{"Entry":[{"Node":[{"Path":"/(urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:test?revision=2014-03-13)test/outer-list"},{"ModificationType":"WRITE"},{"Data":"[ImmutableLeafNode{name=(urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:test?revision=2014-03-13)id, body=8}]"}]}]},{"Entry":[{"Node":[{"Path":"/(urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:test?revision=2014-03-13)test/outer-list"},{"ModificationType":"WRITE"},{"Data":"[ImmutableLeafNode{name=(urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:test?revision=2014-03-13)id, body=9}]"}]}]},{"Entry":[{"Node":[{"Path":"/(urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:test?revision=2014-03-13)test/outer-list"},{"ModificationType":"WRITE"},{"Data":"[ImmutableLeafNode{name=(urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:test?revision=2014-03-13)id, body=10}]"}]}]},{"Entry":[{"Node":[{"Path":"/(urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:test?revision=2014-03-13)test/outer-list"},{"ModificationType":"WRITE"},{"Data":"[ImmutableLeafNode{name=(urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:test?revision=2014-03-13)id, body=11}]"}]}]},{"Entry":[{"Node":[{"Path":"/(urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:test?revision=2014-03-13)test/outer-list"},{"ModificationType":"WRITE"},{"Data":"[ImmutableLeafNode{name=(urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:test?revision=2014-03-13)id, body=12}]"}]}]},{"Entry":[{"Node":[{"Path":"/(urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:test?revision=2014-03-13)test/outer-list"},{"ModificationType":"WRITE"},{"Data":"[ImmutableLeafNode{name=(urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:test?revision=2014-03-13)id, body=13}]"}]}]},{"Entry":[{"Node":[{"Path":"/(urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:test?revision=2014-03-13)test/outer-list"},{"ModificationType":"WRITE"},{"Data":"[ImmutableLeafNode{name=(urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:test?revision=2014-03-13)id, body=14}]"}]}]},{"Entry":[{"Node":[{"Path":"/(urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:test?revision=2014-03-13)test/outer-list"},{"ModificationType":"WRITE"},{"Data":"[ImmutableLeafNode{name=(urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:test?revision=2014-03-13)id, body=15}]"}]}]},{"Entry":[{"Node":[{"Path":"/(urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:test?revision=2014-03-13)test/outer-list"},{"ModificationType":"WRITE"},{"Data":"[ImmutableLeafNode{name=(urn:opendaylight:params:xml:ns:yang:controller:md:sal:dom:store:test?revision=2014-03-13)id, body=16}]"}]}]}]}
\ No newline at end of file
]
}
}
-}
\ No newline at end of file
+}
<parent>
<groupId>org.opendaylight.controller</groupId>
<artifactId>mdsal-parent</artifactId>
- <version>7.0.2-SNAPSHOT</version>
+ <version>9.0.3-SNAPSHOT</version>
<relativePath>../parent</relativePath>
</parent>
<parent>
<groupId>org.opendaylight.controller</groupId>
<artifactId>mdsal-parent</artifactId>
- <version>7.0.2-SNAPSHOT</version>
+ <version>9.0.3-SNAPSHOT</version>
<relativePath>../parent</relativePath>
</parent>
<dependencies>
<dependency>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>repackaged-akka</artifactId>
+ <groupId>com.github.spotbugs</groupId>
+ <artifactId>spotbugs-annotations</artifactId>
+ <optional>true</optional>
</dependency>
- <!-- SAL Dependencies -->
<dependency>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>sal-common-util</artifactId>
+ <groupId>com.google.guava</groupId>
+ <artifactId>guava</artifactId>
</dependency>
<dependency>
- <groupId>org.opendaylight.mdsal</groupId>
- <artifactId>mdsal-dom-api</artifactId>
+ <groupId>com.typesafe</groupId>
+ <artifactId>config</artifactId>
</dependency>
<dependency>
- <groupId>org.opendaylight.mdsal</groupId>
- <artifactId>mdsal-dom-spi</artifactId>
+ <groupId>org.eclipse.jdt</groupId>
+ <artifactId>org.eclipse.jdt.annotation</artifactId>
</dependency>
<dependency>
- <groupId>org.opendaylight.controller</groupId>
- <artifactId>sal-clustering-commons</artifactId>
+ <groupId>org.opendaylight.yangtools</groupId>
+ <artifactId>concepts</artifactId>
</dependency>
- <!-- Yang tools-->
<dependency>
<groupId>org.opendaylight.yangtools</groupId>
- <artifactId>yang-data-api</artifactId>
+ <artifactId>yang-common</artifactId>
</dependency>
<dependency>
<groupId>org.opendaylight.yangtools</groupId>
- <artifactId>yang-model-api</artifactId>
+ <artifactId>yang-data-api</artifactId>
</dependency>
<dependency>
<groupId>org.opendaylight.yangtools</groupId>
- <artifactId>yang-data-impl</artifactId>
+ <artifactId>yang-data-codec-binfmt</artifactId>
</dependency>
<dependency>
<groupId>org.opendaylight.yangtools</groupId>
- <artifactId>yang-common</artifactId>
+ <artifactId>yang-model-api</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.opendaylight.controller</groupId>
+ <artifactId>repackaged-akka</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.opendaylight.controller</groupId>
+ <artifactId>sal-common-util</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.opendaylight.mdsal</groupId>
+ <artifactId>mdsal-common-api</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.opendaylight.mdsal</groupId>
+ <artifactId>mdsal-dom-api</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.opendaylight.mdsal</groupId>
+ <artifactId>mdsal-dom-spi</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.opendaylight.controller</groupId>
+ <artifactId>sal-clustering-commons</artifactId>
</dependency>
<dependency>
<groupId>org.osgi</groupId>
<groupId>org.scala-lang</groupId>
<artifactId>scala-library</artifactId>
</dependency>
+
<!-- Test Dependencies -->
<dependency>
<groupId>com.typesafe.akka</groupId>
<version>1.0</version>
<scope>test</scope>
</dependency>
+ <dependency>
+ <groupId>org.apache.commons</groupId>
+ <artifactId>commons-lang3</artifactId>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.opendaylight.yangtools</groupId>
+ <artifactId>util</artifactId>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.opendaylight.yangtools</groupId>
+ <artifactId>yang-data-impl</artifactId>
+ <scope>test</scope>
+ </dependency>
<dependency>
<groupId>org.opendaylight.yangtools</groupId>
<artifactId>yang-test-util</artifactId>
<type>test-jar</type>
<scope>test</scope>
</dependency>
- <dependency>
- <groupId>commons-lang</groupId>
- <artifactId>commons-lang</artifactId>
- <scope>test</scope>
- </dependency>
</dependencies>
<build>
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-@Component(immediate = true, configurationPid = "org.opendaylight.controller.remoterpc")
+@Component(configurationPid = "org.opendaylight.controller.remoterpc")
@Designate(ocd = OSGiRemoteOpsProvider.Config.class)
public final class OSGiRemoteOpsProvider {
@ObjectClassDefinition()
private static final Logger LOG = LoggerFactory.getLogger(OSGiRemoteOpsProvider.class);
- @Reference
- ActorSystemProvider actorSystemProvider = null;
- @Reference
- DOMRpcProviderService rpcProviderService = null;
- @Reference
- DOMRpcService rpcService = null;
- @Reference
- DOMActionProviderService actionProviderService = null;
- @Reference
- DOMActionService actionService = null;
-
private ActorRef opsManager;
@Activate
- void activate(final Config config) {
+ public OSGiRemoteOpsProvider(@Reference final ActorSystemProvider actorSystemProvider,
+ @Reference final DOMRpcProviderService rpcProviderService, @Reference final DOMRpcService rpcService,
+ @Reference final DOMActionProviderService actionProviderService,
+ @Reference final DOMActionService actionService, final Config config) {
LOG.info("Remote Operations service starting");
final ActorSystem actorSystem = actorSystemProvider.getActorSystem();
final RemoteOpsProviderConfig opsConfig = RemoteOpsProviderConfig.newInstance(actorSystem.name(),
import org.opendaylight.mdsal.dom.api.DOMActionService;
import org.opendaylight.mdsal.dom.api.DOMRpcProviderService;
import org.opendaylight.mdsal.dom.api.DOMRpcService;
-import org.opendaylight.yangtools.concepts.ListenerRegistration;
+import org.opendaylight.yangtools.concepts.Registration;
import scala.concurrent.duration.FiniteDuration;
/**
private final DOMActionProviderService actionProvisionRegistry;
private final DOMActionService actionService;
- private ListenerRegistration<OpsListener> listenerReg;
+ private Registration listenerReg;
private ActorRef opsInvoker;
private ActorRef actionRegistry;
private ActorRef rpcRegistry;
this.rpcProvisionRegistry = requireNonNull(rpcProvisionRegistry);
this.rpcServices = requireNonNull(rpcServices);
this.config = requireNonNull(config);
- this.actionProvisionRegistry = requireNonNull(actionProviderService);
+ actionProvisionRegistry = requireNonNull(actionProviderService);
this.actionService = requireNonNull(actionService);
}
import akka.actor.Address;
import akka.actor.Props;
import java.util.ArrayList;
-import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import org.opendaylight.controller.remote.rpc.registry.ActionRegistry.RemoteActionEndpoint;
import org.opendaylight.controller.remote.rpc.registry.RpcRegistry.Messages.UpdateRemoteEndpoints;
import org.opendaylight.controller.remote.rpc.registry.RpcRegistry.RemoteRpcEndpoint;
-import org.opendaylight.mdsal.dom.api.DOMActionImplementation;
import org.opendaylight.mdsal.dom.api.DOMActionProviderService;
-import org.opendaylight.mdsal.dom.api.DOMRpcImplementation;
import org.opendaylight.mdsal.dom.api.DOMRpcProviderService;
-import org.opendaylight.yangtools.concepts.ObjectRegistration;
+import org.opendaylight.yangtools.concepts.Registration;
/**
* Actor handling registration of RPCs and Actions available on remote nodes with the local
* {@link DOMRpcProviderService} and {@link DOMActionProviderService}.
*/
final class OpsRegistrar extends AbstractUntypedActor {
- private final Map<Address, ObjectRegistration<DOMRpcImplementation>> rpcRegs = new HashMap<>();
- private final Map<Address, ObjectRegistration<DOMActionImplementation>> actionRegs = new HashMap<>();
+ private final Map<Address, Registration> rpcRegs = new HashMap<>();
+ private final Map<Address, Registration> actionRegs = new HashMap<>();
private final DOMRpcProviderService rpcProviderService;
private final RemoteOpsProviderConfig config;
private final DOMActionProviderService actionProviderService;
@Override
public void postStop() throws Exception {
- rpcRegs.values().forEach(ObjectRegistration::close);
+ rpcRegs.values().forEach(Registration::close);
rpcRegs.clear();
- actionRegs.values().forEach(ObjectRegistration::close);
+ actionRegs.values().forEach(Registration::close);
actionRegs.clear();
super.postStop();
* Note that when an RPC moves from one remote node to another, we also do not want to expose the gap,
* hence we register all new implementations before closing all registrations.
*/
- final Collection<ObjectRegistration<?>> prevRegs = new ArrayList<>(rpcEndpoints.size());
+ final var prevRegs = new ArrayList<Registration>(rpcEndpoints.size());
for (Entry<Address, Optional<RemoteRpcEndpoint>> e : rpcEndpoints.entrySet()) {
LOG.debug("Updating RPC registrations for {}", e.getKey());
- final ObjectRegistration<DOMRpcImplementation> prevReg;
+ final Registration prevReg;
final Optional<RemoteRpcEndpoint> maybeEndpoint = e.getValue();
if (maybeEndpoint.isPresent()) {
- final RemoteRpcEndpoint endpoint = maybeEndpoint.get();
+ final RemoteRpcEndpoint endpoint = maybeEndpoint.orElseThrow();
final RemoteRpcImplementation impl = new RemoteRpcImplementation(endpoint.getRouter(), config);
prevReg = rpcRegs.put(e.getKey(), rpcProviderService.registerRpcImplementation(impl,
endpoint.getRpcs()));
}
}
- prevRegs.forEach(ObjectRegistration::close);
+ prevRegs.forEach(Registration::close);
}
/**
* Note that when an Action moves from one remote node to another, we also do not want to expose the gap,
* hence we register all new implementations before closing all registrations.
*/
- final Collection<ObjectRegistration<?>> prevRegs = new ArrayList<>(actionEndpoints.size());
+ final var prevRegs = new ArrayList<Registration>(actionEndpoints.size());
for (Entry<Address, Optional<RemoteActionEndpoint>> e : actionEndpoints.entrySet()) {
LOG.debug("Updating action registrations for {}", e.getKey());
- final ObjectRegistration<DOMActionImplementation> prevReg;
+ final Registration prevReg;
final Optional<RemoteActionEndpoint> maybeEndpoint = e.getValue();
if (maybeEndpoint.isPresent()) {
- final RemoteActionEndpoint endpoint = maybeEndpoint.get();
+ final RemoteActionEndpoint endpoint = maybeEndpoint.orElseThrow();
final RemoteActionImplementation impl = new RemoteActionImplementation(endpoint.getRouter(), config);
prevReg = actionRegs.put(e.getKey(), actionProviderService.registerActionImplementation(impl,
endpoint.getActions()));
}
}
- prevRegs.forEach(ObjectRegistration::close);
+ prevRegs.forEach(Registration::close);
}
}
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
-
package org.opendaylight.controller.remote.rpc;
import java.io.Serializable;
* @author Thomas Pantelis
*/
public class RpcErrorsException extends DOMRpcException {
-
+ @java.io.Serial
private static final long serialVersionUID = 1L;
private static class RpcErrorData implements Serializable {
+ @java.io.Serial
private static final long serialVersionUID = 1L;
final ErrorSeverity severity;
public RpcErrorsException(final String message, final Iterable<? extends RpcError> rpcErrors) {
super(message);
- for (final RpcError rpcError: rpcErrors) {
+ for (var rpcError : rpcErrors) {
rpcErrorDataList.add(new RpcErrorData(rpcError.getSeverity(), rpcError.getErrorType(),
rpcError.getTag(), rpcError.getApplicationTag(), rpcError.getMessage(),
rpcError.getInfo(), rpcError.getCause()));
}
public Collection<RpcError> getRpcErrors() {
- final Collection<RpcError> rpcErrors = new ArrayList<>();
- for (final RpcErrorData ed: rpcErrorDataList) {
+ final var rpcErrors = new ArrayList<RpcError>();
+ for (var ed : rpcErrorDataList) {
final RpcError rpcError = ed.severity == ErrorSeverity.ERROR
? RpcResultBuilder.newError(ed.errorType, ed.tag, ed.message, ed.applicationTag,
ed.info, ed.cause) :
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
import org.opendaylight.yangtools.yang.data.codec.binfmt.NormalizedNodeDataInput;
-import org.opendaylight.yangtools.yang.data.codec.binfmt.NormalizedNodeDataOutput;
import org.opendaylight.yangtools.yang.data.codec.binfmt.NormalizedNodeStreamVersion;
import org.opendaylight.yangtools.yang.model.api.stmt.SchemaNodeIdentifier;
import org.opendaylight.yangtools.yang.model.api.stmt.SchemaNodeIdentifier.Absolute;
@Override
public void writeExternal(final ObjectOutput out) throws IOException {
- try (NormalizedNodeDataOutput stream = NormalizedNodeStreamVersion.current().newDataOutput(out)) {
+ try (var stream = NormalizedNodeStreamVersion.current().newDataOutput(out)) {
stream.writeSchemaNodeIdentifier(executeAction.getType());
- executeAction.getPath().getDatastoreType().writeTo(out);
- stream.writeYangInstanceIdentifier(executeAction.getPath().getRootIdentifier());
+ executeAction.getPath().datastore().writeTo(out);
+ stream.writeYangInstanceIdentifier(executeAction.getPath().path());
stream.writeOptionalNormalizedNode(executeAction.getInput());
}
}
final YangInstanceIdentifier path = stream.readYangInstanceIdentifier();
final ContainerNode input = (ContainerNode) stream.readOptionalNormalizedNode().orElse(null);
- executeAction = new ExecuteAction(absolute, new DOMDataTreeIdentifier(type, path), input);
+ executeAction = new ExecuteAction(absolute, DOMDataTreeIdentifier.of(type, path), input);
}
private Object readResolve() {
import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
import org.opendaylight.mdsal.dom.api.DOMActionInstance;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
-import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
import org.opendaylight.yangtools.yang.data.codec.binfmt.NormalizedNodeDataInput;
import org.opendaylight.yangtools.yang.data.codec.binfmt.NormalizedNodeDataOutput;
import org.opendaylight.yangtools.yang.data.codec.binfmt.NormalizedNodeStreamVersion;
for (DOMActionInstance id : actions) {
final Absolute type = id.getType();
nnout.writeSchemaNodeIdentifier(type);
- nnout.writeYangInstanceIdentifier(YangInstanceIdentifier.create(new NodeIdentifier(
- type.lastNodeIdentifier())));
+ nnout.writeYangInstanceIdentifier(YangInstanceIdentifier.of(type.lastNodeIdentifier()));
}
}
}
if (autoStartGossipTicks) {
- gossipTask = getContext().system().scheduler().schedule(
- new FiniteDuration(1, TimeUnit.SECONDS), //initial delay
- config.getGossipTickInterval(), //interval
- getSelf(), //target
- GOSSIP_TICK, //message
- getContext().dispatcher(), //execution context
- getSelf() //sender
- );
+ gossipTask = getContext().system().scheduler().scheduleAtFixedRate(
+ // initial delay
+ new FiniteDuration(1, TimeUnit.SECONDS),
+ // interval
+ config.getGossipTickInterval(),
+ // target
+ getSelf(),
+ // message
+ GOSSIP_TICK,
+ // execution context
+ getContext().dispatcher(),
+ // sender
+ getSelf());
}
}
import org.opendaylight.controller.remote.rpc.registry.gossip.BucketStoreAccess;
import org.opendaylight.mdsal.dom.api.DOMActionInstance;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
-import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
public class RemoteActionRegistryMXBeanImpl extends AbstractRegistryMXBean<ActionRoutingTable, DOMActionInstance>
implements RemoteActionRegistryMXBean {
-
public RemoteActionRegistryMXBeanImpl(final BucketStoreAccess actionRegistryAccess, final Timeout timeout) {
super("RemoteActionRegistry", "RemoteActionBroker", actionRegistryAccess, timeout);
}
ActionRoutingTable table = localData();
Set<String> routedAction = new HashSet<>(table.getItems().size());
for (DOMActionInstance route : table.getItems()) {
- final YangInstanceIdentifier actionPath = YangInstanceIdentifier.create(new NodeIdentifier(
- route.getType().lastNodeIdentifier()));
+ final YangInstanceIdentifier actionPath = YangInstanceIdentifier.of(route.getType().lastNodeIdentifier());
if (!actionPath.isEmpty()) {
routedAction.add(ROUTE_CONSTANT + actionPath + NAME_CONSTANT + route.getType());
}
Collection<DOMActionInstance> routes = table.getItems();
Map<String, String> actionMap = new HashMap<>(routes.size());
for (DOMActionInstance route : routes) {
- final YangInstanceIdentifier actionPath = YangInstanceIdentifier.create(new NodeIdentifier(
- route.getType().lastNodeIdentifier()));
+ final YangInstanceIdentifier actionPath = YangInstanceIdentifier.of(route.getType().lastNodeIdentifier());
if (!actionPath.isEmpty()) {
String routeString = actionPath.toString();
if (routeString.contains(routeName)) {
Collection<DOMActionInstance> routes = table.getItems();
Map<String, String> actionMap = new HashMap<>(routes.size());
for (DOMActionInstance route : routes) {
- final YangInstanceIdentifier actionPath = YangInstanceIdentifier.create(new NodeIdentifier(
- route.getType().lastNodeIdentifier()));
+ final YangInstanceIdentifier actionPath = YangInstanceIdentifier.of(route.getType().lastNodeIdentifier());
if (!actionPath.isEmpty()) {
String type = route.getType().toString();
if (type.contains(name)) {
import akka.actor.ActorSystem;
import akka.testkit.javadsl.TestKit;
import java.net.URI;
-import java.util.Collection;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
-import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
-import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
+import org.opendaylight.yangtools.yang.data.spi.node.ImmutableNodes;
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
import org.opendaylight.yangtools.yang.model.api.stmt.SchemaNodeIdentifier.Absolute;
import org.opendaylight.yangtools.yang.test.util.YangParserTestUtils;
static final Absolute TEST_RPC_TYPE = Absolute.of(TEST_RPC);
- static final YangInstanceIdentifier TEST_PATH = YangInstanceIdentifier.create(
- new YangInstanceIdentifier.NodeIdentifier(TEST_RPC));
+ static final YangInstanceIdentifier TEST_PATH = YangInstanceIdentifier.of(TEST_RPC);
public static final DOMRpcIdentifier TEST_RPC_ID = DOMRpcIdentifier.create(TEST_RPC, TEST_PATH);
- public static final DOMDataTreeIdentifier TEST_DATA_TREE_ID = new DOMDataTreeIdentifier(
- LogicalDatastoreType.OPERATIONAL, TEST_PATH);
+ public static final DOMDataTreeIdentifier TEST_DATA_TREE_ID =
+ DOMDataTreeIdentifier.of(LogicalDatastoreType.OPERATIONAL, TEST_PATH);
static ActorSystem node1;
static ActorSystem node2;
}
public static ContainerNode makeRPCInput(final String data) {
- return Builders.containerBuilder().withNodeIdentifier(new NodeIdentifier(TEST_RPC_INPUT))
- .withChild(ImmutableNodes.leafNode(TEST_RPC_INPUT_DATA, data)).build();
+ return ImmutableNodes.newContainerBuilder()
+ .withNodeIdentifier(new NodeIdentifier(TEST_RPC_INPUT))
+ .withChild(ImmutableNodes.leafNode(TEST_RPC_INPUT_DATA, data))
+ .build();
}
public static ContainerNode makeRPCOutput(final String data) {
- return Builders.containerBuilder().withNodeIdentifier(new NodeIdentifier(TEST_RPC_OUTPUT))
- .withChild(ImmutableNodes.leafNode(TEST_RPC_OUTPUT, data)).build();
+ return ImmutableNodes.newContainerBuilder()
+ .withNodeIdentifier(new NodeIdentifier(TEST_RPC_OUTPUT))
+ .withChild(ImmutableNodes.leafNode(TEST_RPC_OUTPUT, data))
+ .build();
}
static void assertFailedRpcResult(final DOMRpcResult rpcResult, final ErrorSeverity severity,
final ErrorType errorType, final String tag, final String message,
final String applicationTag, final String info, final String causeMsg) {
assertNotNull("RpcResult was null", rpcResult);
- final Collection<? extends RpcError> rpcErrors = rpcResult.errors();
+ final var rpcErrors = rpcResult.errors();
assertEquals("RpcErrors count", 1, rpcErrors.size());
assertRpcErrorEquals(rpcErrors.iterator().next(), severity, errorType, tag, message,
applicationTag, info, causeMsg);
private static final QName TEST_QNAME = QName.create("test", "2015-06-12", "test");
private static final Absolute RPC_TYPE = Absolute.of(TEST_QNAME);
- private static final YangInstanceIdentifier TEST_PATH =
- YangInstanceIdentifier.create(new YangInstanceIdentifier.NodeIdentifier(TEST_QNAME));
+ private static final YangInstanceIdentifier TEST_PATH = YangInstanceIdentifier.of(TEST_QNAME);
private static final DOMRpcIdentifier RPC_ID = DOMRpcIdentifier.create(TEST_QNAME, TEST_PATH);
private static final DOMActionInstance ACTION_INSTANCE = DOMActionInstance.of(RPC_TYPE,
LogicalDatastoreType.OPERATIONAL, TEST_PATH);
import org.opendaylight.mdsal.dom.api.DOMActionInstance;
import org.opendaylight.mdsal.dom.api.DOMActionProviderService;
import org.opendaylight.mdsal.dom.api.DOMRpcIdentifier;
-import org.opendaylight.mdsal.dom.api.DOMRpcImplementationRegistration;
import org.opendaylight.mdsal.dom.api.DOMRpcProviderService;
import org.opendaylight.yangtools.concepts.ObjectRegistration;
+import org.opendaylight.yangtools.concepts.Registration;
import org.opendaylight.yangtools.yang.common.QName;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
import org.opendaylight.yangtools.yang.model.api.stmt.SchemaNodeIdentifier.Absolute;
@Mock
private DOMActionProviderService actionService;
@Mock
- private DOMRpcImplementationRegistration<RemoteRpcImplementation> oldReg;
+ private Registration oldReg;
@Mock
- private DOMRpcImplementationRegistration<RemoteRpcImplementation> newReg;
+ private Registration newReg;
@Mock
private ObjectRegistration<RemoteActionImplementation> oldActionReg;
@Mock
final QName firstActionQName = QName.create("first:actionIdentifier", "fooAction");
final DOMActionInstance firstActionInstance = DOMActionInstance.of(Absolute.of(firstActionQName),
- LogicalDatastoreType.OPERATIONAL,
- YangInstanceIdentifier.create(new YangInstanceIdentifier.NodeIdentifier(firstActionQName)));
+ LogicalDatastoreType.OPERATIONAL, YangInstanceIdentifier.of(firstActionQName));
final DOMActionInstance secondActionInstance = DOMActionInstance.of(Absolute.of(firstActionQName),
- LogicalDatastoreType.OPERATIONAL,
- YangInstanceIdentifier.create(new YangInstanceIdentifier.NodeIdentifier(firstActionQName)));
+ LogicalDatastoreType.OPERATIONAL, YangInstanceIdentifier.of(firstActionQName));
final TestKit senderKit = new TestKit(system);
firstEndpoint = new RemoteRpcEndpoint(senderKit.getRef(), Collections.singletonList(firstEndpointId));
import com.google.common.util.concurrent.ListenableFuture;
import java.util.Collections;
+import java.util.Optional;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import org.junit.Ignore;
TEST_DATA_TREE_ID, (ContainerNode) invokeActionInput);
assertThat(frontEndFuture, instanceOf(RemoteDOMActionFuture.class));
final DOMActionResult result = frontEndFuture.get(5, TimeUnit.SECONDS);
- assertEquals(actionOutput, result.getOutput().get());
+ assertEquals(Optional.of(actionOutput), result.getOutput());
}
/**
assertThat(frontEndFuture, instanceOf(RemoteDOMActionFuture.class));
final DOMActionResult result = frontEndFuture.get(5, TimeUnit.SECONDS);
- assertEquals(actionOutput, result.getOutput().get());
+ assertEquals(Optional.of(actionOutput), result.getOutput());
}
/**
import static org.junit.Assert.assertEquals;
-import org.apache.commons.lang.SerializationUtils;
+import org.apache.commons.lang3.SerializationUtils;
import org.junit.Test;
import org.opendaylight.controller.remote.rpc.AbstractOpsTest;
ExecuteRpc expected = ExecuteRpc.from(AbstractOpsTest.TEST_RPC_ID,
AbstractOpsTest.makeRPCInput("serialization-test"));
- ExecuteRpc actual = (ExecuteRpc) SerializationUtils.clone(expected);
+ ExecuteRpc actual = SerializationUtils.clone(expected);
assertEquals("getName", expected.getType(), actual.getType());
assertEquals("getInputNormalizedNode", expected.getInput(), actual.getInput());
import java.util.Collections;
import java.util.Optional;
-import org.apache.commons.lang.SerializationUtils;
+import org.apache.commons.lang3.SerializationUtils;
import org.junit.Test;
import org.opendaylight.controller.remote.rpc.AbstractOpsTest;
ActionResponse expectedAction = new ActionResponse(
Optional.of(AbstractOpsTest.makeRPCOutput("serialization-test")), Collections.emptyList());
- RpcResponse actualRpc = (RpcResponse) SerializationUtils.clone(expectedRpc);
+ RpcResponse actualRpc = SerializationUtils.clone(expectedRpc);
- ActionResponse actualAction = (ActionResponse) SerializationUtils.clone(expectedAction);
+ ActionResponse actualAction = SerializationUtils.clone(expectedAction);
assertEquals("getResultNormalizedNode", expectedRpc.getOutput(),
actualRpc.getOutput());
assertNotNull(maybeEndpoint);
assertTrue(maybeEndpoint.isPresent());
- final RemoteActionEndpoint endpoint = maybeEndpoint.get();
+ final RemoteActionEndpoint endpoint = maybeEndpoint.orElseThrow();
final ActorRef router = endpoint.getRouter();
assertNotNull(router);
for (int i = 0; i < nRoutes; i++) {
QName type = QName.create("/mockaction", "mockaction" + routeIdCounter++);
final DOMActionInstance routeId = DOMActionInstance.of(Absolute.of(type), LogicalDatastoreType.OPERATIONAL,
- YangInstanceIdentifier.create(new YangInstanceIdentifier.NodeIdentifier(type)));
+ YangInstanceIdentifier.of(type));
added.add(routeId);
//Uninterruptibles.sleepUninterruptibly(50, TimeUnit.MILLISECONDS);
private List<DOMActionInstance> createRouteIds() {
QName type = QName.create("/mockaction", "mockaction" + routeIdCounter++);
- List<DOMActionInstance> routeIds = new ArrayList<>(1);
+ var routeIds = new ArrayList<DOMActionInstance>(1);
routeIds.add(DOMActionInstance.of(Absolute.of(type), LogicalDatastoreType.OPERATIONAL,
- YangInstanceIdentifier.create(new YangInstanceIdentifier.NodeIdentifier(type))));
+ YangInstanceIdentifier.of(type)));
return routeIds;
}
}
assertNotNull(maybeEndpoint);
assertTrue(maybeEndpoint.isPresent());
- final RemoteRpcEndpoint endpoint = maybeEndpoint.get();
+ final RemoteRpcEndpoint endpoint = maybeEndpoint.orElseThrow();
final ActorRef router = endpoint.getRouter();
assertNotNull(router);
import org.opendaylight.controller.remote.rpc.TerminationMonitor;
public class BucketStoreTest {
-
/**
* Dummy class to eliminate rawtype warnings.
*
* @author gwu
- *
*/
- private static class T implements BucketData<T> {
+ private static final class T implements BucketData<T> {
@Override
public Optional<ActorRef> getWatchActor() {
return Optional.empty();
system = ActorSystem.create("test", ConfigFactory.load().getConfig("unit-test"));
final DOMActionInstance emptyActionIdentifier = DOMActionInstance.of(
- REMOTE_SCHEMA_PATH, LogicalDatastoreType.OPERATIONAL, YangInstanceIdentifier.empty());
+ REMOTE_SCHEMA_PATH, LogicalDatastoreType.OPERATIONAL, YangInstanceIdentifier.of());
final DOMActionInstance localActionIdentifier = DOMActionInstance.of(
LOCAL_SCHEMA_PATH, LogicalDatastoreType.OPERATIONAL, YangInstanceIdentifier.of(LOCAL_QNAME));
system = ActorSystem.create("test", ConfigFactory.load().getConfig("unit-test"));
final DOMRpcIdentifier emptyRpcIdentifier = DOMRpcIdentifier.create(
- REMOTE_QNAME, YangInstanceIdentifier.empty());
+ REMOTE_QNAME, YangInstanceIdentifier.of());
final DOMRpcIdentifier localRpcIdentifier = DOMRpcIdentifier.create(
LOCAL_QNAME, YangInstanceIdentifier.of(LOCAL_QNAME));
<parent>
<groupId>org.opendaylight.controller</groupId>
<artifactId>mdsal-parent</artifactId>
- <version>7.0.2-SNAPSHOT</version>
+ <version>9.0.3-SNAPSHOT</version>
<relativePath>../parent</relativePath>
</parent>
<parent>
<groupId>org.opendaylight.odlparent</groupId>
<artifactId>odlparent-lite</artifactId>
- <version>12.0.1</version>
+ <version>13.0.11</version>
<relativePath/>
</parent>
<groupId>org.opendaylight.controller.samples</groupId>
<artifactId>clustering-it-config</artifactId>
- <version>7.0.2-SNAPSHOT</version>
+ <version>9.0.3-SNAPSHOT</version>
<packaging>jar</packaging>
<build>
<parent>
<artifactId>mdsal-parent</artifactId>
<groupId>org.opendaylight.controller</groupId>
- <version>7.0.2-SNAPSHOT</version>
+ <version>9.0.3-SNAPSHOT</version>
<relativePath>../../../parent/pom.xml</relativePath>
</parent>
<modelVersion>4.0.0</modelVersion>
public DefaultInstanceIdentifierSupport(@Reference final BindingCodecTree bindingCodecTree,
@Reference final BindingRuntimeContext runtimeContext) {
bindingCodec = bindingCodecTree.getInstanceIdentifierCodec();
- jsonCodec = JSONCodecFactorySupplier.RFC7951.createLazy(runtimeContext.getEffectiveModelContext())
+ jsonCodec = JSONCodecFactorySupplier.RFC7951.createLazy(runtimeContext.modelContext())
.codecFor(new FakeLeafDefinition(), null);
}
import org.apache.karaf.shell.api.action.lifecycle.Reference;
import org.apache.karaf.shell.api.action.lifecycle.Service;
import org.opendaylight.clustering.it.karaf.cli.AbstractRpcAction;
-import org.opendaylight.mdsal.binding.api.RpcConsumerRegistry;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.CarService;
+import org.opendaylight.mdsal.binding.api.RpcService;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.RegisterCommitCohort;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.RegisterCommitCohortInputBuilder;
import org.opendaylight.yangtools.yang.common.RpcResult;
@Command(scope = "test-app", name = "register-commit-cohort", description = "Run a register-commit-cohort test")
public class RegisterCommitCohortCommand extends AbstractRpcAction {
@Reference
- private RpcConsumerRegistry rpcService;
+ private RpcService rpcService;
@Override
protected ListenableFuture<? extends RpcResult<?>> invokeRpc() {
- return rpcService.getRpcService(CarService.class)
- .registerCommitCohort(new RegisterCommitCohortInputBuilder().build());
+ return rpcService.getRpc(RegisterCommitCohort.class).invoke(new RegisterCommitCohortInputBuilder().build());
}
}
import org.apache.karaf.shell.api.action.lifecycle.Reference;
import org.apache.karaf.shell.api.action.lifecycle.Service;
import org.opendaylight.clustering.it.karaf.cli.AbstractRpcAction;
-import org.opendaylight.mdsal.binding.api.RpcConsumerRegistry;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.CarService;
+import org.opendaylight.mdsal.binding.api.RpcService;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.RegisterLoggingDtcl;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.RegisterLoggingDtclInputBuilder;
import org.opendaylight.yangtools.yang.common.RpcResult;
@Command(scope = "test-app", name = "register-logging-dtcl", description = "Run a register-logging-dtcl test")
public class RegisterLoggingDtclCommand extends AbstractRpcAction {
@Reference
- private RpcConsumerRegistry rpcService;
+ private RpcService rpcService;
@Override
protected ListenableFuture<? extends RpcResult<?>> invokeRpc() {
- return rpcService.getRpcService(CarService.class)
- .registerLoggingDtcl(new RegisterLoggingDtclInputBuilder().build());
+ return rpcService.getRpc(RegisterLoggingDtcl.class).invoke(new RegisterLoggingDtclInputBuilder().build());
}
}
import org.apache.karaf.shell.api.action.lifecycle.Reference;
import org.apache.karaf.shell.api.action.lifecycle.Service;
import org.opendaylight.clustering.it.karaf.cli.AbstractRpcAction;
-import org.opendaylight.mdsal.binding.api.RpcConsumerRegistry;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.CarService;
+import org.opendaylight.mdsal.binding.api.RpcService;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.RegisterOwnership;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.RegisterOwnershipInputBuilder;
import org.opendaylight.yangtools.yang.common.RpcResult;
@Command(scope = "test-app", name = "register-ownership", description = "Run a register-ownership test")
public class RegisterOwnershipCommand extends AbstractRpcAction {
@Reference
- private RpcConsumerRegistry rpcService;
+ private RpcService rpcService;
@Argument(index = 0, name = "car-id", required = true)
private String carId;
@Override
protected ListenableFuture<? extends RpcResult<?>> invokeRpc() {
- return rpcService.getRpcService(CarService.class)
- .registerOwnership(new RegisterOwnershipInputBuilder().setCarId(carId).build());
+ return rpcService.getRpc(RegisterOwnership.class)
+ .invoke(new RegisterOwnershipInputBuilder().setCarId(carId).build());
}
}
import org.apache.karaf.shell.api.action.lifecycle.Reference;
import org.apache.karaf.shell.api.action.lifecycle.Service;
import org.opendaylight.clustering.it.karaf.cli.AbstractRpcAction;
-import org.opendaylight.mdsal.binding.api.RpcConsumerRegistry;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.CarService;
+import org.opendaylight.mdsal.binding.api.RpcService;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.StopStressTest;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.StopStressTestInputBuilder;
import org.opendaylight.yangtools.yang.common.RpcResult;
@Command(scope = "test-app" , name = "stop-stress-test", description = "Run a stop-stress-test")
public class StopStressTestCommand extends AbstractRpcAction {
@Reference
- private RpcConsumerRegistry rpcService;
+ private RpcService rpcService;
@Override
protected ListenableFuture<? extends RpcResult<?>> invokeRpc() {
- return rpcService.getRpcService(CarService.class).stopStressTest(new StopStressTestInputBuilder().build());
+ return rpcService.getRpc(StopStressTest.class).invoke(new StopStressTestInputBuilder().build());
}
}
import org.apache.karaf.shell.api.action.lifecycle.Reference;
import org.apache.karaf.shell.api.action.lifecycle.Service;
import org.opendaylight.clustering.it.karaf.cli.AbstractRpcAction;
-import org.opendaylight.mdsal.binding.api.RpcConsumerRegistry;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.CarService;
+import org.opendaylight.mdsal.binding.api.RpcService;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.StressTest;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.StressTestInputBuilder;
import org.opendaylight.yangtools.yang.common.RpcResult;
import org.opendaylight.yangtools.yang.common.Uint16;
@Command(scope = "test-app" , name = "stress-test", description = "Run a stress-test")
public class StressTestCommand extends AbstractRpcAction {
@Reference
- private RpcConsumerRegistry rpcService;
+ private RpcService rpcService;
@Argument(index = 0, name = "rate", required = true)
private int rate;
@Argument(index = 1, name = "count", required = true)
@Override
protected ListenableFuture<? extends RpcResult<?>> invokeRpc() {
- return rpcService.getRpcService(CarService.class).stressTest(new StressTestInputBuilder()
+ return rpcService.getRpc(StressTest.class).invoke(new StressTestInputBuilder()
.setRate(Uint16.valueOf(rate))
.setCount(Uint32.valueOf(count))
.build());
import org.apache.karaf.shell.api.action.lifecycle.Reference;
import org.apache.karaf.shell.api.action.lifecycle.Service;
import org.opendaylight.clustering.it.karaf.cli.AbstractRpcAction;
-import org.opendaylight.mdsal.binding.api.RpcConsumerRegistry;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.CarService;
+import org.opendaylight.mdsal.binding.api.RpcService;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.UnregisterCommitCohort;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.UnregisterCommitCohortInputBuilder;
import org.opendaylight.yangtools.yang.common.RpcResult;
@Command(scope = "test-app", name = "unregister-commit-cohort", description = "Run a unregister-commit-cohort test")
public class UnregisterCommitCohortCommand extends AbstractRpcAction {
@Reference
- private RpcConsumerRegistry rpcService;
+ private RpcService rpcService;
@Override
protected ListenableFuture<? extends RpcResult<?>> invokeRpc() {
- return rpcService.getRpcService(CarService.class)
- .unregisterCommitCohort(new UnregisterCommitCohortInputBuilder().build());
+ return rpcService.getRpc(UnregisterCommitCohort.class).invoke(new UnregisterCommitCohortInputBuilder().build());
}
}
import org.apache.karaf.shell.api.action.lifecycle.Reference;
import org.apache.karaf.shell.api.action.lifecycle.Service;
import org.opendaylight.clustering.it.karaf.cli.AbstractRpcAction;
-import org.opendaylight.mdsal.binding.api.RpcConsumerRegistry;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.CarService;
+import org.opendaylight.mdsal.binding.api.RpcService;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.UnregisterLoggingDtcls;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.UnregisterLoggingDtclsInputBuilder;
import org.opendaylight.yangtools.yang.common.RpcResult;
@Command(scope = "test-app", name = "unregister-logging-dtcls", description = "Run and unregister-logging-dtcls test")
public class UnregisterLoggingDtclsCommand extends AbstractRpcAction {
@Reference
- private RpcConsumerRegistry rpcService;
+ private RpcService rpcService;
@Override
protected ListenableFuture<? extends RpcResult<?>> invokeRpc() {
- return rpcService.getRpcService(CarService.class)
- .unregisterLoggingDtcls(new UnregisterLoggingDtclsInputBuilder().build());
+ return rpcService.getRpc(UnregisterLoggingDtcls.class).invoke(new UnregisterLoggingDtclsInputBuilder().build());
}
}
import org.apache.karaf.shell.api.action.lifecycle.Reference;
import org.apache.karaf.shell.api.action.lifecycle.Service;
import org.opendaylight.clustering.it.karaf.cli.AbstractRpcAction;
-import org.opendaylight.mdsal.binding.api.RpcConsumerRegistry;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.CarService;
+import org.opendaylight.mdsal.binding.api.RpcService;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.UnregisterOwnership;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.UnregisterOwnershipInputBuilder;
import org.opendaylight.yangtools.yang.common.RpcResult;
-
@Service
@Command(scope = "test-app", name = "unregister-ownership", description = "Run an unregister-ownership test")
public class UnregisterOwnershipCommand extends AbstractRpcAction {
@Reference
- private RpcConsumerRegistry rpcService;
+ private RpcService rpcService;
@Argument(index = 0, name = "car-id", required = true)
private String carId;
@Override
protected ListenableFuture<? extends RpcResult<?>> invokeRpc() {
- return rpcService.getRpcService(CarService.class)
- .unregisterOwnership(new UnregisterOwnershipInputBuilder().setCarId(carId).build());
+ return rpcService.getRpc(UnregisterOwnership.class)
+ .invoke(new UnregisterOwnershipInputBuilder().setCarId(carId).build());
}
}
import org.apache.karaf.shell.api.action.lifecycle.Service;
import org.opendaylight.clustering.it.karaf.cli.AbstractRpcAction;
import org.opendaylight.clustering.it.karaf.cli.InstanceIdentifierSupport;
-import org.opendaylight.mdsal.binding.api.RpcConsumerRegistry;
+import org.opendaylight.mdsal.binding.api.RpcService;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.purchase.rev140818.BuyCar;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.purchase.rev140818.BuyCarInputBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.purchase.rev140818.CarPurchaseService;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.CarId;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.people.rev140818.PersonId;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.people.rev140818.PersonRef;
@Command(scope = "test-app", name = "buy-car", description = "Run a buy-car test")
public class BuyCarCommand extends AbstractRpcAction {
@Reference
- private RpcConsumerRegistry rpcService;
+ private RpcService rpcService;
@Reference
private InstanceIdentifierSupport iidSupport;
@Argument(index = 0, name = "person-ref", required = true)
@Override
protected ListenableFuture<? extends RpcResult<?>> invokeRpc() {
- return rpcService.getRpcService(CarPurchaseService.class).buyCar(new BuyCarInputBuilder()
+ return rpcService.getRpc(BuyCar.class).invoke(new BuyCarInputBuilder()
.setPerson(new PersonRef(iidSupport.parseArgument(personRef)))
.setCarId(carId)
.setPersonId(personId)
import org.apache.karaf.shell.api.action.lifecycle.Reference;
import org.apache.karaf.shell.api.action.lifecycle.Service;
import org.opendaylight.clustering.it.karaf.cli.AbstractRpcAction;
-import org.opendaylight.mdsal.binding.api.RpcConsumerRegistry;
+import org.opendaylight.mdsal.binding.api.RpcService;
+import org.opendaylight.yang.gen.v1.tag.opendaylight.org._2017.controller.yang.lowlevel.control.rev170215.AddShardReplica;
import org.opendaylight.yang.gen.v1.tag.opendaylight.org._2017.controller.yang.lowlevel.control.rev170215.AddShardReplicaInputBuilder;
-import org.opendaylight.yang.gen.v1.tag.opendaylight.org._2017.controller.yang.lowlevel.control.rev170215.OdlMdsalLowlevelControlService;
import org.opendaylight.yangtools.yang.common.RpcResult;
@Service
@Command(scope = "test-app", name = "add-shard-replica", description = "Run an add-shard-replica test")
public class AddShardReplicaCommand extends AbstractRpcAction {
@Reference
- private RpcConsumerRegistry rpcService;
+ private RpcService rpcService;
@Argument(index = 0, name = "shard-name", required = true)
private String shardName;
@Override
protected ListenableFuture<? extends RpcResult<?>> invokeRpc() {
- return rpcService.getRpcService(OdlMdsalLowlevelControlService.class)
- .addShardReplica(new AddShardReplicaInputBuilder().setShardName(shardName).build());
+ return rpcService.getRpc(AddShardReplica.class)
+ .invoke(new AddShardReplicaInputBuilder().setShardName(shardName).build());
}
}
import org.apache.karaf.shell.api.action.lifecycle.Reference;
import org.apache.karaf.shell.api.action.lifecycle.Service;
import org.opendaylight.clustering.it.karaf.cli.AbstractRpcAction;
-import org.opendaylight.mdsal.binding.api.RpcConsumerRegistry;
+import org.opendaylight.mdsal.binding.api.RpcService;
+import org.opendaylight.yang.gen.v1.tag.opendaylight.org._2017.controller.yang.lowlevel.control.rev170215.CheckPublishNotifications;
import org.opendaylight.yang.gen.v1.tag.opendaylight.org._2017.controller.yang.lowlevel.control.rev170215.CheckPublishNotificationsInputBuilder;
-import org.opendaylight.yang.gen.v1.tag.opendaylight.org._2017.controller.yang.lowlevel.control.rev170215.OdlMdsalLowlevelControlService;
import org.opendaylight.yangtools.yang.common.RpcResult;
@Service
description = "Run a check-publish-notifications test")
public class CheckPublishNotificationsCommand extends AbstractRpcAction {
@Reference
- private RpcConsumerRegistry rpcService;
+ private RpcService rpcService;
@Argument(index = 0, name = "id", required = true)
private String id;
@Override
protected ListenableFuture<? extends RpcResult<?>> invokeRpc() {
- return rpcService.getRpcService(OdlMdsalLowlevelControlService.class)
- .checkPublishNotifications(new CheckPublishNotificationsInputBuilder()
- .setId(id)
- .build());
+ return rpcService.getRpc(CheckPublishNotifications.class)
+ .invoke(new CheckPublishNotificationsInputBuilder().setId(id).build());
}
}
import org.apache.karaf.shell.api.action.lifecycle.Reference;
import org.apache.karaf.shell.api.action.lifecycle.Service;
import org.opendaylight.clustering.it.karaf.cli.AbstractRpcAction;
-import org.opendaylight.mdsal.binding.api.RpcConsumerRegistry;
+import org.opendaylight.mdsal.binding.api.RpcService;
+import org.opendaylight.yang.gen.v1.tag.opendaylight.org._2017.controller.yang.lowlevel.control.rev170215.IsClientAborted;
import org.opendaylight.yang.gen.v1.tag.opendaylight.org._2017.controller.yang.lowlevel.control.rev170215.IsClientAbortedInputBuilder;
-import org.opendaylight.yang.gen.v1.tag.opendaylight.org._2017.controller.yang.lowlevel.control.rev170215.OdlMdsalLowlevelControlService;
import org.opendaylight.yangtools.yang.common.RpcResult;
@Service
@Command(scope = "test-app", name = "is-client-aborted", description = "Run an is-client-aborted test")
public class IsClientAbortedCommand extends AbstractRpcAction {
@Reference
- private RpcConsumerRegistry rpcService;
+ private RpcService rpcService;
@Override
protected ListenableFuture<? extends RpcResult<?>> invokeRpc() {
- return rpcService.getRpcService(OdlMdsalLowlevelControlService.class)
- .isClientAborted(new IsClientAbortedInputBuilder().build());
+ return rpcService.getRpc(IsClientAborted.class).invoke(new IsClientAbortedInputBuilder().build());
}
}
import org.apache.karaf.shell.api.action.lifecycle.Service;
import org.opendaylight.clustering.it.karaf.cli.AbstractRpcAction;
import org.opendaylight.clustering.it.karaf.cli.InstanceIdentifierSupport;
-import org.opendaylight.mdsal.binding.api.RpcConsumerRegistry;
-import org.opendaylight.yang.gen.v1.tag.opendaylight.org._2017.controller.yang.lowlevel.control.rev170215.OdlMdsalLowlevelControlService;
+import org.opendaylight.mdsal.binding.api.RpcService;
+import org.opendaylight.yang.gen.v1.tag.opendaylight.org._2017.controller.yang.lowlevel.control.rev170215.RegisterBoundConstant;
import org.opendaylight.yang.gen.v1.tag.opendaylight.org._2017.controller.yang.lowlevel.control.rev170215.RegisterBoundConstantInputBuilder;
import org.opendaylight.yangtools.yang.common.RpcResult;
@Command(scope = "test-app", name = "register-bound-constant", description = "Run a register-bound-constant test")
public class RegisterBoundConstantCommand extends AbstractRpcAction {
@Reference
- private RpcConsumerRegistry rpcService;
+ private RpcService rpcService;
@Reference
private InstanceIdentifierSupport iidSupport;
@Argument(index = 0, name = "context", required = true)
@Override
protected ListenableFuture<? extends RpcResult<?>> invokeRpc() {
- return rpcService.getRpcService(OdlMdsalLowlevelControlService.class)
- .registerBoundConstant(new RegisterBoundConstantInputBuilder()
+ return rpcService.getRpc(RegisterBoundConstant.class)
+ .invoke(new RegisterBoundConstantInputBuilder()
.setConstant(constant)
.setContext(iidSupport.parseArgument(context))
.build());
import org.apache.karaf.shell.api.action.lifecycle.Reference;
import org.apache.karaf.shell.api.action.lifecycle.Service;
import org.opendaylight.clustering.it.karaf.cli.AbstractRpcAction;
-import org.opendaylight.mdsal.binding.api.RpcConsumerRegistry;
-import org.opendaylight.yang.gen.v1.tag.opendaylight.org._2017.controller.yang.lowlevel.control.rev170215.OdlMdsalLowlevelControlService;
+import org.opendaylight.mdsal.binding.api.RpcService;
+import org.opendaylight.yang.gen.v1.tag.opendaylight.org._2017.controller.yang.lowlevel.control.rev170215.RegisterConstant;
import org.opendaylight.yang.gen.v1.tag.opendaylight.org._2017.controller.yang.lowlevel.control.rev170215.RegisterConstantInputBuilder;
import org.opendaylight.yangtools.yang.common.RpcResult;
@Command(scope = "test-app", name = "register-contact", description = "Run a register-contact test")
public class RegisterConstantCommand extends AbstractRpcAction {
@Reference
- private RpcConsumerRegistry rpcService;
+ private RpcService rpcService;
@Argument(index = 0, name = "constant", required = true)
private String constant;
@Override
protected ListenableFuture<? extends RpcResult<?>> invokeRpc() {
- return rpcService.getRpcService(OdlMdsalLowlevelControlService.class)
- .registerConstant(new RegisterConstantInputBuilder().setConstant(constant).build());
+ return rpcService.getRpc(RegisterConstant.class)
+ .invoke(new RegisterConstantInputBuilder().setConstant(constant).build());
}
}
import org.apache.karaf.shell.api.action.lifecycle.Reference;
import org.apache.karaf.shell.api.action.lifecycle.Service;
import org.opendaylight.clustering.it.karaf.cli.AbstractRpcAction;
-import org.opendaylight.mdsal.binding.api.RpcConsumerRegistry;
-import org.opendaylight.yang.gen.v1.tag.opendaylight.org._2017.controller.yang.lowlevel.control.rev170215.OdlMdsalLowlevelControlService;
+import org.opendaylight.mdsal.binding.api.RpcService;
+import org.opendaylight.yang.gen.v1.tag.opendaylight.org._2017.controller.yang.lowlevel.control.rev170215.RegisterDefaultConstant;
import org.opendaylight.yang.gen.v1.tag.opendaylight.org._2017.controller.yang.lowlevel.control.rev170215.RegisterDefaultConstantInputBuilder;
import org.opendaylight.yangtools.yang.common.RpcResult;
@Command(scope = "test-app", name = "register-default-constant", description = "Run a register-default-constant test")
public class RegisterDefaultConstantCommand extends AbstractRpcAction {
@Reference
- private RpcConsumerRegistry rpcService;
+ private RpcService rpcService;
@Argument(index = 0, name = "constant", required = true)
private String constant;
@Override
protected ListenableFuture<? extends RpcResult<?>> invokeRpc() {
- return rpcService.getRpcService(OdlMdsalLowlevelControlService.class)
- .registerDefaultConstant(new RegisterDefaultConstantInputBuilder()
- .setConstant(constant)
- .build());
+ return rpcService.getRpc(RegisterDefaultConstant.class)
+ .invoke(new RegisterDefaultConstantInputBuilder().setConstant(constant).build());
}
}
import org.apache.karaf.shell.api.action.lifecycle.Reference;
import org.apache.karaf.shell.api.action.lifecycle.Service;
import org.opendaylight.clustering.it.karaf.cli.AbstractRpcAction;
-import org.opendaylight.mdsal.binding.api.RpcConsumerRegistry;
-import org.opendaylight.yang.gen.v1.tag.opendaylight.org._2017.controller.yang.lowlevel.control.rev170215.OdlMdsalLowlevelControlService;
+import org.opendaylight.mdsal.binding.api.RpcService;
+import org.opendaylight.yang.gen.v1.tag.opendaylight.org._2017.controller.yang.lowlevel.control.rev170215.RegisterFlappingSingleton;
import org.opendaylight.yang.gen.v1.tag.opendaylight.org._2017.controller.yang.lowlevel.control.rev170215.RegisterFlappingSingletonInputBuilder;
import org.opendaylight.yangtools.yang.common.RpcResult;
description = "Run a register-flapping-singleton test")
public class RegisterFlappingSingletonCommand extends AbstractRpcAction {
@Reference
- private RpcConsumerRegistry rpcService;
+ private RpcService rpcService;
@Override
protected ListenableFuture<? extends RpcResult<?>> invokeRpc() {
- return rpcService.getRpcService(OdlMdsalLowlevelControlService.class)
- .registerFlappingSingleton(new RegisterFlappingSingletonInputBuilder().build());
+ return rpcService.getRpc(RegisterFlappingSingleton.class)
+ .invoke(new RegisterFlappingSingletonInputBuilder().build());
}
}
import org.apache.karaf.shell.api.action.lifecycle.Reference;
import org.apache.karaf.shell.api.action.lifecycle.Service;
import org.opendaylight.clustering.it.karaf.cli.AbstractRpcAction;
-import org.opendaylight.mdsal.binding.api.RpcConsumerRegistry;
-import org.opendaylight.yang.gen.v1.tag.opendaylight.org._2017.controller.yang.lowlevel.control.rev170215.OdlMdsalLowlevelControlService;
+import org.opendaylight.mdsal.binding.api.RpcService;
+import org.opendaylight.yang.gen.v1.tag.opendaylight.org._2017.controller.yang.lowlevel.control.rev170215.RegisterSingletonConstant;
import org.opendaylight.yang.gen.v1.tag.opendaylight.org._2017.controller.yang.lowlevel.control.rev170215.RegisterSingletonConstantInputBuilder;
import org.opendaylight.yangtools.yang.common.RpcResult;
description = "Run a register-singleton-constant text")
public class RegisterSingletonConstantCommand extends AbstractRpcAction {
@Reference
- private RpcConsumerRegistry rpcService;
+ private RpcService rpcService;
@Argument(index = 0, name = "constant", required = true)
private String constant;
@Override
protected ListenableFuture<? extends RpcResult<?>> invokeRpc() {
- return rpcService.getRpcService(OdlMdsalLowlevelControlService.class)
- .registerSingletonConstant(new RegisterSingletonConstantInputBuilder()
- .setConstant(constant)
- .build());
-
+ return rpcService.getRpc(RegisterSingletonConstant.class)
+ .invoke(new RegisterSingletonConstantInputBuilder().setConstant(constant).build());
}
}
import org.apache.karaf.shell.api.action.lifecycle.Reference;
import org.apache.karaf.shell.api.action.lifecycle.Service;
import org.opendaylight.clustering.it.karaf.cli.AbstractRpcAction;
-import org.opendaylight.mdsal.binding.api.RpcConsumerRegistry;
-import org.opendaylight.yang.gen.v1.tag.opendaylight.org._2017.controller.yang.lowlevel.control.rev170215.OdlMdsalLowlevelControlService;
+import org.opendaylight.mdsal.binding.api.RpcService;
+import org.opendaylight.yang.gen.v1.tag.opendaylight.org._2017.controller.yang.lowlevel.control.rev170215.RemoveShardReplica;
import org.opendaylight.yang.gen.v1.tag.opendaylight.org._2017.controller.yang.lowlevel.control.rev170215.RemoveShardReplicaInputBuilder;
import org.opendaylight.yangtools.yang.common.RpcResult;
@Command(scope = "test-app", name = "remove-shard-replica", description = "Run a remove-shard-replica test")
public class RemoveShardReplicaCommand extends AbstractRpcAction {
@Reference
- private RpcConsumerRegistry rpcService;
+ private RpcService rpcService;
@Argument(index = 0, name = "shard-name", required = true)
private String shardName;
@Override
protected ListenableFuture<? extends RpcResult<?>> invokeRpc() {
- return rpcService.getRpcService(OdlMdsalLowlevelControlService.class)
- .removeShardReplica(new RemoveShardReplicaInputBuilder().setShardName(shardName).build());
+ return rpcService.getRpc(RemoveShardReplica.class)
+ .invoke(new RemoveShardReplicaInputBuilder().setShardName(shardName).build());
}
}
import org.apache.karaf.shell.api.action.lifecycle.Reference;
import org.apache.karaf.shell.api.action.lifecycle.Service;
import org.opendaylight.clustering.it.karaf.cli.AbstractRpcAction;
-import org.opendaylight.mdsal.binding.api.RpcConsumerRegistry;
-import org.opendaylight.yang.gen.v1.tag.opendaylight.org._2017.controller.yang.lowlevel.control.rev170215.OdlMdsalLowlevelControlService;
+import org.opendaylight.mdsal.binding.api.RpcService;
+import org.opendaylight.yang.gen.v1.tag.opendaylight.org._2017.controller.yang.lowlevel.control.rev170215.ShutdownShardReplica;
import org.opendaylight.yang.gen.v1.tag.opendaylight.org._2017.controller.yang.lowlevel.control.rev170215.ShutdownShardReplicaInputBuilder;
import org.opendaylight.yangtools.yang.common.RpcResult;
@Command(scope = "test-app", name = "shutdown-shard-replica", description = " Run a shutdown-shard-replica test")
public class ShutdownShardReplicaCommand extends AbstractRpcAction {
@Reference
- private RpcConsumerRegistry rpcService;
+ private RpcService rpcService;
@Argument(index = 0, name = "shard-name", required = true)
private String shardName;
@Override
protected ListenableFuture<? extends RpcResult<?>> invokeRpc() {
- return rpcService.getRpcService(OdlMdsalLowlevelControlService.class)
- .shutdownShardReplica(new ShutdownShardReplicaInputBuilder()
+ return rpcService.getRpc(ShutdownShardReplica.class)
+ .invoke(new ShutdownShardReplicaInputBuilder()
.setShardName(shardName)
.build());
}
import org.apache.karaf.shell.api.action.lifecycle.Reference;
import org.apache.karaf.shell.api.action.lifecycle.Service;
import org.opendaylight.clustering.it.karaf.cli.AbstractRpcAction;
-import org.opendaylight.mdsal.binding.api.RpcConsumerRegistry;
-import org.opendaylight.yang.gen.v1.tag.opendaylight.org._2017.controller.yang.lowlevel.control.rev170215.OdlMdsalLowlevelControlService;
+import org.opendaylight.mdsal.binding.api.RpcService;
+import org.opendaylight.yang.gen.v1.tag.opendaylight.org._2017.controller.yang.lowlevel.control.rev170215.StartPublishNotifications;
import org.opendaylight.yang.gen.v1.tag.opendaylight.org._2017.controller.yang.lowlevel.control.rev170215.StartPublishNotificationsInputBuilder;
import org.opendaylight.yangtools.yang.common.RpcResult;
import org.opendaylight.yangtools.yang.common.Uint32;
description = "Run a start-publish-notifications test")
public class StartPublishNotificationsCommand extends AbstractRpcAction {
@Reference
- private RpcConsumerRegistry rpcService;
+ private RpcService rpcService;
@Argument(index = 0, name = "id", required = true)
private String id;
@Argument(index = 1, name = "seconds", required = true)
@Override
protected ListenableFuture<? extends RpcResult<?>> invokeRpc() {
- return rpcService.getRpcService(OdlMdsalLowlevelControlService.class)
- .startPublishNotifications(new StartPublishNotificationsInputBuilder()
+ return rpcService.getRpc(StartPublishNotifications.class)
+ .invoke(new StartPublishNotificationsInputBuilder()
.setId(id)
.setSeconds(Uint32.valueOf(seconds))
.setNotificationsPerSecond(Uint32.valueOf(notificationsPerSecond))
import org.apache.karaf.shell.api.action.lifecycle.Reference;
import org.apache.karaf.shell.api.action.lifecycle.Service;
import org.opendaylight.clustering.it.karaf.cli.AbstractRpcAction;
-import org.opendaylight.mdsal.binding.api.RpcConsumerRegistry;
-import org.opendaylight.yang.gen.v1.tag.opendaylight.org._2017.controller.yang.lowlevel.control.rev170215.OdlMdsalLowlevelControlService;
+import org.opendaylight.mdsal.binding.api.RpcService;
+import org.opendaylight.yang.gen.v1.tag.opendaylight.org._2017.controller.yang.lowlevel.control.rev170215.SubscribeDdtl;
import org.opendaylight.yang.gen.v1.tag.opendaylight.org._2017.controller.yang.lowlevel.control.rev170215.SubscribeDdtlInputBuilder;
import org.opendaylight.yangtools.yang.common.RpcResult;
@Command(scope = "test-app", name = "subscribe-ddtl", description = "Run a subscribe-ddtl test")
public class SubscribeDdtlCommand extends AbstractRpcAction {
@Reference
- private RpcConsumerRegistry rpcService;
+ private RpcService rpcService;
@Override
protected ListenableFuture<? extends RpcResult<?>> invokeRpc() {
- return rpcService.getRpcService(OdlMdsalLowlevelControlService.class)
- .subscribeDdtl(new SubscribeDdtlInputBuilder().build());
+ return rpcService.getRpc(SubscribeDdtl.class).invoke(new SubscribeDdtlInputBuilder().build());
}
}
import org.apache.karaf.shell.api.action.lifecycle.Reference;
import org.apache.karaf.shell.api.action.lifecycle.Service;
import org.opendaylight.clustering.it.karaf.cli.AbstractRpcAction;
-import org.opendaylight.mdsal.binding.api.RpcConsumerRegistry;
-import org.opendaylight.yang.gen.v1.tag.opendaylight.org._2017.controller.yang.lowlevel.control.rev170215.OdlMdsalLowlevelControlService;
+import org.opendaylight.mdsal.binding.api.RpcService;
+import org.opendaylight.yang.gen.v1.tag.opendaylight.org._2017.controller.yang.lowlevel.control.rev170215.SubscribeDtcl;
import org.opendaylight.yang.gen.v1.tag.opendaylight.org._2017.controller.yang.lowlevel.control.rev170215.SubscribeDtclInputBuilder;
import org.opendaylight.yangtools.yang.common.RpcResult;
@Command(scope = "test-app", name = "subscribe-dtcl", description = "Run a subscribe-dtcl test")
public class SubscribeDtclCommand extends AbstractRpcAction {
@Reference
- private RpcConsumerRegistry rpcService;
+ private RpcService rpcService;
@Override
protected ListenableFuture<? extends RpcResult<?>> invokeRpc() {
- return rpcService.getRpcService(OdlMdsalLowlevelControlService.class)
- .subscribeDtcl(new SubscribeDtclInputBuilder().build());
+ return rpcService.getRpc(SubscribeDtcl.class).invoke(new SubscribeDtclInputBuilder().build());
}
}
import org.apache.karaf.shell.api.action.lifecycle.Reference;
import org.apache.karaf.shell.api.action.lifecycle.Service;
import org.opendaylight.clustering.it.karaf.cli.AbstractRpcAction;
-import org.opendaylight.mdsal.binding.api.RpcConsumerRegistry;
-import org.opendaylight.yang.gen.v1.tag.opendaylight.org._2017.controller.yang.lowlevel.control.rev170215.OdlMdsalLowlevelControlService;
+import org.opendaylight.mdsal.binding.api.RpcService;
+import org.opendaylight.yang.gen.v1.tag.opendaylight.org._2017.controller.yang.lowlevel.control.rev170215.SubscribeYnl;
import org.opendaylight.yang.gen.v1.tag.opendaylight.org._2017.controller.yang.lowlevel.control.rev170215.SubscribeYnlInputBuilder;
import org.opendaylight.yangtools.yang.common.RpcResult;
@Command(scope = "test-app", name = "subscribe-ynl", description = "Run a subscribe-ynl test")
public class SubscribeYnlCommand extends AbstractRpcAction {
@Reference
- private RpcConsumerRegistry rpcService;
+ private RpcService rpcService;
@Argument(index = 0, name = "id", required = true)
private String id;
@Override
protected ListenableFuture<? extends RpcResult<?>> invokeRpc() {
- return rpcService.getRpcService(OdlMdsalLowlevelControlService.class)
- .subscribeYnl(new SubscribeYnlInputBuilder().setId(id).build());
+ return rpcService.getRpc(SubscribeYnl.class).invoke(new SubscribeYnlInputBuilder().setId(id).build());
}
}
import org.apache.karaf.shell.api.action.lifecycle.Service;
import org.opendaylight.clustering.it.karaf.cli.AbstractRpcAction;
import org.opendaylight.clustering.it.karaf.cli.InstanceIdentifierSupport;
-import org.opendaylight.mdsal.binding.api.RpcConsumerRegistry;
-import org.opendaylight.yang.gen.v1.tag.opendaylight.org._2017.controller.yang.lowlevel.control.rev170215.OdlMdsalLowlevelControlService;
+import org.opendaylight.mdsal.binding.api.RpcService;
+import org.opendaylight.yang.gen.v1.tag.opendaylight.org._2017.controller.yang.lowlevel.control.rev170215.UnregisterBoundConstant;
import org.opendaylight.yang.gen.v1.tag.opendaylight.org._2017.controller.yang.lowlevel.control.rev170215.UnregisterBoundConstantInputBuilder;
import org.opendaylight.yangtools.yang.common.RpcResult;
@Command(scope = "test-app", name = "unregister-bound-constant", description = "Run an unregister-bound-constant test")
public class UnregisterBoundConstantCommand extends AbstractRpcAction {
@Reference
- private RpcConsumerRegistry rpcService;
+ private RpcService rpcService;
@Reference
private InstanceIdentifierSupport iidSupport;
@Argument(index = 0, name = "context", required = true)
@Override
protected ListenableFuture<? extends RpcResult<?>> invokeRpc() {
- return rpcService.getRpcService(OdlMdsalLowlevelControlService.class)
- .unregisterBoundConstant(new UnregisterBoundConstantInputBuilder()
+ return rpcService.getRpc(UnregisterBoundConstant.class)
+ .invoke(new UnregisterBoundConstantInputBuilder()
.setContext(iidSupport.parseArgument(context))
.build());
}
import org.apache.karaf.shell.api.action.lifecycle.Reference;
import org.apache.karaf.shell.api.action.lifecycle.Service;
import org.opendaylight.clustering.it.karaf.cli.AbstractRpcAction;
-import org.opendaylight.mdsal.binding.api.RpcConsumerRegistry;
-import org.opendaylight.yang.gen.v1.tag.opendaylight.org._2017.controller.yang.lowlevel.control.rev170215.OdlMdsalLowlevelControlService;
+import org.opendaylight.mdsal.binding.api.RpcService;
+import org.opendaylight.yang.gen.v1.tag.opendaylight.org._2017.controller.yang.lowlevel.control.rev170215.UnregisterConstant;
import org.opendaylight.yang.gen.v1.tag.opendaylight.org._2017.controller.yang.lowlevel.control.rev170215.UnregisterConstantInputBuilder;
import org.opendaylight.yangtools.yang.common.RpcResult;
@Command(scope = "test-app", name = "unregister-constant", description = "Run an unregister-constant test")
public class UnregisterConstantCommand extends AbstractRpcAction {
@Reference
- private RpcConsumerRegistry rpcService;
+ private RpcService rpcService;
@Override
protected ListenableFuture<? extends RpcResult<?>> invokeRpc() {
- return rpcService.getRpcService(OdlMdsalLowlevelControlService.class)
- .unregisterConstant(new UnregisterConstantInputBuilder().build());
+ return rpcService.getRpc(UnregisterConstant.class).invoke(new UnregisterConstantInputBuilder().build());
}
}
import org.apache.karaf.shell.api.action.lifecycle.Reference;
import org.apache.karaf.shell.api.action.lifecycle.Service;
import org.opendaylight.clustering.it.karaf.cli.AbstractRpcAction;
-import org.opendaylight.mdsal.binding.api.RpcConsumerRegistry;
-import org.opendaylight.yang.gen.v1.tag.opendaylight.org._2017.controller.yang.lowlevel.control.rev170215.OdlMdsalLowlevelControlService;
+import org.opendaylight.mdsal.binding.api.RpcService;
+import org.opendaylight.yang.gen.v1.tag.opendaylight.org._2017.controller.yang.lowlevel.control.rev170215.UnregisterDefaultConstant;
import org.opendaylight.yang.gen.v1.tag.opendaylight.org._2017.controller.yang.lowlevel.control.rev170215.UnregisterDefaultConstantInputBuilder;
import org.opendaylight.yangtools.yang.common.RpcResult;
description = "Run an unregister-default-constant test")
public class UnregisterDefaultConstantCommand extends AbstractRpcAction {
@Reference
- private RpcConsumerRegistry rpcService;
+ private RpcService rpcService;
@Override
protected ListenableFuture<? extends RpcResult<?>> invokeRpc() {
- return rpcService.getRpcService(OdlMdsalLowlevelControlService.class)
- .unregisterDefaultConstant(new UnregisterDefaultConstantInputBuilder().build());
+ return rpcService.getRpc(UnregisterDefaultConstant.class)
+ .invoke(new UnregisterDefaultConstantInputBuilder().build());
}
}
import org.apache.karaf.shell.api.action.lifecycle.Reference;
import org.apache.karaf.shell.api.action.lifecycle.Service;
import org.opendaylight.clustering.it.karaf.cli.AbstractRpcAction;
-import org.opendaylight.mdsal.binding.api.RpcConsumerRegistry;
-import org.opendaylight.yang.gen.v1.tag.opendaylight.org._2017.controller.yang.lowlevel.control.rev170215.OdlMdsalLowlevelControlService;
+import org.opendaylight.mdsal.binding.api.RpcService;
+import org.opendaylight.yang.gen.v1.tag.opendaylight.org._2017.controller.yang.lowlevel.control.rev170215.UnregisterFlappingSingleton;
import org.opendaylight.yang.gen.v1.tag.opendaylight.org._2017.controller.yang.lowlevel.control.rev170215.UnregisterFlappingSingletonInputBuilder;
import org.opendaylight.yangtools.yang.common.RpcResult;
description = "Run an unregister-flapping-singleton test")
public class UnregisterFlappingSingletonCommand extends AbstractRpcAction {
@Reference
- private RpcConsumerRegistry rpcService;
+ private RpcService rpcService;
@Override
protected ListenableFuture<? extends RpcResult<?>> invokeRpc() {
- return rpcService.getRpcService(OdlMdsalLowlevelControlService.class)
- .unregisterFlappingSingleton(new UnregisterFlappingSingletonInputBuilder().build());
+ return rpcService.getRpc(UnregisterFlappingSingleton.class)
+ .invoke(new UnregisterFlappingSingletonInputBuilder().build());
}
}
import org.apache.karaf.shell.api.action.lifecycle.Reference;
import org.apache.karaf.shell.api.action.lifecycle.Service;
import org.opendaylight.clustering.it.karaf.cli.AbstractRpcAction;
-import org.opendaylight.mdsal.binding.api.RpcConsumerRegistry;
-import org.opendaylight.yang.gen.v1.tag.opendaylight.org._2017.controller.yang.lowlevel.control.rev170215.OdlMdsalLowlevelControlService;
+import org.opendaylight.mdsal.binding.api.RpcService;
+import org.opendaylight.yang.gen.v1.tag.opendaylight.org._2017.controller.yang.lowlevel.control.rev170215.UnregisterSingletonConstant;
import org.opendaylight.yang.gen.v1.tag.opendaylight.org._2017.controller.yang.lowlevel.control.rev170215.UnregisterSingletonConstantInputBuilder;
import org.opendaylight.yangtools.yang.common.RpcResult;
description = "Run an unregister-singleton-constant test")
public class UnregisterSingletonConstantCommand extends AbstractRpcAction {
@Reference
- private RpcConsumerRegistry rpcService;
+ private RpcService rpcService;
@Override
protected ListenableFuture<? extends RpcResult<?>> invokeRpc() {
- return rpcService.getRpcService(OdlMdsalLowlevelControlService.class)
- .unregisterSingletonConstant(new UnregisterSingletonConstantInputBuilder().build());
+ return rpcService.getRpc(UnregisterSingletonConstant.class)
+ .invoke(new UnregisterSingletonConstantInputBuilder().build());
}
}
import org.apache.karaf.shell.api.action.lifecycle.Reference;
import org.apache.karaf.shell.api.action.lifecycle.Service;
import org.opendaylight.clustering.it.karaf.cli.AbstractRpcAction;
-import org.opendaylight.mdsal.binding.api.RpcConsumerRegistry;
-import org.opendaylight.yang.gen.v1.tag.opendaylight.org._2017.controller.yang.lowlevel.control.rev170215.OdlMdsalLowlevelControlService;
+import org.opendaylight.mdsal.binding.api.RpcService;
+import org.opendaylight.yang.gen.v1.tag.opendaylight.org._2017.controller.yang.lowlevel.control.rev170215.UnsubscribeDdtl;
import org.opendaylight.yang.gen.v1.tag.opendaylight.org._2017.controller.yang.lowlevel.control.rev170215.UnsubscribeDdtlInputBuilder;
import org.opendaylight.yangtools.yang.common.RpcResult;
@Command(scope = "test-app", name = "unsubscribe-ddtl", description = "Run an unsubscribe-ddtl test")
public class UnsubscribeDdtlCommand extends AbstractRpcAction {
@Reference
- private RpcConsumerRegistry rpcService;
+ private RpcService rpcService;
@Override
protected ListenableFuture<? extends RpcResult<?>> invokeRpc() {
- return rpcService.getRpcService(OdlMdsalLowlevelControlService.class)
- .unsubscribeDdtl(new UnsubscribeDdtlInputBuilder().build());
+ return rpcService.getRpc(UnsubscribeDdtl.class).invoke(new UnsubscribeDdtlInputBuilder().build());
}
}
import org.apache.karaf.shell.api.action.lifecycle.Reference;
import org.apache.karaf.shell.api.action.lifecycle.Service;
import org.opendaylight.clustering.it.karaf.cli.AbstractRpcAction;
-import org.opendaylight.mdsal.binding.api.RpcConsumerRegistry;
-import org.opendaylight.yang.gen.v1.tag.opendaylight.org._2017.controller.yang.lowlevel.control.rev170215.OdlMdsalLowlevelControlService;
+import org.opendaylight.mdsal.binding.api.RpcService;
+import org.opendaylight.yang.gen.v1.tag.opendaylight.org._2017.controller.yang.lowlevel.control.rev170215.UnsubscribeDtcl;
import org.opendaylight.yang.gen.v1.tag.opendaylight.org._2017.controller.yang.lowlevel.control.rev170215.UnsubscribeDtclInputBuilder;
import org.opendaylight.yangtools.yang.common.RpcResult;
@Command(scope = "test-app", name = "unsubscribe-dtcl", description = "Run an unsubscribe-dtcl test")
public class UnsubscribeDtclCommand extends AbstractRpcAction {
@Reference
- private RpcConsumerRegistry rpcService;
+ private RpcService rpcService;
@Override
protected ListenableFuture<? extends RpcResult<?>> invokeRpc() {
- return rpcService.getRpcService(OdlMdsalLowlevelControlService.class)
- .unsubscribeDtcl(new UnsubscribeDtclInputBuilder().build());
+ return rpcService.getRpc(UnsubscribeDtcl.class).invoke(new UnsubscribeDtclInputBuilder().build());
}
}
import org.apache.karaf.shell.api.action.lifecycle.Reference;
import org.apache.karaf.shell.api.action.lifecycle.Service;
import org.opendaylight.clustering.it.karaf.cli.AbstractRpcAction;
-import org.opendaylight.mdsal.binding.api.RpcConsumerRegistry;
-import org.opendaylight.yang.gen.v1.tag.opendaylight.org._2017.controller.yang.lowlevel.control.rev170215.OdlMdsalLowlevelControlService;
+import org.opendaylight.mdsal.binding.api.RpcService;
+import org.opendaylight.yang.gen.v1.tag.opendaylight.org._2017.controller.yang.lowlevel.control.rev170215.UnsubscribeYnl;
import org.opendaylight.yang.gen.v1.tag.opendaylight.org._2017.controller.yang.lowlevel.control.rev170215.UnsubscribeYnlInputBuilder;
import org.opendaylight.yangtools.yang.common.RpcResult;
@Command(scope = "test-app", name = "unsubscribe-ynl", description = "Run an unsubscribe-ynl test")
public class UnsubscribeYnlCommand extends AbstractRpcAction {
@Reference
- private RpcConsumerRegistry rpcService;
+ private RpcService rpcService;
@Argument(index = 0, name = "id", required = true)
private String id;
@Override
protected ListenableFuture<? extends RpcResult<?>> invokeRpc() {
- return rpcService.getRpcService(OdlMdsalLowlevelControlService.class)
- .unsubscribeYnl(new UnsubscribeYnlInputBuilder()
- .setId(id)
- .build());
+ return rpcService.getRpc(UnsubscribeYnl.class)
+ .invoke(new UnsubscribeYnlInputBuilder().setId(id).build());
}
}
import org.apache.karaf.shell.api.action.lifecycle.Reference;
import org.apache.karaf.shell.api.action.lifecycle.Service;
import org.opendaylight.clustering.it.karaf.cli.AbstractRpcAction;
-import org.opendaylight.mdsal.binding.api.RpcConsumerRegistry;
-import org.opendaylight.yang.gen.v1.tag.opendaylight.org._2017.controller.yang.lowlevel.control.rev170215.OdlMdsalLowlevelControlService;
+import org.opendaylight.mdsal.binding.api.RpcService;
+import org.opendaylight.yang.gen.v1.tag.opendaylight.org._2017.controller.yang.lowlevel.control.rev170215.WriteTransactions;
import org.opendaylight.yang.gen.v1.tag.opendaylight.org._2017.controller.yang.lowlevel.control.rev170215.WriteTransactionsInputBuilder;
import org.opendaylight.yangtools.yang.common.RpcResult;
import org.opendaylight.yangtools.yang.common.Uint32;
@Command(scope = "test-app", name = "write-transactions", description = "Run a write-transactions test")
public class WriteTransactionsCommand extends AbstractRpcAction {
@Reference
- private RpcConsumerRegistry rpcService;
+ private RpcService rpcService;
@Argument(index = 0, name = "id", required = true)
private String id;
@Argument(index = 1, name = "seconds", required = true)
@Override
protected ListenableFuture<? extends RpcResult<?>> invokeRpc() {
- return rpcService.getRpcService(OdlMdsalLowlevelControlService.class)
- .writeTransactions(new WriteTransactionsInputBuilder()
+ return rpcService.getRpc(WriteTransactions.class)
+ .invoke(new WriteTransactionsInputBuilder()
.setId(id)
.setSeconds(Uint32.valueOf(seconds))
.setTransactionsPerSecond(Uint32.valueOf(transactionsPerSecond))
import org.apache.karaf.shell.api.action.lifecycle.Reference;
import org.apache.karaf.shell.api.action.lifecycle.Service;
import org.opendaylight.clustering.it.karaf.cli.AbstractRpcAction;
-import org.opendaylight.mdsal.binding.api.RpcConsumerRegistry;
+import org.opendaylight.mdsal.binding.api.RpcService;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.people.rev140818.AddPerson;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.people.rev140818.AddPersonInputBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.people.rev140818.PeopleService;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.people.rev140818.PersonId;
import org.opendaylight.yangtools.yang.common.RpcResult;
import org.opendaylight.yangtools.yang.common.Uint32;
@Command(scope = "test-app", name = "add-person", description = " Run an add-person test")
public class AddPersonCommand extends AbstractRpcAction {
@Reference
- private RpcConsumerRegistry rpcService;
+ private RpcService rpcService;
@Argument(index = 0, name = "id", required = true)
private PersonId id;
@Argument(index = 1, name = "gender", required = true)
@Override
protected ListenableFuture<? extends RpcResult<?>> invokeRpc() {
- return rpcService.getRpcService(PeopleService.class).addPerson(new AddPersonInputBuilder()
+ return rpcService.getRpc(AddPerson.class).invoke(new AddPersonInputBuilder()
.setId(id)
.setGender(gender)
.setAge(Uint32.valueOf(age))
import org.apache.karaf.shell.api.action.lifecycle.Reference;
import org.apache.karaf.shell.api.action.lifecycle.Service;
import org.opendaylight.clustering.it.karaf.cli.AbstractRpcAction;
-import org.opendaylight.mdsal.binding.api.RpcConsumerRegistry;
+import org.opendaylight.mdsal.binding.api.RpcService;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.controller.basic.rpc.test.rev160120.BasicGlobal;
import org.opendaylight.yang.gen.v1.urn.opendaylight.controller.basic.rpc.test.rev160120.BasicGlobalInputBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.controller.basic.rpc.test.rev160120.BasicRpcTestService;
import org.opendaylight.yangtools.yang.common.RpcResult;
@Service
@Command(scope = "test-app", name = "global-basic", description = "Run a global-basic test")
public class BasicGlobalCommand extends AbstractRpcAction {
@Reference
- private RpcConsumerRegistry rpcService;
+ private RpcService rpcService;
@Override
protected ListenableFuture<? extends RpcResult<?>> invokeRpc() {
- return rpcService.getRpcService(BasicRpcTestService.class).basicGlobal(new BasicGlobalInputBuilder().build());
+ return rpcService.getRpc(BasicGlobal.class).invoke(new BasicGlobalInputBuilder().build());
}
}
<parent>
<groupId>org.opendaylight.controller</groupId>
<artifactId>mdsal-parent</artifactId>
- <version>7.0.2-SNAPSHOT</version>
+ <version>9.0.3-SNAPSHOT</version>
<relativePath>../../../parent</relativePath>
</parent>
<parent>
<groupId>org.opendaylight.odlparent</groupId>
<artifactId>odlparent-lite</artifactId>
- <version>12.0.1</version>
+ <version>13.0.11</version>
<relativePath/>
</parent>
<groupId>org.opendaylight.controller.samples</groupId>
<artifactId>clustering-test-app</artifactId>
- <version>7.0.2-SNAPSHOT</version>
+ <version>9.0.3-SNAPSHOT</version>
<packaging>pom</packaging>
<properties>
<parent>
<groupId>org.opendaylight.controller</groupId>
<artifactId>mdsal-parent</artifactId>
- <version>7.0.2-SNAPSHOT</version>
+ <version>9.0.3-SNAPSHOT</version>
<relativePath>../../../parent</relativePath>
</parent>
<packaging>bundle</packaging>
<dependencies>
+ <dependency>
+ <groupId>com.github.spotbugs</groupId>
+ <artifactId>spotbugs-annotations</artifactId>
+ <optional>true</optional>
+ </dependency>
<dependency>
<groupId>org.opendaylight.mdsal</groupId>
<artifactId>mdsal-eos-binding-api</artifactId>
</dependency>
<dependency>
<groupId>org.opendaylight.mdsal</groupId>
- <artifactId>mdsal-singleton-common-api</artifactId>
+ <artifactId>mdsal-singleton-api</artifactId>
</dependency>
<dependency>
<groupId>org.opendaylight.controller.samples</groupId>
import javax.inject.Singleton;
import org.opendaylight.mdsal.binding.api.DataBroker;
import org.opendaylight.mdsal.binding.api.NotificationService;
-import org.opendaylight.mdsal.binding.api.WriteTransaction;
+import org.opendaylight.mdsal.binding.api.NotificationService.Listener;
import org.opendaylight.mdsal.common.api.CommitInfo;
import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.people.rev140818.CarPeople;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.people.rev140818.car.people.CarPersonBuilder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.people.rev140818.car.people.CarPersonKey;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.purchase.rev140818.CarBought;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.purchase.rev140818.CarPurchaseListener;
import org.opendaylight.yangtools.concepts.Registration;
import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
import org.osgi.service.component.annotations.Activate;
@Singleton
@Component(service = { })
-public final class PeopleCarListener implements CarPurchaseListener {
- private static final Logger LOG = LoggerFactory.getLogger(PeopleCarListener.class);
+public final class CarBoughtListener implements Listener<CarBought> {
+ private static final Logger LOG = LoggerFactory.getLogger(CarBoughtListener.class);
private final DataBroker dataProvider;
private final Registration reg;
@Inject
@Activate
- public PeopleCarListener(@Reference final DataBroker dataProvider,
+ public CarBoughtListener(@Reference final DataBroker dataProvider,
@Reference final NotificationService notifService) {
this.dataProvider = requireNonNull(dataProvider);
- reg = notifService.registerNotificationListener(this);
+ reg = notifService.registerListener(CarBought.class, this);
}
@PreDestroy
}
@Override
- public void onCarBought(final CarBought notification) {
-
- final CarPerson carPerson = new CarPersonBuilder()
+ public void onNotification(final CarBought notification) {
+ final var carPerson = new CarPersonBuilder()
.withKey(new CarPersonKey(notification.getCarId(), notification.getPersonId()))
.build();
LOG.info("Car bought, adding car-person entry: [{}]", carPerson);
- InstanceIdentifier<CarPerson> carPersonIId = InstanceIdentifier.builder(CarPeople.class)
+ final var carPersonIId = InstanceIdentifier.builder(CarPeople.class)
.child(CarPerson.class, carPerson.key()).build();
-
- WriteTransaction tx = dataProvider.newWriteOnlyTransaction();
+ final var tx = dataProvider.newWriteOnlyTransaction();
tx.put(LogicalDatastoreType.CONFIGURATION, carPersonIId, carPerson);
tx.commit().addCallback(new FutureCallback<CommitInfo>() {
import com.google.common.collect.ImmutableSet;
import com.google.common.util.concurrent.FutureCallback;
+import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.MoreExecutors;
import com.google.common.util.concurrent.SettableFuture;
import javax.inject.Inject;
import javax.inject.Singleton;
import org.opendaylight.mdsal.binding.api.DataBroker;
+import org.opendaylight.mdsal.binding.api.NotificationPublishService;
import org.opendaylight.mdsal.binding.api.RpcProviderService;
import org.opendaylight.mdsal.binding.api.WriteTransaction;
import org.opendaylight.mdsal.common.api.CommitInfo;
import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.purchase.rev140818.CarPurchaseService;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.purchase.rev140818.BuyCar;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.purchase.rev140818.BuyCarOutputBuilder;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.purchase.rev140818.CarBoughtBuilder;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.people.rev140818.AddPerson;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.people.rev140818.AddPersonInput;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.people.rev140818.AddPersonOutput;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.people.rev140818.AddPersonOutputBuilder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.people.rev140818.People;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.people.rev140818.PeopleService;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.people.rev140818.people.Person;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.people.rev140818.people.PersonBuilder;
-import org.opendaylight.yangtools.concepts.ObjectRegistration;
+import org.opendaylight.yangtools.concepts.Registration;
import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
import org.opendaylight.yangtools.yang.common.ErrorType;
import org.opendaylight.yangtools.yang.common.RpcResult;
@Singleton
@Component(service = { })
-public final class PeopleProvider implements PeopleService, AutoCloseable {
- private static final Logger LOG = LoggerFactory.getLogger(PeopleProvider.class);
+public final class AddPersonImpl implements AddPerson, AutoCloseable {
+ private static final Logger LOG = LoggerFactory.getLogger(AddPersonImpl.class);
- private final Set<ObjectRegistration<?>> regs = new HashSet<>();
- private final DataBroker dataProvider;
+ private final Set<Registration> regs = new HashSet<>();
private final RpcProviderService rpcProviderService;
- private final CarPurchaseService rpcImplementation;
+ private final DataBroker dataProvider;
+ private final BuyCar buyCarRpc;
@Inject
@Activate
- public PeopleProvider(@Reference final DataBroker dataProvider,
- @Reference final RpcProviderService rpcProviderService,
- @Reference final CarPurchaseService rpcImplementation) {
+ public AddPersonImpl(@Reference final DataBroker dataProvider,
+ @Reference final NotificationPublishService notificationProvider,
+ @Reference final RpcProviderService rpcProviderService) {
this.dataProvider = requireNonNull(dataProvider);
this.rpcProviderService = requireNonNull(rpcProviderService);
- this.rpcImplementation = requireNonNull(rpcImplementation);
- // Add global registration
- regs.add(rpcProviderService.registerRpcImplementation(CarPurchaseService.class, rpcImplementation));
+ requireNonNull(notificationProvider);
+ buyCarRpc = input -> {
+ LOG.info("Routed RPC buyCar : generating notification for buying car [{}]", input);
+ final var carBought = new CarBoughtBuilder()
+ .setCarId(input.getCarId())
+ .setPersonId(input.getPersonId())
+ .build();
+ return Futures.transform(notificationProvider.offerNotification(carBought),
+ result -> RpcResultBuilder.success(new BuyCarOutputBuilder().build()).build(),
+ MoreExecutors.directExecutor());
+ };
+
+ regs.add(rpcProviderService.registerRpcImplementation(buyCarRpc));
+ regs.add(rpcProviderService.registerRpcImplementation(this));
}
+ @PreDestroy
+ @Deactivate
@Override
- public ListenableFuture<RpcResult<AddPersonOutput>> addPerson(final AddPersonInput input) {
+ public void close() {
+ regs.forEach(Registration::close);
+ regs.clear();
+ }
+
+ @Override
+ public ListenableFuture<RpcResult<AddPersonOutput>> invoke(final AddPersonInput input) {
LOG.info("RPC addPerson : adding person [{}]", input);
PersonBuilder builder = new PersonBuilder(input);
@Override
public void onSuccess(final CommitInfo result) {
LOG.info("RPC addPerson : person added successfully [{}]", person);
- regs.add(rpcProviderService.registerRpcImplementation(CarPurchaseService.class, rpcImplementation,
- ImmutableSet.of(personId)));
+ regs.add(rpcProviderService.registerRpcImplementation(buyCarRpc, ImmutableSet.of(personId)));
LOG.info("RPC addPerson : routed rpc registered for instance ID [{}]", personId);
futureResult.set(RpcResultBuilder.success(new AddPersonOutputBuilder().build()).build());
}
}, MoreExecutors.directExecutor());
return futureResult;
}
-
- @PreDestroy
- @Deactivate
- @Override
- public void close() {
- regs.forEach(ObjectRegistration::close);
- regs.clear();
- }
}
import javax.inject.Inject;
import javax.inject.Singleton;
import org.opendaylight.mdsal.binding.api.RpcProviderService;
-import org.opendaylight.mdsal.singleton.common.api.ClusterSingletonService;
-import org.opendaylight.mdsal.singleton.common.api.ClusterSingletonServiceProvider;
-import org.opendaylight.mdsal.singleton.common.api.ServiceGroupIdentifier;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.controller.basic.rpc.test.rev160120.BasicGlobalInput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.controller.basic.rpc.test.rev160120.BasicGlobalOutput;
+import org.opendaylight.mdsal.singleton.api.ClusterSingletonService;
+import org.opendaylight.mdsal.singleton.api.ClusterSingletonServiceProvider;
+import org.opendaylight.mdsal.singleton.api.ServiceGroupIdentifier;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.controller.basic.rpc.test.rev160120.BasicGlobal;
import org.opendaylight.yang.gen.v1.urn.opendaylight.controller.basic.rpc.test.rev160120.BasicGlobalOutputBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.controller.basic.rpc.test.rev160120.BasicRpcTestService;
-import org.opendaylight.yangtools.concepts.ObjectRegistration;
import org.opendaylight.yangtools.concepts.Registration;
-import org.opendaylight.yangtools.yang.common.RpcResult;
import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
import org.osgi.service.component.annotations.Activate;
import org.osgi.service.component.annotations.Component;
@Singleton
@Component(service = { })
-public final class BasicRpcTestProvider implements ClusterSingletonService, BasicRpcTestService {
+public final class BasicRpcTestProvider implements ClusterSingletonService {
private static final Logger LOG = LoggerFactory.getLogger(BasicRpcTestProvider.class);
- private static final ServiceGroupIdentifier IDENTIFIER = ServiceGroupIdentifier.create("Basic-rpc-test");
+ private static final ServiceGroupIdentifier IDENTIFIER = new ServiceGroupIdentifier("Basic-rpc-test");
private final RpcProviderService rpcProviderRegistry;
private final Registration singletonRegistration;
- private ObjectRegistration<?> rpcRegistration;
+ private Registration rpcRegistration = null;
@Inject
@Activate
@Override
public void instantiateServiceInstance() {
LOG.info("Basic testing rpc registered as global");
- rpcRegistration = rpcProviderRegistry.registerRpcImplementation(BasicRpcTestService.class, this);
+ rpcRegistration = rpcProviderRegistry.registerRpcImplementation((BasicGlobal) input -> {
+ LOG.info("Basic test global rpc invoked");
+ return RpcResultBuilder.success(new BasicGlobalOutputBuilder().build()).buildFuture();
+ });
}
@Override
public ServiceGroupIdentifier getIdentifier() {
return IDENTIFIER;
}
-
- @Override
- public ListenableFuture<RpcResult<BasicGlobalOutput>> basicGlobal(final BasicGlobalInput input) {
- LOG.info("Basic test global rpc invoked");
-
- return Futures.immediateFuture(RpcResultBuilder.success(new BasicGlobalOutputBuilder().build()).build());
- }
}
*/
package org.opendaylight.controller.clustering.it.provider;
-import org.opendaylight.mdsal.binding.api.DataObjectModification;
-import org.opendaylight.mdsal.binding.api.DataObjectModification.ModificationType;
+import java.util.List;
import org.opendaylight.mdsal.binding.api.DataTreeChangeListener;
import org.opendaylight.mdsal.binding.api.DataTreeModification;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.Cars;
-import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
private static final Logger LOG = LoggerFactory.getLogger(CarDataTreeChangeListener.class);
@Override
- public void onDataTreeChanged(final java.util.Collection<DataTreeModification<Cars>> changes) {
+ public void onDataTreeChanged(final List<DataTreeModification<Cars>> changes) {
if (LOG.isTraceEnabled()) {
- for (DataTreeModification<Cars> change : changes) {
+ for (var change : changes) {
outputChanges(change);
}
}
}
private static void outputChanges(final DataTreeModification<Cars> change) {
- final DataObjectModification<Cars> rootNode = change.getRootNode();
- final ModificationType modificationType = rootNode.getModificationType();
- final InstanceIdentifier<Cars> rootIdentifier = change.getRootPath().getRootIdentifier();
+ final var rootNode = change.getRootNode();
+ final var modificationType = rootNode.modificationType();
+ final var rootIdentifier = change.getRootPath().path();
switch (modificationType) {
- case WRITE:
- case SUBTREE_MODIFIED: {
+ case WRITE, SUBTREE_MODIFIED -> {
LOG.trace("onDataTreeChanged - Cars config with path {} was added or changed from {} to {}",
- rootIdentifier, rootNode.getDataBefore(), rootNode.getDataAfter());
- break;
+ rootIdentifier, rootNode.dataBefore(), rootNode.dataAfter());
}
- case DELETE: {
+ case DELETE -> {
LOG.trace("onDataTreeChanged - Cars config with path {} was deleted", rootIdentifier);
- break;
}
- default: {
+ default -> {
LOG.trace("onDataTreeChanged called with unknown modificationType: {}", modificationType);
- break;
}
}
}
import org.opendaylight.yangtools.yang.data.api.schema.DataContainerNode;
import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
import org.opendaylight.yangtools.yang.data.tree.api.DataTreeCandidateNode;
-import org.opendaylight.yangtools.yang.model.api.SchemaContext;
+import org.opendaylight.yangtools.yang.model.api.EffectiveModelContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
private static final NodeIdentifier YEAR_NODE_ID = new NodeIdentifier(YEAR_QNAME);
@Override
- public FluentFuture<PostCanCommitStep> canCommit(final Object txId, final SchemaContext ctx,
+ public FluentFuture<PostCanCommitStep> canCommit(final Object txId, final EffectiveModelContext ctx,
final Collection<DOMDataTreeCandidate> candidates) {
for (DOMDataTreeCandidate candidate : candidates) {
// Simple data validation - verify the year, if present, is >= 1990
final DataTreeCandidateNode rootNode = candidate.getRootNode();
- final Optional<NormalizedNode> dataAfter = rootNode.getDataAfter();
+ final NormalizedNode dataAfter = rootNode.dataAfter();
LOG.info("In canCommit: modificationType: {}, dataBefore: {}, dataAfter: {}",
- rootNode.getModificationType(), rootNode.getDataBefore(), dataAfter);
+ rootNode.modificationType(), rootNode.dataBefore(), dataAfter);
// Note: we don't want to process DELETE modifications but we don't need to explicitly check the
// ModificationType because dataAfter will not be present. Also dataAfter *should* always contain a
// MapEntryNode but we verify anyway.
- if (dataAfter.isPresent()) {
- final NormalizedNode normalizedNode = dataAfter.get();
- Verify.verify(normalizedNode instanceof DataContainerNode,
- "Expected type DataContainerNode, actual was %s", normalizedNode.getClass());
- DataContainerNode entryNode = (DataContainerNode) normalizedNode;
+ if (dataAfter != null) {
+ Verify.verify(dataAfter instanceof DataContainerNode,
+ "Expected type DataContainerNode, actual was %s", dataAfter.getClass());
+ DataContainerNode entryNode = (DataContainerNode) dataAfter;
final Optional<DataContainerChild> possibleYear = entryNode.findChildByArg(YEAR_NODE_ID);
if (possibleYear.isPresent()) {
- final Number year = (Number) possibleYear.get().body();
+ final Number year = (Number) possibleYear.orElseThrow().body();
LOG.info("year is {}", year);
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.MoreExecutors;
-import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import org.opendaylight.mdsal.common.api.CommitInfo;
import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
import org.opendaylight.mdsal.dom.api.DOMDataBroker;
-import org.opendaylight.mdsal.dom.api.DOMDataTreeCommitCohortRegistration;
-import org.opendaylight.mdsal.dom.api.DOMDataTreeCommitCohortRegistry;
+import org.opendaylight.mdsal.dom.api.DOMDataBroker.CommitCohortExtension;
import org.opendaylight.mdsal.dom.api.DOMDataTreeIdentifier;
import org.opendaylight.mdsal.eos.binding.api.Entity;
-import org.opendaylight.mdsal.eos.binding.api.EntityOwnershipChange;
import org.opendaylight.mdsal.eos.binding.api.EntityOwnershipListener;
import org.opendaylight.mdsal.eos.binding.api.EntityOwnershipService;
import org.opendaylight.mdsal.eos.common.api.CandidateAlreadyRegisteredException;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.CarId;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.CarService;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.Cars;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.CarsBuilder;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.RegisterCommitCohort;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.RegisterCommitCohortInput;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.RegisterCommitCohortOutput;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.RegisterCommitCohortOutputBuilder;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.RegisterLoggingDtcl;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.RegisterLoggingDtclInput;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.RegisterLoggingDtclOutput;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.RegisterLoggingDtclOutputBuilder;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.RegisterOwnership;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.RegisterOwnershipInput;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.RegisterOwnershipOutput;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.RegisterOwnershipOutputBuilder;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.StopStressTest;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.StopStressTestInput;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.StopStressTestOutput;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.StopStressTestOutputBuilder;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.StressTest;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.StressTestInput;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.StressTestOutput;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.StressTestOutputBuilder;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.UnregisterCommitCohort;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.UnregisterCommitCohortInput;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.UnregisterCommitCohortOutput;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.UnregisterCommitCohortOutputBuilder;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.UnregisterLoggingDtcls;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.UnregisterLoggingDtclsInput;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.UnregisterLoggingDtclsOutput;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.UnregisterLoggingDtclsOutputBuilder;
+import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.UnregisterOwnership;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.UnregisterOwnershipInput;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.UnregisterOwnershipOutput;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.UnregisterOwnershipOutputBuilder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.cars.CarEntry;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.rev140818.cars.CarEntryBuilder;
-import org.opendaylight.yangtools.concepts.ListenerRegistration;
import org.opendaylight.yangtools.concepts.ObjectRegistration;
+import org.opendaylight.yangtools.concepts.Registration;
import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
import org.opendaylight.yangtools.yang.common.ErrorType;
import org.opendaylight.yangtools.yang.common.RpcResult;
*/
@Singleton
@Component(service = { })
-@SuppressFBWarnings("SLF4J_ILLEGAL_PASSED_CLASS")
-public final class CarProvider implements CarService {
- private static final Logger LOG_PURCHASE_CAR = LoggerFactory.getLogger(PurchaseCarProvider.class);
-
- private static final Logger LOG_CAR_PROVIDER = LoggerFactory.getLogger(CarProvider.class);
+public final class CarProvider {
+ private static final Logger LOG = LoggerFactory.getLogger(CarProvider.class);
private static final String ENTITY_TYPE = "cars";
private static final InstanceIdentifier<Cars> CARS_IID = InstanceIdentifier.builder(Cars.class).build();
- private static final DataTreeIdentifier<Cars> CARS_DTID = DataTreeIdentifier.create(
+ private static final DataTreeIdentifier<Cars> CARS_DTID = DataTreeIdentifier.of(
LogicalDatastoreType.CONFIGURATION, CARS_IID);
private final DataBroker dataProvider;
private final AtomicLong succcessCounter = new AtomicLong();
private final AtomicLong failureCounter = new AtomicLong();
- private final CarEntityOwnershipListener ownershipListener = new CarEntityOwnershipListener();
- private final AtomicBoolean registeredListener = new AtomicBoolean();
-
- private final Set<ListenerRegistration<?>> carsDclRegistrations = ConcurrentHashMap.newKeySet();
+ private final EntityOwnershipListener ownershipListener = (entity, change, inJeopardy) ->
+ LOG.info("ownershipChanged: entity={} change={} inJeopardy={}", entity, change, inJeopardy);
- private final Set<ObjectRegistration<?>> regs = new HashSet<>();
- private final Set<ListenerRegistration<CarDataTreeChangeListener>> carsDtclRegistrations =
- ConcurrentHashMap.newKeySet();
+ private final AtomicBoolean registeredListener = new AtomicBoolean();
+ private final AtomicReference<Registration> commitCohortReg = new AtomicReference<>();
+ private final Set<ObjectRegistration<?>> carsDclRegistrations = ConcurrentHashMap.newKeySet();
+ private final Set<Registration> regs = new HashSet<>();
+ private final Set<Registration> carsDtclRegistrations = ConcurrentHashMap.newKeySet();
private volatile Thread testThread;
private volatile boolean stopThread;
- private final AtomicReference<DOMDataTreeCommitCohortRegistration<CarEntryDataTreeCommitCohort>> commitCohortReg =
- new AtomicReference<>();
@Inject
@Activate
this.dataProvider = dataProvider;
this.ownershipService = ownershipService;
this.domDataBroker = domDataBroker;
- regs.add(rpcProviderService.registerRpcImplementation(CarService.class, this));
+ regs.add(rpcProviderService.registerRpcImplementations(
+ (StressTest) this::stressTest,
+ (StopStressTest) this::stopStressTest,
+ (RegisterOwnership) this::registerOwnership,
+ (UnregisterOwnership) this::unregisterOwnership,
+ (RegisterLoggingDtcl) this::registerLoggingDtcl,
+ (UnregisterLoggingDtcls) this::unregisterLoggingDtcls,
+ (RegisterCommitCohort) this::registerCommitCohort,
+ (UnregisterCommitCohort) this::unregisterCommitCohort));
}
@PreDestroy
public void close() {
stopThread();
closeCommitCohortRegistration();
- regs.forEach(ObjectRegistration::close);
+ regs.forEach(Registration::close);
regs.clear();
}
}
}
- @Override
- public ListenableFuture<RpcResult<StressTestOutput>> stressTest(final StressTestInput input) {
+ private ListenableFuture<RpcResult<StressTestOutput>> stressTest(final StressTestInput input) {
final int inputRate;
final long inputCount;
// If rate is not provided, or given as zero, then just return.
if (input.getRate() == null || input.getRate().toJava() == 0) {
- LOG_PURCHASE_CAR.info("Exiting stress test as no rate is given.");
+ LOG.info("Exiting stress test as no rate is given.");
return Futures.immediateFuture(RpcResultBuilder.<StressTestOutput>failed()
.withError(ErrorType.PROTOCOL, "invalid rate")
.build());
inputCount = 0;
}
- LOG_PURCHASE_CAR.info("Stress test starting : rate: {} count: {}", inputRate, inputCount);
+ LOG.info("Stress test starting : rate: {} count: {}", inputRate, inputCount);
stopThread();
// clear counters
try {
tx.commit().get(5, TimeUnit.SECONDS);
} catch (TimeoutException | InterruptedException | ExecutionException e) {
- LOG_PURCHASE_CAR.error("Put Cars failed",e);
+ LOG.error("Put Cars failed",e);
return Futures.immediateFuture(RpcResultBuilder.success(new StressTestOutputBuilder().build()).build());
}
public void onFailure(final Throwable ex) {
// Transaction failed
failureCounter.getAndIncrement();
- LOG_CAR_PROVIDER.error("Put Cars failed", ex);
+ LOG.error("Put Cars failed", ex);
}
}, MoreExecutors.directExecutor());
try {
}
if (count.get() % 1000 == 0) {
- LOG_PURCHASE_CAR.info("Cars created {}, time: {}", count.get(), sw.elapsed(TimeUnit.SECONDS));
+ LOG.info("Cars created {}, time: {}", count.get(), sw.elapsed(TimeUnit.SECONDS));
}
// Check if a count is specified in input and we have created that many cars.
}
}
- LOG_PURCHASE_CAR.info("Stress test thread stopping after creating {} cars.", count.get());
+ LOG.info("Stress test thread stopping after creating {} cars.", count.get());
});
testThread.start();
return Futures.immediateFuture(RpcResultBuilder.success(new StressTestOutputBuilder().build()).build());
}
- @Override
- public ListenableFuture<RpcResult<StopStressTestOutput>> stopStressTest(final StopStressTestInput input) {
+ private ListenableFuture<RpcResult<StopStressTestOutput>> stopStressTest(final StopStressTestInput input) {
stopThread();
StopStressTestOutputBuilder stopStressTestOutput;
stopStressTestOutput = new StopStressTestOutputBuilder()
.setFailureCount(Uint32.valueOf(failureCounter.longValue()));
final StopStressTestOutput result = stopStressTestOutput.build();
- LOG_PURCHASE_CAR.info("Executed Stop Stress test; No. of cars created {}; "
- + "No. of cars failed {}; ", succcessCounter, failureCounter);
+ LOG.info("Executed Stop Stress test; No. of cars created {}; No. of cars failed {}; ",
+ succcessCounter, failureCounter);
// clear counters
succcessCounter.set(0);
failureCounter.set(0);
return Futures.immediateFuture(RpcResultBuilder.<StopStressTestOutput>success(result).build());
}
-
- @Override
- public ListenableFuture<RpcResult<RegisterOwnershipOutput>> registerOwnership(final RegisterOwnershipInput input) {
+ private ListenableFuture<RpcResult<RegisterOwnershipOutput>> registerOwnership(final RegisterOwnershipInput input) {
if (registeredListener.compareAndSet(false, true)) {
ownershipService.registerListener(ENTITY_TYPE, ownershipListener);
}
return RpcResultBuilder.success(new RegisterOwnershipOutputBuilder().build()).buildFuture();
}
- @Override
- public ListenableFuture<RpcResult<UnregisterOwnershipOutput>> unregisterOwnership(
+ private ListenableFuture<RpcResult<UnregisterOwnershipOutput>> unregisterOwnership(
final UnregisterOwnershipInput input) {
return RpcResultBuilder.success(new UnregisterOwnershipOutputBuilder().build()).buildFuture();
}
- private static class CarEntityOwnershipListener implements EntityOwnershipListener {
- @Override
- public void ownershipChanged(final EntityOwnershipChange ownershipChange) {
- LOG_CAR_PROVIDER.info("ownershipChanged: {}", ownershipChange);
- }
- }
-
- @Override
- public ListenableFuture<RpcResult<RegisterLoggingDtclOutput>> registerLoggingDtcl(
+ private ListenableFuture<RpcResult<RegisterLoggingDtclOutput>> registerLoggingDtcl(
final RegisterLoggingDtclInput input) {
- LOG_CAR_PROVIDER.info("Registering a new CarDataTreeChangeListener");
- final ListenerRegistration<CarDataTreeChangeListener> carsDtclRegistration =
- dataProvider.registerDataTreeChangeListener(CARS_DTID, new CarDataTreeChangeListener());
-
- carsDtclRegistrations.add(carsDtclRegistration);
+ LOG.info("Registering a new CarDataTreeChangeListener");
+ final var reg = dataProvider.registerTreeChangeListener(CARS_DTID, new CarDataTreeChangeListener());
+ carsDtclRegistrations.add(reg);
return RpcResultBuilder.success(new RegisterLoggingDtclOutputBuilder().build()).buildFuture();
}
- @Override
- public ListenableFuture<RpcResult<UnregisterLoggingDtclsOutput>> unregisterLoggingDtcls(
+ private ListenableFuture<RpcResult<UnregisterLoggingDtclsOutput>> unregisterLoggingDtcls(
final UnregisterLoggingDtclsInput input) {
- LOG_CAR_PROVIDER.info("Unregistering the CarDataTreeChangeListener(s)");
+ LOG.info("Unregistering the CarDataTreeChangeListener(s)");
synchronized (carsDtclRegistrations) {
int numListeners = 0;
- for (ListenerRegistration<CarDataTreeChangeListener> carsDtclRegistration : carsDtclRegistrations) {
+ for (var carsDtclRegistration : carsDtclRegistrations) {
carsDtclRegistration.close();
numListeners++;
}
carsDtclRegistrations.clear();
- LOG_CAR_PROVIDER.info("Unregistered {} CaraDataTreeChangeListener(s)", numListeners);
+ LOG.info("Unregistered {} CaraDataTreeChangeListener(s)", numListeners);
}
return RpcResultBuilder.success(new UnregisterLoggingDtclsOutputBuilder().build()).buildFuture();
}
- @Override
@SuppressWarnings("checkstyle:IllegalCatch")
- public ListenableFuture<RpcResult<UnregisterCommitCohortOutput>> unregisterCommitCohort(
+ private ListenableFuture<RpcResult<UnregisterCommitCohortOutput>> unregisterCommitCohort(
final UnregisterCommitCohortInput input) {
closeCommitCohortRegistration();
}
private void closeCommitCohortRegistration() {
- final DOMDataTreeCommitCohortRegistration<CarEntryDataTreeCommitCohort> reg = commitCohortReg.getAndSet(null);
+ final var reg = commitCohortReg.getAndSet(null);
if (reg != null) {
reg.close();
- LOG_CAR_PROVIDER.info("Unregistered commit cohort");
+ LOG.info("Unregistered commit cohort");
}
}
- @Override
- public synchronized ListenableFuture<RpcResult<RegisterCommitCohortOutput>> registerCommitCohort(
+ private synchronized ListenableFuture<RpcResult<RegisterCommitCohortOutput>> registerCommitCohort(
final RegisterCommitCohortInput input) {
if (commitCohortReg.get() != null) {
return RpcResultBuilder.success(new RegisterCommitCohortOutputBuilder().build()).buildFuture();
}
- final DOMDataTreeCommitCohortRegistry commitCohortRegistry = domDataBroker.getExtensions().getInstance(
- DOMDataTreeCommitCohortRegistry.class);
-
+ final var commitCohortRegistry = domDataBroker.extension(CommitCohortExtension.class);
if (commitCohortRegistry == null) {
// Shouldn't happen
return RpcResultBuilder.<RegisterCommitCohortOutput>failed().withError(ErrorType.APPLICATION,
// to address all list entries, the second path argument is wild-carded by specifying just the CarEntry.QNAME.
final YangInstanceIdentifier carEntryPath = YangInstanceIdentifier.builder(
YangInstanceIdentifier.of(Cars.QNAME)).node(CarEntry.QNAME).node(CarEntry.QNAME).build();
- commitCohortReg.set(commitCohortRegistry.registerCommitCohort(new DOMDataTreeIdentifier(
+ commitCohortReg.set(commitCohortRegistry.registerCommitCohort(DOMDataTreeIdentifier.of(
LogicalDatastoreType.CONFIGURATION, carEntryPath), new CarEntryDataTreeCommitCohort()));
- LOG_CAR_PROVIDER.info("Registered commit cohort");
+ LOG.info("Registered commit cohort");
return RpcResultBuilder.success(new RegisterCommitCohortOutputBuilder().build()).buildFuture();
}
import org.opendaylight.mdsal.binding.dom.codec.api.BindingNormalizedNodeSerializer;
import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
import org.opendaylight.mdsal.dom.api.DOMDataBroker;
-import org.opendaylight.mdsal.dom.api.DOMDataTreeChangeListener;
-import org.opendaylight.mdsal.dom.api.DOMDataTreeChangeService;
+import org.opendaylight.mdsal.dom.api.DOMDataBroker.DataTreeChangeExtension;
import org.opendaylight.mdsal.dom.api.DOMDataTreeIdentifier;
import org.opendaylight.mdsal.dom.api.DOMDataTreeReadTransaction;
-import org.opendaylight.mdsal.dom.api.DOMRpcImplementationRegistration;
import org.opendaylight.mdsal.dom.api.DOMRpcProviderService;
import org.opendaylight.mdsal.dom.api.DOMSchemaService;
-import org.opendaylight.mdsal.singleton.common.api.ClusterSingletonServiceProvider;
-import org.opendaylight.mdsal.singleton.common.api.ClusterSingletonServiceRegistration;
+import org.opendaylight.mdsal.singleton.api.ClusterSingletonServiceProvider;
+import org.opendaylight.yang.gen.v1.tag.opendaylight.org._2017.controller.yang.lowlevel.control.rev170215.AddShardReplica;
import org.opendaylight.yang.gen.v1.tag.opendaylight.org._2017.controller.yang.lowlevel.control.rev170215.AddShardReplicaInput;
import org.opendaylight.yang.gen.v1.tag.opendaylight.org._2017.controller.yang.lowlevel.control.rev170215.AddShardReplicaOutput;
+import org.opendaylight.yang.gen.v1.tag.opendaylight.org._2017.controller.yang.lowlevel.control.rev170215.CheckPublishNotifications;
import org.opendaylight.yang.gen.v1.tag.opendaylight.org._2017.controller.yang.lowlevel.control.rev170215.CheckPublishNotificationsInput;
import org.opendaylight.yang.gen.v1.tag.opendaylight.org._2017.controller.yang.lowlevel.control.rev170215.CheckPublishNotificationsOutput;
import org.opendaylight.yang.gen.v1.tag.opendaylight.org._2017.controller.yang.lowlevel.control.rev170215.CheckPublishNotificationsOutputBuilder;
+import org.opendaylight.yang.gen.v1.tag.opendaylight.org._2017.controller.yang.lowlevel.control.rev170215.IsClientAborted;
import org.opendaylight.yang.gen.v1.tag.opendaylight.org._2017.controller.yang.lowlevel.control.rev170215.IsClientAbortedInput;
import org.opendaylight.yang.gen.v1.tag.opendaylight.org._2017.controller.yang.lowlevel.control.rev170215.IsClientAbortedOutput;
-import org.opendaylight.yang.gen.v1.tag.opendaylight.org._2017.controller.yang.lowlevel.control.rev170215.OdlMdsalLowlevelControlService;
+import org.opendaylight.yang.gen.v1.tag.opendaylight.org._2017.controller.yang.lowlevel.control.rev170215.RegisterBoundConstant;
import org.opendaylight.yang.gen.v1.tag.opendaylight.org._2017.controller.yang.lowlevel.control.rev170215.RegisterBoundConstantInput;
import org.opendaylight.yang.gen.v1.tag.opendaylight.org._2017.controller.yang.lowlevel.control.rev170215.RegisterBoundConstantOutput;
import org.opendaylight.yang.gen.v1.tag.opendaylight.org._2017.controller.yang.lowlevel.control.rev170215.RegisterBoundConstantOutputBuilder;
+import org.opendaylight.yang.gen.v1.tag.opendaylight.org._2017.controller.yang.lowlevel.control.rev170215.RegisterConstant;
import org.opendaylight.yang.gen.v1.tag.opendaylight.org._2017.controller.yang.lowlevel.control.rev170215.RegisterConstantInput;
import org.opendaylight.yang.gen.v1.tag.opendaylight.org._2017.controller.yang.lowlevel.control.rev170215.RegisterConstantOutput;
import org.opendaylight.yang.gen.v1.tag.opendaylight.org._2017.controller.yang.lowlevel.control.rev170215.RegisterConstantOutputBuilder;
+import org.opendaylight.yang.gen.v1.tag.opendaylight.org._2017.controller.yang.lowlevel.control.rev170215.RegisterDefaultConstant;
import org.opendaylight.yang.gen.v1.tag.opendaylight.org._2017.controller.yang.lowlevel.control.rev170215.RegisterDefaultConstantInput;
import org.opendaylight.yang.gen.v1.tag.opendaylight.org._2017.controller.yang.lowlevel.control.rev170215.RegisterDefaultConstantOutput;
+import org.opendaylight.yang.gen.v1.tag.opendaylight.org._2017.controller.yang.lowlevel.control.rev170215.RegisterFlappingSingleton;
import org.opendaylight.yang.gen.v1.tag.opendaylight.org._2017.controller.yang.lowlevel.control.rev170215.RegisterFlappingSingletonInput;
import org.opendaylight.yang.gen.v1.tag.opendaylight.org._2017.controller.yang.lowlevel.control.rev170215.RegisterFlappingSingletonOutput;
import org.opendaylight.yang.gen.v1.tag.opendaylight.org._2017.controller.yang.lowlevel.control.rev170215.RegisterFlappingSingletonOutputBuilder;
+import org.opendaylight.yang.gen.v1.tag.opendaylight.org._2017.controller.yang.lowlevel.control.rev170215.RegisterSingletonConstant;
import org.opendaylight.yang.gen.v1.tag.opendaylight.org._2017.controller.yang.lowlevel.control.rev170215.RegisterSingletonConstantInput;
import org.opendaylight.yang.gen.v1.tag.opendaylight.org._2017.controller.yang.lowlevel.control.rev170215.RegisterSingletonConstantOutput;
import org.opendaylight.yang.gen.v1.tag.opendaylight.org._2017.controller.yang.lowlevel.control.rev170215.RegisterSingletonConstantOutputBuilder;
+import org.opendaylight.yang.gen.v1.tag.opendaylight.org._2017.controller.yang.lowlevel.control.rev170215.RemoveShardReplica;
import org.opendaylight.yang.gen.v1.tag.opendaylight.org._2017.controller.yang.lowlevel.control.rev170215.RemoveShardReplicaInput;
import org.opendaylight.yang.gen.v1.tag.opendaylight.org._2017.controller.yang.lowlevel.control.rev170215.RemoveShardReplicaOutput;
+import org.opendaylight.yang.gen.v1.tag.opendaylight.org._2017.controller.yang.lowlevel.control.rev170215.ShutdownShardReplica;
import org.opendaylight.yang.gen.v1.tag.opendaylight.org._2017.controller.yang.lowlevel.control.rev170215.ShutdownShardReplicaInput;
import org.opendaylight.yang.gen.v1.tag.opendaylight.org._2017.controller.yang.lowlevel.control.rev170215.ShutdownShardReplicaOutput;
import org.opendaylight.yang.gen.v1.tag.opendaylight.org._2017.controller.yang.lowlevel.control.rev170215.ShutdownShardReplicaOutputBuilder;
+import org.opendaylight.yang.gen.v1.tag.opendaylight.org._2017.controller.yang.lowlevel.control.rev170215.StartPublishNotifications;
import org.opendaylight.yang.gen.v1.tag.opendaylight.org._2017.controller.yang.lowlevel.control.rev170215.StartPublishNotificationsInput;
import org.opendaylight.yang.gen.v1.tag.opendaylight.org._2017.controller.yang.lowlevel.control.rev170215.StartPublishNotificationsOutput;
import org.opendaylight.yang.gen.v1.tag.opendaylight.org._2017.controller.yang.lowlevel.control.rev170215.StartPublishNotificationsOutputBuilder;
+import org.opendaylight.yang.gen.v1.tag.opendaylight.org._2017.controller.yang.lowlevel.control.rev170215.SubscribeDdtl;
import org.opendaylight.yang.gen.v1.tag.opendaylight.org._2017.controller.yang.lowlevel.control.rev170215.SubscribeDdtlInput;
import org.opendaylight.yang.gen.v1.tag.opendaylight.org._2017.controller.yang.lowlevel.control.rev170215.SubscribeDdtlOutput;
+import org.opendaylight.yang.gen.v1.tag.opendaylight.org._2017.controller.yang.lowlevel.control.rev170215.SubscribeDtcl;
import org.opendaylight.yang.gen.v1.tag.opendaylight.org._2017.controller.yang.lowlevel.control.rev170215.SubscribeDtclInput;
import org.opendaylight.yang.gen.v1.tag.opendaylight.org._2017.controller.yang.lowlevel.control.rev170215.SubscribeDtclOutput;
import org.opendaylight.yang.gen.v1.tag.opendaylight.org._2017.controller.yang.lowlevel.control.rev170215.SubscribeDtclOutputBuilder;
+import org.opendaylight.yang.gen.v1.tag.opendaylight.org._2017.controller.yang.lowlevel.control.rev170215.SubscribeYnl;
import org.opendaylight.yang.gen.v1.tag.opendaylight.org._2017.controller.yang.lowlevel.control.rev170215.SubscribeYnlInput;
import org.opendaylight.yang.gen.v1.tag.opendaylight.org._2017.controller.yang.lowlevel.control.rev170215.SubscribeYnlOutput;
import org.opendaylight.yang.gen.v1.tag.opendaylight.org._2017.controller.yang.lowlevel.control.rev170215.SubscribeYnlOutputBuilder;
+import org.opendaylight.yang.gen.v1.tag.opendaylight.org._2017.controller.yang.lowlevel.control.rev170215.UnregisterBoundConstant;
import org.opendaylight.yang.gen.v1.tag.opendaylight.org._2017.controller.yang.lowlevel.control.rev170215.UnregisterBoundConstantInput;
import org.opendaylight.yang.gen.v1.tag.opendaylight.org._2017.controller.yang.lowlevel.control.rev170215.UnregisterBoundConstantOutput;
import org.opendaylight.yang.gen.v1.tag.opendaylight.org._2017.controller.yang.lowlevel.control.rev170215.UnregisterBoundConstantOutputBuilder;
+import org.opendaylight.yang.gen.v1.tag.opendaylight.org._2017.controller.yang.lowlevel.control.rev170215.UnregisterConstant;
import org.opendaylight.yang.gen.v1.tag.opendaylight.org._2017.controller.yang.lowlevel.control.rev170215.UnregisterConstantInput;
import org.opendaylight.yang.gen.v1.tag.opendaylight.org._2017.controller.yang.lowlevel.control.rev170215.UnregisterConstantOutput;
import org.opendaylight.yang.gen.v1.tag.opendaylight.org._2017.controller.yang.lowlevel.control.rev170215.UnregisterConstantOutputBuilder;
+import org.opendaylight.yang.gen.v1.tag.opendaylight.org._2017.controller.yang.lowlevel.control.rev170215.UnregisterDefaultConstant;
import org.opendaylight.yang.gen.v1.tag.opendaylight.org._2017.controller.yang.lowlevel.control.rev170215.UnregisterDefaultConstantInput;
import org.opendaylight.yang.gen.v1.tag.opendaylight.org._2017.controller.yang.lowlevel.control.rev170215.UnregisterDefaultConstantOutput;
+import org.opendaylight.yang.gen.v1.tag.opendaylight.org._2017.controller.yang.lowlevel.control.rev170215.UnregisterFlappingSingleton;
import org.opendaylight.yang.gen.v1.tag.opendaylight.org._2017.controller.yang.lowlevel.control.rev170215.UnregisterFlappingSingletonInput;
import org.opendaylight.yang.gen.v1.tag.opendaylight.org._2017.controller.yang.lowlevel.control.rev170215.UnregisterFlappingSingletonOutput;
import org.opendaylight.yang.gen.v1.tag.opendaylight.org._2017.controller.yang.lowlevel.control.rev170215.UnregisterFlappingSingletonOutputBuilder;
+import org.opendaylight.yang.gen.v1.tag.opendaylight.org._2017.controller.yang.lowlevel.control.rev170215.UnregisterSingletonConstant;
import org.opendaylight.yang.gen.v1.tag.opendaylight.org._2017.controller.yang.lowlevel.control.rev170215.UnregisterSingletonConstantInput;
import org.opendaylight.yang.gen.v1.tag.opendaylight.org._2017.controller.yang.lowlevel.control.rev170215.UnregisterSingletonConstantOutput;
import org.opendaylight.yang.gen.v1.tag.opendaylight.org._2017.controller.yang.lowlevel.control.rev170215.UnregisterSingletonConstantOutputBuilder;
+import org.opendaylight.yang.gen.v1.tag.opendaylight.org._2017.controller.yang.lowlevel.control.rev170215.UnsubscribeDdtl;
import org.opendaylight.yang.gen.v1.tag.opendaylight.org._2017.controller.yang.lowlevel.control.rev170215.UnsubscribeDdtlInput;
import org.opendaylight.yang.gen.v1.tag.opendaylight.org._2017.controller.yang.lowlevel.control.rev170215.UnsubscribeDdtlOutput;
+import org.opendaylight.yang.gen.v1.tag.opendaylight.org._2017.controller.yang.lowlevel.control.rev170215.UnsubscribeDtcl;
import org.opendaylight.yang.gen.v1.tag.opendaylight.org._2017.controller.yang.lowlevel.control.rev170215.UnsubscribeDtclInput;
import org.opendaylight.yang.gen.v1.tag.opendaylight.org._2017.controller.yang.lowlevel.control.rev170215.UnsubscribeDtclOutput;
import org.opendaylight.yang.gen.v1.tag.opendaylight.org._2017.controller.yang.lowlevel.control.rev170215.UnsubscribeDtclOutputBuilder;
+import org.opendaylight.yang.gen.v1.tag.opendaylight.org._2017.controller.yang.lowlevel.control.rev170215.UnsubscribeYnl;
import org.opendaylight.yang.gen.v1.tag.opendaylight.org._2017.controller.yang.lowlevel.control.rev170215.UnsubscribeYnlInput;
import org.opendaylight.yang.gen.v1.tag.opendaylight.org._2017.controller.yang.lowlevel.control.rev170215.UnsubscribeYnlOutput;
+import org.opendaylight.yang.gen.v1.tag.opendaylight.org._2017.controller.yang.lowlevel.control.rev170215.WriteTransactions;
import org.opendaylight.yang.gen.v1.tag.opendaylight.org._2017.controller.yang.lowlevel.control.rev170215.WriteTransactionsInput;
import org.opendaylight.yang.gen.v1.tag.opendaylight.org._2017.controller.yang.lowlevel.control.rev170215.WriteTransactionsOutput;
-import org.opendaylight.yangtools.concepts.ListenerRegistration;
+import org.opendaylight.yang.gen.v1.tag.opendaylight.org._2017.controller.yang.lowlevel.target.rev170215.IdSequence;
+import org.opendaylight.yangtools.concepts.AbstractObjectRegistration;
+import org.opendaylight.yangtools.concepts.ObjectRegistration;
import org.opendaylight.yangtools.concepts.Registration;
import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
import org.opendaylight.yangtools.yang.common.ErrorTag;
@Singleton
@Component(service = {})
-public final class MdsalLowLevelTestProvider implements OdlMdsalLowlevelControlService {
+public final class MdsalLowLevelTestProvider {
private static final Logger LOG = LoggerFactory.getLogger(MdsalLowLevelTestProvider.class);
private final Registration registration;
private final NotificationService notificationService;
private final ClusterSingletonServiceProvider singletonService;
private final DOMRpcProviderService domRpcService;
- private final DOMDataTreeChangeService domDataTreeChangeService;
+ private final DataTreeChangeExtension dataTreeChangeExtension;
- private final Map<InstanceIdentifier<?>, DOMRpcImplementationRegistration<RoutedGetConstantService>>
- routedRegistrations = new HashMap<>();
-
- private final Map<String, ListenerRegistration<YnlListener>> ynlRegistrations = new HashMap<>();
+ private final Map<InstanceIdentifier<?>, Registration> routedRegistrations = new HashMap<>();
+ private final Map<String, ObjectRegistration<YnlListener>> ynlRegistrations = new HashMap<>();
+ private final Map<String, PublishNotificationsTask> publishNotificationsTasks = new HashMap<>();
- private DOMRpcImplementationRegistration<GetConstantService> globalGetConstantRegistration = null;
- private ClusterSingletonServiceRegistration getSingletonConstantRegistration;
+ private Registration globalGetConstantRegistration = null;
+ private Registration getSingletonConstantRegistration;
private FlappingSingletonService flappingSingletonService;
- private ListenerRegistration<DOMDataTreeChangeListener> dtclReg;
+ private Registration dtclReg;
private IdIntsListener idIntsListener;
- private final Map<String, PublishNotificationsTask> publishNotificationsTasks = new HashMap<>();
@Inject
@Activate
this.domDataBroker = domDataBroker;
this.configDataStore = configDataStore;
- domDataTreeChangeService = domDataBroker.getExtensions().getInstance(DOMDataTreeChangeService.class);
-
- registration = rpcRegistry.registerRpcImplementation(OdlMdsalLowlevelControlService.class, this);
+ dataTreeChangeExtension = domDataBroker.extension(DataTreeChangeExtension.class);
+
+ registration = rpcRegistry.registerRpcImplementations(
+ (UnregisterSingletonConstant) this::unregisterSingletonConstant,
+ (StartPublishNotifications) this::startPublishNotifications,
+ (SubscribeDdtl) this::subscribeDdtl,
+ (WriteTransactions) this::writeTransactions,
+ (IsClientAborted) this::isClientAborted,
+ (RemoveShardReplica) this::removeShardReplica,
+ (SubscribeYnl) this::subscribeYnl,
+ (UnregisterBoundConstant) this::unregisterBoundConstant,
+ (RegisterSingletonConstant) this::registerSingletonConstant,
+ (RegisterDefaultConstant) this::registerDefaultConstant,
+ (UnregisterConstant) this::unregisterConstant,
+ (UnregisterFlappingSingleton) this::unregisterFlappingSingleton,
+ (AddShardReplica) this::addShardReplica,
+ (RegisterBoundConstant) this::registerBoundConstant,
+ (RegisterFlappingSingleton) this::registerFlappingSingleton,
+ (UnsubscribeDdtl) this::unsubscribeDdtl,
+ (UnsubscribeYnl) this::unsubscribeYnl,
+ (CheckPublishNotifications) this::checkPublishNotifications,
+ (ShutdownShardReplica) this::shutdownShardReplica,
+ (RegisterConstant) this::registerConstant,
+ (UnregisterDefaultConstant) this::unregisterDefaultConstant,
+ (SubscribeDtcl) this::subscribeDtcl,
+ (UnsubscribeDtcl) this::unsubscribeDtcl);
}
@PreDestroy
registration.close();
}
- @Override
@SuppressWarnings("checkstyle:IllegalCatch")
- public ListenableFuture<RpcResult<UnregisterSingletonConstantOutput>> unregisterSingletonConstant(
+ private ListenableFuture<RpcResult<UnregisterSingletonConstantOutput>> unregisterSingletonConstant(
final UnregisterSingletonConstantInput input) {
LOG.info("In unregisterSingletonConstant");
}
}
- @Override
- public ListenableFuture<RpcResult<StartPublishNotificationsOutput>> startPublishNotifications(
+ private ListenableFuture<RpcResult<StartPublishNotificationsOutput>> startPublishNotifications(
final StartPublishNotificationsInput input) {
LOG.info("In startPublishNotifications - input: {}", input);
return RpcResultBuilder.success(new StartPublishNotificationsOutputBuilder().build()).buildFuture();
}
- @Override
- public ListenableFuture<RpcResult<SubscribeDtclOutput>> subscribeDtcl(final SubscribeDtclInput input) {
+ private ListenableFuture<RpcResult<SubscribeDtclOutput>> subscribeDtcl(final SubscribeDtclInput input) {
LOG.info("In subscribeDtcl - input: {}", input);
if (dtclReg != null) {
idIntsListener = new IdIntsListener();
- dtclReg = domDataTreeChangeService.registerDataTreeChangeListener(
- new DOMDataTreeIdentifier(LogicalDatastoreType.CONFIGURATION, WriteTransactionsHandler.ID_INT_YID),
+ dtclReg = dataTreeChangeExtension.registerTreeChangeListener(
+ DOMDataTreeIdentifier.of(LogicalDatastoreType.CONFIGURATION, WriteTransactionsHandler.ID_INT_YID),
idIntsListener);
return RpcResultBuilder.success(new SubscribeDtclOutputBuilder().build()).buildFuture();
}
- @Override
- public ListenableFuture<RpcResult<WriteTransactionsOutput>> writeTransactions(final WriteTransactionsInput input) {
+ private ListenableFuture<RpcResult<WriteTransactionsOutput>> writeTransactions(final WriteTransactionsInput input) {
return WriteTransactionsHandler.start(domDataBroker, input);
}
- @Override
- public ListenableFuture<RpcResult<IsClientAbortedOutput>> isClientAborted(final IsClientAbortedInput input) {
+ private ListenableFuture<RpcResult<IsClientAbortedOutput>> isClientAborted(final IsClientAbortedInput input) {
return null;
}
- @Override
- public ListenableFuture<RpcResult<RemoveShardReplicaOutput>> removeShardReplica(
+ private ListenableFuture<RpcResult<RemoveShardReplicaOutput>> removeShardReplica(
final RemoveShardReplicaInput input) {
return null;
}
- @Override
- public ListenableFuture<RpcResult<SubscribeYnlOutput>> subscribeYnl(final SubscribeYnlInput input) {
+ private ListenableFuture<RpcResult<SubscribeYnlOutput>> subscribeYnl(final SubscribeYnlInput input) {
LOG.info("In subscribeYnl - input: {}", input);
if (ynlRegistrations.containsKey(input.getId())) {
.buildFuture();
}
- ynlRegistrations.put(input.getId(),
- notificationService.registerNotificationListener(new YnlListener(input.getId())));
+ final var id = input.getId();
+ final var listener = new YnlListener(id);
+ final var reg = notificationService.registerListener(IdSequence.class, listener);
+ ynlRegistrations.put(id, new AbstractObjectRegistration<>(listener) {
+ @Override
+ protected void removeRegistration() {
+ reg.close();
+ }
+ });
return RpcResultBuilder.success(new SubscribeYnlOutputBuilder().build()).buildFuture();
}
- @Override
- public ListenableFuture<RpcResult<UnregisterBoundConstantOutput>> unregisterBoundConstant(
+ private ListenableFuture<RpcResult<UnregisterBoundConstantOutput>> unregisterBoundConstant(
final UnregisterBoundConstantInput input) {
LOG.info("In unregisterBoundConstant - {}", input);
- final DOMRpcImplementationRegistration<RoutedGetConstantService> rpcRegistration =
- routedRegistrations.remove(input.getContext());
-
+ final var rpcRegistration = routedRegistrations.remove(input.getContext());
if (rpcRegistration == null) {
return RpcResultBuilder.<UnregisterBoundConstantOutput>failed()
.withError(ErrorType.RPC, ErrorTag.DATA_MISSING,
return RpcResultBuilder.success(new UnregisterBoundConstantOutputBuilder().build()).buildFuture();
}
- @Override
- public ListenableFuture<RpcResult<RegisterSingletonConstantOutput>> registerSingletonConstant(
+ private ListenableFuture<RpcResult<RegisterSingletonConstantOutput>> registerSingletonConstant(
final RegisterSingletonConstantInput input) {
LOG.info("In registerSingletonConstant - input: {}", input);
return RpcResultBuilder.success(new RegisterSingletonConstantOutputBuilder().build()).buildFuture();
}
- @Override
- public ListenableFuture<RpcResult<RegisterDefaultConstantOutput>> registerDefaultConstant(
+ private ListenableFuture<RpcResult<RegisterDefaultConstantOutput>> registerDefaultConstant(
final RegisterDefaultConstantInput input) {
return null;
}
- @Override
- public ListenableFuture<RpcResult<UnregisterConstantOutput>> unregisterConstant(
+ private ListenableFuture<RpcResult<UnregisterConstantOutput>> unregisterConstant(
final UnregisterConstantInput input) {
LOG.info("In unregisterConstant");
return RpcResultBuilder.success(new UnregisterConstantOutputBuilder().build()).buildFuture();
}
- @Override
- public ListenableFuture<RpcResult<UnregisterFlappingSingletonOutput>> unregisterFlappingSingleton(
+ private ListenableFuture<RpcResult<UnregisterFlappingSingletonOutput>> unregisterFlappingSingleton(
final UnregisterFlappingSingletonInput input) {
LOG.info("In unregisterFlappingSingleton");
.buildFuture();
}
- @Override
- public ListenableFuture<RpcResult<AddShardReplicaOutput>> addShardReplica(final AddShardReplicaInput input) {
+ private ListenableFuture<RpcResult<AddShardReplicaOutput>> addShardReplica(final AddShardReplicaInput input) {
throw new UnsupportedOperationException();
}
- @Override
- public ListenableFuture<RpcResult<SubscribeDdtlOutput>> subscribeDdtl(final SubscribeDdtlInput input) {
+ private ListenableFuture<RpcResult<SubscribeDdtlOutput>> subscribeDdtl(final SubscribeDdtlInput input) {
throw new UnsupportedOperationException();
}
- @Override
- public ListenableFuture<RpcResult<RegisterBoundConstantOutput>> registerBoundConstant(
+ private ListenableFuture<RpcResult<RegisterBoundConstantOutput>> registerBoundConstant(
final RegisterBoundConstantInput input) {
LOG.info("In registerBoundConstant - input: {}", input);
.buildFuture();
}
- final DOMRpcImplementationRegistration<RoutedGetConstantService> rpcRegistration =
- RoutedGetConstantService.registerNew(bindingNormalizedNodeSerializer, domRpcService,
- input.getConstant(), input.getContext());
+ final var rpcRegistration = RoutedGetConstantService.registerNew(bindingNormalizedNodeSerializer, domRpcService,
+ input.getConstant(), input.getContext());
routedRegistrations.put(input.getContext(), rpcRegistration);
return RpcResultBuilder.success(new RegisterBoundConstantOutputBuilder().build()).buildFuture();
}
- @Override
- public ListenableFuture<RpcResult<RegisterFlappingSingletonOutput>> registerFlappingSingleton(
+ private ListenableFuture<RpcResult<RegisterFlappingSingletonOutput>> registerFlappingSingleton(
final RegisterFlappingSingletonInput input) {
LOG.info("In registerFlappingSingleton");
return RpcResultBuilder.success(new RegisterFlappingSingletonOutputBuilder().build()).buildFuture();
}
- @Override
- public ListenableFuture<RpcResult<UnsubscribeDtclOutput>> unsubscribeDtcl(final UnsubscribeDtclInput input) {
+ private ListenableFuture<RpcResult<UnsubscribeDtclOutput>> unsubscribeDtcl(final UnsubscribeDtclInput input) {
LOG.info("In unsubscribeDtcl");
if (idIntsListener == null || dtclReg == null) {
.buildFuture();
}
- final boolean nodesEqual = idIntsListener.checkEqual(readResult.get());
+ final boolean nodesEqual = idIntsListener.checkEqual(readResult.orElseThrow());
if (!nodesEqual) {
LOG.error("Final read of id-int does not match IdIntsListener's copy. {}",
- idIntsListener.diffWithLocalCopy(readResult.get()));
+ idIntsListener.diffWithLocalCopy(readResult.orElseThrow()));
}
return RpcResultBuilder.success(new UnsubscribeDtclOutputBuilder().setCopyMatches(nodesEqual).build())
}
}
- @Override
- public ListenableFuture<RpcResult<UnsubscribeYnlOutput>> unsubscribeYnl(final UnsubscribeYnlInput input) {
+ private ListenableFuture<RpcResult<UnsubscribeYnlOutput>> unsubscribeYnl(final UnsubscribeYnlInput input) {
LOG.info("In unsubscribeYnl - input: {}", input);
if (!ynlRegistrations.containsKey(input.getId())) {
.buildFuture();
}
- final ListenerRegistration<YnlListener> reg = ynlRegistrations.remove(input.getId());
- final UnsubscribeYnlOutput output = reg.getInstance().getOutput();
-
- reg.close();
-
- return RpcResultBuilder.<UnsubscribeYnlOutput>success().withResult(output).buildFuture();
+ try (var reg = ynlRegistrations.remove(input.getId())) {
+ return RpcResultBuilder.<UnsubscribeYnlOutput>success()
+ .withResult(reg.getInstance().getOutput())
+ .buildFuture();
+ }
}
- @Override
- public ListenableFuture<RpcResult<CheckPublishNotificationsOutput>> checkPublishNotifications(
+ private ListenableFuture<RpcResult<CheckPublishNotificationsOutput>> checkPublishNotifications(
final CheckPublishNotificationsInput input) {
LOG.info("In checkPublishNotifications - input: {}", input);
return RpcResultBuilder.success(output).buildFuture();
}
- @Override
- public ListenableFuture<RpcResult<ShutdownShardReplicaOutput>> shutdownShardReplica(
+ private ListenableFuture<RpcResult<ShutdownShardReplicaOutput>> shutdownShardReplica(
final ShutdownShardReplicaInput input) {
LOG.info("In shutdownShardReplica - input: {}", input);
return rpcResult;
}
- @Override
- public ListenableFuture<RpcResult<RegisterConstantOutput>> registerConstant(final RegisterConstantInput input) {
+ private ListenableFuture<RpcResult<RegisterConstantOutput>> registerConstant(final RegisterConstantInput input) {
LOG.info("In registerConstant - input: {}", input);
if (input.getConstant() == null) {
return RpcResultBuilder.success(new RegisterConstantOutputBuilder().build()).buildFuture();
}
- @Override
- public ListenableFuture<RpcResult<UnregisterDefaultConstantOutput>> unregisterDefaultConstant(
+ private ListenableFuture<RpcResult<UnregisterDefaultConstantOutput>> unregisterDefaultConstant(
final UnregisterDefaultConstantInput input) {
throw new UnsupportedOperationException();
}
- @Override
@SuppressWarnings("checkstyle:IllegalCatch")
- public ListenableFuture<RpcResult<UnsubscribeDdtlOutput>> unsubscribeDdtl(final UnsubscribeDdtlInput input) {
+ private ListenableFuture<RpcResult<UnsubscribeDdtlOutput>> unsubscribeDdtl(final UnsubscribeDdtlInput input) {
throw new UnsupportedOperationException();
}
}
+++ /dev/null
-/*
- * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
- *
- * This program and the accompanying materials are made available under the
- * terms of the Eclipse Public License v1.0 which accompanies this distribution,
- * and is available at http://www.eclipse.org/legal/epl-v10.html
- */
-package org.opendaylight.controller.clustering.it.provider;
-
-import static java.util.Objects.requireNonNull;
-
-import com.google.common.util.concurrent.Futures;
-import com.google.common.util.concurrent.ListenableFuture;
-import com.google.common.util.concurrent.MoreExecutors;
-import javax.inject.Inject;
-import javax.inject.Singleton;
-import org.opendaylight.mdsal.binding.api.NotificationPublishService;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.purchase.rev140818.BuyCarInput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.purchase.rev140818.BuyCarOutput;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.purchase.rev140818.BuyCarOutputBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.purchase.rev140818.CarBoughtBuilder;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.config.sal.clustering.it.car.purchase.rev140818.CarPurchaseService;
-import org.opendaylight.yangtools.yang.common.RpcResult;
-import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
-import org.osgi.service.component.annotations.Activate;
-import org.osgi.service.component.annotations.Component;
-import org.osgi.service.component.annotations.Reference;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-@Singleton
-@Component(service = CarPurchaseService.class)
-public final class PurchaseCarProvider implements CarPurchaseService {
- private static final Logger LOG = LoggerFactory.getLogger(PurchaseCarProvider.class);
-
- private final NotificationPublishService notificationProvider;
-
- @Inject
- @Activate
- public PurchaseCarProvider(@Reference final NotificationPublishService notificationProvider) {
- this.notificationProvider = requireNonNull(notificationProvider);
- }
-
- @Override
- public ListenableFuture<RpcResult<BuyCarOutput>> buyCar(final BuyCarInput input) {
- LOG.info("Routed RPC buyCar : generating notification for buying car [{}]", input);
-
- return Futures.transform(notificationProvider.offerNotification(new CarBoughtBuilder()
- .setCarId(input.getCarId())
- .setPersonId(input.getPersonId())
- .build()),
- result -> RpcResultBuilder.success(new BuyCarOutputBuilder().build()).build(),
- MoreExecutors.directExecutor());
- }
-}
*/
package org.opendaylight.controller.clustering.it.provider.impl;
+import static java.util.Objects.requireNonNull;
+
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;
-import org.opendaylight.mdsal.singleton.common.api.ClusterSingletonService;
-import org.opendaylight.mdsal.singleton.common.api.ClusterSingletonServiceProvider;
-import org.opendaylight.mdsal.singleton.common.api.ClusterSingletonServiceRegistration;
-import org.opendaylight.mdsal.singleton.common.api.ServiceGroupIdentifier;
+import org.opendaylight.mdsal.singleton.api.ClusterSingletonService;
+import org.opendaylight.mdsal.singleton.api.ClusterSingletonServiceProvider;
+import org.opendaylight.mdsal.singleton.api.ServiceGroupIdentifier;
+import org.opendaylight.yangtools.concepts.Registration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public final class FlappingSingletonService implements ClusterSingletonService {
private static final Logger LOG = LoggerFactory.getLogger(FlappingSingletonService.class);
private static final ServiceGroupIdentifier SERVICE_GROUP_IDENTIFIER =
- ServiceGroupIdentifier.create("flapping-singleton-service");
+ new ServiceGroupIdentifier("flapping-singleton-service");
private final ClusterSingletonServiceProvider singletonServiceProvider;
private final AtomicBoolean active = new AtomicBoolean(true);
-
private final AtomicLong flapCount = new AtomicLong();
- private volatile ClusterSingletonServiceRegistration registration;
+
+ private volatile Registration registration;
public FlappingSingletonService(final ClusterSingletonServiceProvider singletonServiceProvider) {
LOG.debug("Registering flapping-singleton-service.");
-
- this.singletonServiceProvider = singletonServiceProvider;
+ this.singletonServiceProvider = requireNonNull(singletonServiceProvider);
registration = singletonServiceProvider.registerClusterSingletonService(this);
}
import com.google.common.util.concurrent.ListenableFuture;
import org.opendaylight.mdsal.dom.api.DOMRpcIdentifier;
import org.opendaylight.mdsal.dom.api.DOMRpcImplementation;
-import org.opendaylight.mdsal.dom.api.DOMRpcImplementationRegistration;
import org.opendaylight.mdsal.dom.api.DOMRpcProviderService;
import org.opendaylight.mdsal.dom.api.DOMRpcResult;
import org.opendaylight.mdsal.dom.spi.DefaultDOMRpcResult;
+import org.opendaylight.yangtools.concepts.Registration;
import org.opendaylight.yangtools.yang.common.QName;
import org.opendaylight.yangtools.yang.common.QNameModule;
-import org.opendaylight.yangtools.yang.common.Revision;
-import org.opendaylight.yangtools.yang.common.XMLNamespace;
import org.opendaylight.yangtools.yang.common.YangConstants;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
-import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
-import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
+import org.opendaylight.yangtools.yang.data.spi.node.ImmutableNodes;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public final class GetConstantService implements DOMRpcImplementation {
private static final Logger LOG = LoggerFactory.getLogger(GetConstantService.class);
- private static final QNameModule MODULE = QNameModule.create(
- XMLNamespace.of("tag:opendaylight.org,2017:controller:yang:lowlevel:target"), Revision.of("2017-02-15"))
- .intern();
+ private static final QNameModule MODULE =
+ QNameModule.ofRevision("tag:opendaylight.org,2017:controller:yang:lowlevel:target", "2017-02-15").intern();
private static final QName OUTPUT = YangConstants.operationOutputQName(MODULE).intern();
private static final QName CONSTANT = QName.create(MODULE, "constant").intern();
this.constant = constant;
}
- public static DOMRpcImplementationRegistration<GetConstantService> registerNew(
- final DOMRpcProviderService rpcProviderService, final String constant) {
+ public static Registration registerNew(final DOMRpcProviderService rpcProviderService, final String constant) {
LOG.debug("Registering get-constant service, constant value: {}", constant);
return rpcProviderService.registerRpcImplementation(new GetConstantService(constant),
DOMRpcIdentifier.create(GET_CONSTANT));
public ListenableFuture<DOMRpcResult> invokeRpc(final DOMRpcIdentifier rpc, final ContainerNode input) {
LOG.debug("get-constant invoked, current value: {}", constant);
- return Futures.immediateFuture(new DefaultDOMRpcResult(Builders.containerBuilder()
+ return Futures.immediateFuture(new DefaultDOMRpcResult(ImmutableNodes.newContainerBuilder()
.withNodeIdentifier(new NodeIdentifier(OUTPUT))
.withChild(ImmutableNodes.leafNode(CONSTANT, constant))
.build()));
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import java.util.HashMap;
import java.util.List;
-import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
-import org.opendaylight.mdsal.dom.api.ClusteredDOMDataTreeChangeListener;
-import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
+import org.opendaylight.mdsal.dom.api.DOMDataTreeChangeListener;
+import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-public final class IdIntsListener implements ClusteredDOMDataTreeChangeListener {
+public final class IdIntsListener implements DOMDataTreeChangeListener {
private static final Logger LOG = LoggerFactory.getLogger(IdIntsListener.class);
private static final long SECOND_AS_NANO = 1000000000;
- private volatile NormalizedNode localCopy;
private final AtomicLong lastNotifTimestamp = new AtomicLong(0);
- private ScheduledExecutorService executorService;
- private ScheduledFuture<?> scheduledFuture;
+ private ScheduledExecutorService executorService = null;
+ private ScheduledFuture<?> scheduledFuture = null;
+
+ private volatile NormalizedNode localCopy;
@Override
public void onInitialData() {
LOG.debug("Received data tree changed");
changes.forEach(change -> {
- if (change.getRootNode().getDataAfter().isPresent()) {
- LOG.trace("Received change, data before: {}, data after: {}",
- change.getRootNode().getDataBefore().isPresent()
- ? change.getRootNode().getDataBefore().get() : "",
- change.getRootNode().getDataAfter().get());
-
- localCopy = change.getRootNode().getDataAfter().get();
+ final var root = change.getRootNode();
+ final var after = root.dataAfter();
+ if (after != null) {
+ final var before = root.dataBefore();
+ LOG.trace("Received change, data before: {}, data after: {}", before != null ? before : "", after);
+ localCopy = after;
} else {
LOG.warn("getDataAfter() is missing from notification. change: {}", change);
}
public Future<Void> tryFinishProcessing() {
executorService = Executors.newSingleThreadScheduledExecutor();
- final SettableFuture<Void> settableFuture = SettableFuture.create();
+ final var settableFuture = SettableFuture.<Void>create();
scheduledFuture = executorService.scheduleAtFixedRate(new CheckFinishedTask(settableFuture),
0, 1, TimeUnit.SECONDS);
public static String diffNodes(final MapNode expected, final MapNode actual) {
StringBuilder builder = new StringBuilder("MapNodes diff:");
- final YangInstanceIdentifier.NodeIdentifier itemNodeId = new YangInstanceIdentifier.NodeIdentifier(ITEM);
+ final var itemNodeId = new NodeIdentifier(ITEM);
- Map<NodeIdentifierWithPredicates, MapEntryNode> expIdIntMap = new HashMap<>();
- expected.body().forEach(node -> expIdIntMap.put(node.getIdentifier(), node));
+ final var expIdIntMap = new HashMap<NodeIdentifierWithPredicates, MapEntryNode>();
+ expected.body().forEach(node -> expIdIntMap.put(node.name(), node));
actual.body().forEach(actIdInt -> {
- final MapEntryNode expIdInt = expIdIntMap.remove(actIdInt.getIdentifier());
+ final var expIdInt = expIdIntMap.remove(actIdInt.name());
if (expIdInt == null) {
- builder.append('\n').append(" Unexpected id-int entry for ").append(actIdInt.getIdentifier());
+ builder.append('\n').append(" Unexpected id-int entry for ").append(actIdInt.name());
return;
}
- Map<NodeIdentifierWithPredicates, MapEntryNode> expItemMap = new HashMap<>();
- ((MapNode)expIdInt.findChildByArg(itemNodeId).get()).body()
- .forEach(node -> expItemMap.put(node.getIdentifier(), node));
+ final var expItemMap = new HashMap<NodeIdentifierWithPredicates, MapEntryNode>();
+ ((MapNode)expIdInt.getChildByArg(itemNodeId)).body()
+ .forEach(node -> expItemMap.put(node.name(), node));
- ((MapNode)actIdInt.findChildByArg(itemNodeId).get()).body().forEach(actItem -> {
- final MapEntryNode expItem = expItemMap.remove(actItem.getIdentifier());
+ ((MapNode)actIdInt.getChildByArg(itemNodeId)).body().forEach(actItem -> {
+ final var expItem = expItemMap.remove(actItem.name());
if (expItem == null) {
- builder.append('\n').append(" Unexpected item entry ").append(actItem.getIdentifier())
- .append(" for id-int entry ").append(actIdInt.getIdentifier());
+ builder.append('\n').append(" Unexpected item entry ").append(actItem.name())
+ .append(" for id-int entry ").append(actIdInt.name());
}
});
expItemMap.values().forEach(node -> builder.append('\n')
- .append(" Actual is missing item entry ").append(node.getIdentifier())
- .append(" for id-int entry ").append(actIdInt.getIdentifier()));
+ .append(" Actual is missing item entry ").append(node.name())
+ .append(" for id-int entry ").append(actIdInt.name()));
});
expIdIntMap.values().forEach(node -> builder.append('\n')
- .append(" Actual is missing id-int entry for ").append(node.getIdentifier()));
+ .append(" Actual is missing id-int entry for ").append(node.name()));
return builder.toString();
}
- private class CheckFinishedTask implements Runnable {
-
+ private final class CheckFinishedTask implements Runnable {
private final SettableFuture<Void> future;
CheckFinishedTask(final SettableFuture<Void> future) {
import org.opendaylight.mdsal.binding.dom.codec.api.BindingNormalizedNodeSerializer;
import org.opendaylight.mdsal.dom.api.DOMRpcIdentifier;
import org.opendaylight.mdsal.dom.api.DOMRpcImplementation;
-import org.opendaylight.mdsal.dom.api.DOMRpcImplementationRegistration;
import org.opendaylight.mdsal.dom.api.DOMRpcProviderService;
import org.opendaylight.mdsal.dom.api.DOMRpcResult;
import org.opendaylight.mdsal.dom.spi.DefaultDOMRpcResult;
+import org.opendaylight.yangtools.concepts.Registration;
import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
import org.opendaylight.yangtools.yang.common.QName;
import org.opendaylight.yangtools.yang.common.QNameModule;
-import org.opendaylight.yangtools.yang.common.Revision;
-import org.opendaylight.yangtools.yang.common.XMLNamespace;
import org.opendaylight.yangtools.yang.common.YangConstants;
-import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
-import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
-import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
+import org.opendaylight.yangtools.yang.data.spi.node.ImmutableNodes;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public final class RoutedGetConstantService implements DOMRpcImplementation {
private static final Logger LOG = LoggerFactory.getLogger(RoutedGetConstantService.class);
- private static final QNameModule MODULE = QNameModule.create(
- XMLNamespace.of("tag:opendaylight.org,2017:controller:yang:lowlevel:target"), Revision.of("2017-02-15"))
- .intern();
+ private static final QNameModule MODULE =
+ QNameModule.ofRevision("tag:opendaylight.org,2017:controller:yang:lowlevel:target", "2017-02-15").intern();
private static final QName OUTPUT = YangConstants.operationOutputQName(MODULE).intern();
private static final QName CONSTANT = QName.create(MODULE, "constant").intern();
private static final QName GET_CONTEXTED_CONSTANT = QName.create(MODULE, "get-contexted-constant").intern();
this.constant = constant;
}
- public static DOMRpcImplementationRegistration<RoutedGetConstantService> registerNew(
- final BindingNormalizedNodeSerializer codec, final DOMRpcProviderService rpcProviderService,
- final String constant, final InstanceIdentifier<?> context) {
+ public static Registration registerNew(final BindingNormalizedNodeSerializer codec,
+ final DOMRpcProviderService rpcProviderService, final String constant,
+ final InstanceIdentifier<?> context) {
LOG.debug("Registering get-contexted-constant on context: {}, with value: {}", context, constant);
- final YangInstanceIdentifier yid = codec.toYangInstanceIdentifier(context);
- final DOMRpcIdentifier id = DOMRpcIdentifier.create(GET_CONTEXTED_CONSTANT, yid);
+ final var yid = codec.toYangInstanceIdentifier(context);
+ final var id = DOMRpcIdentifier.create(GET_CONTEXTED_CONSTANT, yid);
return rpcProviderService.registerRpcImplementation(new RoutedGetConstantService(constant), id);
}
public ListenableFuture<DOMRpcResult> invokeRpc(final DOMRpcIdentifier rpc, final ContainerNode input) {
LOG.debug("get-contexted-constant invoked, current value: {}", constant);
- return Futures.immediateFuture(new DefaultDOMRpcResult(Builders.containerBuilder()
+ return Futures.immediateFuture(new DefaultDOMRpcResult(ImmutableNodes.newContainerBuilder()
.withNodeIdentifier(new NodeIdentifier(OUTPUT))
.withChild(ImmutableNodes.leafNode(CONSTANT, constant))
.build()));
import com.google.common.util.concurrent.ListenableFuture;
import org.opendaylight.mdsal.dom.api.DOMRpcIdentifier;
import org.opendaylight.mdsal.dom.api.DOMRpcImplementation;
-import org.opendaylight.mdsal.dom.api.DOMRpcImplementationRegistration;
import org.opendaylight.mdsal.dom.api.DOMRpcProviderService;
import org.opendaylight.mdsal.dom.api.DOMRpcResult;
import org.opendaylight.mdsal.dom.spi.DefaultDOMRpcResult;
-import org.opendaylight.mdsal.singleton.common.api.ClusterSingletonService;
-import org.opendaylight.mdsal.singleton.common.api.ClusterSingletonServiceProvider;
-import org.opendaylight.mdsal.singleton.common.api.ClusterSingletonServiceRegistration;
-import org.opendaylight.mdsal.singleton.common.api.ServiceGroupIdentifier;
+import org.opendaylight.mdsal.singleton.api.ClusterSingletonService;
+import org.opendaylight.mdsal.singleton.api.ClusterSingletonServiceProvider;
+import org.opendaylight.mdsal.singleton.api.ServiceGroupIdentifier;
+import org.opendaylight.yangtools.concepts.Registration;
import org.opendaylight.yangtools.yang.common.QName;
import org.opendaylight.yangtools.yang.common.QNameModule;
-import org.opendaylight.yangtools.yang.common.Revision;
-import org.opendaylight.yangtools.yang.common.XMLNamespace;
import org.opendaylight.yangtools.yang.common.YangConstants;
import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
-import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
-import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
+import org.opendaylight.yangtools.yang.data.spi.node.ImmutableNodes;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public final class SingletonGetConstantService implements DOMRpcImplementation, ClusterSingletonService {
private static final Logger LOG = LoggerFactory.getLogger(SingletonGetConstantService.class);
- private static final QNameModule MODULE = QNameModule.create(
- XMLNamespace.of("tag:opendaylight.org,2017:controller:yang:lowlevel:target"), Revision.of("2017-02-15"))
- .intern();
+ private static final QNameModule MODULE =
+ QNameModule.ofRevision("tag:opendaylight.org,2017:controller:yang:lowlevel:target", "2017-02-15").intern();
private static final QName OUTPUT = YangConstants.operationOutputQName(MODULE).intern();
private static final QName CONSTANT = QName.create(MODULE, "constant").intern();
private static final QName CONTEXT = QName.create(MODULE, "context").intern();
private static final QName GET_SINGLETON_CONSTANT = QName.create(MODULE, "get-singleton-constant").intern();
private static final ServiceGroupIdentifier SERVICE_GROUP_IDENTIFIER =
- ServiceGroupIdentifier.create("get-singleton-constant-service");
+ new ServiceGroupIdentifier("get-singleton-constant-service");
private final DOMRpcProviderService rpcProviderService;
private final String constant;
- private DOMRpcImplementationRegistration<SingletonGetConstantService> rpcRegistration;
+
+ private Registration rpcRegistration = null;
private SingletonGetConstantService(final DOMRpcProviderService rpcProviderService, final String constant) {
this.rpcProviderService = rpcProviderService;
this.constant = constant;
}
- public static ClusterSingletonServiceRegistration registerNew(
- final ClusterSingletonServiceProvider singletonService, final DOMRpcProviderService rpcProviderService,
- final String constant) {
+ public static Registration registerNew(final ClusterSingletonServiceProvider singletonService,
+ final DOMRpcProviderService rpcProviderService, final String constant) {
LOG.debug("Registering get-singleton-constant into ClusterSingletonService, value {}", constant);
return singletonService.registerClusterSingletonService(
public ListenableFuture<DOMRpcResult> invokeRpc(final DOMRpcIdentifier rpc, final ContainerNode input) {
LOG.debug("get-singleton-constant invoked, current value: {}", constant);
- return Futures.immediateFuture(new DefaultDOMRpcResult(Builders.containerBuilder()
+ return Futures.immediateFuture(new DefaultDOMRpcResult(ImmutableNodes.newContainerBuilder()
.withNodeIdentifier(new NodeIdentifier(OUTPUT))
.withChild(ImmutableNodes.leafNode(CONSTANT, constant))
.build()));
package org.opendaylight.controller.clustering.it.provider.impl;
import static java.util.Objects.requireNonNull;
+import static org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes.mapEntryBuilder;
import com.google.common.util.concurrent.FluentFuture;
+import com.google.common.util.concurrent.FutureCallback;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.SettableFuture;
import java.util.LinkedHashSet;
import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
import org.opendaylight.mdsal.common.api.OptimisticLockFailedException;
import org.opendaylight.mdsal.dom.api.DOMDataBroker;
-import org.opendaylight.mdsal.dom.api.DOMDataTreeTransaction;
import org.opendaylight.mdsal.dom.api.DOMDataTreeWriteTransaction;
import org.opendaylight.mdsal.dom.api.DOMTransactionChain;
-import org.opendaylight.mdsal.dom.api.DOMTransactionChainListener;
import org.opendaylight.yang.gen.v1.tag.opendaylight.org._2017.controller.yang.lowlevel.control.rev170215.WriteTransactionsInput;
import org.opendaylight.yang.gen.v1.tag.opendaylight.org._2017.controller.yang.lowlevel.control.rev170215.WriteTransactionsOutput;
import org.opendaylight.yang.gen.v1.tag.opendaylight.org._2017.controller.yang.lowlevel.control.rev170215.WriteTransactionsOutputBuilder;
+import org.opendaylight.yangtools.yang.common.Empty;
import org.opendaylight.yangtools.yang.common.ErrorType;
import org.opendaylight.yangtools.yang.common.RpcResult;
import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
import org.opendaylight.yangtools.yang.data.api.schema.MapEntryNode;
import org.opendaylight.yangtools.yang.data.api.schema.MapNode;
-import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
-import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNodes;
+import org.opendaylight.yangtools.yang.data.spi.node.ImmutableNodes;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public abstract class WriteTransactionsHandler extends AbstractTransactionHandler {
- private static final class Chained extends WriteTransactionsHandler implements DOMTransactionChainListener {
+ private static final class Chained extends WriteTransactionsHandler implements FutureCallback<Empty> {
private final SplittableRandom random = new SplittableRandom();
private final DOMTransactionChain transactionChain;
Chained(final DOMDataBroker dataBroker, final YangInstanceIdentifier idListItem,
final WriteTransactionsInput input) {
super(idListItem, input);
- transactionChain = dataBroker.createTransactionChain(this);
+ transactionChain = dataBroker.createTransactionChain();
+ transactionChain.addCallback(this);
}
@Override
}
@Override
- public void onTransactionChainFailed(final DOMTransactionChain chain, final DOMDataTreeTransaction transaction,
- final Throwable cause) {
+ public void onFailure(final Throwable cause) {
// This is expected to happen frequently in isolation testing.
LOG.debug("Transaction chain failed.", cause);
// Do not return RPC here, rely on transaction failure to call runFailed.
}
@Override
- public void onTransactionChainSuccessful(final DOMTransactionChain chain) {
+ public void onSuccess(final Empty result) {
LOG.debug("Transaction chain closed successfully.");
}
}
LOG.info("Starting write transactions with input {}", input);
final String id = input.getId();
- final MapEntryNode entry = ImmutableNodes.mapEntryBuilder(ID_INT, ID, id)
- .withChild(ImmutableNodes.mapNodeBuilder(ITEM).build())
+ final MapEntryNode entry = mapEntryBuilder(ID_INT, ID, id)
+ .withChild(ImmutableNodes.newSystemMapBuilder()
+ .withNodeIdentifier(new NodeIdentifier(ITEM))
+ .build())
.build();
- final YangInstanceIdentifier idListItem = ID_INT_YID.node(entry.getIdentifier());
+ final YangInstanceIdentifier idListItem = ID_INT_YID.node(entry.name());
- final ContainerNode containerNode = Builders.containerBuilder()
+ final ContainerNode containerNode = ImmutableNodes.newContainerBuilder()
.withNodeIdentifier(new NodeIdentifier(ID_INTS))
- .withChild(ImmutableNodes.mapNodeBuilder(ID_INT).build())
+ .withChild(ImmutableNodes.newSystemMapBuilder()
+ .withNodeIdentifier(new NodeIdentifier(ID_INT))
+ .build())
.build();
DOMDataTreeWriteTransaction tx = domDataBroker.newWriteOnlyTransaction();
final YangInstanceIdentifier itemListId = idListItem.node(ITEM);
tx = domDataBroker.newWriteOnlyTransaction();
- final MapNode itemListNode = ImmutableNodes.mapNodeBuilder(ITEM).build();
+ final MapNode itemListNode = ImmutableNodes.newSystemMapBuilder()
+ .withNodeIdentifier(new NodeIdentifier(ITEM))
+ .build();
tx.put(LogicalDatastoreType.CONFIGURATION, itemListId, itemListNode);
try {
} else {
LOG.debug("Inserting item: {}", i);
insertTx.incrementAndGet();
- final MapEntryNode entry = ImmutableNodes.mapEntry(ITEM, NUMBER, i);
- tx.put(LogicalDatastoreType.CONFIGURATION, entryId, entry);
+ tx.put(LogicalDatastoreType.CONFIGURATION, entryId, mapEntryBuilder(ITEM, NUMBER, i).build());
usedValues.add(i);
}
import static java.util.Objects.requireNonNull;
import java.util.concurrent.atomic.AtomicLong;
+import org.opendaylight.mdsal.binding.api.NotificationService.Listener;
import org.opendaylight.yang.gen.v1.tag.opendaylight.org._2017.controller.yang.lowlevel.control.rev170215.UnsubscribeYnlOutput;
import org.opendaylight.yang.gen.v1.tag.opendaylight.org._2017.controller.yang.lowlevel.control.rev170215.UnsubscribeYnlOutputBuilder;
import org.opendaylight.yang.gen.v1.tag.opendaylight.org._2017.controller.yang.lowlevel.target.rev170215.IdSequence;
-import org.opendaylight.yang.gen.v1.tag.opendaylight.org._2017.controller.yang.lowlevel.target.rev170215.OdlMdsalLowlevelTargetListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-public class YnlListener implements OdlMdsalLowlevelTargetListener {
+public class YnlListener implements Listener<IdSequence> {
private static final Logger LOG = LoggerFactory.getLogger(YnlListener.class);
private final String id;
}
@Override
- public void onIdSequence(final IdSequence notification) {
+ public void onNotification(final IdSequence notification) {
LOG.debug("Received id-sequence notification, : {}", notification);
allNot.incrementAndGet();
<parent>
<groupId>org.opendaylight.odlparent</groupId>
<artifactId>odlparent-lite</artifactId>
- <version>12.0.1</version>
+ <version>13.0.11</version>
<relativePath/>
</parent>
<groupId>org.opendaylight.controller.samples</groupId>
<artifactId>samples-aggregator</artifactId>
- <version>7.0.2-SNAPSHOT</version>
+ <version>9.0.3-SNAPSHOT</version>
<packaging>pom</packaging>
<properties>
<parent>
<groupId>org.opendaylight.controller</groupId>
<artifactId>mdsal-parent</artifactId>
- <version>7.0.2-SNAPSHOT</version>
+ <version>9.0.3-SNAPSHOT</version>
<relativePath>../../parent</relativePath>
</parent>
<groupId>org.opendaylight.controller</groupId>
<artifactId>sal-common-util</artifactId>
</dependency>
+ <dependency>
+ <groupId>org.opendaylight.mdsal</groupId>
+ <artifactId>mdsal-binding-api</artifactId>
+ </dependency>
<dependency>
<groupId>org.opendaylight.mdsal</groupId>
<artifactId>yang-binding</artifactId>
</dependency>
+ <dependency>
+ <groupId>jakarta.annotation</groupId>
+ <artifactId>jakarta.annotation-api</artifactId>
+ <optional>true</optional>
+ </dependency>
+ <dependency>
+ <groupId>org.osgi</groupId>
+ <artifactId>org.osgi.service.component.annotations</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>com.guicedee.services</groupId>
+ <artifactId>javax.inject</artifactId>
+ <optional>true</optional>
+ </dependency>
</dependencies>
<scm>
import com.google.common.collect.ImmutableList.Builder;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
-import com.google.common.util.concurrent.ListeningExecutorService;
import com.google.common.util.concurrent.MoreExecutors;
import java.util.List;
+import java.util.Set;
import java.util.concurrent.ExecutionException;
+import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
+import javax.annotation.PreDestroy;
+import javax.inject.Inject;
+import javax.inject.Singleton;
import org.opendaylight.controller.md.sal.common.util.jmx.AbstractMXBean;
import org.opendaylight.controller.sample.kitchen.api.EggsType;
import org.opendaylight.controller.sample.kitchen.api.KitchenService;
import org.opendaylight.controller.sample.kitchen.api.KitchenServiceRuntimeMXBean;
-import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.MakeToastInput;
+import org.opendaylight.mdsal.binding.api.NotificationService;
+import org.opendaylight.mdsal.binding.api.NotificationService.CompositeListener;
+import org.opendaylight.mdsal.binding.api.RpcService;
+import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.MakeToast;
import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.MakeToastInputBuilder;
import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.MakeToastOutput;
import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.MakeToastOutputBuilder;
import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.ToastType;
-import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.ToasterListener;
import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.ToasterOutOfBread;
import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.ToasterRestocked;
-import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.ToasterService;
import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.WheatBread;
+import org.opendaylight.yangtools.concepts.Registration;
import org.opendaylight.yangtools.yang.common.ErrorTag;
import org.opendaylight.yangtools.yang.common.ErrorType;
import org.opendaylight.yangtools.yang.common.RpcError;
import org.opendaylight.yangtools.yang.common.RpcResult;
import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
import org.opendaylight.yangtools.yang.common.Uint32;
+import org.osgi.service.component.annotations.Activate;
+import org.osgi.service.component.annotations.Component;
+import org.osgi.service.component.annotations.Deactivate;
+import org.osgi.service.component.annotations.Reference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-public class KitchenServiceImpl extends AbstractMXBean
- implements KitchenService, KitchenServiceRuntimeMXBean, ToasterListener {
-
+@Singleton
+@Component(service = KitchenService.class, immediate = true)
+public final class KitchenServiceImpl extends AbstractMXBean implements KitchenService, KitchenServiceRuntimeMXBean {
private static final Logger LOG = LoggerFactory.getLogger(KitchenServiceImpl.class);
private static final MakeToastOutput EMPTY_MAKE_OUTPUT = new MakeToastOutputBuilder().build();
- private final ToasterService toaster;
-
- private final ListeningExecutorService executor = MoreExecutors.listeningDecorator(Executors.newCachedThreadPool());
+ private final ExecutorService executor = Executors.newCachedThreadPool();
+ private final MakeToast makeToast;
+ private final Registration reg;
private volatile boolean toasterOutOfBread;
- public KitchenServiceImpl(final ToasterService toaster) {
+ @Inject
+ @Activate
+ public KitchenServiceImpl(@Reference final RpcService rpcService,
+ @Reference final NotificationService notifService) {
super("KitchenService", "toaster-consumer", null);
- this.toaster = toaster;
+ makeToast = rpcService.getRpc(MakeToast.class);
+ reg = notifService.registerCompositeListener(new CompositeListener(Set.of(
+ new CompositeListener.Component<>(ToasterOutOfBread.class, notification -> {
+ LOG.info("ToasterOutOfBread notification");
+ toasterOutOfBread = true;
+ }),
+ new CompositeListener.Component<>(ToasterRestocked.class, notification -> {
+ LOG.info("ToasterRestocked notification - amountOfBread: {}", notification.getAmountOfBread());
+ toasterOutOfBread = false;
+ }))));
+ register();
+ }
+
+ @PreDestroy
+ @Deactivate
+ public void close() {
+ unregister();
+ reg.close();
}
@Override
}
private ListenableFuture<RpcResult<Void>> makeEggs(final EggsType eggsType) {
- return executor.submit(() -> RpcResultBuilder.<Void>success().build());
+ return Futures.submit(() -> RpcResultBuilder.<Void>success().build(), executor);
}
private ListenableFuture<RpcResult<MakeToastOutput>> makeToast(final ToastType toastType, final int toastDoneness) {
}
// Access the ToasterService to make the toast.
-
- MakeToastInput toastInput = new MakeToastInputBuilder().setToasterDoneness(Uint32.valueOf(toastDoneness))
- .setToasterToastType(toastType).build();
-
- return toaster.makeToast(toastInput);
+ return makeToast.invoke(new MakeToastInputBuilder()
+ .setToasterDoneness(Uint32.valueOf(toastDoneness))
+ .setToasterToastType(toastType)
+ .build());
}
@Override
return Boolean.FALSE;
}
-
- /**
- * Implemented from the ToasterListener interface.
- */
- @Override
- public void onToasterOutOfBread(final ToasterOutOfBread notification) {
- LOG.info("ToasterOutOfBread notification");
- toasterOutOfBread = true;
- }
-
- /**
- * Implemented from the ToasterListener interface.
- */
- @Override
- public void onToasterRestocked(final ToasterRestocked notification) {
- LOG.info("ToasterRestocked notification - amountOfBread: {}", notification.getAmountOfBread());
- toasterOutOfBread = false;
- }
}
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<blueprint xmlns="http://www.osgi.org/xmlns/blueprint/v1.0.0"
- xmlns:odl="http://opendaylight.org/xmlns/blueprint/v1.0.0"
- odl:use-default-for-reference-types="true">
-
- <!-- Retrieves the RPC service for the ToasterService interface -->
- <odl:rpc-service id="toasterService" interface="org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.ToasterService"/>
-
- <!-- Create the KitchenServiceImpl instance and inject the RPC service identified by "toasterService" -->
- <bean id="kitchenService" class="org.opendaylight.controller.sample.kitchen.impl.KitchenServiceImpl"
- init-method="register" destroy-method="unregister">
- <argument ref="toasterService"/>
- </bean>
-
- <!-- Register the KitchenServiceImpl to receive yang notifications -->
- <odl:notification-listener ref="kitchenService"/>
-
- <!-- Advertise the KitchenServiceImpl with the OSGi registry with the type property set to "default" . The
- type property is optional but can be used to distinguish this implementation from any other potential
- KitchenService implementations (if there were any). Clients consuming the KitchenService can pick the
- desired implementation via the particular type.
- -->
- <service ref="kitchenService" interface="org.opendaylight.controller.sample.kitchen.api.KitchenService"
- odl:type="default"/>
-</blueprint>
<parent>
<groupId>org.opendaylight.controller</groupId>
<artifactId>mdsal-it-parent</artifactId>
- <version>7.0.2-SNAPSHOT</version>
+ <version>9.0.3-SNAPSHOT</version>
<relativePath>../../mdsal-it-parent</relativePath>
</parent>
<artifactId>sample-toaster-it</artifactId>
import org.opendaylight.controller.sample.kitchen.api.EggsType;
import org.opendaylight.controller.sample.kitchen.api.KitchenService;
import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.HashBrown;
+import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.MakeToast;
import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.WhiteBread;
import org.ops4j.pax.exam.junit.PaxExam;
import org.ops4j.pax.exam.options.MavenUrlReference;
@Inject
@Filter(timeout = 60 * 1000)
KitchenService kitchenService;
+ @Inject
+ @Filter(timeout = 60 * 1000)
+ // proxy for the entire toaster, nothing else
+ MakeToast makeToast;
@Override
public MavenUrlReference getFeatureRepo() {
<parent>
<groupId>org.opendaylight.controller</groupId>
<artifactId>mdsal-parent</artifactId>
- <version>7.0.2-SNAPSHOT</version>
+ <version>9.0.3-SNAPSHOT</version>
<relativePath>../../parent</relativePath>
</parent>
<groupId>org.opendaylight.mdsal</groupId>
<artifactId>mdsal-binding-test-utils</artifactId>
</dependency>
+
+ <dependency>
+ <groupId>jakarta.annotation</groupId>
+ <artifactId>jakarta.annotation-api</artifactId>
+ <optional>true</optional>
+ </dependency>
+ <dependency>
+ <groupId>org.osgi</groupId>
+ <artifactId>org.osgi.service.component.annotations</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>com.guicedee.services</groupId>
+ <artifactId>javax.inject</artifactId>
+ <optional>true</optional>
+ </dependency>
+ <dependency>
+ <groupId>org.osgi</groupId>
+ <artifactId>org.osgi.service.metatype.annotations</artifactId>
+ <scope>compile</scope>
+ </dependency>
</dependencies>
<scm>
package org.opendaylight.controller.sample.toaster.provider;
import static java.util.Objects.requireNonNull;
-import static org.opendaylight.mdsal.binding.api.DataObjectModification.ModificationType.DELETE;
-import static org.opendaylight.mdsal.binding.api.DataObjectModification.ModificationType.WRITE;
import static org.opendaylight.mdsal.common.api.LogicalDatastoreType.CONFIGURATION;
import static org.opendaylight.mdsal.common.api.LogicalDatastoreType.OPERATIONAL;
import static org.opendaylight.yangtools.yang.common.ErrorType.APPLICATION;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.MoreExecutors;
import com.google.common.util.concurrent.SettableFuture;
-import java.util.Collection;
+import java.util.List;
import java.util.Optional;
import java.util.concurrent.Callable;
+import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Function;
+import javax.annotation.PreDestroy;
+import javax.inject.Inject;
+import javax.inject.Singleton;
+import org.eclipse.jdt.annotation.NonNull;
import org.opendaylight.controller.md.sal.common.util.jmx.AbstractMXBean;
import org.opendaylight.mdsal.binding.api.DataBroker;
-import org.opendaylight.mdsal.binding.api.DataObjectModification;
import org.opendaylight.mdsal.binding.api.DataTreeChangeListener;
import org.opendaylight.mdsal.binding.api.DataTreeIdentifier;
import org.opendaylight.mdsal.binding.api.DataTreeModification;
import org.opendaylight.mdsal.binding.api.NotificationPublishService;
import org.opendaylight.mdsal.binding.api.ReadWriteTransaction;
+import org.opendaylight.mdsal.binding.api.RpcProviderService;
import org.opendaylight.mdsal.binding.api.WriteTransaction;
import org.opendaylight.mdsal.common.api.CommitInfo;
import org.opendaylight.mdsal.common.api.OptimisticLockFailedException;
import org.opendaylight.mdsal.common.api.TransactionCommitFailedException;
+import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.CancelToast;
import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.CancelToastInput;
import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.CancelToastOutput;
import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.CancelToastOutputBuilder;
import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.DisplayString;
+import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.MakeToast;
import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.MakeToastInput;
import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.MakeToastOutput;
import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.MakeToastOutputBuilder;
+import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.RestockToaster;
import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.RestockToasterInput;
import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.RestockToasterOutput;
import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.RestockToasterOutputBuilder;
import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.ToasterOutOfBreadBuilder;
import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.ToasterRestocked;
import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.ToasterRestockedBuilder;
-import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.ToasterService;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.toaster.app.config.rev160503.ToasterAppConfig;
-import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.toaster.app.config.rev160503.ToasterAppConfigBuilder;
-import org.opendaylight.yangtools.concepts.ListenerRegistration;
+import org.opendaylight.yangtools.concepts.Registration;
import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
import org.opendaylight.yangtools.yang.common.ErrorTag;
import org.opendaylight.yangtools.yang.common.ErrorType;
import org.opendaylight.yangtools.yang.common.RpcError;
import org.opendaylight.yangtools.yang.common.RpcResult;
import org.opendaylight.yangtools.yang.common.RpcResultBuilder;
-import org.opendaylight.yangtools.yang.common.Uint16;
-import org.opendaylight.yangtools.yang.common.Uint32;
+import org.osgi.service.component.annotations.Activate;
+import org.osgi.service.component.annotations.Component;
+import org.osgi.service.component.annotations.Deactivate;
+import org.osgi.service.component.annotations.Reference;
+import org.osgi.service.metatype.annotations.AttributeDefinition;
+import org.osgi.service.metatype.annotations.Designate;
+import org.osgi.service.metatype.annotations.ObjectClassDefinition;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-public class OpendaylightToaster extends AbstractMXBean
- implements ToasterService, ToasterProviderRuntimeMXBean, DataTreeChangeListener<Toaster>, AutoCloseable {
+@Singleton
+@Component(service = MakeToast.class, immediate = true)
+@Designate(ocd = OpendaylightToaster.Configuration.class)
+public final class OpendaylightToaster extends AbstractMXBean
+ implements MakeToast, ToasterProviderRuntimeMXBean, DataTreeChangeListener<Toaster>, AutoCloseable {
+ @ObjectClassDefinition
+ public @interface Configuration {
+ @AttributeDefinition(description = "The name of the toaster's manufacturer", max = "255")
+ String manufacturer() default TOASTER_MANUFACTURER;
+ @AttributeDefinition(description = "The name of the toaster's model", max = "255")
+ String modelNumber() default TOASTER_MODEL_NUMBER;
+ @AttributeDefinition(description = "How many times we attempt to make toast before failing ",
+ min = "0", max = "65535")
+ int maxMakeToastTries() default 2;
+ }
private static final CancelToastOutput EMPTY_CANCEL_OUTPUT = new CancelToastOutputBuilder().build();
private static final MakeToastOutput EMPTY_MAKE_OUTPUT = new MakeToastOutputBuilder().build();
private static final Logger LOG = LoggerFactory.getLogger(OpendaylightToaster.class);
private static final InstanceIdentifier<Toaster> TOASTER_IID = InstanceIdentifier.builder(Toaster.class).build();
- private static final DisplayString TOASTER_MANUFACTURER = new DisplayString("Opendaylight");
- private static final DisplayString TOASTER_MODEL_NUMBER = new DisplayString("Model 1 - Binding Aware");
+ private static final String TOASTER_MANUFACTURER = "Opendaylight";
+ private static final String TOASTER_MODEL_NUMBER = "Model 1 - Binding Aware";
- private DataBroker dataBroker;
- private NotificationPublishService notificationProvider;
- private ListenerRegistration<OpendaylightToaster> dataTreeChangeListenerRegistration;
+ private final DataBroker dataBroker;
+ private final NotificationPublishService notificationProvider;
+ private final Registration dataTreeChangeListenerRegistration;
+ private final Registration reg;
private final ExecutorService executor;
private final AtomicLong toastsMade = new AtomicLong(0);
private final AtomicLong darknessFactor = new AtomicLong(1000);
- private final ToasterAppConfig toasterAppConfig;
-
- public OpendaylightToaster() {
- this(new ToasterAppConfigBuilder().setManufacturer(TOASTER_MANUFACTURER).setModelNumber(TOASTER_MODEL_NUMBER)
- .setMaxMakeToastTries(Uint16.valueOf(2)).build());
- }
+ private final @NonNull DisplayString manufacturer;
+ private final @NonNull DisplayString modelNumber;
+ private final int maxMakeToastTries;
- public OpendaylightToaster(final ToasterAppConfig toasterAppConfig) {
+ public OpendaylightToaster(final DataBroker dataProvider,
+ final NotificationPublishService notificationPublishService, final RpcProviderService rpcProviderService,
+ final String manufacturer, final String modelNumber, final int maxMakeToastTries) {
super("OpendaylightToaster", "toaster-provider", null);
- executor = Executors.newFixedThreadPool(1);
- this.toasterAppConfig = toasterAppConfig;
- }
+ notificationProvider = requireNonNull(notificationPublishService);
+ dataBroker = requireNonNull(dataProvider);
- public void setNotificationProvider(final NotificationPublishService notificationPublishService) {
- notificationProvider = notificationPublishService;
- }
+ this.manufacturer = new DisplayString(manufacturer);
+ this.modelNumber = new DisplayString(modelNumber);
+ this.maxMakeToastTries = maxMakeToastTries;
- public void setDataBroker(final DataBroker dataBroker) {
- this.dataBroker = dataBroker;
- }
+ executor = Executors.newFixedThreadPool(1);
+ reg = rpcProviderService.registerRpcImplementations(
+ (CancelToast) this::cancelToast,
+ this,
+ (RestockToaster) this::restockToaster);
- public void init() {
LOG.info("Initializing...");
dataTreeChangeListenerRegistration = requireNonNull(dataBroker, "dataBroker must be set")
- .registerDataTreeChangeListener(DataTreeIdentifier.create(CONFIGURATION, TOASTER_IID), this);
- setToasterStatusUp(null);
+ .registerTreeChangeListener(DataTreeIdentifier.of(CONFIGURATION, TOASTER_IID), this);
+ try {
+ setToasterStatusUp(null).get();
+ } catch (InterruptedException | ExecutionException e) {
+ throw new IllegalStateException("Failed to commit initial data", e);
+ }
// Register our MXBean.
register();
}
+ @Inject
+ public OpendaylightToaster(final DataBroker dataProvider,
+ final NotificationPublishService notificationPublishService, final RpcProviderService rpcProviderService) {
+ this(dataProvider, notificationPublishService, rpcProviderService, TOASTER_MANUFACTURER, TOASTER_MODEL_NUMBER,
+ 2);
+ }
+
+ @Activate
+ public OpendaylightToaster(@Reference final DataBroker dataProvider,
+ @Reference final NotificationPublishService notificationPublishService,
+ @Reference final RpcProviderService rpcProviderService, final @NonNull Configuration configuration) {
+ this(dataProvider, notificationPublishService, rpcProviderService, configuration.manufacturer(),
+ configuration.modelNumber(), configuration.maxMakeToastTries());
+ }
+
/**
* Implemented from the AutoCloseable interface.
*/
@Override
+ @PreDestroy
+ @Deactivate
public void close() {
LOG.info("Closing...");
// Unregister our MXBean.
unregister();
+ reg.close();
// When we close this service we need to shutdown our executor!
executor.shutdown();
// note - we are simulating a device whose manufacture and model are
// fixed (embedded) into the hardware.
// This is why the manufacture and model number are hardcoded.
- return new ToasterBuilder().setToasterManufacturer(toasterAppConfig.getManufacturer())
- .setToasterModelNumber(toasterAppConfig.getModelNumber()).setToasterStatus(status).build();
+ return new ToasterBuilder()
+ .setToasterManufacturer(manufacturer)
+ .setToasterModelNumber(modelNumber)
+ .setToasterStatus(status)
+ .build();
}
/**
* Implemented from the DataTreeChangeListener interface.
*/
@Override
- public void onDataTreeChanged(final Collection<DataTreeModification<Toaster>> changes) {
- for (DataTreeModification<Toaster> change: changes) {
- DataObjectModification<Toaster> rootNode = change.getRootNode();
- if (rootNode.getModificationType() == WRITE) {
- Toaster oldToaster = rootNode.getDataBefore();
- Toaster newToaster = rootNode.getDataAfter();
- LOG.info("onDataTreeChanged - Toaster config with path {} was added or replaced: "
- + "old Toaster: {}, new Toaster: {}", change.getRootPath().getRootIdentifier(),
- oldToaster, newToaster);
-
- Uint32 darkness = newToaster.getDarknessFactor();
- if (darkness != null) {
- darknessFactor.set(darkness.toJava());
+ public void onDataTreeChanged(final List<DataTreeModification<Toaster>> changes) {
+ for (var change: changes) {
+ final var rootNode = change.getRootNode();
+ switch (rootNode.modificationType()) {
+ case WRITE -> {
+ final var oldToaster = rootNode.dataBefore();
+ final var newToaster = rootNode.dataAfter();
+ LOG.info("onDataTreeChanged - Toaster config with path {} was added or replaced: old Toaster: {}, "
+ + "new Toaster: {}", change.getRootPath().path(), oldToaster, newToaster);
+
+ final var darkness = newToaster.getDarknessFactor();
+ if (darkness != null) {
+ darknessFactor.set(darkness.toJava());
+ }
+ }
+ case DELETE -> LOG.info("onDataTreeChanged - Toaster config with path {} was deleted: old Toaster: {}",
+ change.getRootPath().path(), rootNode.dataBefore());
+ default -> {
+ // No-op
}
- } else if (rootNode.getModificationType() == DELETE) {
- LOG.info("onDataTreeChanged - Toaster config with path {} was deleted: old Toaster: {}",
- change.getRootPath().getRootIdentifier(), rootNode.getDataBefore());
}
}
}
/**
* RPC call implemented from the ToasterService interface that cancels the current toast, if any.
*/
- @Override
- public ListenableFuture<RpcResult<CancelToastOutput>> cancelToast(final CancelToastInput input) {
- Future<?> current = currentMakeToastTask.getAndSet(null);
+ private ListenableFuture<RpcResult<CancelToastOutput>> cancelToast(final CancelToastInput input) {
+ final var current = currentMakeToastTask.getAndSet(null);
if (current != null) {
current.cancel(true);
}
* RPC call implemented from the ToasterService interface that attempts to make toast.
*/
@Override
- public ListenableFuture<RpcResult<MakeToastOutput>> makeToast(final MakeToastInput input) {
+ public ListenableFuture<RpcResult<MakeToastOutput>> invoke(final MakeToastInput input) {
LOG.info("makeToast: {}", input);
-
- final SettableFuture<RpcResult<MakeToastOutput>> futureResult = SettableFuture.create();
-
- checkStatusAndMakeToast(input, futureResult, toasterAppConfig.getMaxMakeToastTries().toJava());
-
+ final var futureResult = SettableFuture.<RpcResult<MakeToastOutput>>create();
+ checkStatusAndMakeToast(input, futureResult, maxMakeToastTries);
return futureResult;
}
Futures.transformAsync(readFuture, toasterData -> {
ToasterStatus toasterStatus = ToasterStatus.Up;
if (toasterData.isPresent()) {
- toasterStatus = toasterData.get().getToasterStatus();
+ toasterStatus = toasterData.orElseThrow().getToasterStatus();
}
LOG.debug("Read toaster status: {}", toasterStatus);
* Restocks the bread for the toaster, resets the toastsMade counter to 0, and sends a
* ToasterRestocked notification.
*/
- @Override
- public ListenableFuture<RpcResult<RestockToasterOutput>> restockToaster(final RestockToasterInput input) {
+ private ListenableFuture<RpcResult<RestockToasterOutput>> restockToaster(final RestockToasterInput input) {
LOG.info("restockToaster: {}", input);
amountOfBreadInStock.set(input.getAmountOfBreadToStock().toJava());
return toastsMade.get();
}
- private void setToasterStatusUp(final Function<Boolean, MakeToastOutput> resultCallback) {
+ private ListenableFuture<?> setToasterStatusUp(final Function<Boolean, MakeToastOutput> resultCallback) {
WriteTransaction tx = dataBroker.newWriteOnlyTransaction();
tx.put(OPERATIONAL,TOASTER_IID, buildToaster(ToasterStatus.Up));
- Futures.addCallback(tx.commit(), new FutureCallback<CommitInfo>() {
+ final var future = tx.commit();
+ Futures.addCallback(future, new FutureCallback<CommitInfo>() {
@Override
public void onSuccess(final CommitInfo result) {
LOG.info("Successfully set ToasterStatus to Up");
}
}
}, MoreExecutors.directExecutor());
+
+ return future;
}
private boolean outOfBread() {
+++ /dev/null
-<?xml version="1.0" encoding="UTF-8"?>
-<blueprint xmlns="http://www.osgi.org/xmlns/blueprint/v1.0.0"
- xmlns:odl="http://opendaylight.org/xmlns/blueprint/v1.0.0"
- xmlns:cm="http://aries.apache.org/blueprint/xmlns/blueprint-cm/v1.1.0"
- odl:restart-dependents-on-updates="true" odl:use-default-for-reference-types="true">
-
- <!-- "restart-dependents-on-updates" is an ODL extension attribute that processes any "property-placeholder"
- elements and reacts to updates to the corresponding cfg file by restarting this blueprint container any
- dependent containers that consume OSGi services provided by this container in an atomic and orderly
- manner.
-
- "use-default-for-reference-types" is an ODL extension attribute that adds a filter to all services
- imported via "reference" elements where the "type" property is either not set or set to "default" if
- the odl:type attribute isn't explicitly specified. This ensures the default implementation is imported
- if there are other implementations advertised with other types.
- -->
-
- <!-- Accesses properties via the etc/org.opendaylight.toaster.cfg file. The properties are made available
- as variables that can be referenced. The variables are substituted with the actual values read from
- the cfg file, if present, or the default-properties.
- -->
- <cm:property-placeholder persistent-id="org.opendaylight.toaster" update-strategy="none">
- <cm:default-properties>
- <cm:property name="databroker-type" value="default"/>
- </cm:default-properties>
- </cm:property-placeholder>
-
- <!-- "clustered-app-config" is an ODL extension that obtains an application configuration yang container
- from the MD-SAL data store and makes the binding DataObject available as a bean that can be injected
- into other beans. Here we obtain the ToasterAppConfig container DataObject. This also shows how to
- specify default data via the "default-config" child element. While default leaf values defined in the
- yang are returned, one may have more complex data, eg lists, that require default data. The
- "default-config" must contain the XML representation of the yang data, including namespace, wrapped
- in a CDATA section to prevent the blueprint container from treating it as markup.
- -->
- <odl:clustered-app-config id="toasterAppConfig"
- binding-class="org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.toaster.app.config.rev160503.ToasterAppConfig">
- <odl:default-config><![CDATA[
- <toaster-app-config xmlns="urn:opendaylight:params:xml:ns:yang:controller:toaster-app-config">
- <max-make-toast-tries>3</max-make-toast-tries>
- </toaster-app-config>
- ]]></odl:default-config>
- </odl:clustered-app-config>
-
- <!-- Import MD-SAL services. For the DataBroker, we explicitly specify the odl:type which is configurable
- via the cfg file. In this manner the toaster can be configured to use the default clustered DataBroker
- or the specialized "pingpong" DataBroker (or any other DataBroker implementation).
- -->
- <reference id="dataBroker" interface="org.opendaylight.mdsal.binding.api.DataBroker" odl:type="${databroker-type}" />
- <reference id="notificationService" interface="org.opendaylight.mdsal.binding.api.NotificationPublishService"/>
-
- <!-- Create the OpendaylightToaster instance and inject its dependencies -->
- <bean id="toaster" class="org.opendaylight.controller.sample.toaster.provider.OpendaylightToaster"
- init-method="init" destroy-method="close">
- <argument ref="toasterAppConfig"/>
- <property name="dataBroker" ref="dataBroker"/>
- <property name="notificationProvider" ref="notificationService"/>
- </bean>
-
- <!-- Register the OpendaylightToaster instance as an RPC implementation provider. The "rpc-implementation"
- element automatically figures out the RpcService interface although it can be explicitly specified.
- -->
- <odl:rpc-implementation ref="toaster"/>
-</blueprint>
+++ /dev/null
-module toaster-app-config {
- yang-version 1;
-
- namespace "urn:opendaylight:params:xml:ns:yang:controller:toaster-app-config";
- prefix toaster-app-config;
-
- import toaster { prefix toaster; revision-date 2009-11-20; }
-
- description
- "Configuration for the Opendaylight toaster application.";
-
- revision "2016-05-03" {
- description
- "Initial revision.";
- }
-
- container toaster-app-config {
- leaf manufacturer {
- type toaster:DisplayString;
- default "Opendaylight";
- }
-
- leaf model-number {
- type toaster:DisplayString;
- default "Model 1 - Binding Aware";
- }
-
- leaf max-make-toast-tries {
- type uint16;
- default 2;
- }
- }
-}
\ No newline at end of file
import org.opendaylight.mdsal.binding.api.DataBroker;
import org.opendaylight.mdsal.binding.api.NotificationPublishService;
import org.opendaylight.mdsal.binding.api.ReadTransaction;
+import org.opendaylight.mdsal.binding.api.RpcProviderService;
import org.opendaylight.mdsal.binding.dom.adapter.test.AbstractConcurrentDataBrokerTest;
import org.opendaylight.mdsal.common.api.LogicalDatastoreType;
import org.opendaylight.yang.gen.v1.http.netconfcentral.org.ns.toaster.rev091120.DisplayString;
@Before
public void setupToaster() {
- toaster = new OpendaylightToaster();
- toaster.setDataBroker(getDataBroker());
- toaster.init();
-
- // We'll mock the NotificationProviderService.
- NotificationPublishService mockNotification = mock(NotificationPublishService.class);
- toaster.setNotificationProvider(mockNotification);
+ toaster = new OpendaylightToaster(getDataBroker(), mock(NotificationPublishService.class),
+ mock(RpcProviderService.class));
}
@Test
assertNotNull(optional);
assertTrue("Operational toaster not present", optional.isPresent());
- Toaster toasterData = optional.get();
+ Toaster toasterData = optional.orElseThrow();
assertEquals(Toaster.ToasterStatus.Up, toasterData.getToasterStatus());
assertEquals(new DisplayString("Opendaylight"), toasterData.getToasterManufacturer());
// NOTE: In a real test we would want to override the Thread.sleep() to
// prevent our junit test
// for sleeping for a second...
- Future<RpcResult<MakeToastOutput>> makeToast = toaster.makeToast(toastInput);
+ Future<RpcResult<MakeToastOutput>> makeToast = toaster.invoke(toastInput);
RpcResult<MakeToastOutput> rpcResult = makeToast.get();
<parent>
<groupId>org.opendaylight.controller</groupId>
<artifactId>mdsal-parent</artifactId>
- <version>7.0.2-SNAPSHOT</version>
+ <version>9.0.3-SNAPSHOT</version>
<relativePath>../../parent</relativePath>
</parent>
<parent>
<groupId>org.opendaylight.odlparent</groupId>
<artifactId>odlparent-lite</artifactId>
- <version>12.0.1</version>
+ <version>13.0.11</version>
<relativePath/>
</parent>
<groupId>org.opendaylight.controller</groupId>
<artifactId>releasepom</artifactId>
- <version>7.0.2-SNAPSHOT</version>
+ <version>9.0.3-SNAPSHOT</version>
<packaging>pom</packaging>
<name>controller</name>
<!-- Used by Sonar to set project name -->
<module>karaf</module>
<module>akka</module>
+ <module>atomix-storage</module>
<module>bundle-parent</module>
<module>benchmark</module>
<module>jolokia</module>
- <!-- md-sal -->
- <module>opendaylight/md-sal</module>
- <!-- config -->
- <module>opendaylight/config</module>
-
<module>opendaylight/blueprint</module>
+ <module>opendaylight/md-sal</module>
</modules>
<profiles>