mirror of https://github.com/OpenIdentityPlatform/OpenDJ.git

Valery Kharseko
20 hours ago 400fb2694641b05e53217d3c742a6e49e3a254c6
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
/*
 * The contents of this file are subject to the terms of the Common Development and
 * Distribution License (the License). You may not use this file except in compliance with the
 * License.
 *
 * You can obtain a copy of the License at legal/CDDLv1.0.txt. See the License for the
 * specific language governing permission and limitations under the License.
 *
 * When distributing Covered Software, include this CDDL Header Notice in each file and include
 * the License file at legal/CDDLv1.0.txt. If applicable, add the following below the CDDL
 * Header, with the fields enclosed by brackets [] replaced by your own identifying
 * information: "Portions copyright [year] [name of copyright owner]".
 *
 * Copyright 2026 3A Systems, LLC.
 */
package org.opends.server.replication.plugin;
 
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Base64;
import java.util.Locale;
import java.util.zip.CRC32;
 
import org.forgerock.i18n.LocalizableMessage;
import org.opends.server.api.ServerShutdownListener;
import org.opends.server.core.DirectoryServer;
import org.opends.server.replication.common.CSN;
import org.opends.server.replication.common.CSNGenerator;
import org.opends.server.replication.service.ReplicationDomain;
 
/** Opt-in, test-only evidence of every locally allocated CSN, including failed operations. */
final class CsnAllocationTrace
{
  private static final String DIRECTORY = "org.opends.server.replication.csnTraceDirectory";
  private static final String TOKEN = "org.opends.server.replication.csnTraceToken";
  private static final String TOKEN_FILE = "org.opends.server.replication.csnTraceTokenFile";
  private static final CsnAllocationTrace ACTIVE = start();
 
  private final Path path;
  private final OutputStream output;
  private final CRC32 checksum = new CRC32();
  private long count;
  private boolean finished;
  private boolean failed;
 
  private static CsnAllocationTrace start()
  {
    String directory = System.getProperty(DIRECTORY);
    if (directory == null)
    {
      return null;
    }
    try
    {
      String token = resolveToken(System.getProperty(TOKEN, ""), System.getProperty(TOKEN_FILE));
      CsnAllocationTrace trace = new CsnAllocationTrace(Paths.get(directory), token);
      // DirectoryServer runs shutdown hooks concurrently. Its listener runs after the work
      // queue, replication and shutdown plugins have stopped, including offline messages.
      // A crash, or a shutdown that never reaches this point, leaves no valid footer.
      DirectoryServer.registerShutdownListener(new ServerShutdownListener()
      {
        @Override
        public String getShutdownListenerName()
        {
          return "CSN allocation trace";
        }
 
        @Override
        public void processServerShutdown(LocalizableMessage reason)
        {
          trace.finish();
        }
      });
      return trace;
    }
    catch (IOException e)
    {
      throw new IllegalStateException("Cannot start the requested CSN allocation trace", e);
    }
  }
 
  static String resolveToken(String defaultToken, String tokenFile) throws IOException
  {
    if (tokenFile == null || Files.notExists(Paths.get(tokenFile)))
    {
      return defaultToken;
    }
    return Files.readString(Paths.get(tokenFile), StandardCharsets.US_ASCII).trim();
  }
 
  CsnAllocationTrace(Path directory, String token) throws IOException
  {
    if (!token.matches("[a-zA-Z0-9_-]+"))
    {
      throw new IllegalArgumentException("A CSN trace requires a generation token");
    }
    Files.createDirectories(directory);
    path = Files.createTempFile(directory, "trace-", ".txt");
    output = new BufferedOutputStream(Files.newOutputStream(path), 65536);
    output.write(("START 1 " + token + "\n").getBytes(StandardCharsets.US_ASCII));
    output.flush();
  }
 
  static String domain(ReplicationDomain domain)
  {
    return ACTIVE != null ? encodeDomain(domain.getBaseDN().toString()) : null;
  }
 
  static String encodeDomain(String name)
  {
    return Base64.getEncoder().encodeToString(name.getBytes(StandardCharsets.UTF_8));
  }
 
  static CSN next(CSNGenerator generator, String domain, char kind)
  {
    return ACTIVE != null ? ACTIVE.allocate(generator, domain, kind) : generator.newCSN();
  }
 
  synchronized CSN allocate(CSNGenerator generator, String domain, char kind)
  {
    try
    {
      // Mark before allocating, so even a thread stopped immediately afterwards cannot
      // make a completed trace conceal an allocation made during the shutdown hooks.
      if (finished)
      {
        output.write("AFTER-END\n".getBytes(StandardCharsets.US_ASCII));
        output.flush();
        return generator.newCSN();
      }
      if (failed)
      {
        throw new IllegalStateException("The CSN allocation trace has failed");
      }
      CSN csn = generator.newCSN();
      byte[] line = (kind + " " + domain + " " + csn + "\n").getBytes(StandardCharsets.US_ASCII);
      output.write(line);
      checksum.update(line);
      count++;
      if (count % 4096 == 0)
      {
        output.flush();
      }
      return csn;
    }
    catch (IOException e)
    {
      failed = true;
      throw new IllegalStateException("Cannot write the CSN allocation trace", e);
    }
  }
 
  synchronized void finish()
  {
    if (finished)
    {
      return;
    }
    finished = true;
    if (failed)
    {
      return;
    }
    try
    {
      output.write(String.format(Locale.ROOT, "END %d %08x\n", count, checksum.getValue())
          .getBytes(StandardCharsets.US_ASCII));
      output.flush();
    }
    catch (IOException e)
    {
      // A missing or partial footer makes the trace invalid to its consumer.
      System.err.println("Cannot finish the CSN allocation trace: " + e);
    }
  }
 
  Path path()
  {
    return path;
  }
}