Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to AOP aspectj in OSGi with Apache Felix

I'm currently working on an OSGi project. Without many experiences in AOP combined with OSGi, I would like to know how to best do AOP in an OSGi environment? We have implemented the AOP scenario to create a console that intercept the call to a bundle in order to store the elapsed time for each task started by this bundle. Today, this aspect has been deployed on a jboss container using the LoadTimeWeaver provided by aspectj (adding an agent to the jboss start script in order to instrument the jars in the container -javaagent:%APP_HOME%\application\lib\aspectjweaver-1.6.11.jar). I've read some articles about this problem, but did not find a solution that suits well for me. There is, for example, an Equinox Incubator project for AspectJ. But since I'm using Apache Felix and Bnd(tools) I want to avoid using something from Equinox. One requirement for the weaving process will be that it should be at load-time as well (a bundle for aspectj that instrument the method inside another bundle). Someone can share experiences with such a use case using AOP aspectj with OSGI Felix ?

like image 732
freedomind Avatar asked Nov 09 '22 13:11

freedomind


1 Answers

Here is a working example of minimal felix aspectj setup

The basic pattern is:

  1. register weaving hook on activation

    public class Activator implements BundleActivator {
       public void start(BundleContext context) throws Exception {
           AspectWeaver weaver = new AspectWeaver();
           servList.add(context.registerService(WeavingHook.class, weaver, null));
       }
    }
    
  2. inject weaving definition context:

    public class AspectContext extends DefaultWeavingContext {
        @Override
        public List<Definition> getDefinitions(final ClassLoader loader, final WeavingAdaptor adaptor) {
            if (definitionList == null) {
                definitionList = AspectSupport.definitionList(loader, rootConfig);
            }
            return definitionList;
        }
    }
    
  3. provide weaving hook implementation

    public class AspectWeaver implements WeavingHook {
      @Override
      public void weave(WovenClass woven) {
          String name = woven.getClassName();
          BundleWiring wiring = woven.getBundleWiring();
          ClassLoaderWeavingAdaptor adaptor = ensureAdaptor(wiring);
          final byte[] source = woven.getBytes();
          final byte[] target;
          // aspectj is single-threaded
          synchronized (adaptor) {
              target = adaptor.weaveClass(name, source);
          }
          woven.setBytes(target);
     }
    
like image 60
Andrei Pozolotin Avatar answered Dec 15 '22 03:12

Andrei Pozolotin