Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: 6f11c7b1e8b1a5c18eced6e54ab66d005b0acbe3 (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
/*******************************************************************************
 * Copyright (c) 2003, 2016 IBM Corporation and others.
 *
 * This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License 2.0
 * which accompanies this distribution, and is available at
 * https://www.eclipse.org/legal/epl-2.0/
 *
 * SPDX-License-Identifier: EPL-2.0
 * 
 * Contributors:
 *     IBM Corporation - initial API and implementation
 *******************************************************************************/
package org.eclipse.osgi.internal.debug;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import org.eclipse.osgi.internal.framework.EquinoxConfiguration;
import org.eclipse.osgi.internal.location.LocationHelper;
import org.eclipse.osgi.service.debug.DebugOptions;
import org.eclipse.osgi.service.debug.DebugOptionsListener;
import org.eclipse.osgi.service.debug.DebugTrace;
import org.osgi.framework.BundleContext;
import org.osgi.framework.InvalidSyntaxException;
import org.osgi.framework.ServiceReference;
import org.osgi.util.tracker.ServiceTracker;
import org.osgi.util.tracker.ServiceTrackerCustomizer;

/**
 * The DebugOptions implementation class that allows accessing the list of debug options specified
 * for the application as well as creating {@link DebugTrace} objects for the purpose of having
 * dynamic enablement of debug tracing.
 * 
 * @since 3.1
 */
public class FrameworkDebugOptions implements DebugOptions, ServiceTrackerCustomizer<DebugOptionsListener, DebugOptionsListener> {

	private static final String OSGI_DEBUG = "osgi.debug"; //$NON-NLS-1$
	private static final String OSGI_DEBUG_VERBOSE = "osgi.debug.verbose"; //$NON-NLS-1$
	public static final String PROP_TRACEFILE = "osgi.tracefile"; //$NON-NLS-1$
	/** The default name of the .options file if loading when the -debug command-line argument is used */
	private static final String OPTIONS = ".options"; //$NON-NLS-1$

	/** A lock object used to synchronize access to the trace file */
	private final static Object writeLock = new Object();
	/** monitor used to lock the options maps */
	private final Object lock = new Object();
	/** A current map of all the options with values set */
	private Properties options = null;
	/** A map of all the disabled options with values set at the time debug was disabled */
	private Properties disabledOptions = null;
	/** A cache of all of the bundles <code>DebugTrace</code> in the format <key,value> --> <bundle name, DebugTrace> */
	protected final Map<String, DebugTrace> debugTraceCache = new HashMap<>();
	/** The File object to store messages.  This value may be null. */
	protected File outFile = null;
	/** Is verbose debugging enabled?  Changing this value causes a new tracing session to start. */
	protected boolean verboseDebug = true;
	/** A flag to determine if the message being written is done to a new file (i.e. should the header information be written) */
	private boolean newSession = true;
	private final EquinoxConfiguration environmentInfo;
	private volatile BundleContext context;
	private volatile ServiceTracker<DebugOptionsListener, DebugOptionsListener> listenerTracker;

	public FrameworkDebugOptions(EquinoxConfiguration environmentInfo) {
		this.environmentInfo = environmentInfo;
		// check if verbose debugging was set during initialization.  This needs to be set even if debugging is disabled
		this.verboseDebug = Boolean.valueOf(environmentInfo.getConfiguration(OSGI_DEBUG_VERBOSE, Boolean.TRUE.toString())).booleanValue();
		// if no debug option was specified, don't even bother to try.
		// Must ensure that the options slot is null as this is the signal to the
		// platform that debugging is not enabled.
		String debugOptionsFilename = environmentInfo.getConfiguration(OSGI_DEBUG);
		if (debugOptionsFilename == null)
			return;
		options = new Properties();
		URL optionsFile;
		if (debugOptionsFilename.length() == 0) {
			// default options location is user.dir (install location may be r/o so
			// is not a good candidate for a trace options that need to be updatable by
			// by the user)
			String userDir = System.getProperty("user.dir").replace(File.separatorChar, '/'); //$NON-NLS-1$
			if (!userDir.endsWith("/")) //$NON-NLS-1$
				userDir += "/"; //$NON-NLS-1$
			debugOptionsFilename = new File(userDir, OPTIONS).toString();
		}
		optionsFile = LocationHelper.buildURL(debugOptionsFilename, false);
		if (optionsFile == null) {
			System.out.println("Unable to construct URL for options file: " + debugOptionsFilename); //$NON-NLS-1$
			return;
		}
		System.out.print("Debug options:\n    " + optionsFile.toExternalForm()); //$NON-NLS-1$
		try {
			InputStream input = LocationHelper.getStream(optionsFile);
			try {
				options.load(input);
				System.out.println(" loaded"); //$NON-NLS-1$
			} finally {
				input.close();
			}
		} catch (FileNotFoundException e) {
			System.out.println(" not found"); //$NON-NLS-1$
		} catch (IOException e) {
			System.out.println(" did not parse"); //$NON-NLS-1$
			e.printStackTrace(System.out);
		}
		// trim off all the blanks since properties files don't do that.
		for (Object key : options.keySet()) {
			options.put(key, ((String) options.get(key)).trim());
		}
	}

	public void start(BundleContext bc) {
		this.context = bc;
		listenerTracker = new ServiceTracker<>(bc, DebugOptionsListener.class.getName(), this);
		listenerTracker.open();
	}

	public void stop(BundleContext bc) {
		listenerTracker.close();
		listenerTracker = null;
		this.context = null;
	}

	/**
	 * @see DebugOptions#getBooleanOption(String, boolean)
	 */
	@Override
	public boolean getBooleanOption(String option, boolean defaultValue) {
		String optionValue = getOption(option);
		return optionValue != null ? optionValue.equalsIgnoreCase("true") : defaultValue; //$NON-NLS-1$
	}

	/**
	 * @see DebugOptions#getOption(String)
	 */
	@Override
	public String getOption(String option) {
		return getOption(option, null);
	}

	/**
	 * @see DebugOptions#getOption(String, String)
	 */
	@Override
	public String getOption(String option, String defaultValue) {
		synchronized (lock) {
			if (options != null) {
				return options.getProperty(option, defaultValue);
			}
		}
		return defaultValue;
	}

	/**
	 * @see DebugOptions#getIntegerOption(String, int)
	 */
	@Override
	public int getIntegerOption(String option, int defaultValue) {
		String value = getOption(option);
		try {
			return value == null ? defaultValue : Integer.parseInt(value);
		} catch (NumberFormatException e) {
			return defaultValue;
		}
	}

	@SuppressWarnings({"unchecked", "rawtypes"})
	@Override
	public Map<String, String> getOptions() {
		Map<String, String> snapShot = new HashMap<>();
		synchronized (lock) {
			if (options != null)
				snapShot.putAll((Map) options);
			else if (disabledOptions != null)
				snapShot.putAll((Map) disabledOptions);
		}
		return snapShot;
	}

	/*
	 * (non-Javadoc)
	 * @see org.eclipse.osgi.service.debug.DebugOptions#getAllOptions()
	 */
	String[] getAllOptions() {

		String[] optionsArray = null;
		synchronized (lock) {
			if (options != null) {
				optionsArray = new String[options.size()];
				final Iterator<Map.Entry<Object, Object>> entrySetIterator = options.entrySet().iterator();
				int i = 0;
				while (entrySetIterator.hasNext()) {
					Map.Entry<Object, Object> entry = entrySetIterator.next();
					optionsArray[i] = ((String) entry.getKey()) + "=" + ((String) entry.getValue()); //$NON-NLS-1$
					i++;
				}
			}
		}
		if (optionsArray == null) {
			optionsArray = new String[1]; // TODO this is strange; null is the only element so we can print null in writeSession
		}
		return optionsArray;
	}

	/*
	 * (non-Javadoc)
	 * @see org.eclipse.osgi.service.debug.DebugOptions#removeOption(java.lang.String)
	 */
	@Override
	public void removeOption(String option) {
		if (option == null)
			return;
		String fireChangedEvent = null;
		synchronized (lock) {
			if (options != null && options.remove(option) != null) {
				fireChangedEvent = getSymbolicName(option);
			}
		}
		// Send the options change event outside the sync block
		if (fireChangedEvent != null) {
			optionsChanged(fireChangedEvent);
		}
	}

	/*
	 * (non-Javadoc)
	 * @see org.eclipse.osgi.service.debug.DebugOptions#setOption(java.lang.String, java.lang.String)
	 */
	@Override
	public void setOption(String option, String value) {

		if (option == null || value == null) {
			throw new IllegalArgumentException("The option and value must not be null."); //$NON-NLS-1$
		}
		String fireChangedEvent = null;
		value = value != null ? value.trim() : null;
		synchronized (lock) {
			if (options != null) {
				// get the current value
				String currentValue = options.getProperty(option);

				if (currentValue != null) {
					if (!currentValue.equals(value)) {
						fireChangedEvent = getSymbolicName(option);
					}
				} else {
					if (value != null) {
						fireChangedEvent = getSymbolicName(option);
					}
				}
				if (fireChangedEvent != null) {
					options.put(option, value);
				}
			}
		}
		// Send the options change event outside the sync block
		if (fireChangedEvent != null) {
			optionsChanged(fireChangedEvent);
		}
	}

	private String getSymbolicName(String option) {
		int firstSlashIndex = option.indexOf('/');
		if (firstSlashIndex > 0)
			return option.substring(0, firstSlashIndex);
		return null;
	}

	@SuppressWarnings("cast")
	@Override
	public void setOptions(Map<String, String> ops) {
		if (ops == null)
			throw new IllegalArgumentException("The options must not be null."); //$NON-NLS-1$
		Properties newOptions = new Properties();
		for (Map.Entry<String, String> entry : ops.entrySet()) {
			if (!(entry.getKey() instanceof String) || !(entry.getValue() instanceof String))
				throw new IllegalArgumentException("Option keys and values must be of type String: " + entry.getKey() + "=" + entry.getValue()); //$NON-NLS-1$ //$NON-NLS-2$
			newOptions.put(entry.getKey(), entry.getValue().trim());
		}
		Set<String> fireChangesTo = null;

		synchronized (lock) {
			if (options == null) {
				disabledOptions = newOptions;
				// no events to fire
				return;
			}
			fireChangesTo = new HashSet<>();
			// first check for removals
			for (Iterator<Object> keys = options.keySet().iterator(); keys.hasNext();) {
				String key = (String) keys.next();
				if (!newOptions.containsKey(key)) {
					String symbolicName = getSymbolicName(key);
					if (symbolicName != null)
						fireChangesTo.add(symbolicName);
				}
			}
			// now check for changes to existing values
			for (Map.Entry<Object, Object> entry : newOptions.entrySet()) {
				String existingValue = (String) options.get(entry.getKey());
				if (!entry.getValue().equals(existingValue)) {
					String symbolicName = getSymbolicName((String) entry.getKey());
					if (symbolicName != null)
						fireChangesTo.add(symbolicName);
				}
			}
			// finally set the actual options
			options = newOptions;
		}
		if (fireChangesTo != null)
			for (Iterator<String> iChanges = fireChangesTo.iterator(); iChanges.hasNext();)
				optionsChanged(iChanges.next());
	}

	/*
	 * (non-Javadoc)
	 * @see org.eclipse.osgi.service.debug.DebugOptions#isDebugEnabled()
	 */
	@Override
	public boolean isDebugEnabled() {
		synchronized (lock) {
			return options != null;
		}
	}

	/*
	 * (non-Javadoc)
	 * @see org.eclipse.osgi.service.debug.DebugOptions#setDebugEnabled()
	 */
	@Override
	public void setDebugEnabled(boolean enabled) {
		boolean fireChangedEvent = false;
		synchronized (lock) {
			if (enabled) {
				if (options != null)
					return;
				// notify the trace that a new session is started
				this.newSession = true;

				// enable platform debugging - there is no .options file
				environmentInfo.setConfiguration(OSGI_DEBUG, ""); //$NON-NLS-1$
				if (disabledOptions != null) {
					options = disabledOptions;
					disabledOptions = null;
					// fire changed event to indicate some options were re-enabled
					fireChangedEvent = true;
				} else {
					options = new Properties();
				}
			} else {
				if (options == null)
					return;
				// disable platform debugging.
				environmentInfo.clearConfiguration(OSGI_DEBUG);
				if (options.size() > 0) {
					// Save the current options off in case debug is re-enabled
					disabledOptions = options;
					// fire changed event to indicate some options were disabled
					fireChangedEvent = true;
				}
				options = null;
			}
		}
		if (fireChangedEvent) {
			// (Bug 300911) need to fire event to listeners that options have been disabled
			optionsChanged("*"); //$NON-NLS-1$
		}
	}

	/*
	 * (non-Javadoc)
	 * @see org.eclipse.osgi.service.debug.DebugOptions#createTrace(java.lang.String)
	 */
	@Override
	public final DebugTrace newDebugTrace(String bundleSymbolicName) {

		return this.newDebugTrace(bundleSymbolicName, null);
	}

	/*
	 * (non-Javadoc)
	 * @see org.eclipse.osgi.service.debug.DebugOptions#createTrace(java.lang.String, java.lang.Class)
	 */
	@Override
	public final DebugTrace newDebugTrace(String bundleSymbolicName, Class<?> traceEntryClass) {

		DebugTrace debugTrace = null;
		synchronized (debugTraceCache) {
			debugTrace = debugTraceCache.get(bundleSymbolicName);
			if (debugTrace == null) {
				debugTrace = new EclipseDebugTrace(bundleSymbolicName, this, traceEntryClass);
				debugTraceCache.put(bundleSymbolicName, debugTrace);
			}
		}
		return debugTrace;
	}

	/*
	 * (non-Javadoc)
	 * @see org.eclipse.osgi.service.debug.DebugOptions#getFile()
	 */
	@Override
	public final File getFile() {

		return this.outFile;
	}

	/*
	 * (non-Javadoc)
	 * @see org.eclipse.osgi.service.debug.DebugOptions#setFile(java.io.File)
	 */
	@Override
	public void setFile(final File traceFile) {
		synchronized (lock) {
			this.outFile = traceFile;
			if (this.outFile != null)
				environmentInfo.setConfiguration(PROP_TRACEFILE, this.outFile.getAbsolutePath());
			else
				environmentInfo.clearConfiguration(PROP_TRACEFILE);
			// the file changed so start a new session
			this.newSession = true;
		}
	}

	boolean newSession() {
		synchronized (lock) {
			if (newSession) {
				this.newSession = false;
				return true;
			}
			return false;
		}
	}

	Object getWriteLock() {
		return writeLock;
	}

	/*
	 * (non-Javadoc)
	 * @see org.eclipse.osgi.service.debug.DebugOptions#getVerbose()
	 */
	boolean isVerbose() {

		return this.verboseDebug;
	}

	EquinoxConfiguration getConfiguration() {
		return this.environmentInfo;
	}

	/*
	 * (non-Javadoc)
	 * @see org.eclipse.osgi.service.debug.DebugOptions#setVerbose(boolean)
	 */
	public void setVerbose(final boolean verbose) {
		synchronized (lock) {
			this.verboseDebug = verbose;
			// the verbose flag changed so start a new session
			this.newSession = true;
		}
	}

	/**
	 * Notifies the trace listener for the specified bundle that its option-path has changed.
	 * @param bundleSymbolicName The bundle of the owning trace listener to notify.
	 */
	private void optionsChanged(String bundleSymbolicName) {
		// use osgi services to get the listeners
		BundleContext bc = context;
		if (bc == null)
			return;
		// do not use the service tracker because that is only used to call all listeners initially when they are registered
		// here we only want the services with the specified name.
		ServiceReference<?>[] listenerRefs = null;
		try {
			listenerRefs = bc.getServiceReferences(DebugOptionsListener.class.getName(), "(" + DebugOptions.LISTENER_SYMBOLICNAME + "=" + bundleSymbolicName + ")"); //$NON-NLS-1$//$NON-NLS-2$ //$NON-NLS-3$
		} catch (InvalidSyntaxException e) {
			// consider logging; should not happen
		}
		if (listenerRefs == null)
			return;
		for (ServiceReference<?> listenerRef : listenerRefs) {
			DebugOptionsListener service = (DebugOptionsListener) bc.getService(listenerRef);
			if (service == null)
				continue;
			try {
				service.optionsChanged(this);
			}catch (Throwable t) {
				// TODO consider logging
			} finally {
				bc.ungetService(listenerRef);
			}
		}
	}

	@Override
	public DebugOptionsListener addingService(ServiceReference<DebugOptionsListener> reference) {
		DebugOptionsListener listener = context.getService(reference);
		listener.optionsChanged(this);
		return listener;
	}

	@Override
	public void modifiedService(ServiceReference<DebugOptionsListener> reference, DebugOptionsListener service) {
		// nothing
	}

	@Override
	public void removedService(ServiceReference<DebugOptionsListener> reference, DebugOptionsListener service) {
		context.ungetService(reference);
	}
}

Back to the top