github.com/jk-he/cni@v0.8.1/plugins/test/noop/debug/debug.go (about)

     1  // Copyright 2016 CNI 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  // debug supports tests that use the noop plugin
    16  package debug
    17  
    18  import (
    19  	"encoding/json"
    20  	"io/ioutil"
    21  
    22  	"github.com/containernetworking/cni/pkg/skel"
    23  )
    24  
    25  const EmptyReportResultMessage = "set debug.ReportResult and call debug.WriteDebug() before calling this plugin"
    26  
    27  // Debug is used to control and record the behavior of the noop plugin
    28  type Debug struct {
    29  	// Report* fields allow the test to control the behavior of the no-op plugin
    30  	ReportResult         string
    31  	ReportError          string
    32  	ReportStderr         string
    33  	ReportVersionSupport []string
    34  	ExitWithCode         int
    35  
    36  	// Command stores the CNI command that the plugin received
    37  	Command string
    38  
    39  	// CmdArgs stores the CNI Args and Env Vars that the plugin received
    40  	CmdArgs skel.CmdArgs
    41  }
    42  
    43  // ReadDebug will return a debug file recorded by the noop plugin
    44  func ReadDebug(debugFilePath string) (*Debug, error) {
    45  	debugBytes, err := ioutil.ReadFile(debugFilePath)
    46  	if err != nil {
    47  		return nil, err
    48  	}
    49  
    50  	var debug Debug
    51  	err = json.Unmarshal(debugBytes, &debug)
    52  	if err != nil {
    53  		return nil, err
    54  	}
    55  
    56  	return &debug, nil
    57  }
    58  
    59  // WriteDebug will create a debug file to control the noop plugin
    60  func (debug *Debug) WriteDebug(debugFilePath string) error {
    61  	debugBytes, err := json.Marshal(debug)
    62  	if err != nil {
    63  		return err
    64  	}
    65  
    66  	err = ioutil.WriteFile(debugFilePath, debugBytes, 0600)
    67  	if err != nil {
    68  		return err
    69  	}
    70  
    71  	return nil
    72  }