jaypipes / ghw

Go HardWare discovery/inspection library
Apache License 2.0
1.64k stars 180 forks source link

context: allow reuse in auxiliary packages #278

Closed ffromani closed 3 years ago

ffromani commented 3 years ago

The PR #236 fixes a snapshot directory leakage issue, but also highlight a context lifecycle/ownership issue.

In general in ghw each package creates its own context, including the cases on which a package is consumed by another, for example topology and pci. However, in this case, it would make more sense to reuse the context from the parent package.

Before the introduction of the the transparent snapshot support (#202), the above mechanism worked, because each context, each time, was consuming over and over again the same parameters (e.g. environment variables); besides some resource waste, this had no negative effect.

When introducing snapshots in the picture, repeatedly unpacking the same snapshot to consume the same data is much more wasteful. So it makes sense now to introduce explicitly the concept of dependent context.

To move forward and make the ownership more explicit, we add a new function NewWithContext in all the subpackages. The function NewWithContext will assume the context it gets as argument is ready to be consumed and it will use as-is, attempting no setup or teardown in any circumstances.

The usage rules are pretty simple:

  1. In your client code, you most likely just need to use New as usual.
  2. When consuming a package from another (e.g. topology from pci), always use the NewWithContext function to get a handle for the auxiliary package, passing through the context from the top-level package.
  3. Within a NewWithContext function, all calls to other NewWithContext functions should be made to preserve the properties.
ffromani commented 3 years ago

replaced by https://github.com/jaypipes/ghw/pull/280