...

Source file src/github.com/chaos-mesh/chaos-mesh/pkg/fusedev/fusedev_linux.go

Documentation: github.com/chaos-mesh/chaos-mesh/pkg/fusedev

     1  // Copyright 2020 Chaos Mesh Authors.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // See the License for the specific language governing permissions and
    12  // limitations under the License.
    13  
    14  package fusedev
    15  
    16  import (
    17  	"bufio"
    18  	"fmt"
    19  	"os"
    20  	"strings"
    21  
    22  	"github.com/pingcap/errors"
    23  )
    24  
    25  // GrantAccess appends 'c 10:229 rwm' to devices.allow
    26  func GrantAccess() error {
    27  	pid := os.Getpid()
    28  	cgroupPath := fmt.Sprintf("/proc/%d/cgroup", pid)
    29  
    30  	cgroupFile, err := os.Open(cgroupPath)
    31  	if err != nil {
    32  		return err
    33  	}
    34  	defer cgroupFile.Close()
    35  
    36  	// TODO: encapsulate these logic with chaos-daemon StressChaos part
    37  	cgroupScanner := bufio.NewScanner(cgroupFile)
    38  	var deviceCgroupPath string
    39  	for cgroupScanner.Scan() {
    40  		var (
    41  			text  = cgroupScanner.Text()
    42  			parts = strings.SplitN(text, ":", 3)
    43  		)
    44  		if len(parts) < 3 {
    45  			return errors.Errorf("invalid cgroup entry: %q", text)
    46  		}
    47  
    48  		if parts[1] == "devices" {
    49  			deviceCgroupPath = parts[2]
    50  		}
    51  	}
    52  
    53  	if err := cgroupScanner.Err(); err != nil {
    54  		return err
    55  	}
    56  
    57  	if len(deviceCgroupPath) == 0 {
    58  		return errors.Errorf("fail to find device cgroup")
    59  	}
    60  
    61  	deviceCgroupPath = "/sys/fs/cgroup/devices" + deviceCgroupPath + "/devices.allow"
    62  	f, err := os.OpenFile(deviceCgroupPath, os.O_WRONLY, 0)
    63  	if err != nil {
    64  		return err
    65  	}
    66  	defer f.Close()
    67  
    68  	// 10, 229 according to https://www.kernel.org/doc/Documentation/admin-guide/devices.txt
    69  	content := "c 10:229 rwm"
    70  	_, err = f.WriteString(content)
    71  	if err != nil {
    72  		return err
    73  	}
    74  
    75  	return nil
    76  }
    77