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

abobrov
13.03.2009 27ede8298aee9ed2b6f83863173ba2415189b4f6
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
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
/*
 * CDDL HEADER START
 *
 * The contents of this file are subject to the terms of the
 * Common Development and Distribution License, Version 1.0 only
 * (the "License").  You may not use this file except in compliance
 * with the License.
 *
 * You can obtain a copy of the license at
 * trunk/opends/resource/legal-notices/OpenDS.LICENSE
 * or https://OpenDS.dev.java.net/OpenDS.LICENSE.
 * See the License for the specific language governing permissions
 * and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL HEADER in each
 * file and include the License file at
 * trunk/opends/resource/legal-notices/OpenDS.LICENSE.  If applicable,
 * add the following below this CDDL HEADER, with the fields enclosed
 * by brackets "[]" replaced with your own identifying information:
 *      Portions Copyright [yyyy] [name of copyright owner]
 *
 * CDDL HEADER END
 *
 *
 *      Copyright 2008-2009 Sun Microsystems, Inc.
 */
package org.opends.server.backends.ndb;
import com.mysql.cluster.ndbj.Ndb;
import com.mysql.cluster.ndbj.NdbApiException;
import com.mysql.cluster.ndbj.NdbApiTemporaryException;
import com.mysql.cluster.ndbj.NdbClusterConnection;
import org.opends.messages.Message;
import java.util.concurrent.ConcurrentHashMap;
import java.util.*;
import java.util.concurrent.LinkedBlockingQueue;
import org.opends.server.types.DN;
import org.opends.server.types.ConfigChangeResult;
import org.opends.server.types.ResultCode;
import org.opends.server.api.Backend;
import org.opends.server.admin.server.ConfigurationChangeListener;
import org.opends.server.admin.std.server.NdbBackendCfg;
import org.opends.server.config.ConfigException;
import static org.opends.server.loggers.ErrorLogger.logError;
import static org.opends.server.loggers.debug.DebugLogger.*;
import static org.opends.messages.NdbMessages.*;
import org.opends.server.loggers.debug.DebugTracer;
import org.opends.server.types.DebugLogLevel;
 
/**
 * Root container holds all the entry containers for each base DN.
 * It also maintains all the openings and closings of the entry
 * containers.
 */
