autopwn
autopwn

Reputation: 13

javassist ExprEditor - how to distinguish multiple method calls on same type

Given the following example class, I want to count the calls to doThis() and doThat() per Instance (sc1, sc2) using Javassist (ExprEditor) and the Prometheus Java client library, but I find no way to distinguish the calls within Javassist.

public class InstrumentedClass {

    private SomeClass sc1 = new SomeClass();
    private SomeClass sc2 = new SomeClass();

    public void doSomething() {
        sc1.doThis();
        sc2.doOther();
        sc2.doThis();
        sc1.doOther();
        // number of occurrences and order of this calls is object to change
        // so I cannot rely on line numbers (e.g. insertAt())
    }
}

My general approach is to replace each method call with a block statement containing the original expression followed by the incrementation of a Prometheus counter object. Unfortunately, the code is kind of hard to read given the neccessary type cast and fully-qualified class name.

cc.getDeclaredMethod("doSomething").instrument(new ExprEditor() {
    public void edit(MethodCall m) throws CannotCompileException {
        if (m.getClassName().equals("SomeClass")) {
            if (m.getMethodName().equals("doThis")) {

                m.replace("{ $_ = $proceed($$); ((io.prometheus.metrics.core.datapoints.CounterDataPoint) " +
                    "counterDoThis.labelValues(new java.lang.String[] {"MissingPiece"})).inc(1.0); }");

            } else if (m.getMethodName().equals("doOther")) {

                m.replace("{ $_ = $proceed($$); ((io.prometheus.metrics.core.datapoints.CounterDataPoint) " +
                    "counterdoOther.labelValues(new java.lang.String[] {"MissingPiece"})).inc(1.0); }");

            }
        }
    }
});

Now the challenge is to replace the label "MissingPiece" with something that allows me to distinguish between the calls on sc1 or sc2. The type is not an option as it is the same. I could use object ids for example, but those are to volatile and not human readable to be used as labels accross application restarts.

My fear is that this type of information is not available anymore in the bytecode and my plan is doomed to fail.

But maybe someone has a smart idea :)

Upvotes: 1

Views: 70

Answers (0)

Related Questions