github.com/u-root/u-root@v7.0.1-0.20200915234505-ad7babab0a8e+incompatible/pkg/checker/checker.go (about)

     1  // Copyright 2017-2019 the u-root Authors. All rights reserved
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package checker
     6  
     7  import "fmt"
     8  
     9  // Checker is the type of checking functions
    10  type Checker func() error
    11  
    12  // Remediator is the type of remediation functions
    13  type Remediator func() error
    14  
    15  // Check is a type that implements a netboot check
    16  type Check struct {
    17  	Name        string
    18  	Run         Checker
    19  	Remediate   Remediator
    20  	StopOnError bool
    21  }
    22  
    23  // Run runs the checks and remediations from a check list, in order, and prints the
    24  // check and remediation status.
    25  func Run(checklist []Check) error {
    26  	for idx, check := range checklist {
    27  		fmt.Printf(green("#%d", idx+1)+" Running check '%s'.. ", check.Name)
    28  		if checkErr := check.Run(); checkErr != nil {
    29  			fmt.Println(red("failed: %v", checkErr))
    30  			if check.Remediate != nil {
    31  				fmt.Println(yellow("  -> running remediation"))
    32  				if remErr := check.Remediate(); remErr != nil {
    33  					fmt.Print(red("     Remediation for '%s' failed: %v\n", check.Name, remErr))
    34  					if check.StopOnError {
    35  						fmt.Println("Exiting")
    36  						return remErr
    37  					}
    38  				} else {
    39  					fmt.Printf("     Remediation for '%s' succeeded\n", check.Name)
    40  				}
    41  			} else {
    42  				msg := fmt.Sprintf(" -> no remediation found for %s", check.Name)
    43  				if check.StopOnError {
    44  					fmt.Println(yellow(msg + ", stop on error requested. Exiting."))
    45  					return checkErr
    46  				}
    47  				fmt.Println(yellow(msg + ", skipping."))
    48  			}
    49  		} else {
    50  			fmt.Println(green("OK"))
    51  		}
    52  	}
    53  	return nil
    54  }