A collection of small hacks which I discovered recently. This time: ssh ControlMaster and the synergy of dataclass and @cached_property in python.

cut_image

ssh ControlMaster

I use remote SSL tunnels a lot in my daily routine for browsing, access to HPC, file sync, and backup. Unfortunately, ssh, scp and rsync do take a few seconds to establish a new secure connection. It becomes especially annoying if you use scp to copy files as a part of a loop for example. But you can fix it using ControlMaster.

ControlMaster is a mechanism to share one secure connection across multiple applications. To activate it, I have the following in my .ssh/config.

Host *
    ControlPath ~/.ssh/controlmasters/%[email protected]%h:%p
    ControlMaster auto
    ControlPersist 10m

The above configuration means that secure sockets will be created inside my .ssh/controlmasters folder (note that it has to be created separately). ssh, scp and other applications will first check if a secure connection to the desired host is already present in the folder. If yes, they will re-use it in parallel to other programs. If not, they will create a new one. ControlPersist specifies the timeout for closing idle connections. This way, my remote manipulations become almost instant (including auto-completion in scp and rsync). A small downside is that broken uplink will lag ControlMaster sockets: you might need to cleanup the corresponding folder once the uplink is restored.

python dataclass + @cached_property

I enjoyed combining these two modern patterns recently for read-only classes with many attributes.

@dataclass(frozen=True)
class Dog:
    name: str
    head: float
    body: float
    tail: float

    @cached_property
    def size(self):
        return self.head + self.body + self.tail

    @cached_property
    def __str__(self):
        return f"{self.name}({self.size})"

This pattern has many advantages; to name a few:

  • Simple logic: you know exactly that there is nothing fancy about the constructor and it is straightforward to implement copy, serialization, and other standard class methods.
  • Zero maintenance cost for dependent attributes: they are defined in compact isolated blocks of code, they are cached and they are not evaluated unless necessary.
  • Concise code structure: there is a clear distinction between independent and children attributes. The class is literally a computational graph that can be traced over rather easily.

I recently switched to these patterns in my miniff package which I develop to model nanosystems.