Skip to main content
summaryrefslogtreecommitdiffstats
blob: 0521a19c6d78163867f2f96223d9e6d7d7f6f405 (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
/*******************************************************************************
 * Copyright (c) 2005 BEA Systems, Inc. 
 * 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:
 *    rfrost@bea.com - initial API and implementation
 *    
 *    Based on GenericServerBehavior by Gorkem Ercan
 *******************************************************************************/
package org.eclipse.jst.server.generic.core.internal;

import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.debug.core.ILaunch;
import org.eclipse.debug.core.ILaunchConfigurationWorkingCopy;
import org.eclipse.debug.core.ILaunchManager;
import org.eclipse.debug.core.model.IProcess;
import org.eclipse.jdt.launching.IJavaLaunchConfigurationConstants;
import org.eclipse.jst.server.generic.internal.xml.Resolver;
import org.eclipse.jst.server.generic.servertype.definition.External;
import org.eclipse.jst.server.generic.servertype.definition.ServerRuntime;
import org.eclipse.osgi.util.NLS;
import org.eclipse.wst.server.core.IServer;
import org.eclipse.wst.server.core.ServerPort;
import org.eclipse.wst.server.core.util.SocketUtil;

/**
 * Subclass of <code>GenericServerBehavior</code> that supports 
 * servers which are started/stopped via external executables (e.g. scripts).
 */
public class ExternalServerBehaviour extends GenericServerBehaviour {
	
	// config for debugging session
	private ILaunchConfigurationWorkingCopy fLaunchConfigurationWC;
    private String fMode;
    private ILaunch fLaunch; 
    private IProgressMonitor fProgressMonitor;
    
    /**
     * Override to reset the status if the state was unknown
     * @param force 
     */
    public void stop(boolean force) {
    	resetStatus(getServer().getServerState());
    	super.stop(force);
    }

    /**
     * Override to set status to unknown if the port was in use and to reset the status if the state was 
     * unknown and an exception was not thrown. Will want to change logic once external generic server pings
     * server process to determine state instead of maintaining handle to process. 
     */
    protected void setupLaunch(ILaunch launch, String launchMode, IProgressMonitor monitor) throws CoreException {
    	int state = getServer().getServerState();
    	try {
    		super.setupLaunch(launch, launchMode, monitor);
    	} catch (CoreException ce) {
    		ServerPort portInUse = portInUse();
    		if (portInUse != null) {
    			Trace.trace(Trace.WARNING, "Port " + portInUse.getPort() + " is currently in use");  //$NON-NLS-1$//$NON-NLS-2$
				Status status = new Status(IStatus.WARNING, CorePlugin.PLUGIN_ID, IStatus.OK, 
							NLS.bind(GenericServerCoreMessages.errorPortInUse,Integer.toString(portInUse.getPort()),portInUse.getName()), null);
				setServerStatus(status);
				setServerState(IServer.STATE_UNKNOWN);
    		}
    		throw ce;
    	}
    	resetStatus(state);
    }
    
    private ServerPort portInUse() {
    	ServerPort[] ports = getServer().getServerPorts(null);
    	ServerPort sp;
    	for(int i=0;i<ports.length;i++){
    		sp = ports[i];
    		if (SocketUtil.isPortInUse(sp.getPort(), 5)) {
    			return sp;
    		}
    	}
    	return null;
	}
    
	/**
	 * Override to trigger the launch of the debugging session (if appropriate).
	 */
	protected synchronized void setServerStarted() {
		if (fLaunchConfigurationWC != null) {
			try {
				setupSourceLocator( fLaunch );
				ExternalLaunchConfigurationDelegate.startDebugging(fLaunchConfigurationWC, fMode, fLaunch, fProgressMonitor);
			} catch (CoreException ce) {
				// failed to start debugging, so set mode to run
				setMode(ILaunchManager.RUN_MODE);
				final Status status = new Status(IStatus.ERROR, CorePlugin.PLUGIN_ID, 1,
							GenericServerCoreMessages.errorStartingExternalDebugging, ce); 
				CorePlugin.getDefault().getLog().log(status);
				Trace.trace(Trace.SEVERE, GenericServerCoreMessages.errorStartingExternalDebugging, ce);
			} finally {
				clearDebuggingConfig();
			}
		}
		setServerState(IServer.STATE_STARTED);
 	}
	
	/**
	 * Subclasses may override this method to replace default source locator or add additional
	 * sourceLookupParticipant, if necessary 
	 * @param launch 	the ILaunch object of the debug session
	 */
	protected void setupSourceLocator(ILaunch launch) {
        //nothing to do
	}

	/*
	 * If the server state is unknown, reset the status to OK
	 */
	private void resetStatus(int state) {
		if (state == IServer.STATE_UNKNOWN) {
			setServerStatus(null);
		}
	}
	
	/**
	 * Since terminate() is called during restart, need to override to
	 * call shutdown instead of just killing the original process.
	 */
	protected void terminate() {
		int state = getServer().getServerState();
		if (state == IServer.STATE_STOPPED) 
    		return;
    
		// cache a ref to the current process
		IProcess currentProcess = process;
		// set the process var to null so that GenericServerBehavior.setProcess()
		// will grab the stop executable (and declare the server stopped when it exits)
		process = null;

		// execute the standard shutdown
		shutdown(state);
		
		// if the shutdown did not terminate the process, forcibly terminate it
		try {
    		if (currentProcess != null && !currentProcess.isTerminated()) {
    			Trace.trace(Trace.FINER, "About to kill process: " + currentProcess); //$NON-NLS-1$
    			currentProcess.terminate();
    			currentProcess = null;
    		}
    	} catch (Exception e) {
    		Trace.trace(Trace.SEVERE, "Error killing the process", e); //$NON-NLS-1$
    	}
	}
	
	/**
	 * Override superclass method to correctly setup the launch configuration for starting an external
	 * server.
	 * @param workingCopy
	 * @param monitor
	 * @throws CoreException 
	 */
	public void setupLaunchConfiguration(ILaunchConfigurationWorkingCopy workingCopy,
										 IProgressMonitor monitor) throws CoreException {
		clearDebuggingConfig();
		ServerRuntime serverDef = getServerDefinition();
		Resolver resolver = serverDef.getResolver();
		workingCopy.setAttribute(IJavaLaunchConfigurationConstants.ATTR_WORKING_DIRECTORY,
					resolver.resolveProperties(serverDef.getStart().getWorkingDirectory()));
		String external = resolver.resolveProperties(getExternalForOS(serverDef.getStart().getExternal()));
		workingCopy.setAttribute(ExternalLaunchConfigurationDelegate.COMMANDLINE, external);
		workingCopy.setAttribute(ExternalLaunchConfigurationDelegate.DEBUG_PORT, 
					resolver.resolveProperties(serverDef.getStart().getDebugPort()));
		workingCopy.setAttribute(ExternalLaunchConfigurationDelegate.HOST, getServer().getHost());
		
		// just use the commandline for now
		workingCopy.setAttribute(ExternalLaunchConfigurationDelegate.EXECUTABLE_NAME, external);
        Map environVars = getEnvironmentVariables(getServerDefinition().getStart());
        if(!environVars.isEmpty()){
        	workingCopy.setAttribute(ILaunchManager.ATTR_ENVIRONMENT_VARIABLES,environVars);
        }
        String existingProgArgs  = workingCopy.getAttribute(IJavaLaunchConfigurationConstants.ATTR_PROGRAM_ARGUMENTS, (String)null);
        String serverProgArgs =  getProgramArguments();
        if(existingProgArgs==null || existingProgArgs.indexOf(serverProgArgs)<0) {
            workingCopy.setAttribute(IJavaLaunchConfigurationConstants.ATTR_PROGRAM_ARGUMENTS,serverProgArgs);
        }
	}

	/*
	 * Returns the first external whose "os" attribute matches (case insensitive) the beginning 
	 * of the name of the current OS (as determined by the System "os.name" property). If
	 * no such match is found, returns the first external that does not have an OS attribute.
	 */
	private String getExternalForOS(List externals) {
		String currentOS = System.getProperty("os.name").toLowerCase(); //$NON-NLS-1$
		External external;
		String matchingExternal = null;
		String externalOS;
		Iterator i = externals.iterator();
		while (i.hasNext()) {
			external= (External) i.next();
			externalOS = external.getOs();
			if (externalOS == null) {
				if (matchingExternal == null) {
					matchingExternal = external.getValue();
				}
			} else if (currentOS.startsWith(externalOS.toLowerCase())) {
				matchingExternal = external.getValue();
				break;
			}
		}
		return matchingExternal;
	}

	/**
     * Returns the String ID of the launch configuration type.
     * @return launchTypeID
     */
	protected String getConfigTypeID() {
		return ExternalLaunchConfigurationDelegate.ID_EXTERNAL_LAUNCH_TYPE;
	}

	/**
	 * Returns the String name of the stop launch configuration.
	 * @return launcherName
	 */
	protected String getStopLaunchName() {
		return GenericServerCoreMessages.externalStopLauncher;
	}
	
	/**
	 * Sets up the launch configuration for stopping the server.
	 * 
	 */
	protected void setupStopLaunchConfiguration(GenericServerRuntime runtime, ILaunchConfigurationWorkingCopy wc) {
		clearDebuggingConfig();
		ServerRuntime serverDef = getServerDefinition();
		Resolver resolver = serverDef.getResolver(); 
		wc.setAttribute(IJavaLaunchConfigurationConstants.ATTR_WORKING_DIRECTORY,
					resolver.resolveProperties(serverDef.getStop().getWorkingDirectory()));
		String external = resolver.resolveProperties(getExternalForOS(serverDef.getStop().getExternal()));
		wc.setAttribute(ExternalLaunchConfigurationDelegate.COMMANDLINE, external);
		// just use commandline for now
        Map environVars = getEnvironmentVariables(getServerDefinition().getStop());
        if(!environVars.isEmpty()){
        	wc.setAttribute(ILaunchManager.ATTR_ENVIRONMENT_VARIABLES,environVars);
        }
		wc.setAttribute(
				IJavaLaunchConfigurationConstants.ATTR_PROGRAM_ARGUMENTS,
				resolver.resolveProperties(serverDef.getStop().getProgramArgumentsAsString()));
		wc.setAttribute(ExternalLaunchConfigurationDelegate.EXECUTABLE_NAME, external); 	
		wc.setAttribute(ATTR_SERVER_ID, getServer().getId());
	}
	
	/**
	 * Sets the configuration to use for launching a debugging session
	 */
	protected synchronized void setDebuggingConfig(ILaunchConfigurationWorkingCopy wc,
					 			      String mode,
					 			      ILaunch launch, 
					 			      IProgressMonitor monitor) {
		this.fLaunchConfigurationWC = wc;
		this.fMode = mode;
		this.fLaunch = launch;
		this.fProgressMonitor = monitor;
	}
	
	private synchronized void clearDebuggingConfig() {
		this.fLaunchConfigurationWC = null;
		this.fMode = null;
		this.fLaunch = null;
		this.fProgressMonitor = null;
	}
	
	
}

Back to the top