This repository has been archived by the owner on May 6, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 15
/
ksm.go
540 lines (433 loc) · 10.5 KB
/
ksm.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
//
// Copyright (c) 2017 Intel Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
package main
import (
"bufio"
"errors"
"fmt"
"io/ioutil"
"os"
"os/signal"
"path/filepath"
"strconv"
"strings"
"sync"
"syscall"
"time"
)
type ksmSetting struct {
// run describes if we want KSM to be on or off.
run bool
// pagesPerScanFactor describes how many pages we want
// to scan per KSM run.
// ksmd will san N pages, where N*pagesPerScanFactor is
// equal to the number of anonymous pages.
pagesPerScanFactor int64
// scanIntervalMS is the KSM scan interval in milliseconds.
scanIntervalMS uint32
}
func anonPages() (int64, error) {
// We're going to parse meminfo
f, err := os.Open(memInfo)
if err != nil {
return -1, err
}
defer f.Close()
scan := bufio.NewScanner(f)
for scan.Scan() {
line := scan.Text()
// We only care about anonymous pages
if !strings.HasPrefix(line, "AnonPages:") {
continue
}
// Extract the before last (value) and last (unit) fields
fields := strings.Split(line, " ")
value := fields[len(fields)-2]
totalMemory, err := strconv.ParseInt(value, 10, 64)
if err != nil {
return -1, fmt.Errorf("Invalid integer")
}
// meminfo gives us kB
totalMemory *= 1024
// Fetch the system page size
pageSize := (int64)(os.Getpagesize())
nPages := totalMemory / pageSize
return nPages, nil
}
return 0, fmt.Errorf("Could not compute number of pages")
}
func (s ksmSetting) pagesToScan() (string, error) {
if s.pagesPerScanFactor == 0 {
return "", errors.New("Invalid KSM setting")
}
nPages, err := anonPages()
if err != nil {
return "", err
}
pagesToScan := nPages / s.pagesPerScanFactor
return fmt.Sprintf("%v", pagesToScan), nil
}
type ksmMode string
const (
ksmInitial ksmMode = "initial"
ksmOff ksmMode = "off"
ksmSlow ksmMode = "slow"
ksmStandard ksmMode = "standard"
ksmAggressive ksmMode = "aggressive"
ksmAuto ksmMode = "auto"
)
var ksmSettings = map[ksmMode]ksmSetting{
ksmOff: {false, 1000, 500}, // Turn KSM off
ksmSlow: {true, 500, 100}, // Every 100ms, we scan 1 page for every 500 pages available in the system
ksmStandard: {true, 100, 10}, // Every 10ms, we scan 1 page for every 100 pages available in the system
ksmAggressive: {true, 10, 1}, // Every ms, we scan 1 page for every 10 pages available in the system
}
func (k ksmMode) String() string {
switch k {
case ksmOff:
return "off"
case ksmInitial:
return "initial"
case ksmAuto:
return "auto"
}
return ""
}
func (k *ksmMode) Set(value string) error {
for _, r := range strings.Split(value, ",") {
if r == "off" {
*k = ksmOff
return nil
} else if r == "initial" {
*k = ksmInitial
return nil
} else if r == "auto" {
*k = ksmAuto
return nil
}
return fmt.Errorf("Unsupported KSM knob %v", r)
}
return nil
}
var defaultKSMRoot = "/sys/kernel/mm/ksm/"
var errKSMUnavailable = errors.New("KSM is unavailable")
var memInfo = "/proc/meminfo"
const (
ksmRunFile = "run"
ksmPagesToScan = "pages_to_scan"
ksmSleepMillisec = "sleep_millisecs"
ksmStart = "1"
ksmStop = "0"
defaultKSMMode = ksmAuto
)
type sysfsAttribute struct {
path string
file *os.File
}
func (attr *sysfsAttribute) open() error {
file, err := os.OpenFile(attr.path, os.O_RDWR|syscall.O_NONBLOCK, 0660)
attr.file = file
return err
}
func (attr *sysfsAttribute) close() error {
err := attr.file.Close()
attr.file = nil
return err
}
func (attr *sysfsAttribute) read() (string, error) {
_, err := attr.file.Seek(0, os.SEEK_SET)
if err != nil {
return "", err
}
data, err := ioutil.ReadAll(attr.file)
if err != nil {
return "", err
}
return string(data), nil
}
func (attr *sysfsAttribute) write(value string) error {
_, err := attr.file.Seek(0, os.SEEK_SET)
if err != nil {
return err
}
err = attr.file.Truncate(0)
if err != nil {
return err
}
_, err = attr.file.WriteString(value)
return err
}
type ksm struct {
root string
run sysfsAttribute
pagesToScan sysfsAttribute
sleepInterval sysfsAttribute
initialized bool
initialPagesToScan string
initialSleepInterval string
initialKSMRun string
currentKnob ksmMode
throttling bool
kickChannel chan bool
sync.Mutex
}
func (k *ksm) isAvailable() error {
info, err := os.Stat(k.root)
if err != nil || !info.IsDir() {
return fmt.Errorf("%s is not available", k.root)
}
return nil
}
func newKSM(root string) (*ksm, error) {
var err error
var k ksm
k.initialized = false
k.throttling = false
k.root = root
if root == "" {
return nil, errors.New("Invalid KSM root")
}
if err := k.isAvailable(); err != nil {
return nil, err
}
k.pagesToScan = sysfsAttribute{
path: filepath.Join(k.root, ksmPagesToScan),
}
k.sleepInterval = sysfsAttribute{
path: filepath.Join(k.root, ksmSleepMillisec),
}
k.run = sysfsAttribute{
path: filepath.Join(k.root, ksmRunFile),
}
defer func(err error) {
if err != nil {
_ = k.run.close()
_ = k.sleepInterval.close()
_ = k.pagesToScan.close()
}
}(err)
if err := k.run.open(); err != nil {
return nil, err
}
if err := k.sleepInterval.open(); err != nil {
return nil, err
}
if err := k.pagesToScan.open(); err != nil {
return nil, err
}
k.initialPagesToScan, err = k.pagesToScan.read()
if err != nil {
return nil, err
}
k.initialSleepInterval, err = k.sleepInterval.read()
if err != nil {
return nil, err
}
k.initialKSMRun, err = k.run.read()
if err != nil {
return nil, err
}
k.initialized = true
k.kickChannel = make(chan bool)
return &k, nil
}
func startKSM(root string, mode ksmMode) (*ksm, error) {
k, err := newKSM(root)
if err != nil {
return k, err
}
// We just no-op if going for initial settings
if mode != ksmInitial {
// We want to catch termination to restore the initial sysfs values
c := make(chan os.Signal, 2)
signal.Notify(c, os.Interrupt, syscall.SIGTERM)
go func() {
<-c
_ = k.restore()
os.Exit(0)
}()
if mode == ksmAuto {
k.throttle()
} else {
setting, ok := ksmSettings[mode]
if !ok {
return k, fmt.Errorf("Invalide KSM mode %v", mode)
}
if err := k.tune(setting); err != nil {
return k, err
}
}
}
return k, nil
}
// restoreSysFS is unlocked. You should take the ksm lock before calling it.
func (k *ksm) restoreSysFS() error {
var err error
if !k.initialized {
return errKSMUnavailable
}
if err = k.pagesToScan.write(k.initialPagesToScan); err != nil {
return err
}
if err = k.sleepInterval.write(k.initialSleepInterval); err != nil {
return err
}
return k.run.write(k.initialKSMRun)
}
func (k *ksm) restore() error {
var err error
k.Lock()
defer k.Unlock()
if !k.initialized {
return errors.New("KSM is unavailable")
}
if err = k.restoreSysFS(); err != nil {
return err
}
if err := k.run.close(); err != nil {
return err
}
if err := k.sleepInterval.close(); err != nil {
return err
}
if err := k.pagesToScan.close(); err != nil {
return err
}
k.initialized = false
return nil
}
func (k *ksm) tune(s ksmSetting) error {
k.Lock()
defer k.Unlock()
if !k.initialized {
return errKSMUnavailable
}
if !s.run {
return k.run.write(ksmStop)
}
newPagesToScan, err := s.pagesToScan()
if err != nil {
return err
}
if err = k.run.write(ksmStop); err != nil {
return err
}
if err = k.pagesToScan.write(newPagesToScan); err != nil {
return err
}
if err = k.sleepInterval.write(fmt.Sprintf("%v", s.scanIntervalMS)); err != nil {
return err
}
return k.run.write(ksmStart)
}
type ksmThrottleInterval struct {
interval time.Duration
nextKnob ksmMode
}
var ksmAggressiveInterval = 30 * time.Second
var ksmStandardInterval = 120 * time.Second
var ksmSlowInterval = 120 * time.Second
var ksmThrottleIntervals = map[ksmMode]ksmThrottleInterval{
ksmAggressive: {
// From aggressive: move to standard and wait 120s
interval: ksmStandardInterval,
nextKnob: ksmStandard,
},
ksmStandard: {
// From standard: move to slow and wait 120s
interval: ksmSlowInterval,
nextKnob: ksmSlow,
},
ksmSlow: {
// From slow: move to the initial settings and stop there
interval: 0,
nextKnob: ksmInitial,
},
// We should never make it here
ksmInitial: {
interval: 0, // We stay here unless a new container shows up
},
}
func (k *ksm) throttle() {
k.Lock()
defer k.Unlock()
if !k.initialized {
proxyLog.Error(errors.New("KSM is unavailable"))
return
}
k.currentKnob = ksmAggressive
k.throttling = true
go func() {
throttleTimer := time.NewTimer(ksmThrottleIntervals[k.currentKnob].interval)
for {
select {
case <-k.kickChannel:
// We got kicked, this means a new VM has been created.
// We will enter the aggressive setting until we throttle down.
_ = throttleTimer.Stop()
if err := k.tune(ksmSettings[ksmAggressive]); err != nil {
proxyLog.Error(err)
continue
}
k.Lock()
k.currentKnob = ksmAggressive
k.Unlock()
_ = throttleTimer.Reset(ksmAggressiveInterval)
case <-throttleTimer.C:
// Our throttling down timer kicked in.
// We will move down to the next knob and start the next time,
// if necessary.
var throttle = ksmThrottleIntervals[k.currentKnob]
if throttle.interval == 0 {
if throttle.nextKnob == ksmInitial {
k.Lock()
if err := k.restoreSysFS(); err != nil {
proxyLog.Error(err)
}
k.Unlock()
}
continue
}
nextKnob := ksmThrottleIntervals[k.currentKnob].nextKnob
interval := ksmThrottleIntervals[k.currentKnob].interval
if err := k.tune(ksmSettings[nextKnob]); err != nil {
proxyLog.Error(err)
continue
}
k.Lock()
k.currentKnob = nextKnob
k.Unlock()
_ = throttleTimer.Reset(interval)
}
}
}()
}
// kick gets us back to the aggressive setting
func (k *ksm) kick() {
k.Lock()
if !k.initialized {
proxyLog.Error(errors.New("KSM is unavailable"))
k.Unlock()
return
}
// If we're not throttling, we must not kick.
if !k.throttling {
k.Unlock()
return
}
k.Unlock()
k.kickChannel <- true
}