Grails - restarting Rabbitmq plugin consumers by calling method on plugin class - grails

I am using the Grails Rabbitmq Native plugin. When I launch the application, I don't want the RMQ consumers to be automatically started, so in my Config.groovy I have defined:
rabbitmq.enabled == false
The code within doWithSpring() (https://github.com/budjb/grails-rabbitmq-native/blob/master/RabbitmqNativeGrailsPlugin.groovy#L114) means that certain wiring isn't carried out if this flag is false.
At some point, I want to be able to start the RMQ system up. I'd like to call a method defined within the plugin class, such as restartRabbitContext() (https://github.com/budjb/grails-rabbitmq-native/blob/master/RabbitmqNativeGrailsPlugin.groovy#L231) to start up the RMQ consumers. I think I will need to carry out some of the wiring myself.
Is there a way to do this? What is the import required to be able to access the plugin class's methods?

Your best bet is to use the GrailsPluginManager to access your plugin by name using getGrailsPlugin. From there you should be able to access the plugin as a GrailsPlugin and access the public methods defined in the plugin itself.
The GrailsPluginManager can be obtained though the grailsApplication such as: grailsApplication.pluginManager. In the very rare event you can't use DI you can always fall back to Holders to get to the GrailsPluginManager (though this is a very rare case).

Related

Jersey HK2 : Dependency injection and healthchecks

My app has got quite a few of async (cron) processes and they all have their separate binder classes in Jersey. These processes are started and managed through independent scripts.
Now, if I make a change in the classes used by these processes, (e.g. add a dependency in the classes) and forget to update the binder class inadvertently, the processes still start up but fail with org.glassfish.hk2.api.UnsatisfiedDependencyException (which is expected). However, this does not stop the process on the node and monitoring tool still thinks that the process is running fine.
I am looking to implement Healthchecks in these process so that I can see if the process has come up fine after deployment and is able to start without any dependency error. I am exploring following options:
An async lightweight process that exports ServiceLocator health status to a monitoring system (e.g. prometheus)
An API endpoint that can be polled externally and returns response based on ServiceLocator status
I have got a couple of questions:
Is there a native way in Jersey HK2 to do this?
How do I know if Locator is able to resolve all the dependencies (i.e. there is no UnsatisfiedDependencyException)?
In hk2 there is a special service called the ErrorService which you can use to see if there are failures creating services. Since hk2 is a dynamic framework this error service implementation will not get called until someone attempts to create the service that is failing.
You also might want to seriously look into the automatic binding options of hk2. Makes everything so much easier IMO. See the section on Automatic Service Population
Here is an example of using the ErrorService:
#Service
public class ExampleErrorService implements ErrorService {
#Override
public void onFailure(ErrorInformation ei) throws MultiException {
if (ErrorType.SERVICE_CREATION_FAILURE.equals(ei.getErrorType())) {
// Tell your health check service there was an exception
return;
}
// Maybe log other failures?
}
}

What is a Grails "transactional" service?

I'm reading the Grails docs on services which make numerous mention of transactions/transactionality, but without really defining what a transactional service method really is.
Given the nature of services, they frequently require transactional behaviour.
What exactly does this mean? Are transactional methods only those that use JPA/JDBC to communicate with a relational DB, or do they apply to anything covered by JTA?
Is there any reason why I just wouldn't make a service class #Transactional in case it evolves to some day use a transaction? In other words, are there performance concerns to making all service methods transactional?
Grails services are transactional by default - if you don't want a service to be transactional, you need to remove all #Transactional annotations (both Grails' #grails.transaction.Transactional and Spring's #org.springframework.transaction.annotation.Transactional) and add
static transactional = false
If you haven't disabled transactions with the transactional property and have no annotations, the service works the same as if it were annotated with Spring's annotation. That is, at runtime Spring creates a CGLIB proxy of your class and registers an instance of the proxy as the Spring bean, and it delegates to an instance of your actual class to do the database access and your business logic. This lets the proxy intercept all public method calls and start a new transaction, join an existing one, create a new one, etc.
The newer Grails annotation has all of the same settings as the Spring annotation, but it works a bit differently. Instead of triggering the creation of a single proxy, each method is rewritten by an AST transform during compilation, essentially creating a mini proxy for each method (this is obviously a simplification). This is better because the database access and transaction semantics are the same, but if you call one annotated method from another annotated with different settings, the different settings will be respected. But with a proxy, it's a direct call inside the delegate instance, and the proxy is bypassed. Since the proxy has all of the logic to create a new transaction or use other different settings, the two methods will use the first method's settings. With the Grails annotation every method works as expected.
There is a small performance hit involved for transactional methods, and this can accumulate if there are a lot of calls and/or a lot of traffic. Before your code runs, a transaction is started (assuming one isn't active) and to do this, a connection must be retrieved from the pool (DataSource) and configured to turn off autocommit, and make the various transaction settings (isolation, timeout, readonly, etc.) have to be made. But the Grails DataSource is actually a smart wrapper around the "real" one. It doesn't get a real JDBC Connection until you start a query, so all of the configuration settings are cached until then, and then "replayed" on the real connection. If the method doesn't do any database work (either because it never does, or because it exits early based on some condition before the db access code fires), then there's basically no database cost. But if it does, then things work as expected.
Don't rely on this DataSource proxying logic though - it's best to be explicit about which services are transactional and which aren't, and within each service which methods are transactional and which aren't. The best way to do this is by annotating methods as needed, or adding a single annotation at the class level if all methods use the same settings.
You can get more info in this talk I did about transactions in Grails.
First, if your performance concerns are due to the fact your services are transactional then you have reached nirvana. I say this because there are going to be plenty of other bottle necks in your application long before this is a major (or even minor) concern. So, don't fret about that.
Typically in Grails a transaction relates to the transactional state of a database connection or hibernate session. Though it could be anything managed by the JTA with the proper Spring configuration.
In simple terms, it's usually means (by default) a database transaction.

How can I tell how many database connections my application is using?

I have a grails web application which is connecting to a Postgres database. I'm concerned that the code is opening multiple database connections.
How can I find out how many connections it is holding during a request?
There's a lot of magic going on in there with GORM etc and I'm not sure how it's managing its connections.
It's managed by the dataSource bean, which is a javax.sql.DataSource. Unfortunately this interface is very basic, with only 4 methods - 2 getConnection() methods (one with and one without a username/password) and unwrap and isWrapperFor from its parent interface. The actual implementation classes typically have many different methods for configuration and monitoring, but there isn't really any standard, and definitely no interface.
If you're using a recent version of Grails and haven't reconfigured anything, the backing implementation is the Tomcat JDBC Pool, which doesn't depend on Tomcat but was written by a Tomcat committer. You can't just cast that bean to the pool implementation class however, because Grails wraps the actual datasource instance in two proxies. Fortunately the "real" instance is easy to get to - dependency-inject the dataSourceUnproxied bean in a service or wherever you wanted to look at usage:
def dataSourceUnproxied
and then you can call any of its methods (see the Javadoc for what's available)
It's not needed for Groovy of course, but if you want IDE autocompletion add this import
import org.apache.tomcat.jdbc.pool.DataSource
and cast it and call the methods on that, e.g.
DataSource tomcatDataSource = dataSourceUnproxied
log.debug "$tomcatDataSource.active active (max $tomcatDataSource.maxActive, initial $tomcatDataSource.initialSize), $tomcatDataSource.idle idle (max $tomcatDataSource.maxIdle, min $tomcatDataSource.minIdle)"

Looking for interceptors for grails service class

Is there any interceptor I can use to validate incoming requests to the Grails service classes/Endpoints?
I know interceptors for controllers but I want to do it for Service/endpoint.
This sounds like what you are looking for:
Intercepting Service Methods
In the link mentioned above(Kelly's reply), interceptor logic for Service has been added in BootStrap class. That might suffice in most of the cases but not all. In case you are using Quartz scheduler then job might get triggered even before BootStrap has made required modifications.
The best place to modify a service method would be via custom plugin. You can decorate service method in doWithApplicationContext or doWithDynamicMethod available in Plugin class. These methods are triggered at first and guarantee that changes made will be available to all other classes. Please refer Grails custom plugin documentation for more information.

Spring.NET, Quartz & Transactions

I've just run into a problem with a Quartz job that I'm invoking through Spring. My ExecuteInternal method had a [Transaction] attribute (because it does a load of DB calls) but when it runs, I get the 'No NHibernate session bound to thread' error.
Just wondering if that's because Spring.NET doesn't support the [Transaction] attribute in Quartz objects?
If not, that's fine... I can start a transaction manually, but wanted to check that it was the case, and not a silly error in my config somewhere.
[Update]
I figured it out actually. In the API docs, it says the preferable way to do this is use transactions on the service layer. My job was using DAOs to do its work, but my transactions are on my service layer, so I just called service methods from my job instead to do the same work (saving, updating records etc) since they already existed.
It also suggests that if you give the SchedulerFactoryObject a DbProvider, you can use transactions in the job itself, but when I did that it seemed to want to find my triggers configured in a special table in the DB (which I haven't set up since my triggers are all in XML) but that's possibly another way to do it.
Calling service methods works fine for me though.
The transaction attribute works using aop. Spring.NET creates an aop proxy for the decorated object. This proxy creates the session and starts the transaction.
In the ExecuteInternal method, you don't call the method on a proxy, but on the target itself. Therefore spring cannot intercept the call and do its transaction magic.
Your services are injected and therefore the transaction attribute works for them.
There's a good explanation in the spring docs on this subject: http://www.springframework.net/doc-latest/reference/html/transaction.html#tx-understandingimpl

Resources