I need some help with creating an automatic timing script with ColdFusion. My assumption is cfschedule and conditionals will be used to get this done. I am looking for something automatic, not on browser loads.
Anyways, every 60 minutes I would like to see if a page on one of my servers (http://www.mysite.com/page.php) is working or not.
If the page is down when it is checked, then it will check again in 5 minutes to see if the page is back up.
If it is not back up, then I am sent an e-mail to email#mysite.com. If it is back up, then no action is required and we start the 60 minute cycle check again.
Can anybody please help me with this?
Mike,
Not sure what version of CFML you are on but you could certainly set a scheduled task in your cf-administrator (I prefer the admin over cfschedule ... personal preference is all) to run your "site checker" script/page each hour and then, in that script/page, you could do something along the lines of:
<cfhttp url="http://mysite.com/ping-this-mofo.cfm" method="get" >
<cfif cfhttp.statusCode neq "200 OK">
<!--- some code to sleep for 5 minutes or a one-time cfschedule to check the site again --->
<cfschedule action="run" task="my-task-thingy" url="script-that-will-run" interval="once" startDate="today" startTime="5 minutes from now" />
</cfif>
Then, when that "sub-scheduled task" runs, you could check for the server being active and, if it isn't, fire off a an email via cfmail.
Related
I have an application which has different types of users. I need to set sessionTimeout based on user type. For example admin 30 minutes, user 10 minutes. To do this, I gave a default sessionTimeout of 30 minutes in application.cfc
<cfcomponent output="false" extends="org.corfield.framework">
<cfset this.applicationTimeout = createTimeSpan(1,0,0,0) />
<cfset this.sessionManagement = true />
<cfset this.sessionTimeout = createTimeSpan(0,0,30,0) />
.............
............
</cfcomponent>
When I dump the application variables I can see sessionTimeout is 600 which is correct. Now in the onRequestStart method, I wrote a code to check the loggedIn user type and set the sessionTimeout accordingly.
<cfif StructKeyExists(session,"user") AND ListLast(CGI.HTTP_REFERER,"/") EQ "login.cfm" >
<cfif session.user.userType EQ "GSA">
<cfset this.sessionTimeout = createTimeSpan(0,0,10,0) />
</cfif>
</cfif>
After this when I dump application variables, sessionTimeout is showing in days not in seconds. And also session is not getting ended after 10 minutes.
Can someone help on this? How to implement two different sessionTimeout in an application? Also why it is showing the sessionTimeout in days instead of seconds once I set the sessionTimeout again?
I don't believe there is any way to modify this scope metadata from inside one of these functions: onApplicationStart, onSessionStart or onRequestStart. Meaning you can't set this.sessionTimeout in any of those methods.
I was recently looking into this ColdFusion 11: Changing Application "this" Scope metadata from different functions in extended Application.cfc. However metadata is set for every request made by ColdFusion. Meaning you can try an approach like mentioned in this article, by Ben Nadel, and move the logic that sets the timeout out of onRequest() and onto the this scope and try creating dynamic session timeouts.
Delaying ColdFusion Session Persistence Until User Logs In
You are probably going to have to get creative in figuring out which user is logging in at that point though. ( Even if authentication occurs later ... any harm in setting a timeout?)
Session timeouts are common for all users. The timeout duration is set application-wide when the first request comes.
I think the short answer is, you cannot set two different session timeout durations.
Here is one method you can use. It's kind of creating your own session management client side, but it would allow for custom session timeouts per user role.
Create a timestamp in the session scope that is initially set to the current time a user logs on to your app. In your app's client JavaScript, create a timer that calls a function every minute or so that in turn calls a server side function to see how much time has elapsed since the last recorded timestamp for that user. If the time elapsed reaches the maximum allowed for that user's role, use the JavaScript function to logout the user.
With this method you reset the timestamp each time the user "interacts" with the app (runs a script, calls a cfc library function, etc.), such that the user does not get logged out while actively using the app. The user is only logged out after "x" minutes of inactivity that you define, and the function you call on the server side can further define what that number is per user role.
I've used this in railo but i think it applies to coldfusion too.
getPageContext().getSession().setMaxInactiveInterval(javaCast("int", 60));
It basically sets the session time out value of the currently running request to 60 something (i can't remember if it's in minutes or seconds)
With scheduled tasks, but none that are chained, I get the below error in my exception.log when starting Adobe ColdFusion 10 services (on Windows). How do I troubleshoot this back to the source of the error?
"Error","DefaultQuartzScheduler_Worker-2","09/15/14","15:12:02",,"Task invokehandler could not be chained"
java.lang.Exception: Task invokehandler could not be chained
at coldfusion.scheduling.CronTask.onCompleteTask(CronTask.java:214)
at coldfusion.scheduling.CronTask.execute(CronTask.java:130)
at org.quartz.core.JobRunShell.run(JobRunShell.java:213)
Note: I get three nearly identical errors the only difference is where it says "Worker-2" in the error above, I also get "Worker-1" and "Worker-3"
There are a couple of things you could do here. You could write a ColdFusion page that checks the health of your scheduled tasks and monitor that page manually (Check health of scheduled tasks). Of course that code could also be a scheduled task itself. Or you can add logging to your scheduled task(s) at various points to "see" what they are doing. I prefer the latter.
For the simplest of logging you can check the "Enable Logging for Scheduled Tasks" in the ColdFusion administrator, under the Logging Settings Page. This will create a new log file named scheduler.log. This option will report when a task is started, when it ends, if it errors, etc. BUT this log still only contains generic information such as the task's name and the thread name used to execute the task. This in itself probably won't help you much but it will show you which thread is running which task.
For more detailed information you will need to add your own logging within your scheduled task(s) code. I typically place the logging code at main points during the code's execution; "started", "retrieving data", "updating database", "writing file", "done", etc. Then whenever you need to check what happened with the task you just read your log file to have a look.
Here is some sample code:
<cftry>
<cflog file="your_file_name" type="information" text="Starting scheduled job xyz">
... code ...
<cflog file="your_file_name" type="information" text="Step 123">
... code ...
<cflog file="your_file_name" type="information" text="Step 456">
... code ...
<cflog file="your_file_name" type="information" text="Scheduled job xyz finished successfully">
<cfcatch type="any">
<cflog file="your_file_name" type="error" text="Error: #cfcatch.Type#, #cfcatch.Message#, #cfcatch.Detail#">
<!--- I usually send an email to myself for errors as well using <cfmail ... /> --->
</cfcatch>
</cftry>
And here is a link to the documentation for the <cflog> tag.
I found the same error for Task invokehandler could not be chained in exception logs after performing an upgrade to a newer ColdFusion version using the migration wizard. This appears to have been caused by the insertion of the text invokehandler during Scheduled Tasks import.
Remedy this behavior with the following steps:
Log in to the ColdFusion Administrator
Edit each scheduled task (click the pencil icon) and perform the following:
Scroll down and click Show Advanced Settings
Remove the text invokedhandler from the On Complete field
Click Submit
The errors should cease at this point after editing all your scheduled tasks.
I am running some code as a scheduled task, setup in CF Administrator.
Is there a way to tell in the code that the code ran as a scheduled task, whether it was ran by clicking the run icon in the CF Administrator scheduled task area, or whether it was called directly in a browser?
Adding additional variables will not work?
From the test link in the CF admin
If you're asking if you can identify the difference between a scheduled task being run manually by clicking the test link in the coldfusion admin or run on schedule, you can enable logging of scheduled tasks. Any time the task is run by the user the log entry will say [name of job] Executing because of user request at {timestamp}. If it ran naturally, the log entry will say [name of job] Executing at {timestamp}
I've looked for a way to tell by code and I can't find anything. It would depend on the accuracy of the scheduler but you could look to see if now() is equal to the time of the schedule. Something like (pseudo code):
<!--- disclaimer: I've heard stories that cfschedule sometimes runs a little late --->
<cfset scheduleTime = "2:00 am">
<cfif cgi.HTTP_USER_AGENT eq "CFSCHEDULE" and timeFormat(now(), "h:mm tt") eq scheduleTime>
<!--- ran naturally --->
<cfelse>
<!--- ran by force --->
</cfif>
From a browser
If you want to know if your scheduled task was run by the schedule or if the file was hit by the browser you can look at cgi.HTTP_USER_AGENT. if it is run by the scheduler it will equal CFSCHEDULE otherwise it will equal whatever the client is set to send.
Perhaps, Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.97 Safari/537.11
or if you're lucky enough to have a bot hit it, something like: Mozilla/5.0 (compatible; MJ12bot/v1.4.3; http://www.majestic12.co.uk/bot.php?+)
It is possible to spoof the client or server request to make the user user agent to say CFSCHEDULE but it isn't likely.
on a side note...
The default user agent for cfhttp is "COLDFUSION", in case you were interested.
Is there any way to restart the CF server through the Application.cfc, when the application times out? As per Adobe documentation, they showed as follows:
<cffunction name="onApplicationEnd">
<cfargument name="ApplicationScope" required=true/>
<cflog file="#This.Name#" type="Information"
text="Application #Arguments.ApplicationScope.applicationname# Ended" >
</cffunction>
What I would like to do is replace the <cflog> above with <cfexecute> as follows:
<cfexecute name = "C:\CFRestart.bat"
outputFile = "C:\output.txt"
timeout = "1">
</cfexecute>
So OnApplicationEnd will run the CFRestart.bat file when the application times out. Is this possible or not?
onApplicationEnd is not likely to be reached unless you have a very quiet application because every time someone access the application the timeout is reset.
I'd be very uncomfortable using an application to restart a coldfusion instance. I can see all sorts of horrible security issues etc looming. To be honest I'm not really sure why you'd want to restart the server if your application end.
Also, according to the docs onApplicationEnd is called when the server is restarted, so if you did get this working, when you restart your server the application would also have a go at restarting your server. This would get very messy.
Don't believe you can call the .bat script from ColdFusion. Because once it stops the service the <cfexecute> will also terminate (think it runs under the CF service), never reaching the restart.
Guessing you have a server that routinely fails because you're hitting an Out of Memory (OOM) exception. To get over the hump in those situations I setup as batch script as a Windows Scheduled Task (see the first answer there for how) that restarts the server periodically, say every 24, 12, or 6 hours. Choose an interval that makes sense for your situation.
Assuming OOM is the root cause, I suggest downloading a Java JDK, configuring ColdFusion to use it (i.e. jvmhome in jvm.config file), and passing parameters to enable a JMX connection. You use this JMX connection to monitor ColdFusion using Visual VM, which comes with the JDK. From there you can generate a heap dump file and/or tell the VM to generate one on OOM. Tehn I've had very good success running that through the Eclipse Memory Analyzer Tool, which has a suspected leaks report that more than once has helped track down the root cause of server OOM crashes.
If that is not your scenario then I suggest enabling snapshots if you're using ColdFusion enterprise, otherwise cfstat is you friend on standard. For either one, you can also setup probes that send a notification when the server is running slowly. This can help you connect to the server in question and generate a dump at the appropriate time or identify if the problem is load related instead.
This may not be your answer, but I use this often to help the garbage collection in JVM memory.
Set this as a scheduled task to run every 5 minutes, and i never get jvm memmory problems anymore.
<cfparam name="url.maxused" default="999">
<cfparam name="url.minfree" default="300">
<cfif NOT isDefined("runtime")>
<Cfset runtime = CreateObject("java","java.lang.Runtime").getRuntime()>
</cfif>
<cfset fm = runtime.freememory()/>
<Cfset fm = int((fm/1024)/1024)/>
<cfset usedmem = 1270-fm/>
<cfoutput>
#Now()#<br>
Before<br>
Free: #fm# megs<br>
Used: #usedmem# megs<br>
</cfoutput>
<br>
<!--- check if we are using too much memory --->
<cfif usedmem gt url.maxused or fm lt url.minfree>
<cfset runtime.gc()>
Released Memory<br>
<cfelse>
No need to release memory using the thresholds you provided<br>
</cfif>
<br>
<cfset fm = runtime.freememory()/>
<Cfset fm = int((fm/1024)/1024)/>
<cfset usedmem = 1270-fm/>
<cfoutput>
After<br>
Free: #fm# megs<br>
Used: #usedmem# megs<br>
</cfoutput>
This has been hanging around unanswered for an age, so I thought I'd help getting it cleared up.
First, this:
"Server Error The server encountered an internal error and was unable to complete your request. Could not connect to JRun Server."
This is NOT an application timeout, this is just the server becoming unresponsive, or running out of memory, or just encountering something it doesn't like. But it's nothing to do with the application timing out.
The application times out when there's been no activity (ie: no page requests... no visitors) on that site for longer than the application timeout period, which by default is two days (or whatever you have set in your Application.cfc).
Now... I can understand why you might want to recover if your server becomes unresponsive, bur you're approaching this from the wrong angle. Intrinsically if the server ain't working, you can't use that server to do anything (like cure itself)! What is generally done here is that some other process checks that the server is responsive, and if that service determines the server is not responsive, issues a restart.
So you should look at some other software which can perform an HTTP request to your CF server, and if the reaction to the HTTP request suggests the CF server is unresponsive, then the monitoring software tells CF to restart.
To add to the answer by Stephen Moretti and may be the possible solution you were looking for to your interesting question above:
Will the OnApplicationEnd run CFRestart BAT file when application is
timeout?
The straight answer is no. Since the OnApplicationEnd() event is a part of the Application's life cycle, so when the application itself is timed out, there is no event that will be called here. This must be clear.
Getting straight to your question though, yes, you can make a custom script file run on the event of an application timeout or end (whatever is the case). You will have to deal with the Serve Scope here.
First up, the application doesn't timeout, a page request does. On request timeout the onApplicationEnd() function is not called. That is only called if the application is shutting down. Here is some info on the CF application life cycle.
Second, in my experience, restarting application servers for whatever reason is probably masking your real problem. If you application is running slow / crashing etc. then I suggest you look into the real reason this is happening rather than restarting it.
However, I can't think of a reason this would not work in principle, but I would suggest you conduct a quick test if this really is what you wish to do.
Hope that helps.
Our CF server occasionally stops processing mail. This is problematic, as many of our clients depend on it.
We found suggestions online that mention zero-byte files in the undeliverable folder, so I created a task that removes them every three minutes. However, the stoppage has occurred again.
I am looking for suggestions for diagnosing and fixing this issue.
CF 8 standard
Win2k3
Added:
There are no errors in the mail log at the time the queue fails
We have not tried to run this without using the queue, due to the large amount of mail we send
Added 2:
It does not seem to be a problem with any of the files in the spool folder. When we restart the mail queue, they all seem to process correctly.
Added 3:
We are not using attachments.
What we ended up doing:
I wrote two scheduled tasks. The first checked to see if there were any messages in the queue folder older than n minues (currently set to 30). The second reset the queue every night during low usage.
Unfortunately, we never really discovered why the queue would come off the rails, but it only seems to happen when we use Exchange -- other mail servers we've tried do not have this issue.
Edit: I was asked to post my code, so here's the one to restart when old mail is found:
<cfdirectory action="list" directory="c:\coldfusion8\mail\spool\" name="spool" sort="datelastmodified">
<cfset restart = 0>
<cfif datediff('n', spool.datelastmodified, now()) gt 30>
<cfset restart = 1>
</cfif>
<cfif restart>
<cfset sFactory = CreateObject("java","coldfusion.server.ServiceFactory")>
<cfset MailSpoolService = sFactory.mailSpoolService>
<cfset MailSpoolService.stop()>
<cfset MailSpoolService.start()>
</cfif>
We have not tried to run this without using the queue, due to the large amount of mail we send
Regardless, have you tried turning off spooling? I've seen mail get sent at a rate of 500-600 messages in a half second, and that's on kind of a crappy server. With the standard page timeout at 60 seconds, that would be ~72,000 emails you could send before the page would time out. Are you sending more than 72,000 at a time?
An alternative I used before CFMail was this fast was to build a custom spooler. Instead of sending the emails on the fly, save them to a database table. Then setup a scheduled job to send a few hundred of the messages and reschedule itself for a few minutes later, until the table is empty.
We scheduled the job to run once a day; and it can re-schedule itself to run again in a couple of minutes if the table isn't empty. Never had a problem with it.
Have you tried just bypassing the queue altogether? (In CF Admin, under Mail Spool settings, uncheck "Spool mail messages for delivery.")
I have the same problem sometimes and it isn't due to a zero byte file though that problem did crop up in the past. It seems like one or two files (the oldest ones in the folder) will keep the queue from processing. What I do is move all of the messages to a holding folder, restart the mail queue and copy the messages back in a chunk at a time in reverse chronological order, wait for them to go out and move some more over. The messages which were holding up the queue are put in a separate folder to be examined latter.
You can probably programmatically do this by stopping the queue, moving the oldest file to another folder, then start the mail queue and see if sending begins successfully by checking folder file counts and dates. If removing the oldest file doesn't work, repeat the previous process until all of the offending mail files are moved and sending continues successfully.
I hope the helps.
We have actually an identical setup, 32bit CF8 on Win2K3.
We employed Ben's solution about a year ago, and that certain has helped auto re-queue emails that get stuck.
However recently for no particular reason one of our 7 web servers decided to get into this state with every email attempt.
An exception occurred when setting up mail server parameters.
This exception was caused by:
coldfusion.mail.MailSessionException:
An exception occurred when setting up mail server
parameters..
Each of our web servers are identical clones of each other, so why it was only happening to that one is bizarre.
Another item to note is that we had a script which reboot the machine in the middle of the night due to JRUN's memory management issues. The act of rebooting seemed to initiate the problem. A subsequent restarting of the CF service would then clear it, and the machine would be fine until it rebooted again.
We found that the problem is related to the McAfee virus scanner, after updating it to exclude the c:\ColdFusion8 directory, the problem went away.
Hope that helps.
There is a bug in Ben Doom's code. Thank you anyway ben, the code is great, and we use it now on one of our servers with CF8 installed, but:
if directory (\spool) is empty, the code fails (error: Date value passed to date function DateDiff is unspecified or invalid.) That's because if the query object spool is empty (spool.recordcount EQ 0), the datediff function produces an error.
we used this now:
<!--- check if request for this page is local to prevent "webusers" to request this page over and over, only localhost (server) can get it e.g. by cf scheduled tasks--->
<cfsetting requesttimeout="30000">
<cfset who = CGI.SERVER_NAME>
<cfif find("localhost",who) LT 1>
security restriction, access denied.
<cfabort>
</cfif>
<!--- get spool directory info --->
<cfdirectory action="list" directory="C:\JRun4\servers\cfusion\cfusion-ear\cfusion-war\WEB-INF\cfusion\Mail\Spool\" name="spool" sort="datelastmodified">
<cfset restart = 0>
<cfif spool.recordcount GT 0><!--- content there? --->
<cfif datediff('n', spool.datelastmodified, now()) gt 120>
<cfset restart = 1>
</cfif>
</cfif>
<cfif restart><!--- restart --->
<cfsavecontent variable="liste">
<cfdump var="#list#">
</cfsavecontent>
<!--- info --->
<cfmail to="x#y.com" subject="cfmailqueue restarted by daemon" server="xxx" port="25" from="xxxx" username="xxxx" password="xxx" replyto="xxxx">
1/2 action: ...try to restart. Send another mail if succeeded!
#now()#
Mails:
#liste#
</cfmail>
<cfset sFactory = CreateObject("java","coldfusion.server.ServiceFactory")>
<cfset MailSpoolService = sFactory.mailSpoolService>
<cfset MailSpoolService.stop()>
<cfset MailSpoolService.start()>
<!--- info --->
<cfmail to="x#y.com" subject="cfmailqueue restarted by daemon" server="xxx" port="25" from="xxxx" username="xxxx" password="xxx" replyto="xxxx">
2/2 action: ...succeeded!
#now()#
</cfmail>
</cfif>
There is/was an issue with the mail spooler and messages with attachments in CFMX 8 that was fixed with one of the Hotfixes. Version 8.0.1, at least, should have had that fixed.