github.com/fafucoder/cilium@v1.6.11/pkg/modules/modules.go (about)

     1  // Copyright 2019 Authors of Cilium
     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  package modules
    16  
    17  import (
    18  	"fmt"
    19  
    20  	"github.com/cilium/cilium/pkg/command/exec"
    21  	"github.com/cilium/cilium/pkg/defaults"
    22  	"github.com/cilium/cilium/pkg/set"
    23  )
    24  
    25  // ModulesManager is a manager which stores information about loaded modules
    26  // and provides a search operation.
    27  type ModulesManager struct {
    28  	modulesList []string
    29  }
    30  
    31  // Init initializes the internal modules information store of modules manager.
    32  func (m *ModulesManager) Init() error {
    33  	modulesList, err := listModules()
    34  	if err != nil {
    35  		return err
    36  	}
    37  	m.modulesList = modulesList
    38  	return nil
    39  }
    40  
    41  // FindModules checks whether the given kernel modules are loaded and also
    42  // returns a slice with names of modules which are not loaded.
    43  func (m *ModulesManager) FindModules(expectedNames ...string) (bool, []string) {
    44  	return set.SliceSubsetOf(expectedNames, m.modulesList)
    45  }
    46  
    47  // FindOrLoadModules checks whether the given kernel modules are loaded and
    48  // tries to load those which are not.
    49  func (m *ModulesManager) FindOrLoadModules(expectedNames ...string) error {
    50  	found, diff := m.FindModules(expectedNames...)
    51  	if found {
    52  		return nil
    53  	}
    54  	for _, unloadedModule := range diff {
    55  		if _, err := exec.WithTimeout(
    56  			defaults.ExecTimeout, moduleLoader(), unloadedModule).CombinedOutput(
    57  			nil, false); err != nil {
    58  			return fmt.Errorf("could not load module %s: %s",
    59  				unloadedModule, err)
    60  		}
    61  	}
    62  	return nil
    63  }