Skip to main content
summaryrefslogtreecommitdiffstats
blob: 78f7f0fc1e390122551c1797d289766ddd7a0f61 (plain) (blame)
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
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
/*
 * Copyright (c) 2013 Eike Stepper (Berlin, Germany) 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
 *
 * Contributors:
 *    Christian W. Damus (CEA LIST) - initial API and implementation
 */
package org.eclipse.emf.cdo.server.internal.admin;

import org.eclipse.emf.cdo.common.lob.CDOLobUtil;
import org.eclipse.emf.cdo.common.lob.CDOLobUtil.CDOClobWriter;
import org.eclipse.emf.cdo.eresource.CDOResource;
import org.eclipse.emf.cdo.security.Access;
import org.eclipse.emf.cdo.security.FilterPermission;
import org.eclipse.emf.cdo.security.Realm;
import org.eclipse.emf.cdo.security.Role;
import org.eclipse.emf.cdo.security.SecurityFactory;
import org.eclipse.emf.cdo.security.User;
import org.eclipse.emf.cdo.server.IRepository;
import org.eclipse.emf.cdo.server.admin.RepositoryConfigurationManager;
import org.eclipse.emf.cdo.server.internal.admin.bundle.OM;
import org.eclipse.emf.cdo.server.internal.admin.catalog.AdminRepository;
import org.eclipse.emf.cdo.server.internal.admin.catalog.CatalogFactory;
import org.eclipse.emf.cdo.server.internal.admin.catalog.RepositoryCatalog;
import org.eclipse.emf.cdo.server.security.ISecurityManager;
import org.eclipse.emf.cdo.server.security.ISecurityManager.RealmOperation;
import org.eclipse.emf.cdo.server.security.SecurityManagerUtil;
import org.eclipse.emf.cdo.spi.server.AuthenticationUtil;
import org.eclipse.emf.cdo.spi.server.IAppExtension;
import org.eclipse.emf.cdo.spi.server.IAppExtension2;
import org.eclipse.emf.cdo.spi.server.IAuthenticationProtocol;
import org.eclipse.emf.cdo.spi.server.InternalRepository;
import org.eclipse.emf.cdo.spi.server.InternalSessionManager;
import org.eclipse.emf.cdo.spi.server.RepositoryConfigurator;
import org.eclipse.emf.cdo.spi.server.RepositoryFactory;
import org.eclipse.emf.cdo.transaction.CDOTransaction;

import org.eclipse.net4j.util.ObjectUtil;
import org.eclipse.net4j.util.StringUtil;
import org.eclipse.net4j.util.WrappedException;
import org.eclipse.net4j.util.container.ContainerEventAdapter;
import org.eclipse.net4j.util.container.IContainer;
import org.eclipse.net4j.util.container.IManagedContainer;
import org.eclipse.net4j.util.container.IManagedContainer.ContainerAware;
import org.eclipse.net4j.util.container.IPluginContainer;
import org.eclipse.net4j.util.event.IListener;
import org.eclipse.net4j.util.factory.ProductCreationException;
import org.eclipse.net4j.util.lifecycle.ILifecycle;
import org.eclipse.net4j.util.lifecycle.Lifecycle;
import org.eclipse.net4j.util.lifecycle.LifecycleEventAdapter;
import org.eclipse.net4j.util.lifecycle.LifecycleUtil;
import org.eclipse.net4j.util.om.trace.ContextTracer;
import org.eclipse.net4j.util.security.IAuthenticator2;

import org.eclipse.emf.ecore.util.EcoreUtil;

import org.eclipse.core.runtime.IConfigurationElement;
import org.eclipse.core.runtime.IExtensionRegistry;
import org.eclipse.core.runtime.Platform;

import org.w3c.dom.Document;

import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import java.util.List;
import java.util.Map;

/**
 * A default implementation of the {@link RepositoryConfigurationManager} interface
 * that stores dynamically created repositories' configurations in XML files.
 *
 * @author Christian W. Damus (CEA LIST)
 */
