本文整理匯總了Golang中github.com/CiscoCloud/distributive/wrkutils.GenericError函數的典型用法代碼示例。如果您正苦於以下問題:Golang GenericError函數的具體用法?Golang GenericError怎麽用?Golang GenericError使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。
在下文中一共展示了GenericError函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。
示例1: phpConfig
// phpConfig checks the value of a PHP configuration variable
func phpConfig(parameters []string) (exitCode int, exitMessage string) {
// getPHPVariable returns the value of a PHP configuration value as a string
// or just "" if it doesn't exist
getPHPVariable := func(name string) (val string) {
quote := func(str string) string {
return "\"" + str + "\""
}
// php -r 'echo get_cfg_var("default_mimetype");
echo := fmt.Sprintf("echo get_cfg_var(%s);", quote(name))
cmd := exec.Command("php", "-r", echo)
out, err := cmd.CombinedOutput()
if err != nil {
wrkutils.ExecError(cmd, string(out), err)
}
return string(out)
}
name := parameters[0]
value := parameters[1]
actualValue := getPHPVariable(name)
if actualValue == value {
return 0, ""
} else if actualValue == "" {
msg := "PHP configuration variable not set"
return wrkutils.GenericError(msg, value, []string{actualValue})
}
msg := "PHP variable did not match expected value"
return wrkutils.GenericError(msg, value, []string{actualValue})
}
示例2: getIPWorker
// getIPWorker(exitCode int, exitMessage string) is an abstraction of Ip4 and Ip6
func getIPWorker(name string, address string, version int) (exitCode int, exitMessage string) {
ips := getInterfaceIPs(name, version)
if tabular.StrIn(address, ips) {
return 0, ""
}
return wrkutils.GenericError("Interface does not have IP", address, ips)
}
示例3: routingTableMatch
// routingTableMatch(exitCode int, exitMessage string) constructs a Worker that returns whether or not the
// given string was found in the given column of the routing table. It is an
// astraction of routingTableDestination, routingTableInterface, and
// routingTableGateway
func routingTableMatch(col string, str string) (exitCode int, exitMessage string) {
column := routingTableColumn(col)
if tabular.StrIn(str, column) {
return 0, ""
}
return wrkutils.GenericError("Not found in routing table", str, column)
}
示例4: timersWorker
// timers(exitCode int, exitMessage string) is pure DRY for systemctlTimer and systemctlTimerLoaded
func timersWorker(unit string, all bool) (exitCode int, exitMessage string) {
timers := getTimers(all)
if tabular.StrIn(unit, timers) {
return 0, ""
}
return wrkutils.GenericError("Timer not found", unit, timers)
}
示例5: systemctlUnitFileStatus
// systemctlUnitFileStatus checks whether or not the given unit file has the
// given status: static | enabled | disabled
func systemctlUnitFileStatus(parameters []string) (exitCode int, exitMessage string) {
// getUnitFilesWithStatuses returns a pair of string slices that hold
// the name of unit files with their current statuses.
getUnitFilesWithStatuses := func() (units []string, statuses []string) {
cmd := exec.Command("systemctl", "--no-pager", "list-unit-files")
units = wrkutils.CommandColumnNoHeader(0, cmd)
cmd = exec.Command("systemctl", "--no-pager", "list-unit-files")
statuses = wrkutils.CommandColumnNoHeader(1, cmd)
// last two are empty line and junk statistics we don't care about
msg := fmt.Sprint(cmd.Args) + " didn't output enough lines"
wrkutils.IndexError(msg, 2, units)
wrkutils.IndexError(msg, 2, statuses)
return units[:len(units)-2], statuses[:len(statuses)-2]
}
unit := parameters[0]
status := parameters[1]
units, statuses := getUnitFilesWithStatuses()
var actualStatus string
// TODO check if unit could be found at all
for i, un := range units {
if un == unit {
actualStatus = statuses[i]
if actualStatus == status {
return 0, ""
}
}
}
msg := "Unit didn't have status"
return wrkutils.GenericError(msg, status, []string{actualStatus})
}
示例6: freeMemOrSwap
// freeMemOrSwap is an abstraction of freeMemory and freeSwap, which measures
// if the desired resource has a quantity free above the amount specified
func freeMemOrSwap(input string, swapOrMem string) (exitCode int, exitMessage string) {
// get numbers and units
units := wrkutils.GetByteUnits(input)
re := regexp.MustCompile(`\d+`)
amountString := re.FindString(input)
// report errors
if amountString == "" {
log.WithFields(log.Fields{
"input": input,
"regexp": re.String(),
}).Fatal("Configuration error: couldn't extract number from string")
} else if units == "" {
log.WithFields(log.Fields{
"input": input,
}).Fatal("Configuration error: couldn't extract byte units from string")
}
amount := wrkutils.ParseMyInt(amountString)
actualAmount := getSwapOrMemory("free", swapOrMem, units)
if actualAmount > amount {
return 0, ""
}
msg := "Free " + swapOrMem + " lower than defined threshold"
actualString := fmt.Sprint(actualAmount) + units
return wrkutils.GenericError(msg, input, []string{actualString})
}
示例7: groupNotFound
// groupNotFound creates generic error messages and exit codes for groupExits,
// userInGroup, and groupID
func groupNotFound(name string) (int, string) {
// get a nicely formatted list of groups that do exist
var existing []string
for _, group := range getGroups() {
existing = append(existing, group.Name)
}
return wrkutils.GenericError("Group not found", name, existing)
}
示例8: responseMatchesGeneral
// responseMatchesGeneral is an abstraction of responseMatches and
// responseMatchesInsecure that simply varies in the security of the connection
func responseMatchesGeneral(parameters []string, secure bool) (exitCode int, exitMessage string) {
urlstr := parameters[0]
re := wrkutils.ParseUserRegex(parameters[1])
body := wrkutils.URLToBytes(urlstr, secure)
if re.Match(body) {
return 0, ""
}
msg := "Response didn't match regexp"
return wrkutils.GenericError(msg, re.String(), []string{string(body)})
}
示例9: swapUsage
// swapUsage checks to see whether or not the system has a swap usage
// percentage below a certain threshold
func swapUsage(parameters []string) (exitCode int, exitMessage string) {
maxPercentUsed := wrkutils.ParseMyInt(parameters[0])
actualPercentUsed := getUsedPercent("swap")
if actualPercentUsed < float32(maxPercentUsed) {
return 0, ""
}
msg := "Swap usage above defined maximum"
slc := []string{fmt.Sprint(actualPercentUsed)}
return wrkutils.GenericError(msg, fmt.Sprint(maxPercentUsed), slc)
}
示例10: systemctlSock
// systemctlSock is an abstraction of systemctlSockPath and systemctlSockUnit,
// it reads from `systemctl list-sockets` and sees if the value is in the
// appropriate column.
func systemctlSock(value string, column string) (exitCode int, exitMessage string) {
outstr := wrkutils.CommandOutput(exec.Command("systemctl", "list-sockets"))
lines := tabular.Lines(outstr)
msg := "systemctl list-sockers didn't output enough rows"
wrkutils.IndexError(msg, len(lines)-4, lines)
unlines := tabular.Unlines(lines[:len(lines)-4])
table := tabular.SeparateOnAlignment(unlines)
values := tabular.GetColumnByHeader(column, table)
if tabular.StrIn(value, values) {
return 0, ""
}
return wrkutils.GenericError("Socket not found", value, values)
}
示例11: userInGroup
// userInGroup checks whether or not a given user is in a given group
func userInGroup(parameters []string) (exitCode int, exitMessage string) {
user := parameters[0]
group := parameters[0]
groups := getGroups()
for _, g := range groups {
if g.Name == group {
if tabular.StrIn(user, g.Users) {
return 0, ""
}
return wrkutils.GenericError("User not found in group", user, g.Users)
}
}
return groupNotFound(group)
}
示例12: commandOutputMatches
// commandOutputMatches checks to see if a command's combined output matches a
// given regexp
func commandOutputMatches(parameters []string) (exitCode int, exitMessage string) {
toExec := parameters[0]
re := wrkutils.ParseUserRegex(parameters[1])
cmd := exec.Command("bash", "-c", toExec)
out, err := cmd.CombinedOutput()
if err != nil {
wrkutils.ExecError(cmd, string(out), err)
}
if re.Match(out) {
return 0, ""
}
msg := "Command output did not match regexp"
return wrkutils.GenericError(msg, re.String(), []string{string(out)})
}
示例13: module
// module checks to see if a kernel module is installed
func module(parameters []string) (exitCode int, exitMessage string) {
// kernelModules returns a list of all modules that are currently loaded
// TODO just read from /proc/modules
kernelModules := func() (modules []string) {
cmd := exec.Command("/sbin/lsmod")
return wrkutils.CommandColumnNoHeader(0, cmd)
}
name := parameters[0]
modules := kernelModules()
if tabular.StrIn(name, modules) {
return 0, ""
}
return wrkutils.GenericError("Module is not loaded", name, modules)
}
示例14: permissions
// permissions checks to see if a file's octal permissions match the given set
func permissions(parameters []string) (exitCode int, exitMessage string) {
path := parameters[0]
givenMode := parameters[1]
finfo, err := os.Stat(path)
if err != nil {
wrkutils.CouldntReadError(path, err)
}
actualMode := fmt.Sprint(finfo.Mode().Perm()) // -rwxrw-r-- format
if actualMode == givenMode {
return 0, ""
}
msg := "File modes did not match"
return wrkutils.GenericError(msg, givenMode, []string{actualMode})
}
示例15: temp
// temp parses the output of lm_sensors and determines if Core 0 (all cores) are
// over a certain threshold as specified in the JSON.
func temp(parameters []string) (exitCode int, exitMessage string) {
// TODO: check for negative, outrageously high temperatures
// allCoreTemps returns the temperature of each core
allCoreTemps := func() (temps []int) {
cmd := exec.Command("sensors")
out, err := cmd.CombinedOutput()
outstr := string(out)
wrkutils.ExecError(cmd, outstr, err)
restr := `Core\s\d+:\s+[\+\-](?P<temp>\d+)\.*\d*°C`
re := regexp.MustCompile(restr)
for _, line := range regexp.MustCompile(`\n+`).Split(outstr, -1) {
if re.MatchString(line) {
// submatch captures only the integer part of the temperature
matchDict := wrkutils.SubmatchMap(re, line)
if _, ok := matchDict["temp"]; !ok {
log.WithFields(log.Fields{
"regexp": re.String(),
"matchDict": matchDict,
"output": outstr,
}).Fatal("Couldn't find any temperatures in `sensors` output")
}
tempInt64, err := strconv.ParseInt(matchDict["temp"], 10, 64)
if err != nil {
log.WithFields(log.Fields{
"regexp": re.String(),
"matchDict": matchDict,
"output": outstr,
"error": err.Error(),
}).Fatal("Couldn't parse integer from `sensors` output")
}
temps = append(temps, int(tempInt64))
}
}
return temps
}
// getCoreTemp returns an integer temperature for a certain core
getCoreTemp := func(core int) (temp int) {
temps := allCoreTemps()
wrkutils.IndexError("No such core available", core, temps)
return temps[core]
}
max := wrkutils.ParseMyInt(parameters[0])
temp := getCoreTemp(0)
if temp < max {
return 0, ""
}
msg := "Core temp exceeds defined maximum"
return wrkutils.GenericError(msg, max, []string{fmt.Sprint(temp)})
}