public class RootContainer
     implements ConfigurationChangeListener<NdbBackendCfg>
{
  /**
   * The tracer object for the debug logger.
   */
  private static final DebugTracer TRACER = getTracer();
 
  /**
   * The backend configuration.
   */
  private NdbBackendCfg config;
 
  /**
   * The backend to which this entry root container belongs.
   */
  private Backend backend;
 
  /**
   * The base DNs contained in this entryContainer.
   */
  private ConcurrentHashMap<DN, EntryContainer> entryContainers;
 
  /**
   * NDB connection objects.
   */
  private static NdbClusterConnection[] ndbConns;
 
  /**
   * NDB handle objects.
   */
  private static LinkedBlockingQueue<Ndb> ndbQueue;
 
  /**
   * NDB thread count.
   */
  private int ndbThreadCount;
 
  /**
   * NDB number of connections.
   */
  private int ndbNumConnections;
 
  /**
   * The range to use when requesting next ID.
   */
  private static final long NDB_NEXTID_RANGE = 1000;
 
  /**
   * The maximum number of NDB threads.
   */
  private static final int NDB_MAX_THREAD_COUNT = 128;
 
  /**
   * Timeout for the first node/group to become ready.
   */
  private static final int NDB_TIMEOUT_FIRST_ALIVE = 60;
 
  /**
   * Timeout for the rest of nodes/groups to become ready.
   */
  private static final int NDB_TIMEOUT_AFTER_FIRST_ALIVE = 60;
 
 
 
  /**
   * Creates a new RootContainer object.
   *
   * @param config The configuration of the NDB backend.
   * @param backend A reference to the NDB backend that is creating this
   *                root container.
   */
  public RootContainer(Backend backend, NdbBackendCfg config)
  {
    this.entryContainers = new ConcurrentHashMap<DN, EntryContainer>();
    this.backend = backend;
    this.config = config;
 
    this.ndbNumConnections = this.config.getNdbNumConnections();
    this.ndbConns = new NdbClusterConnection[ndbNumConnections];
 
    this.ndbThreadCount = this.config.getNdbThreadCount();
    if (this.ndbThreadCount > NDB_MAX_THREAD_COUNT) {
      this.ndbThreadCount = NDB_MAX_THREAD_COUNT;
    }
 
    this.ndbQueue = new LinkedBlockingQueue<Ndb>(
      this.ndbThreadCount);
 
    config.addNdbChangeListener(this);
  }
 
  /**
   * Opens the root container using the NDB configuration object provided.
   *
   * @throws NdbApiException If an error occurs when opening.
   * @throws ConfigException If an configuration error occurs while opening.
   * @throws Exception If an unknown error occurs when opening.
   */
  public void open()
      throws NdbApiException, ConfigException, Exception
  {
    // Log a message indicating upcoming NDB connect.
    logError(NOTE_NDB_WAITING_FOR_CLUSTER.get());
 
    // Connect to the cluster.
    for (int i = 0; i < this.ndbNumConnections; i++) {
      try {
        this.ndbConns[i] = NdbClusterConnection.create(
          this.config.getNdbConnectString());
        this.ndbConns[i].connect(5, 3, true);
        this.ndbConns[i].waitUntilReady(NDB_TIMEOUT_FIRST_ALIVE,
          NDB_TIMEOUT_AFTER_FIRST_ALIVE);
      } catch (NdbApiTemporaryException e) {
        if (debugEnabled()) {
          TRACER.debugCaught(DebugLogLevel.ERROR, e);
        }
        // Retry.
        if (this.ndbConns[i] != null) {
          this.ndbConns[i].close();
          this.ndbConns[i] = null;
        }
        i--;
        continue;
      }
    }
 
    // Get NDB objects.
    int connsIndex = 0;
    for (int i = 0; i < this.ndbThreadCount; i++) {
      Ndb ndb = ndbConns[connsIndex].createNdb(
        BackendImpl.DATABASE_NAME, 1024);
      connsIndex++;
      if (connsIndex >= this.ndbNumConnections) {
        connsIndex = 0;
      }
      try {
        this.ndbQueue.put(ndb);
      } catch (Exception e) {
        if (debugEnabled())
        {
          TRACER.debugCaught(DebugLogLevel.ERROR, e);
        }
        if (ndb != null) {
          ndb.close();
        }
      }
    }
 
    openAndRegisterEntryContainers(config.getBaseDN());
  }
 
  /**
   * Opens the entry container for a base DN. If the entry container does not
   * exist for the base DN, it will be created. The entry container will be
   * opened with the same mode as the root container. Any entry containers
   * opened in a read only root container will also be read only. Any entry
   * containers opened in a non transactional root container will also be non
   * transactional.
   *
   * @param baseDN The base DN of the entry container to open.
   * @return The opened entry container.
   * @throws NdbApiException If an error occurs while opening the entry
   *                           container.
   * @throws ConfigException If an configuration error occurs while opening
   *                         the entry container.
   */
  public EntryContainer openEntryContainer(DN baseDN)
      throws NdbApiException, ConfigException
  {
    String databasePrefix = baseDN.toNormalizedString();
 
    EntryContainer ec = new EntryContainer(baseDN, databasePrefix,
                                           backend, config, this);
    ec.open();
    return ec;
  }
 
  /**
   * Registeres the entry container for a base DN.
   *
   * @param baseDN The base DN of the entry container to register.
   * @param entryContainer The entry container to register for the baseDN.
   * @throws Exception If an error occurs while registering the entry
   *                           container.
   */
  public void registerEntryContainer(DN baseDN,
                                     EntryContainer entryContainer)
      throws Exception
  {
    EntryContainer ec1 = this.entryContainers.get(baseDN);
 
    // If an entry container for this baseDN is already open we don't allow
    // another to be opened.
    if (ec1 != null)
      // FIXME: Should be NDBException instance.
      throw new Exception("An entry container named " +
          ec1.getDatabasePrefix() + " is alreadly registered for base DN " +
          baseDN.toString());
 
    this.entryContainers.put(baseDN, entryContainer);
  }
 
  /**
   * Opens the entry containers for multiple base DNs.
   *
   * @param baseDNs The base DNs of the entry containers to open.
   * @throws NdbApiException If an error occurs while opening the entry
   *                           container.
   * @throws ConfigException if a configuration error occurs while opening the
   *                         container.
   */
  private void openAndRegisterEntryContainers(Set<DN> baseDNs)
      throws NdbApiException, ConfigException, Exception
  {
    for(DN baseDN : baseDNs)
    {
      EntryContainer ec = openEntryContainer(baseDN);
      registerEntryContainer(baseDN, ec);
    }
  }
 
  /**
   * Unregisteres the entry container for a base DN.
   *
   * @param baseDN The base DN of the entry container to close.
   * @return The entry container that was unregistered or NULL if a entry
   * container for the base DN was not registered.
   */
  public EntryContainer unregisterEntryContainer(DN baseDN)
  {
    return entryContainers.remove(baseDN);
 
  }
 
  /**
   * Close the root entryContainer.
   *
   * @throws NdbApiException If an error occurs while attempting to close
   * the entryContainer.
   */
  public void close() throws NdbApiException
  {
    for(DN baseDN : entryContainers.keySet())
    {
      EntryContainer ec = unregisterEntryContainer(baseDN);
      ec.exclusiveLock.lock();
      try
      {
        ec.close();
      }
      finally
      {
        ec.exclusiveLock.unlock();
      }
    }
 
    while (!this.ndbQueue.isEmpty()) {
      Ndb ndb = null;
      try {
        ndb = this.ndbQueue.poll();
        if (ndb != null) {
          ndb.close();
        }
      } catch (Exception e) {
        if (debugEnabled())
        {
          TRACER.debugCaught(DebugLogLevel.ERROR, e);
        }
      }
    }
    this.ndbQueue.clear();
 
    for (NdbClusterConnection ndbConn : ndbConns) {
      ndbConn.close();
    }
 
    config.removeNdbChangeListener(this);
  }
 
  /**
   * Get NDB handle from the queue.
   * @return NDB handle.
   */
  protected Ndb getNDB()
  {
    try {
      return ndbQueue.take();
    } catch (Exception e) {
      if (debugEnabled())
      {
        TRACER.debugCaught(DebugLogLevel.ERROR, e);
      }
      return null;
    }
  }
 
  /**
   * Release NDB handle to the queue.
   * @param ndb handle to release.
   */
  protected void releaseNDB(Ndb ndb)
  {
    try {
      ndbQueue.put(ndb);
    } catch (Exception e) {
      if (debugEnabled())
      {
        TRACER.debugCaught(DebugLogLevel.ERROR, e);
      }
      if (ndb != null) {
        ndb.close();
      }
      return;
    }
  }
 
  /**
   * Return all the entry containers in this root container.
   *
   * @return The entry containers in this root container.
   */
  public Collection<EntryContainer> getEntryContainers()
  {
    return entryContainers.values();
  }
 
  /**
   * Returns all the baseDNs this root container stores.
   *
   * @return The set of DNs this root container stores.
   */
  public Set<DN> getBaseDNs()
  {
    return entryContainers.keySet();
  }
 
  /**
   * Return the entry container for a specific base DN.
   *
   * @param baseDN The base DN of the entry container to retrive.
   * @return The entry container for the base DN.
   */
  public EntryContainer getEntryContainer(DN baseDN)
  {
    EntryContainer ec = null;
    DN nodeDN = baseDN;
 
    while (ec == null && nodeDN != null)
    {
      ec = entryContainers.get(nodeDN);
      if (ec == null)
      {
        nodeDN = nodeDN.getParentDNInSuffix();
      }
    }
 
    return ec;
  }
 
  /**
   * Get the backend configuration used by this root container.
   *
   * @return The NDB backend configuration used by this root container.
   */
  public NdbBackendCfg getConfiguration()
  {
    return config;
  }
 
  /**
   * Get the total number of entries in this root container.
   *
   * @return The number of entries in this root container
   * @throws NdbApiException If an error occurs while retrieving the entry
   *                           count.
   */
  public long getEntryCount() throws NdbApiException
  {
    long entryCount = 0;
    for(EntryContainer ec : this.entryContainers.values())
    {
      ec.sharedLock.lock();
      try
      {
        entryCount += ec.getEntryCount();
      }
      finally
      {
        ec.sharedLock.unlock();
      }
    }
 
    return entryCount;
  }
 
  /**
   * Assign the next entry ID.
   * @param ndb Ndb handle.
   * @return The assigned entry ID.
   */
  public long getNextEntryID(Ndb ndb)
  {
    long eid = 0;
    try
    {
      eid = ndb.getAutoIncrementValue(BackendImpl.NEXTID_TABLE,
        NDB_NEXTID_RANGE);
    }
    catch (NdbApiException e)
    {
      if (debugEnabled())
      {
        TRACER.debugCaught(DebugLogLevel.ERROR, e);
      }
    }
 
    return eid;
  }
 
  /**
   * {@inheritDoc}
   */
  public boolean isConfigurationChangeAcceptable(
      NdbBackendCfg cfg,
      List<Message> unacceptableReasons)
  {
    boolean acceptable = true;
 
    return acceptable;
  }
 
  /**
   * {@inheritDoc}
   */
  public ConfigChangeResult applyConfigurationChange(NdbBackendCfg cfg)
  {
    ConfigChangeResult ccr;
    boolean adminActionRequired = false;
    ArrayList<Message> messages = new ArrayList<Message>();
 
    ccr = new ConfigChangeResult(ResultCode.SUCCESS, adminActionRequired,
                                 messages);
    return ccr;
  }
}