...

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 2021 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  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  //
    15  
    16  package fusedev
    17  
    18  import (
    19  	"bufio"
    20  	"fmt"
    21  	"os"
    22  	"strings"
    23  
    24  	"github.com/pingcap/errors"
    25  )
    26  
    27  // GrantAccess appends 'c 10:229 rwm' to devices.allow
    28  func GrantAccess() error {
    29  	pid := os.Getpid()
    30  	cgroupPath := fmt.Sprintf("/proc/%d/cgroup", pid)
    31  
    32  	cgroupFile, err := os.Open(cgroupPath)
    33  	if err != nil {
    34  		return err
    35  	}
    36  	defer cgroupFile.Close()
    37  
    38  	// TODO: encapsulate these logic with chaos-daemon StressChaos part
    39  	cgroupScanner := bufio.NewScanner(cgroupFile)
    40  	var deviceCgroupPath string
    41  	for cgroupScanner.Scan() {
    42  		var (
    43  			text  = cgroupScanner.Text()
    44  			parts = strings.SplitN(text, ":", 3)
    45  		)
    46  		if len(parts) < 3 {
    47  			return errors.Errorf("invalid cgroup entry: %q", text)
    48  		}
    49  
    50  		if parts[1] == "devices" {
    51  			deviceCgroupPath = parts[2]
    52  		}
    53  	}
    54  
    55  	if err := cgroupScanner.Err(); err != nil {
    56  		return err
    57  	}
    58  
    59  	if len(deviceCgroupPath) == 0 {
    60  		return errors.New("fail to find device cgroup")
    61  	}
    62  
    63  	// It's hard to use /pkg/chaosdaemon/cgroups to wrap this logic.
    64  	deviceCgroupPath = "/host-sys/fs/cgroup/devices" + deviceCgroupPath + "/devices.allow"
    65  	f, err := os.OpenFile(deviceCgroupPath, os.O_WRONLY, 0)
    66  	if err != nil {
    67  		return err
    68  	}
    69  	defer f.Close()
    70  
    71  	// 10, 229 according to https://www.kernel.org/doc/Documentation/admin-guide/devices.txt
    72  	content := "c 10:229 rwm"
    73  	_, err = f.WriteString(content)
    74  	return err
    75  }
    76