How to implement a java daemon program in weblogic? - java

I have the task to port a standalone java deamon program to J2EE on weblogic.
Old: The java program starts two threads which loop endlessly based on an interval that can be configured via a properties file.
New: The program should run on weblogic 10.1.x and start when the managed server it will deployed to is started or the servlet is initialized and it shouldn't have to be invoked by a client.
I know already that creating your own threads is highly discouraged for weblogic so I'll search for another way to make this happen. I already tried via startup class, but that means the server remains in the state STARTING forever because naturally the programm is designed to run forever, I didn't know the server is actually waiting for the Startup Class to end. Next best thing I know of would be the usual servlet by calling its URL once and implement starting the programm in it. Even then, how would you prevent the browser from getting hung up on the servlet call (because it does run forever) without making the program logic asynchronous by creating a thread? Also I read something about Listeners, would that be the thing I should be looking for?
One last thing, I definitly need to run it on weblogic, so suggestions for other solutions wouldn't help me.

This is a confusing question because it's so basic... You just need to create a web service with your endless loops in it. You don't need to hit a URL to start it. Just deploy a .war or .ear file with your code and you're done.
http://docs.oracle.com/cd/E13222_01/wls/docs81/webserv/example.html

Related

Blackboard server - issue with restarting

SEVERE: The web application [/webapps/bb-nautilus-BBLEARN] appears to have started a thread named [MessageQueueHandler-bb-nautilus-content-blitz-0] but has failed to stop it. This is very likely to create a memory leak.
If an application starts all kinds of stuff (registering jdbc drivers, starting threads, ...) when it is fired up, it is the responsibility of that application to also clean up after itself when it is stopped.
Are you the author of this application ? Correct your code. Not the author of this application ? Submit a bug report.
In the latter case, until the bug is addressed it might be possible to add a ServletContextListener of your own making to the deployment. But clearing up leftover Threads from "foreign" code is at any rate going to require you to figure out how to find those Thread objects and then subsequently stop() them, which is a deprecated method.
MessageQueue may be busy doing something strange. It refuses to exit. So, reboot the server and try starting Bb Learn after that. Post the new error after you know that no part of Bb Learn was running after a failed app restart.

Why does net.exe start <servicename> report a failure when the service starts?

I have a Java application that uses the Apache Daemon service installer to register it as a Windows service. I am using Puppet to run an exec{} block to register the service, which works, and then chains a service{} block to start the service. Puppet uses "net.exe start" to run the service, but that command reports an error, even though the service starts correctly.
The output from running the command in a powershell shell is:
PS C:\ProgramData\PuppetLabs\puppet\etc\modules> net start myservice
The myservice_descriptive_name service is starting.....
The myservice_descriptive_name service could not be started.
More help is available by typing NET HELPMSG 3523.
As I refresh the Windows service panel while this command is running, I see the state change from:
blank field -> starting -> started
Is this a problem caused by the apache wrapper, which is starting a jvm in a separate shell or some other side effect? And, more importantly, can I get around this problem in Puppet while still using the service{} block? Is it possible to substitute sc.exe, which does not suffer the same problem, short of using an exec{} block?
To take the questions in order:
The net start command reports failure because the service appears to have hung.
Yes, the problem is caused by the Apache wrapper.
Specifically, the wrapper is telling Windows that it will reach the first checkpoint within two seconds. Since there does not appear to be any way for the Java code to implement a checkpoint, or to change the wait hint, this means that the service must start within two seconds to be compliant with the Windows service specification.
(In principle, Windows is entitled to terminate your service at this point. So far as I know, no current versions of Windows do so, though they may log error messages.)
Short of modifying Puppet or (preferably) the Apache wrapper, the only obvious workaround is to ensure that your service "starts" immediately, rather than waiting for initialization to complete.
This is less than ideal, since it means that the service can't provide feedback to Puppet if it really does fail to initialize, but no worse than your suggestion of using sc start instead of net start.
JPBlanc's answer explains why the net.exe times out waiting on the service to start, even though it does end up starting. You can definitely try swapping out net.exe calls for sc.exe (Service Control) instead.
I've created a ticket to address this - https://tickets.puppetlabs.com/browse/PUP-5475
If you find that it doesn't also timeout while waiting, please comment and/or file a pull request containing the change. At any rate, using something better than net.exe would be preferred.
The explanation is that the service takes too much time to start and does not communicate correctly with the starter.
When you write a service that initiate communications or DB connections you have to communicate with the Service Control Manager (SCM) to give the information that you are starting. Doing this kind of "I'am still starting message" the SCM can wait as mus time as you need to start. But much service writer or or tools to encapsulate exe files as services ignore that, so the SCM return "service could not be started". In Win32 this is handled by SetServiceStatus function, you will have much details there.

