Skip to content

Commit

Permalink
Fix division by zero (#71)
Browse files Browse the repository at this point in the history
* Fix division by zero in cgroups

* Fix division by zero in cgroups2

* Add test data for zero period cgroups

* Add test data for zero period cgroups quota

* Add test data for zero period cgroups2

* Add cgroups test

* Add cgroups2 zero period test
  • Loading branch information
Zamony committed Jun 18, 2023
1 parent f6364fc commit d064ede
Show file tree
Hide file tree
Showing 7 changed files with 19 additions and 2 deletions.
4 changes: 2 additions & 2 deletions internal/cgroups/cgroups.go
Original file line number Diff line number Diff line change
Expand Up @@ -110,8 +110,8 @@ func (cg CGroups) CPUQuota() (float64, bool, error) {
}

cfsPeriodUs, err := cpuCGroup.readInt(_cgroupCPUCFSPeriodUsParam)
if err != nil {
return -1, false, err
if defined := cfsPeriodUs > 0; err != nil || !defined {
return -1, defined, err
}

return float64(cfsQuotaUs) / float64(cfsPeriodUs), true, nil
Expand Down
4 changes: 4 additions & 0 deletions internal/cgroups/cgroups2.go
Original file line number Diff line number Diff line change
Expand Up @@ -159,6 +159,10 @@ func (cg *CGroups2) CPUQuota() (float64, bool, error) {
if err != nil {
return -1, false, err
}

if period == 0 {
return -1, false, errors.New("zero value for period is not allowed")
}
}

return float64(max) / float64(period), true, nil
Expand Down
4 changes: 4 additions & 0 deletions internal/cgroups/cgroups2_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -125,6 +125,10 @@ func TestCGroupsCPUQuotaV2(t *testing.T) {
name: "too-many-fields",
wantErr: "invalid format",
},
{
name: "zero-period",
wantErr: "zero value for period is not allowed",
},
}

mountPoint := filepath.Join(testDataCGroupsPath, "v2")
Expand Down
6 changes: 6 additions & 0 deletions internal/cgroups/cgroups_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,12 @@ func TestCGroupsCPUQuota(t *testing.T) {
expectedDefined: false,
shouldHaveError: false,
},
{
name: "zero-period",
expectedQuota: -1.0,
expectedDefined: false,
shouldHaveError: false,
},
{
name: "undefined-period",
expectedQuota: -1.0,
Expand Down
1 change: 1 addition & 0 deletions internal/cgroups/testdata/cgroups/v2/zero-period
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
250000 0
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
0
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
600000

0 comments on commit d064ede

Please sign in to comment.