Introducing `jhack eval`: aka python evaluation on live charms

Hey there! Perhaps you’ve recently seen jhack script come around. I decided to streamline its one-liner use case and expose it as jhack eval.

This command is aliased to jhack crpc, for charm rpc

Starting from jhack 0.4.0.4 (semver FTW!!), now on edge, you can run:

jhack eval myapp/0 <python expression>

Usage

You can retrieve any value you can access from the charm instance:

$ jhack eval unit/0 self.app.name
"unit"
$ jhack eval unit/0 self.model.relations['endpoint-name'][2].app.name
"remote"

You can invoke any method you can refer to from the charm instance:

$ jhack eval unit/0 self._adder._add(1, 1)
2

Set attributes:

$ jhack eval unit/0 setattr(self.unit, "status", ops.ActiveStatus("foo"))
None

With a little bit of python magic you can also do assignment operations and mutate anything the charm can mutate (this does not get around permission rules e.g. involving leadership…)

$ jhack eval unit/0 self._some_relation.data[self.unit].__setitem__("foo", "bar")
None

Call a method on the charm:

in this case it’s an event handler, but it can be any method on your charm (or a nested object). In fact, anything you can access from the charm instance as self or from the ops namespace!

jhack script

For more complex use cases, when you want to do conditional logic or stuff that gets too complicated to golf into a single line (I personally draw the line at assignment operations), you can still fall back to jhack script.

11 Likes

Sweet! I’ve dumped this in our internal communication at Dwellir too!

2 Likes