Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: 58cd1e93f9899a73ead3f0d90a87b29dfedb5eb6 (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
/*******************************************************************************
 * Copyright (c) 2012, 2016 IBM Corporation 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:
 *     IBM Corporation - initial API and implementation
 *******************************************************************************/
package org.eclipse.osgi.container;

import java.util.*;
import java.util.concurrent.TimeUnit;
import org.eclipse.osgi.container.ModuleContainer.ContainerStartLevel;
import org.eclipse.osgi.container.ModuleContainerAdaptor.ContainerEvent;
import org.eclipse.osgi.container.ModuleContainerAdaptor.ModuleEvent;
import org.eclipse.osgi.internal.messages.Msg;
import org.eclipse.osgi.report.resolution.ResolutionReport;
import org.osgi.framework.*;
import org.osgi.framework.launch.Framework;
import org.osgi.service.resolver.ResolutionException;

/**
 * A special kind of module that represents the system module for the container.  Additinal
 * methods are available on the system module for operations that effect the whole container.
 * For example, initializing the container, restarting and waiting for the container to stop.
 * @since 3.10
 */
public abstract class SystemModule extends Module {
	private final Map<Thread, ContainerEvent> forStop = new HashMap<Thread, ContainerEvent>(2);

	public SystemModule(ModuleContainer container) {
		super(new Long(0), Constants.SYSTEM_BUNDLE_LOCATION, container, EnumSet.of(Settings.AUTO_START, Settings.USE_ACTIVATION_POLICY), new Integer(0));
	}

	/**
	 * Initializes the module container
	 * @throws BundleException if an exeption occurred while initializing
	 */
	public final void init() throws BundleException {
		getRevisions().getContainer().checkAdminPermission(getBundle(), AdminPermission.EXECUTE);

		boolean lockedStarted = false;
		// Indicate we are in the middle of a start.
		// This must be incremented before we acquire the STARTED lock the first time.
		inStart.incrementAndGet();
		try {
			lockStateChange(ModuleEvent.STARTED);
			lockedStarted = true;
			getContainer().getAdaptor().initBegin();
			checkValid();
			if (ACTIVE_SET.contains(getState()))
				return;
			getRevisions().getContainer().open();
			if (getState().equals(State.INSTALLED)) {
				// must unlock to avoid out of order locks when multiple unresolved
				// bundles are started at the same time from different threads
				unlockStateChange(ModuleEvent.STARTED);
				lockedStarted = false;
				ResolutionReport report;
				try {
					report = getRevisions().getContainer().resolve(Arrays.asList((Module) this), true);
				} finally {
					lockStateChange(ModuleEvent.STARTED);
					lockedStarted = true;
				}
				// need to check valid again in case someone uninstalled the bundle
				checkValid();
				ResolutionException e = report.getResolutionException();
				if (e != null) {
					if (e.getCause() instanceof BundleException) {
						throw (BundleException) e.getCause();
					}
				}
				if (ACTIVE_SET.contains(getState()))
					return;
				if (getState().equals(State.INSTALLED)) {
					String reportMessage = report.getResolutionReportMessage(getCurrentRevision());
					throw new BundleException(Msg.Module_ResolveError + reportMessage, BundleException.RESOLVE_ERROR);
				}
			}

			setState(State.STARTING);
			publishEvent(ModuleEvent.STARTING);
			try {
				initWorker();
			} catch (Throwable t) {
				setState(State.STOPPING);
				publishEvent(ModuleEvent.STOPPING);
				setState(State.RESOLVED);
				publishEvent(ModuleEvent.STOPPED);
				getRevisions().getContainer().close();
				if (t instanceof BundleException) {
					throw (BundleException) t;
				}
				throw new BundleException("Error initializing container.", BundleException.ACTIVATOR_ERROR, t); //$NON-NLS-1$
			}
		} finally {
			getContainer().getAdaptor().initEnd();
			if (lockedStarted) {
				unlockStateChange(ModuleEvent.STARTED);
			}
			inStart.decrementAndGet();
		}
	}

	/**
	 * Waits until the module container has stopped.
	 * @param timeout The amount of time to wait.
	 * @return The container event indicated why the framework stopped
	 * or if there was a time out waiting for stop.
	 * @see Framework#waitForStop(long)
	 * @throws InterruptedException if the thread was interrupted while waiting
	 */
	public ContainerEvent waitForStop(long timeout) throws InterruptedException {
		final boolean waitForever = timeout == 0;
		final long start = System.currentTimeMillis();
		final Thread current = Thread.currentThread();
		long timeLeft = timeout;
		ContainerEvent event = null;
		boolean stateLocked;
		if (timeout == 0) {
			stateChangeLock.lockInterruptibly();
			stateLocked = true;
		} else {
			stateLocked = stateChangeLock.tryLock(timeLeft, TimeUnit.MILLISECONDS);
		}
		if (stateLocked) {
			synchronized (forStop) {
				try {
					if (!Module.ACTIVE_SET.contains(getState())) {
						return ContainerEvent.STOPPED;
					}
					event = forStop.remove(current);
					if (event == null) {
						forStop.put(current, null);
					}
				} finally {
					stateChangeLock.unlock();
				}
				timeLeft = waitForever ? 0 : start + timeout - System.currentTimeMillis();
				while (event == null && (waitForever || timeLeft > 0)) {
					forStop.wait(timeLeft);
					event = forStop.remove(current);
					if (!waitForever) {
						timeLeft = start + timeout - System.currentTimeMillis();
					}
				}
			}
		}
		return event == null ? ContainerEvent.STOPPED_TIMEOUT : event;
	}

	private void notifyWaitForStop(ContainerEvent event) {
		synchronized (forStop) {
			Collection<Thread> waiting = new ArrayList<Thread>(forStop.keySet());
			for (Thread t : waiting) {
				forStop.put(t, event);
			}
			forStop.notifyAll();
		}
	}

	/**
	 * @throws BundleException  
	 */
	protected void initWorker() throws BundleException {
		// Do nothing
	}

	@Override
	public void start(StartOptions... options) throws BundleException {
		// make sure to init if needed
		init();
		// Always transient
		super.start(StartOptions.TRANSIENT, StartOptions.USE_ACTIVATION_POLICY);
		getRevisions().getContainer().adaptor.publishContainerEvent(ContainerEvent.STARTED, this, null);
	}

	@Override
	public void stop(StopOptions... options) throws BundleException {
		ContainerEvent containerEvent = ContainerEvent.STOPPED_TIMEOUT;
		// Need to lock the state change lock with no state to prevent 
		// other threads from starting the framework while we are shutting down
		try {
			if (stateChangeLock.tryLock(10, TimeUnit.SECONDS)) {
				try {
					try {
						// Always transient
						super.stop(StopOptions.TRANSIENT);
					} catch (BundleException e) {
						getRevisions().getContainer().adaptor.publishContainerEvent(ContainerEvent.ERROR, this, e);
						// must continue on
					}
					if (holdsTransitionEventLock(ModuleEvent.UPDATED)) {
						containerEvent = ContainerEvent.STOPPED_UPDATE;
					} else if (holdsTransitionEventLock(ModuleEvent.UNRESOLVED)) {
						containerEvent = ContainerEvent.STOPPED_REFRESH;
					} else {
						containerEvent = ContainerEvent.STOPPED;
					}
					getRevisions().getContainer().adaptor.publishContainerEvent(containerEvent, this, null);
					getRevisions().getContainer().close();
				} finally {
					stateChangeLock.unlock();
				}
			} else {
				throw new BundleException(Msg.SystemModule_LockError);
			}
		} catch (InterruptedException e) {
			getRevisions().getContainer().adaptor.publishContainerEvent(ContainerEvent.ERROR, this, e);
		}
		notifyWaitForStop(containerEvent);
	}

	/**
	 * Restarts the module container.
	 * @see Framework#update()
	 * @throws BundleException
	 */
	public void update() throws BundleException {
		getContainer().checkAdminPermission(getBundle(), AdminPermission.LIFECYCLE);
		State previousState;
		lockStateChange(ModuleEvent.UPDATED);
		try {
			previousState = getState();
			stop();
		} finally {
			unlockStateChange(ModuleEvent.UPDATED);
		}
		// would publish an updated event here but the listener services are down
		switch (previousState) {
			case STARTING :
				init();
				break;
			case ACTIVE :
				start();
			default :
				break;
		}
	}

	@Override
	protected void startWorker() throws BundleException {
		super.startWorker();
		((ContainerStartLevel) getRevisions().getContainer().getFrameworkStartLevel()).doContainerStartLevel(this, ContainerStartLevel.USE_BEGINNING_START_LEVEL);
	}

	@Override
	protected void stopWorker() throws BundleException {
		super.stopWorker();
		((ContainerStartLevel) getRevisions().getContainer().getFrameworkStartLevel()).doContainerStartLevel(this, 0);
	}
}

Back to the top