Jboss WS and Threads

I have made test WebService which starts Thread, which writes to file timestamp every 10 second. I intentionally don't have Thread stop mehanism.
Now, if I stop test WebService, and even delete it, the Thread live in Jboss forever
(needs JBoss restart).
Is this normal that JBoss isn't aware of Threads made within WebService context ?
Within JVM, when app shuts down, all threads are killed, but here is JVM owned by Jboss,
which dynamically loads classes.
Is this a "feature" or bug ?
I am asking this, cause we have 3rd party application doing threading, and I noticed they're not shutted down on WebService destructor, so after re-publish, we have an issue.
Cleaning up resources used by a WebService, is the responsibility of the WebService itself.
Tomcat will help you by logging warnings when a WebService is not doing this properly (e.g. when the MySQL JDBC driver is leaving a thread hanging) and it will even try to clean ThreadLocals for you (see also comments in this utility class).
In your case, since you are using the 3rd party application in a WebService, you are responsible for cleaning up resources used by the 3rd party application when your WebService is unplugged. It would be nice if JBoss could at least report "resource leakage" like Tomcat does, but that would be a feature and not a bug.
I have made test WebService which starts Thread, which writes to file timestamp every 10 second. I intentionally don't have Thread stop mehanism. Now, if I stop test WebService, and even delete it, the Thread live in Jboss forever (needs JBoss restart). Is this normal that JBoss isn't aware of Threads made within WebService context ?
You aren't supposed to launch your own threads, so JBoss won't clean your stuff up for you.
See also why spawning threads in Java EE is discouraged (mostly applies to Enterprise Java Beans) or "Java EE specification and multi threading".
If the 3rd party application does its own threading and you can't change it, then it might not be a good fit for an application server. An old trick to graft an old application into Java EE is to manage its lifecycle using a ServletContextListener, which has an init and destroy method.
If you can change it though, check the Concurrency Utils API example from the question / answer I linked to above, using an ExecutorService is the modern way to manage threads so that the server is aware of your handywork.

I want my service to run unelevated, but as a user who happens to be an Administrator (Windows / UAC)

