Skip to main content
summaryrefslogtreecommitdiffstats
blob: d6085277c0ab841885cb69f665c8bc87444ce44c (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
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
/**
 * Copyright (c) 2004 - 2009 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:
 *    Simon McDuff - initial API and implementation
 *    Eike Stepper - maintenance
 */
package org.eclipse.emf.internal.cdo.transaction;

import org.eclipse.emf.cdo.common.id.CDOID;
import org.eclipse.emf.cdo.common.id.CDOIDUtil;
import org.eclipse.emf.cdo.common.revision.CDOReferenceAdjuster;
import org.eclipse.emf.cdo.internal.common.id.CDOIDTempObjectExternalImpl;
import org.eclipse.emf.cdo.spi.common.revision.CDOIDMapper;
import org.eclipse.emf.cdo.transaction.CDOSavepoint;
import org.eclipse.emf.cdo.transaction.CDOTransaction;
import org.eclipse.emf.cdo.transaction.CDOXATransaction;
import org.eclipse.emf.cdo.util.CDOUtil;
import org.eclipse.emf.cdo.view.CDOView;
import org.eclipse.emf.cdo.view.CDOViewSet;

import org.eclipse.emf.internal.cdo.messages.Messages;

import org.eclipse.net4j.util.CheckUtil;
import org.eclipse.net4j.util.om.monitor.EclipseMonitor;
import org.eclipse.net4j.util.om.monitor.OMMonitor;
import org.eclipse.net4j.util.om.monitor.EclipseMonitor.SynchonizedSubProgressMonitor;
import org.eclipse.net4j.util.transaction.TransactionException;

import org.eclipse.emf.common.notify.Adapter;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.common.notify.Notifier;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.util.EcoreUtil;
import org.eclipse.emf.spi.cdo.CDOSessionProtocol;
import org.eclipse.emf.spi.cdo.CDOTransactionStrategy;
import org.eclipse.emf.spi.cdo.InternalCDOTransaction;
import org.eclipse.emf.spi.cdo.InternalCDOXATransaction;
import org.eclipse.emf.spi.cdo.CDOSessionProtocol.CommitTransactionResult;
import org.eclipse.emf.spi.cdo.InternalCDOTransaction.InternalCDOCommitContext;

import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.SubProgressMonitor;

import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

/**
 * Three-phase commit.
 * <p>
 * Phase 1 does the following for each CDOTransaction:<br>
 * - preCommit <br>
 * - Accumulate external temporary ID.<br>
 * - request the commit to the server.<br>
 * - The server registers the commit context and returns the final ID for each temporary ID.
 * <p>
 * Phase 2 does the following for each CDOTransaction:<br>
 * - Transfer to the server a list of mapping of temporary externalID and final external ID that we accumulate
 * previously<br>
 * - Returns to the client only when commit process is ready to flush to disk (commit). <br>
 * <p>
 * Phase 3 does the following for each CDOTransaction:<br>
 * - Make modifications permanent.<br>
 * - PostCommit.
 * <p>
 * If an exception occurred during phase 1 or phase 2, the commit will be cancelled for all {@link CDOTransaction}
 * include in the XA transaction. If an exception occurred during phase 3, the commit will be cancelled only for the
 * {@link CDOTransaction} where the error happened.
 * <p>
 * All {@link CDOTransaction} includes in the commit process need to have finish their phase before moving to the next
 * phase. For one phase, every {@link CDOTransaction} could have their own thread. It depends of the ExecutorService.
 * <p>
 * 
 * @author Simon McDuff
 * @since 2.0
 */
public class CDOXATransactionImpl implements InternalCDOXATransaction
{
  private List<InternalCDOTransaction> transactions = new ArrayList<InternalCDOTransaction>();

  private boolean allRequestEnabled = true;

  private ExecutorService executorService = Executors.newFixedThreadPool(10);

  private Map<InternalCDOTransaction, CDOXACommitContextImpl> activeContext = new HashMap<InternalCDOTransaction, CDOXACommitContextImpl>();

  private Map<InternalCDOTransaction, Set<CDOID>> requestedCDOID = new HashMap<InternalCDOTransaction, Set<CDOID>>();

  private CDOXASavepointImpl lastSavepoint = new CDOXASavepointImpl(this, null);

  private CDOXASavepointImpl firstSavepoint = lastSavepoint;

  private CDOTransactionStrategy transactionStrategy = new CDOXATransactionStrategyImpl();

  private CDOXAInternalAdapter internalAdapter = new CDOXAInternalAdapter();

  private Map<EObject, CDOIDTempObjectExternalImpl> objectToID = new HashMap<EObject, CDOIDTempObjectExternalImpl>();

  public CDOXATransactionImpl()
  {
  }

  public boolean isAllowRequestFromTransactionEnabled()
  {
    return allRequestEnabled;
  }

  public void setAllowRequestFromTransactionEnabled(boolean allRequest)
  {
    allRequestEnabled = allRequest;
  }

  public void add(InternalCDOTransaction transaction)
  {
    transaction.setTransactionStrategy(transactionStrategy);
  }

  public void remove(InternalCDOTransaction transaction)
  {
    transaction.setTransactionStrategy(null);
  }

  public synchronized void add(CDOViewSet viewSet)
  {
    CDOXATransaction transSet = CDOUtil.getXATransaction(viewSet);
    if (transSet != null)
    {
      throw new IllegalArgumentException(Messages.getString("CDOXATransactionImpl.0")); //$NON-NLS-1$
    }

    viewSet.eAdapters().add(internalAdapter);

    for (InternalCDOTransaction transaction : getTransactions(viewSet))
    {
      add(transaction);
    }
  }

  public synchronized void remove(CDOViewSet viewSet)
  {
    CDOXATransaction transSet = CDOUtil.getXATransaction(viewSet);
    if (transSet != this)
    {
      throw new IllegalArgumentException(Messages.getString("CDOXATransactionImpl.1")); //$NON-NLS-1$
    }

    for (InternalCDOTransaction transaction : getTransactions(viewSet))
    {
      remove(transaction);
    }

    viewSet.eAdapters().remove(internalAdapter);
  };

  public synchronized CDOIDTempObjectExternalImpl getCDOIDExternalTemp(EObject object)
  {
    CDOIDTempObjectExternalImpl cdoID = objectToID.get(object);
    if (cdoID == null)
    {
      cdoID = (CDOIDTempObjectExternalImpl)CDOIDUtil.createTempObjectExternal(EcoreUtil.getURI(object).toString());
      objectToID.put(object, cdoID);
    }
  
    return cdoID;
  }

  public void add(InternalCDOTransaction view, CDOID object)
  {
    synchronized (requestedCDOID)
    {
      Set<CDOID> ids = requestedCDOID.get(view);
      if (ids == null)
      {
        ids = new HashSet<CDOID>();
        requestedCDOID.put(view, ids);
      }

      ids.add(object);
    }
  }

  public CDOID[] get(InternalCDOTransaction transaction)
  {
    Set<CDOID> ids = requestedCDOID.get(transaction);
    return ids.toArray(new CDOID[ids.size()]);
  }

  public CDOXACommitContextImpl getCommitContext(CDOTransaction transaction)
  {
    return activeContext.get(transaction);
  }

  private void send(Collection<CDOXACommitContextImpl> xaContexts, final IProgressMonitor progressMonitor)
      throws InterruptedException, ExecutionException
  {
    progressMonitor.beginTask("", xaContexts.size()); //$NON-NLS-1$

    try
    {
      List<Future<Object>> futures = new ArrayList<Future<Object>>();
      for (CDOXACommitContextImpl xaContext : xaContexts)
      {
        xaContext.setProgressMonitor(new SynchonizedSubProgressMonitor(progressMonitor, 1));
        futures.add(executorService.submit(xaContext));
      }

      int nbProcessDone;
      do
      {
        nbProcessDone = 0;
        for (Future<Object> future : futures)
        {
          try
          {
            future.get(1, TimeUnit.MILLISECONDS);
            nbProcessDone++;
          }
          catch (TimeoutException ex)
          {
          }
        }
      } while (xaContexts.size() != nbProcessDone);
    }
    finally
    {
      progressMonitor.done();
      for (CDOXACommitContextImpl xaContext : xaContexts)
      {
        xaContext.setProgressMonitor(null);
      }
    }
  }

  private void cleanUp()
  {
    activeContext.clear();
    requestedCDOID.clear();
  }

  private List<InternalCDOTransaction> getTransactions(CDOViewSet viewSet)
  {
    List<InternalCDOTransaction> transactions = new ArrayList<InternalCDOTransaction>();
    for (CDOView view : viewSet.getViews())
    {
      if (view instanceof InternalCDOTransaction)
      {
        transactions.add((InternalCDOTransaction)view);
      }
    }

    return transactions;
  }

  public void commit() throws TransactionException
  {
    commit(new NullProgressMonitor());
  }

  public void commit(IProgressMonitor progressMonitor) throws TransactionException
  {
    CheckUtil.checkArg(progressMonitor, "progressMonitor"); //$NON-NLS-1$
    progressMonitor.beginTask(Messages.getString("CDOXATransactionImpl.4"), 3); //$NON-NLS-1$
    int phase = 0;

    objectToID.clear();

    for (InternalCDOTransaction transaction : transactions)
    {
      InternalCDOCommitContext context = transaction.createCommitContext();
      CDOXACommitContextImpl xaContext = new CDOXACommitContextImpl(this, context);
      xaContext.setState(CDOXAPhase1State.INSTANCE);
      activeContext.put(transaction, xaContext);
    }

    try
    {
      // We need to complete 3 phases
      while (phase < 3)
      {
        send(activeContext.values(), new SubProgressMonitor(progressMonitor, 1));
        ++phase;
      }
    }
    catch (Exception ex)
    {
      if (phase < 2)
      {
        // Phase 0 and 1 are the only two phases we can cancel.
        for (CDOXACommitContextImpl transaction : activeContext.values())
        {
          transaction.setState(CDOXACancel.INSTANCE);
        }

        try
        {
          send(activeContext.values(), new SubProgressMonitor(progressMonitor, 2 - phase));
        }
        catch (InterruptedException ignore)
        {
        }
        catch (ExecutionException ignore)
        {
        }
      }

      throw new TransactionException(ex);
    }
    finally
    {
      cleanUp();
      progressMonitor.done();
    }
  }

  public CDOXASavepointImpl getLastSavepoint()
  {
    return lastSavepoint;
  }

  public void rollback()
  {
    rollback(firstSavepoint);
  }

  public void rollback(CDOSavepoint savepoint)
  {
    if (savepoint == null)
    {
      throw new IllegalArgumentException(Messages.getString("CDOXATransactionImpl.5")); //$NON-NLS-1$
    }

    if (savepoint.getUserTransaction() != this)
    {
      throw new IllegalArgumentException(MessageFormat.format(Messages.getString("CDOXATransactionImpl.6"), savepoint)); //$NON-NLS-1$
    }

    if (!savepoint.isValid())
    {
      throw new IllegalArgumentException(Messages.getString("CDOXATransactionImpl.7") + savepoint); //$NON-NLS-1$
    }

    CDOXASavepointImpl savepointSet = (CDOXASavepointImpl)savepoint;
    List<CDOSavepoint> savepoints = savepointSet.getSavepoints();
    if (savepoints == null)
    {
      savepoints = getListSavepoints();
    }

    for (CDOSavepoint indexSavePoint : savepoints)
    {
      InternalCDOTransaction transaction = (InternalCDOTransaction)indexSavePoint.getUserTransaction();
      CDOSingleTransactionStrategyImpl.INSTANCE.rollback(transaction, indexSavePoint);
    }

    lastSavepoint = savepointSet;
    lastSavepoint.setNextSavepoint(null);
    lastSavepoint.setSavepoints(null);
  }

  public CDOSavepoint setSavepoint()
  {
    List<CDOSavepoint> savepoints = getListSavepoints();
    for (CDOSavepoint savepoint : savepoints)
    {
      InternalCDOTransaction transaction = (InternalCDOTransaction)savepoint.getUserTransaction();
      CDOSingleTransactionStrategyImpl.INSTANCE.setSavepoint(transaction);
    }

    getLastSavepoint().setSavepoints(savepoints);
    lastSavepoint = new CDOXASavepointImpl(this, getLastSavepoint());
    return lastSavepoint;
  }

  private List<CDOSavepoint> getListSavepoints()
  {
    synchronized (transactions)
    {
      List<CDOSavepoint> savepoints = new ArrayList<CDOSavepoint>();
      for (InternalCDOTransaction transaction : transactions)
      {
        savepoints.add(transaction.getLastSavepoint());
      }

      return savepoints;
    }
  }

  /**
   * @author Simon McDuff
   */
  private final class CDOXATransactionStrategyImpl implements CDOTransactionStrategy
  {
    public CDOXATransactionStrategyImpl()
    {
    }

    public void setTarget(InternalCDOTransaction transaction)
    {
      synchronized (transactions)
      {
        transactions.add(transaction);
      }
    }

    public void unsetTarget(InternalCDOTransaction transaction)
    {
      synchronized (transactions)
      {
        transactions.remove(transaction);
      }
    }

    private void checkAccess()
    {
      if (!allRequestEnabled)
      {
        throw new IllegalStateException(Messages.getString("CDOXATransactionImpl.8")); //$NON-NLS-1$
      }
    }

    public void commit(InternalCDOTransaction transactionCommit, IProgressMonitor progressMonitor) throws Exception
    {
      checkAccess();
      CDOXATransactionImpl.this.commit(progressMonitor);
    }

    public void rollback(InternalCDOTransaction transaction, CDOSavepoint savepoint)
    {
      checkAccess();
      CDOXATransactionImpl.this.rollback(savepoint);
    }

    public CDOSavepoint setSavepoint(InternalCDOTransaction transaction)
    {
      checkAccess();
      return CDOXATransactionImpl.this.setSavepoint();
    }
  }

  /**
   * @author Simon McDuff
   */
  public static abstract class CDOXAState
  {
    public static final CDOXAState DONE = new CDOXAState()
    {
      @Override
      protected void handle(CDOXACommitContextImpl xaContext, IProgressMonitor progressMonitor) throws Exception
      {
        progressMonitor.done();
      }
    };

    protected void check_result(CommitTransactionResult result)
    {
      if (result != null && result.getRollbackMessage() != null)
      {
        throw new TransactionException(result.getRollbackMessage());
      }
    }

    protected abstract void handle(CDOXACommitContextImpl xaContext, IProgressMonitor progressMonitor) throws Exception;
  };

  /**
   * @author Simon McDuff
   */
  public static class CDOXAPhase1State extends CDOXAState
  {
    public static final CDOXAPhase1State INSTANCE = new CDOXAPhase1State();

    @Override
    protected void handle(CDOXACommitContextImpl xaContext, IProgressMonitor progressMonitor) throws Exception
    {
      CDOIDMapper idMapper = new CDOIDMapper();

      CDOReferenceAdjuster referenceAdjuster = xaContext.createAdjuster(idMapper);

      CDOSavepointImpl.applyReferenceAdjuster(xaContext, referenceAdjuster);

      xaContext.preCommit();

      CommitTransactionResult result = null;
      if (xaContext.getTransaction().isDirty())
      {
        CDOSessionProtocol sessionProtocol = xaContext.getTransaction().getSession().getSessionProtocol();
        OMMonitor monitor = new EclipseMonitor(progressMonitor);
        result = sessionProtocol.commitTransactionPhase1(xaContext, monitor);
        check_result(result);
      }

      xaContext.setResult(result);
      xaContext.setState(CDOXAPhase2State.INSTANCE);
    }
  };

  /**
   * @author Simon McDuff
   */
  public static class CDOXAPhase2State extends CDOXAState
  {
    public static final CDOXAPhase2State INSTANCE = new CDOXAPhase2State();

    public CDOXAPhase2State()
    {
    }

    @Override
    protected void handle(CDOXACommitContextImpl xaContext, IProgressMonitor progressMonitor) throws Exception
    {
      if (xaContext.getTransaction().isDirty())
      {
        CDOSessionProtocol sessionProtocol = xaContext.getTransaction().getSession().getSessionProtocol();
        OMMonitor monitor = new EclipseMonitor(progressMonitor);
        CommitTransactionResult result = sessionProtocol.commitTransactionPhase2(xaContext, monitor);
        check_result(result);
      }

      xaContext.setState(CDOXAPhase3State.INSTANCE);
    }
  };

  /**
   * @author Simon McDuff
   */
  public static class CDOXAPhase3State extends CDOXAState
  {
    public static final CDOXAPhase3State INSTANCE = new CDOXAPhase3State();

    public CDOXAPhase3State()
    {
    }

    @Override
    protected void handle(CDOXACommitContextImpl xaContext, IProgressMonitor progressMonitor) throws Exception
    {
      if (xaContext.getTransaction().isDirty())
      {
        CDOSessionProtocol sessionProtocol = xaContext.getTransaction().getSession().getSessionProtocol();
        OMMonitor monitor = new EclipseMonitor(progressMonitor);
        CommitTransactionResult result = sessionProtocol.commitTransactionPhase3(xaContext, monitor);
        check_result(result);
      }

      xaContext.postCommit(xaContext.getResult());
      xaContext.setState(null);
    }
  };

  /**
   * @author Simon McDuff
   */
  public static class CDOXACancel extends CDOXAState
  {
    public static final CDOXACancel INSTANCE = new CDOXACancel();

    public CDOXACancel()
    {
    }

    @Override
    protected void handle(CDOXACommitContextImpl xaContext, IProgressMonitor progressMonitor) throws Exception
    {
      CDOSessionProtocol sessionProtocol = xaContext.getTransaction().getSession().getSessionProtocol();
      OMMonitor monitor = new EclipseMonitor(progressMonitor);
      CommitTransactionResult result = sessionProtocol.commitTransactionCancel(xaContext, monitor);
      xaContext.commitFail();
      check_result(result);
    }
  };

  /**
   * @author Simon McDuff
   */
  public class CDOXAInternalAdapter implements Adapter
  {
    public CDOXAInternalAdapter()
    {
    }

    public CDOXATransactionImpl getCDOXA()
    {
      return CDOXATransactionImpl.this;
    }

    public Notifier getTarget()
    {
      return null;
    }

    public boolean isAdapterForType(Object type)
    {
      return false;
    }

    public void notifyChanged(Notification notification)
    {
      switch (notification.getEventType())
      {
      case Notification.ADD:
        if (notification.getNewValue() instanceof InternalCDOTransaction)
        {
          CDOXATransactionImpl.this.add((InternalCDOTransaction)notification.getNewValue());
        }

        break;

      case Notification.REMOVE:
        if (notification.getOldValue() instanceof InternalCDOTransaction)
        {
          CDOXATransactionImpl.this.remove((InternalCDOTransaction)notification.getNewValue());
        }

        break;
      }
    }

    public void setTarget(Notifier newTarget)
    {
    }
  }
}

Back to the top