gopsutil icon indicating copy to clipboard operation
gopsutil copied to clipboard

Use the context provide to UsageWithContext public function

Open GustavoCaso opened this issue 8 months ago • 2 comments

Currently, at work, we use gopsutil. We wanted to use the disk.UsageWithContext to allow setting some timeout when calling the Usage function.

We realized that the function UsageWithContext does not use the ctx provided.

It think would be a good addition to this great package.

That way, the user can do:

ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()

usage, err := UsageWithContext(ctx, "/")
if err != nil {
	log.Fatal(err)
}

Before adding a test or applying this pattern to other functions *WithContext, I wanted to know if we would be okay with having it in the package. If so, I can add tests and extend the pattern to the rest of the *WithContext functions.

Looking forward for your feedback.

GustavoCaso avatar Apr 11 '25 11:04 GustavoCaso

Thank you for your suggestion.

gopsutil aims to support a wide range of platforms. Some of these platforms use context internally in their implementation, while others do not. For example, disk/disk_aix_nocgo.go makes use of ctx. Because of these differences, we can't write a universal implementation that cancels the context in all cases.

If we were to implement such logic, I believe the best approach would be to define a separate function that handles context cancellation, and then call that function within each platform-specific UsageWithContext function only when necessary. This way, platforms that don't need it can simply omit the call.

shirou avatar Apr 20 '25 05:04 shirou

To be honest, the WithContext() functions were initially introduced because of wmi disastrous performance on windows https://github.com/shirou/gopsutil/issues/469#issuecomment-352672929, I personally wouldn't mind them to be simply removed instead (that would be a breaking change so for a major version bump), they've been a bit of a maintenance annoyance more than anything, duplicating all the API only for a few functions calling wmi on windows, while the number of these slow wmi calls has been greatly reduced over the years.

Lomanic avatar Apr 24 '25 14:04 Lomanic