Like the title says, I have written a program runs 'in the background', preferably as a Windows service. (It happens to be written in Java, with the service part provided by the tanuki wrapper, if this matters. Also, I'm running Vista, but am assuming that this happens on all versions of Windows with UAC.) I run the service as 'User X'.
I also have a companion GUI program which is typically run from the start menu (unprivileged - i.e. 'asInvoker') - also as 'User X'.
The background program (aka the service) creates files. My main need is for the unelevated GUI program to be able to read, write, and delete these files that are created by the service.
This works without hassle as long as 'User X' is not a member of the Administrators group. (Of course an admin login is required to create the service, but that's okay.)
It also works if I turn off UAC, or if I run the background program not as a service (eg. from a command prompt).
But I just can't get it to work when 'User X' is a member of Administrators, and the background program is running as a service.
The symptoms of this problem are that process explorer shows my service process as running privileged (which I glean from the processes properties' Security tab showing 'BUILTIN\Administrators - Owner'). Also, all files created by the service are owned by 'Administrators'.
If I run my background program unprivileged from a command prompt, then process explorer shows 'BUILTIN\Administrators - Deny' and all files created by the program are owned by 'User X'.
Interesting question. I just looked up some information and cannot seem to find an answer for your question as asked initially, but I have a few alternative suggestions.
First, is it feasible to change your service app so that it creates the files required then it changes the permissions on them to what you want?
Second, does the service itself really have to run as "User X"? If so, why? Is there any way around that restriction? If you can bypass that requirement, then you can just make a normal user for the service to run as.
Third, you said preferably as a service, but not that this is a requirement. Does the environment this is used in allow you to use a scheduled task? The task scheduler itself runs as a system service, and it spawns other processes to do the work of the tasks you set up. And, when setting up a scheduled task, there is an option (a check box if you're using the GUI interface) to run the task with highest privileges or not. If you go this route, you can either have the task run at logon, or you can have it run at system start (in which case, make sure you do NOT have selected "run only if logged on"). This should otherwise be similar to your service setup.
Based on your comment below, I think the third suggestion might still be an option. You could still have status information similar to that of a service by making the program handle this in its own way. Your application could have a socket open for its cross-process communication. The background process could open a ServerSocket on a known port, and it could listen for status requests.
Your client application that your users are using could attempt to connect to this socket. If the socket connects, the process is running, otherwise it is not.
If you wanted only a "running/not running" status, this would be sufficient, and the ServerSocket could accept() a connection and then immediately shutdown and close the resulting Socket; you don't even have to accept or send any information since the initial connection is all you need.
If you want to keep the ability to startup/shutdown the task, you could use this same ServerSocket for that ability. If you aren't using the socket for any other data (only for the running-or-not mentioned above), you could have the background process terminate upon receiving any data at all on the socket, regardless of what it is, and the client (or whatever you use to shut down the background process) need only connect and send a byte instead of connect and immediately disconnect.
For startup, if you want to restrain the background process to one instance, there are a few ways to easily do that. I think you should be able to configure it via the task scheduler to only allow one instance of the task. Even if not, you could have a background process starting up connect to the given port it would otherwise listen on to see if it gets a connection from something else already there, if yes this is a second instance of it so abort. Or, even simpler yet, the creation of the ServerSocket should automatically fail if you are using a static port number, so just let the new ServerSocket(myPort) fail on its own, catch the exception, and abort. So there are three different ways to ensure that your process is acting like a proper service.
To start it up in the first place, you can tell the task scheduler to start it up on user logon, or on system boot as mentioned before. You can also configure the task so that users can initiate it themselves (if for whatever reason it's not already running), in fact, you could even have the client the user's are interacting with check on the status of the process and possibly start it automatically if it's not already started - try making a new process and exec() a command such as "schtasks /run /tn "Your Task Name""
I think that covers all the bases you mentioned, and then some. And all of the above should be pretty simple. If you do decide that this might be the route you'd like to take and if either I've overlooked something or you have other criteria which further restrict you from this, let us know again.
In the end I implemented a work-around using Windows scheduled tasks, similar to what is described above, but instead of implementing my own 'start/stop' interface, I wrote a Windows service that manages my program, run as a task. When the service starts, it starts a task, and when the service is asked to stop, is stops the task. So instead of using a socket for the parent to query if the child is running, I use schtasks /Query and parse the output. To make the task exit if the parent exits, I used an RMI keepalive method on my app that was already there.
Windows scheduled tasks have some undesirable defaults for a service that are modifiable through the task scheduler GUI, but not through schtasks' command-line options - namely ExecutionTimeLimit, DisallowStartIfOnBatteries, StopIfGoingOnBatteries.) But these options can be queried and modified using the '/XML' option to schtasks /Query and /Create. So that's what I did.
I also needed to detect if I'm running on a newer or older version of Windows, because if it's an older version (without UAC) then this will all be unnecessary but more importantly defining the task will not work without supplying a password, because the /NP option to schtasks is not available.
The only weakness (other than being complicated) that I know of with my implementation is due to schtasks' note on the /NP option - "Only local resources are available." This turns out to mean that mapped network drives won't be accessible (and I hope that's all it means.) I have SMB support implemented independently, in Java, in my app where it is needed, so this weakness wasn't the end of the world.
This was a lot of work for what can probably be done with a single Win32 call. Maybe one day I will figure out how to do that.

embedded Tomcat 6 - shut down after start

I wanna use an embedded Tomcat V6. The code works perfectly, but only as long as the programm is running. So if there is no Thread.Sleep it will exit immediately, otherwiese keep on running till the time is up.
How can I keep the emmbedded Tomcat alive. setAwait(true) should deal with this, shouldn't it? But i does not work. Tried to figure out more about this, but there is nothing in the description. Any other ideas?
If you want your embedded Tomcat to run indefinitively you will need some code to handle outside administrative requests (like restart, shutdown, stuff like that). That will go in your main thread, incidentially keeping the Tomcat instance alive.
This class should do what you are looking for.

Categories

Resources