public class DefaultRepositoryConfigurationManager extends Lifecycle implements InternalRepositoryConfigurationManager,
    ContainerAware
{
  private static final ContextTracer TRACER = new ContextTracer(OM.DEBUG, DefaultRepositoryConfigurationManager.class);

  private IManagedContainer container = IPluginContainer.INSTANCE;

  private InternalRepository adminRepository;

  private String catalogPath = DEFAULT_CATALOG_PATH;

  private RepositoryCatalog catalog;

  private ISecurityManager securityManager;

  private final IListener repositoryListener = new LifecycleEventAdapter()
  {
    @Override
    protected void onActivated(ILifecycle lifecycle)
    {
      initializeCatalog();
    }

    @Override
    protected void onDeactivated(ILifecycle lifecycle)
    {
      DefaultRepositoryConfigurationManager.this.deactivate();
    }
  };

  public DefaultRepositoryConfigurationManager()
  {
  }

  public IManagedContainer getManagedContainer()
  {
    return container;
  }

  public void setManagedContainer(IManagedContainer container)
  {
    this.container = container;
  }

  public void setAdminRepository(InternalRepository adminRepository)
  {
    this.adminRepository = adminRepository;
    if (isActive())
    {
      initializeCatalog();
    }
  }

  public void setCatalogPath(String catalogPath)
  {
    this.catalogPath = StringUtil.isEmpty(catalogPath) ? DEFAULT_CATALOG_PATH : catalogPath;
  }

  public IRepository addRepository(String name, Document configurationXML)
  {
    checkActive();
    IManagedContainer container = requireContainer();

    if (getRepository(container, name) != null)
    {
      throw new IllegalArgumentException("Repository already exists: " + name); //$NON-NLS-1$
    }

    try
    {
      AdminRepository configuration = createConfiguration(name, configurationXML);
      return startRepository(configuration);
    }
    catch (RuntimeException e)
    {
      OM.LOG.error(e);
      throw e;
    }
    catch (Exception e)
    {
      OM.LOG.error(e);
      throw WrappedException.wrap(e);
    }
  }

  public void removeRepository(IRepository repository)
  {
    checkActive();
    deleteConfiguration(repository.getName());
  }

  public boolean canRemoveRepository(IRepository repository)
  {
    checkActive();

    return isInCatalog(repository.getName());
  }

  public Map<String, IRepository> getRepositories()
  {
    checkActive();

    Map<String, IRepository> result = new java.util.HashMap<String, IRepository>();
    if (catalog != null)
    {
      for (AdminRepository configuration : catalog.getRepositories())
      {
        IRepository repository = getRepository(getManagedContainer(), configuration.getName());
        if (repository != null)
        {
          result.put(repository.getName(), repository);
        }
      }
    }

    return result;
  }

  public void authenticateAdministrator()
  {
    requireSecurityManager();

    IAuthenticationProtocol authProtocol = AuthenticationUtil.getAuthenticationProtocol();
    if (authProtocol != null)
    {
      InternalSessionManager sessionManager = adminRepository.getSessionManager();
      String userID = sessionManager.authenticateUser(authProtocol);

      // If the user could authenticate without an ID, then there is no security manager
      if (userID != null)
      {
        IAuthenticator2 auth = ObjectUtil.tryCast(sessionManager.getAuthenticator(), IAuthenticator2.class);
        if (auth != null && !auth.isAdministrator(userID))
        {
          throw new SecurityException("Must be a server administrator to add and delete repositories.");
        }
      }
    }
  }

  @Override
  protected void doActivate() throws Exception
  {
    if (TRACER.isEnabled())
    {
      TRACER.format("Starting dynamically managed repositories.");
    }

    initializeCatalog();
  }

  @Override
  protected void doDeactivate() throws Exception
  {
    if (TRACER.isEnabled())
    {
      TRACER.format("Stopping dynamically managed repositories.");
    }

    // Stop any repositories that I manage
    for (IRepository repository : getRepositories().values())
    {
      try
      {
        LifecycleUtil.deactivate(repository);
      }
      catch (Exception e)
      {
        OM.LOG.error(e);
      }
    }

    catalog = null;
  }

  protected IManagedContainer requireContainer()
  {
    IManagedContainer result = getManagedContainer();
    if (result == null)
    {
      throw new IllegalStateException("No container."); //$NON-NLS-1$
    }

    return result;
  }

  protected IRepository startRepository(AdminRepository configuration) throws Exception
  {
    RepositoryConfigurator configurator = new RepositoryConfigurator(requireContainer());
    IRepository[] result = configurator.configure(configuration.getConfigXML().getContents());
    if (result.length == 1)
    {
      startExtensions(result[0], configuration);
    }

    return result.length == 0 ? null : result[0];
  }

  protected final ISecurityManager requireSecurityManager()
  {
    if (securityManager == null)
    {
      throw new IllegalStateException("The administrative repository does not have a security manager.");
    }

    return securityManager;
  }

  protected <T> T modify(CatalogOperation<T> operation)
  {
    return modify(operation, false);
  }

  protected <T> T modify(final CatalogOperation<T> operation, boolean waitUntilReadable)
  {
    checkActive();

    final Object[] result = new Object[1];
    requireSecurityManager().modify(new RealmOperation()
    {

      public void execute(Realm realm)
      {
        try
        {
          RepositoryCatalog localCatalog = realm.cdoView().getObject(catalog);
          result[0] = operation.execute(localCatalog);
        }
        catch (Exception e)
        {
          throw WrappedException.wrap(e);
        }
      }
    }, waitUntilReadable);

    // This cast is known to be safe according to the operation signature
    @SuppressWarnings("unchecked")
    T resultAsT = (T)result[0];
    return resultAsT;
  }

  private IRepository getRepository(IManagedContainer container, String name)
  {
    for (Object element : container.getElements(RepositoryFactory.PRODUCT_GROUP))
    {
      if (element instanceof IRepository)
      {
        IRepository repository = (IRepository)element;
        if (repository.getName().equals(name))
        {
          return repository;
        }
      }
    }

    return null;
  }

  private void startExtensions(IRepository repository, AdminRepository configuration)
  {
    final List<IAppExtension2> extensions = new java.util.ArrayList<IAppExtension2>(3);

    IExtensionRegistry registry = Platform.getExtensionRegistry();
    @SuppressWarnings("restriction")
    IConfigurationElement[] elements = registry.getConfigurationElementsFor(
        org.eclipse.emf.cdo.internal.server.bundle.OM.BUNDLE_ID, IAppExtension.EXT_POINT);
    for (final IConfigurationElement element : elements)
    {
      if ("appExtension".equals(element.getName())) //$NON-NLS-1$
      {
        try
        {
          IAppExtension extension = (IAppExtension)element.createExecutableExtension("class"); //$NON-NLS-1$
          if (extension instanceof IAppExtension2)
          {
            IAppExtension2 extension2 = (IAppExtension2)extension;
            extension2.startDynamic(configuration.getConfigXML().getContents());
            extensions.add(extension2);
          }
        }
        catch (Exception ex)
        {
          OM.LOG.error(ex);
        }
      }
    }

    if (!extensions.isEmpty())
    {
      // I have added some extensions, so stop them if and when the repository is shut down
      repository.addListener(new LifecycleEventAdapter()
      {
        @Override
        protected void onDeactivated(ILifecycle lifecycle)
        {
          for (IAppExtension extension : extensions)
          {
            try
            {
              extension.stop();
            }
            catch (Exception e)
            {
              OM.LOG.error(e);
            }
          }
        }
      });
    }
  }

  private AdminRepository createConfiguration(final String repositoryName, final Document configuration)
      throws Exception
  {
    modify(new CatalogOperation<AdminRepository>()
    {
      public AdminRepository execute(RepositoryCatalog catalog) throws Exception
      {
        AdminRepository result = CatalogFactory.eINSTANCE.createAdminRepository();
        result.setName(repositoryName);
        CDOClobWriter writer = CDOLobUtil.writeClob();

        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, "yes"); //$NON-NLS-1$
        transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); //$NON-NLS-1$ //$NON-NLS-2$
        StreamResult streamResult = new StreamResult(writer);
        DOMSource source = new DOMSource(configuration);
        transformer.transform(source, streamResult);
        writer.close();
        result.setConfigXML(writer.getClob());
        catalog.getRepositories().add(result);

        return result;
      }
    }, true);

    return catalog.getRepository(repositoryName);
  }

  private void deleteConfiguration(final String repositoryName)
  {
    modify(new CatalogOperation<Void>()
    {
      public Void execute(RepositoryCatalog catalog) throws Exception
      {
        AdminRepository configuration = catalog.getRepository(repositoryName);

        if (configuration != null)
        {
          EcoreUtil.remove(configuration);
        }

        return null;
      }
    });
  }

  private boolean isInCatalog(String repositoryName)
  {
    return catalog.getRepository(repositoryName) != null;
  }

  private void initializeCatalog()
  {
    if (catalog != null)
    {
      // Already initialized
      return;
    }

    if (adminRepository == null)
    {
      // Cannot initialize
      return;
    }

    adminRepository.addListener(repositoryListener);
    if (!LifecycleUtil.isActive(adminRepository))
    {
      // Cannot initialize now
      return;
    }

    securityManager = SecurityManagerUtil.getSecurityManager(adminRepository);
    if (securityManager == null)
    {
      // We are initializing ahead of the Security Manager. Wait for it
      getManagedContainer().addListener(new ContainerEventAdapter<Object>()
      {
        @Override
        protected void onAdded(IContainer<Object> container, Object element)
        {
          if (element instanceof ISecurityManager)
          {
            ISecurityManager securityManager = (ISecurityManager)element;
            if (securityManager.getRepository() == adminRepository)
            {
              // This is my repository's security manager. Finish initialization
              try
              {
                initializeCatalog();
              }
              finally
              {
                // Don't need any further events
                container.removeListener(this);
              }
            }
          }
        }
      });

      // Double-check
      securityManager = SecurityManagerUtil.getSecurityManager(adminRepository);
      if (securityManager == null)
      {
        return;
      }
    }

    requireSecurityManager().modify(new RealmOperation()
    {
      public void execute(Realm realm)
      {
        CDOTransaction initialTransaction = (CDOTransaction)realm.cdoView();
        boolean firstTime = !initialTransaction.hasResource(catalogPath);
        if (firstTime)
        {
          CDOResource resource = initialTransaction.createResource(catalogPath);
          catalog = createCatalog(resource, realm);
          OM.LOG.info("Repository catalog created in " + catalogPath);
        }
        else
        {
          CDOResource resource = initialTransaction.getResource(catalogPath);
          catalog = (RepositoryCatalog)resource.getContents().get(0);
          OM.LOG.info("Repository catalog loaded from " + catalogPath);
        }
      }
    });

    // Get the read-only view of the catalog now from the security manager's view
    requireSecurityManager().read(new RealmOperation()
    {
      public void execute(Realm realm)
      {
        catalog = realm.cdoView().getObject(catalog);
      }
    });

    // And load our repositories
    if (catalog != null)
    {
      OM.LOG.info("Starting managed repositories.");

      for (AdminRepository configuration : catalog.getRepositories())
      {
        try
        {
          startRepository(configuration);
        }
        catch (Exception e)
        {
          OM.LOG.error(e);
        }
      }

      OM.LOG.info("Managed repositories started.");
    }
  }

  private RepositoryCatalog createCatalog(CDOResource resource, Realm realm)
  {
    RepositoryCatalog result = CatalogFactory.eINSTANCE.createRepositoryCatalog();
    resource.getContents().add(result);

    // Give the Administrator read access to the catalog
    Role serverAdmin = realm.addRole("Server Administration"); //$NON-NLS-1$
    FilterPermission catalogAccess = SecurityFactory.eINSTANCE.createFilterPermission(Access.READ,
        SecurityFactory.eINSTANCE.createResourceFilter(resource.getPath()));
    serverAdmin.getPermissions().add(catalogAccess);
    realm.getUser(User.ADMINISTRATOR).getRoles().add(serverAdmin);

    return result;
  }

  /**
   * @author Christian W. Damus (CEA LIST)
   */
  public static class Factory extends RepositoryConfigurationManager.Factory
  {
    public static final String TYPE = "default"; //$NON-NLS-1$

    public Factory()
    {
      super(TYPE);
    }

    @Override
    public RepositoryConfigurationManager create(String description) throws ProductCreationException
    {
      DefaultRepositoryConfigurationManager result = new DefaultRepositoryConfigurationManager();
      result.setCatalogPath(description);
      return result;
    }
  }

  protected static interface CatalogOperation<T>
  {
    public T execute(RepositoryCatalog catalog) throws Exception;
  }
}

Back to the top