• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Golang wrkutils.GenericError函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Golang中github.com/CiscoCloud/distributive/wrkutils.GenericError函数的典型用法代码示例。如果您正苦于以下问题:Golang GenericError函数的具体用法?Golang GenericError怎么用?Golang GenericError使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了GenericError函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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})
}
开发者ID:pinterb,项目名称:distributive,代码行数:29,代码来源:misc.go


示例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)
}
开发者ID:orimarti,项目名称:distributive,代码行数:8,代码来源:network.go


示例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)
}
开发者ID:orimarti,项目名称:distributive,代码行数:11,代码来源:network.go


示例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)
}
开发者ID:pinterb,项目名称:distributive,代码行数:8,代码来源:systemctl.go


示例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})
}
开发者ID:pinterb,项目名称:distributive,代码行数:32,代码来源:systemctl.go


示例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})

}
开发者ID:pinterb,项目名称:distributive,代码行数:28,代码来源:usage.go


示例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)
}
开发者ID:pinterb,项目名称:distributive,代码行数:10,代码来源:users-and-groups.go


示例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)})
}
开发者ID:orimarti,项目名称:distributive,代码行数:12,代码来源:network.go


示例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)
}
开发者ID:pinterb,项目名称:distributive,代码行数:12,代码来源:usage.go


示例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)
}
开发者ID:pinterb,项目名称:distributive,代码行数:16,代码来源:systemctl.go


示例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)
}
开发者ID:pinterb,项目名称:distributive,代码行数:15,代码来源:users-and-groups.go


示例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)})
}
开发者ID:pinterb,项目名称:distributive,代码行数:16,代码来源:misc.go


示例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)
}
开发者ID:pinterb,项目名称:distributive,代码行数:15,代码来源:misc.go


示例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})
}
开发者ID:pinterb,项目名称:distributive,代码行数:15,代码来源:filesystem.go


示例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)})
}
开发者ID:pinterb,项目名称:distributive,代码行数:51,代码来源:misc.go


示例16: groupID

// groupID checks to see if a group of a certain name has a given integer id
func groupID(parameters []string) (exitCode int, exitMessage string) {
	name := parameters[0]
	id := wrkutils.ParseMyInt(parameters[1])
	groups := getGroups()
	for _, g := range groups {
		if g.Name == name {
			if g.ID == id {
				return 0, ""
			}
			msg := "Group does not have expected ID"
			return wrkutils.GenericError(msg, fmt.Sprint(id), []string{fmt.Sprint(g.ID)})
		}
	}
	return groupNotFound(name)
}
开发者ID:pinterb,项目名称:distributive,代码行数:16,代码来源:users-and-groups.go


示例17: systemctlService

// systemctlService checks to see if a service has a givens status
// status: active | loaded
func systemctlService(service string, activeOrLoaded string) (exitCode int, exitMessage string) {
	// cmd depends on whether we're checking active or loaded
	cmd := exec.Command("systemctl", "show", "-p", "ActiveState", service)
	if activeOrLoaded == "loaded" {
		cmd = exec.Command("systemctl", "show", "-p", "LoadState", service)
	}
	outString := wrkutils.CommandOutput(cmd)
	contained := "ActiveState=active"
	if activeOrLoaded == "loaded" {
		contained = "LoadState=loaded"
	}
	if strings.Contains(outString, contained) {
		return 0, ""
	}
	msg := "Service not " + activeOrLoaded
	return wrkutils.GenericError(msg, service, []string{outString})
}
开发者ID:pinterb,项目名称:distributive,代码行数:19,代码来源:systemctl.go


示例18: interfaceExists

// interfaceExists detects if a network interface exists,
func interfaceExists(parameters []string) (exitCode int, exitMessage string) {
	// getInterfaceNames returns the names of all network interfaces
	getInterfaceNames := func() (interfaces []string) {
		for _, iface := range getInterfaces() {
			interfaces = append(interfaces, iface.Name)
		}
		return
	}
	name := parameters[0]
	interfaces := getInterfaceNames()
	for _, iface := range interfaces {
		if iface == name {
			return 0, ""
		}
	}
	return wrkutils.GenericError("Interface does not exist", name, interfaces)
}
开发者ID:orimarti,项目名称:distributive,代码行数:18,代码来源:network.go


示例19: up

// up determines if a network interface is up and running or not
func up(parameters []string) (exitCode int, exitMessage string) {
	// getUpInterfaces returns all the names of the interfaces that are up
	getUpInterfaces := func() (interfaceNames []string) {
		for _, iface := range getInterfaces() {
			if iface.Flags&net.FlagUp != 0 {
				interfaceNames = append(interfaceNames, iface.Name)
			}
		}
		return interfaceNames

	}
	name := parameters[0]
	upInterfaces := getUpInterfaces()
	if tabular.StrIn(name, upInterfaces) {
		return 0, ""
	}
	return wrkutils.GenericError("Interface is not up", name, upInterfaces)
}
开发者ID:orimarti,项目名称:distributive,代码行数:19,代码来源:network.go


示例20: pacmanIgnore

// pacmanIgnore checks to see whether a given package is in /etc/pacman.conf's
// IgnorePkg setting
func pacmanIgnore(parameters []string) (exitCode int, exitMessage string) {
	pkg := parameters[0]
	path := "/etc/pacman.conf"
	data := wrkutils.FileToString(path)
	re := regexp.MustCompile(`[^#]IgnorePkg\s+=\s+.+`)
	find := re.FindString(data)
	var packages []string
	if find != "" {
		spl := strings.Split(find, " ")
		wrkutils.IndexError("Not enough lines in "+path, 2, spl)
		packages = spl[2:] // first two are "IgnorePkg" and "="
		if tabular.StrIn(pkg, packages) {
			return 0, ""
		}
	}
	msg := "Couldn't find package in IgnorePkg"
	return wrkutils.GenericError(msg, pkg, packages)
}
开发者ID:pinterb,项目名称:distributive,代码行数:20,代码来源:packages.go



注:本文中的github.com/CiscoCloud/distributive/wrkutils.GenericError函数示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Golang envconfig.Env类代码示例发布时间:2022-05-23
下一篇:
Golang tabular.StrIn函数代码示例发布时间:2022-05-23
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap