helpers_linux.go 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. // +build linux
  2. /*
  3. Copyright 2018 The Kubernetes Authors.
  4. Licensed under the Apache License, Version 2.0 (the "License");
  5. you may not use this file except in compliance with the License.
  6. You may obtain a copy of the License at
  7. http://www.apache.org/licenses/LICENSE-2.0
  8. Unless required by applicable law or agreed to in writing, software
  9. distributed under the License is distributed on an "AS IS" BASIS,
  10. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11. See the License for the specific language governing permissions and
  12. limitations under the License.
  13. */
  14. package kuberuntime
  15. const (
  16. // Taken from lmctfy https://github.com/google/lmctfy/blob/master/lmctfy/controllers/cpu_controller.cc
  17. minShares = 2
  18. sharesPerCPU = 1024
  19. milliCPUToCPU = 1000
  20. // 100000 is equivalent to 100ms
  21. quotaPeriod = 100000
  22. minQuotaPeriod = 1000
  23. )
  24. // milliCPUToShares converts milliCPU to CPU shares
  25. func milliCPUToShares(milliCPU int64) int64 {
  26. if milliCPU == 0 {
  27. // Return 2 here to really match kernel default for zero milliCPU.
  28. return minShares
  29. }
  30. // Conceptually (milliCPU / milliCPUToCPU) * sharesPerCPU, but factored to improve rounding.
  31. shares := (milliCPU * sharesPerCPU) / milliCPUToCPU
  32. if shares < minShares {
  33. return minShares
  34. }
  35. return shares
  36. }
  37. // milliCPUToQuota converts milliCPU to CFS quota and period values
  38. func milliCPUToQuota(milliCPU int64, period int64) (quota int64) {
  39. // CFS quota is measured in two values:
  40. // - cfs_period_us=100ms (the amount of time to measure usage across)
  41. // - cfs_quota=20ms (the amount of cpu time allowed to be used across a period)
  42. // so in the above example, you are limited to 20% of a single CPU
  43. // for multi-cpu environments, you just scale equivalent amounts
  44. // see https://www.kernel.org/doc/Documentation/scheduler/sched-bwc.txt for details
  45. if milliCPU == 0 {
  46. return
  47. }
  48. // we then convert your milliCPU to a value normalized over a period
  49. quota = (milliCPU * period) / milliCPUToCPU
  50. // quota needs to be a minimum of 1ms.
  51. if quota < minQuotaPeriod {
  52. quota = minQuotaPeriod
  53. }
  54. return
  55. }