本文整理汇总了Golang中github.com/cloudfoundry/bosh-agent/internal/github.com/cloudfoundry/bosh-utils/errors.WrapError函数的典型用法代码示例。如果您正苦于以下问题:Golang WrapError函数的具体用法?Golang WrapError怎么用?Golang WrapError使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了WrapError函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Golang代码示例。
示例1: SetupNetworking
func (net UbuntuNetManager) SetupNetworking(networks boshsettings.Networks, errCh chan error) error {
staticConfigs, dhcpConfigs, dnsServers, err := net.ComputeNetworkConfig(networks)
if err != nil {
return bosherr.WrapError(err, "Computing network configuration")
}
interfacesChanged, err := net.writeNetworkInterfaces(dhcpConfigs, staticConfigs, dnsServers)
if err != nil {
return bosherr.WrapError(err, "Writing network configuration")
}
dhcpChanged := false
if len(dhcpConfigs) > 0 {
dhcpChanged, err = net.writeDHCPConfiguration(dnsServers)
if err != nil {
return err
}
}
if interfacesChanged || dhcpChanged {
err = net.removeDhcpDNSConfiguration()
if err != nil {
return err
}
net.restartNetworkingInterfaces()
}
net.broadcastIps(staticConfigs, dhcpConfigs, errCh)
return nil
}
开发者ID:viovanov,项目名称:bosh-agent,代码行数:31,代码来源:ubuntu_net_manager.go
示例2: partitionEphemeralDisk
func (p linux) partitionEphemeralDisk(realPath string) (string, string, error) {
p.logger.Info(logTag, "Creating swap & ephemeral partitions on ephemeral disk...")
p.logger.Debug(logTag, "Getting device size of `%s'", realPath)
diskSizeInBytes, err := p.diskManager.GetPartitioner().GetDeviceSizeInBytes(realPath)
if err != nil {
return "", "", bosherr.WrapError(err, "Getting device size")
}
p.logger.Debug(logTag, "Calculating ephemeral disk partition sizes of `%s' with total disk size %dB", realPath, diskSizeInBytes)
swapSizeInBytes, linuxSizeInBytes, err := p.calculateEphemeralDiskPartitionSizes(diskSizeInBytes)
if err != nil {
return "", "", bosherr.WrapError(err, "Calculating partition sizes")
}
partitions := []boshdisk.Partition{
{SizeInBytes: swapSizeInBytes, Type: boshdisk.PartitionTypeSwap},
{SizeInBytes: linuxSizeInBytes, Type: boshdisk.PartitionTypeLinux},
}
p.logger.Info(logTag, "Partitioning ephemeral disk `%s' with %s", realPath, partitions)
err = p.diskManager.GetPartitioner().Partition(realPath, partitions)
if err != nil {
return "", "", bosherr.WrapErrorf(err, "Partitioning ephemeral disk `%s'", realPath)
}
swapPartitionPath := realPath + "1"
dataPartitionPath := realPath + "2"
return swapPartitionPath, dataPartitionPath, nil
}
开发者ID:tacgomes,项目名称:bosh-agent,代码行数:29,代码来源:linux_platform.go
示例3: handleSyslogMsg
func (a Agent) handleSyslogMsg(errCh chan error) boshsyslog.CallbackFunc {
return func(msg boshsyslog.Msg) {
alertAdapter := boshalert.NewSSHAdapter(
msg,
a.settingsService,
a.uuidGenerator,
a.timeService,
a.logger,
)
if alertAdapter.IsIgnorable() {
a.logger.Debug(agentLogTag, "Ignored ssh event: ", msg.Content)
return
}
alert, err := alertAdapter.Alert()
if err != nil {
errCh <- bosherr.WrapError(err, "Adapting SSH alert")
}
err = a.mbusHandler.Send(boshhandler.HealthMonitor, boshhandler.Alert, alert)
if err != nil {
errCh <- bosherr.WrapError(err, "Sending SSH alert")
}
}
}
开发者ID:tacgomes,项目名称:bosh-agent,代码行数:25,代码来源:agent.go
示例4: Start
func (h *natsHandler) Start(handlerFunc boshhandler.Func) error {
h.RegisterAdditionalFunc(handlerFunc)
connProvider, err := h.getConnectionInfo()
if err != nil {
return bosherr.WrapError(err, "Getting connection info")
}
err = h.client.Connect(connProvider)
if err != nil {
return bosherr.WrapError(err, "Connecting")
}
settings := h.settingsService.GetSettings()
subject := fmt.Sprintf("agent.%s", settings.AgentID)
h.logger.Info(h.logTag, "Subscribing to %s", subject)
_, err = h.client.Subscribe(subject, func(natsMsg *yagnats.Message) {
for _, handlerFunc := range h.handlerFuncs {
h.handleNatsMsg(natsMsg, handlerFunc)
}
})
if err != nil {
return bosherr.WrapErrorf(err, "Subscribing to %s", subject)
}
return nil
}
开发者ID:viovanov,项目名称:bosh-agent,代码行数:31,代码来源:nats_handler.go
示例5: marshalResponse
func marshalResponse(response Response, maxResponseLength int, logger boshlog.Logger) ([]byte, error) {
respJSON, err := json.Marshal(response)
if err != nil {
logger.Error(mbusHandlerLogTag, "Failed to marshal response: %s", err.Error())
return respJSON, bosherr.WrapError(err, "Marshalling JSON response")
}
if maxResponseLength == UnlimitedResponseLength {
return respJSON, nil
}
if len(respJSON) > maxResponseLength {
respJSON, err = json.Marshal(response.Shorten())
if err != nil {
logger.Error(mbusHandlerLogTag, "Failed to marshal response: %s", err.Error())
return respJSON, bosherr.WrapError(err, "Marshalling JSON response")
}
}
if len(respJSON) > maxResponseLength {
respJSON, err = BuildErrorWithJSON(responseMaxLengthErrMsg, logger)
if err != nil {
logger.Error(mbusHandlerLogTag, "Failed to build 'max length exceeded' response: %s", err.Error())
return respJSON, bosherr.WrapError(err, "Building error")
}
}
return respJSON, nil
}
开发者ID:viovanov,项目名称:bosh-agent,代码行数:29,代码来源:perform_handler_with_json.go
示例6: writeNetworkInterfaces
func (net UbuntuNetManager) writeNetworkInterfaces(dhcpConfigs DHCPInterfaceConfigurations, staticConfigs StaticInterfaceConfigurations, dnsServers []string) (bool, error) {
sort.Stable(dhcpConfigs)
sort.Stable(staticConfigs)
networkInterfaceValues := networkInterfaceConfig{
DHCPConfigs: dhcpConfigs,
StaticConfigs: staticConfigs,
HasDNSNameServers: true,
DNSServers: dnsServers,
}
buffer := bytes.NewBuffer([]byte{})
t := template.Must(template.New("network-interfaces").Parse(networkInterfacesTemplate))
err := t.Execute(buffer, networkInterfaceValues)
if err != nil {
return false, bosherr.WrapError(err, "Generating config from template")
}
changed, err := net.fs.ConvergeFileContents("/etc/network/interfaces", buffer.Bytes())
if err != nil {
return changed, bosherr.WrapError(err, "Writing to /etc/network/interfaces")
}
return changed, nil
}
开发者ID:viovanov,项目名称:bosh-agent,代码行数:27,代码来源:ubuntu_net_manager.go
示例7: handleJobFailure
func (a Agent) handleJobFailure(errCh chan error) boshjobsuper.JobFailureHandler {
return func(monitAlert boshalert.MonitAlert) error {
alertAdapter := boshalert.NewMonitAdapter(monitAlert, a.settingsService, a.timeService)
if alertAdapter.IsIgnorable() {
a.logger.Debug(agentLogTag, "Ignored monit event: ", monitAlert.Event)
return nil
}
severity, found := alertAdapter.Severity()
if !found {
a.logger.Error(agentLogTag, "Unknown monit event name `%s', using default severity %d", monitAlert.Event, severity)
}
alert, err := alertAdapter.Alert()
if err != nil {
errCh <- bosherr.WrapError(err, "Adapting monit alert")
}
err = a.mbusHandler.Send(boshhandler.HealthMonitor, boshhandler.Alert, alert)
if err != nil {
errCh <- bosherr.WrapError(err, "Sending monit alert")
}
return nil
}
}
开发者ID:tacgomes,项目名称:bosh-agent,代码行数:26,代码来源:agent.go
示例8: Run
func (a DrainAction) Run(drainType DrainType, newSpecs ...boshas.V1ApplySpec) (int, error) {
currentSpec, err := a.specService.Get()
if err != nil {
return 0, bosherr.WrapError(err, "Getting current spec")
}
params, err := a.determineParams(drainType, currentSpec, newSpecs)
if err != nil {
return 0, err
}
a.logger.Debug(a.logTag, "Unmonitoring")
err = a.jobSupervisor.Unmonitor()
if err != nil {
return 0, bosherr.WrapError(err, "Unmonitoring services")
}
var scripts []boshscript.Script
for _, job := range currentSpec.Jobs() {
script := a.jobScriptProvider.NewDrainScript(job.BundleName(), params)
scripts = append(scripts, script)
}
parallelScript := a.jobScriptProvider.NewParallelScript("drain", scripts)
return 0, parallelScript.Run()
}
开发者ID:pivotal-nader-ziada,项目名称:bosh-agent,代码行数:29,代码来源:drain.go
示例9: Run
func (a ApplyAction) Run(desiredSpec boshas.V1ApplySpec) (string, error) {
settings := a.settingsService.GetSettings()
resolvedDesiredSpec, err := a.specService.PopulateDHCPNetworks(desiredSpec, settings)
if err != nil {
return "", bosherr.WrapError(err, "Resolving dynamic networks")
}
if desiredSpec.ConfigurationHash != "" {
currentSpec, err := a.specService.Get()
if err != nil {
return "", bosherr.WrapError(err, "Getting current spec")
}
err = a.applier.Apply(currentSpec, resolvedDesiredSpec)
if err != nil {
return "", bosherr.WrapError(err, "Applying")
}
}
err = a.specService.Set(resolvedDesiredSpec)
if err != nil {
return "", bosherr.WrapError(err, "Persisting apply spec")
}
return "applied", nil
}
开发者ID:viovanov,项目名称:bosh-agent,代码行数:27,代码来源:apply.go
示例10: Run
func (a MountDiskAction) Run(diskCid string) (interface{}, error) {
err := a.settingsService.LoadSettings()
if err != nil {
return nil, bosherr.WrapError(err, "Refreshing the settings")
}
settings := a.settingsService.GetSettings()
diskSettings, found := settings.PersistentDiskSettings(diskCid)
if !found {
return nil, bosherr.Errorf("Persistent disk with volume id '%s' could not be found", diskCid)
}
mountPoint := a.dirProvider.StoreDir()
isMountPoint, err := a.mountPoints.IsMountPoint(mountPoint)
if err != nil {
return nil, bosherr.WrapError(err, "Checking mount point")
}
if isMountPoint {
mountPoint = a.dirProvider.StoreMigrationDir()
}
err = a.diskMounter.MountPersistentDisk(diskSettings, mountPoint)
if err != nil {
return nil, bosherr.WrapError(err, "Mounting persistent disk")
}
return map[string]string{}, nil
}
开发者ID:viovanov,项目名称:bosh-agent,代码行数:30,代码来源:mount_disk.go
示例11: Chown
func (fs *osFileSystem) Chown(path, username string) error {
fs.logger.Debug(fs.logTag, "Chown %s to user %s", path, username)
uid, err := fs.runCommand(fmt.Sprintf("id -u %s", username))
if err != nil {
return bosherr.WrapErrorf(err, "Getting user id for '%s'", username)
}
uidAsInt, err := strconv.Atoi(uid)
if err != nil {
return bosherr.WrapError(err, "Converting UID to integer")
}
gid, err := fs.runCommand(fmt.Sprintf("id -g %s", username))
if err != nil {
return bosherr.WrapErrorf(err, "Getting group id for '%s'", username)
}
gidAsInt, err := strconv.Atoi(gid)
if err != nil {
return bosherr.WrapError(err, "Converting GID to integer")
}
err = os.Chown(path, uidAsInt, gidAsInt)
if err != nil {
return bosherr.WrapError(err, "Doing Chown")
}
return nil
}
开发者ID:viovanov,项目名称:bosh-agent,代码行数:30,代码来源:os_file_system.go
示例12: setupSSH
func (a SSHAction) setupSSH(params SSHParams) (SSHResult, error) {
var result SSHResult
boshSSHPath := filepath.Join(a.dirProvider.BaseDir(), "bosh_ssh")
err := a.platform.CreateUser(params.User, params.Password, boshSSHPath)
if err != nil {
return result, bosherr.WrapError(err, "Creating user")
}
err = a.platform.AddUserToGroups(params.User, []string{boshsettings.VCAPUsername, boshsettings.AdminGroup})
if err != nil {
return result, bosherr.WrapError(err, "Adding user to groups")
}
err = a.platform.SetupSSH(params.PublicKey, params.User)
if err != nil {
return result, bosherr.WrapError(err, "Setting ssh public key")
}
settings := a.settingsService.GetSettings()
defaultIP, found := settings.Networks.DefaultIP()
if !found {
return result, errors.New("No default ip could be found")
}
result = SSHResult{
Command: "setup",
Status: "success",
IP: defaultIP,
}
return result, nil
}
开发者ID:viovanov,项目名称:bosh-agent,代码行数:35,代码来源:ssh.go
示例13: findRootDevicePath
func (p linux) findRootDevicePath() (string, error) {
mounts, err := p.diskManager.GetMountsSearcher().SearchMounts()
if err != nil {
return "", bosherr.WrapError(err, "Searching mounts")
}
for _, mount := range mounts {
if mount.MountPoint == "/" && strings.HasPrefix(mount.PartitionPath, "/dev/") {
p.logger.Debug(logTag, "Found root partition: `%s'", mount.PartitionPath)
stdout, _, _, err := p.cmdRunner.RunCommand("readlink", "-f", mount.PartitionPath)
if err != nil {
return "", bosherr.WrapError(err, "Shelling out to readlink")
}
rootPartition := strings.Trim(stdout, "\n")
p.logger.Debug(logTag, "Symlink is: `%s'", rootPartition)
validRootPartition := regexp.MustCompile(`^/dev/[a-z]+1$`)
if !validRootPartition.MatchString(rootPartition) {
return "", bosherr.Error("Root partition is not the first partition")
}
return strings.Trim(rootPartition, "1"), nil
}
}
return "", bosherr.Error("Getting root partition device")
}
开发者ID:tacgomes,项目名称:bosh-agent,代码行数:29,代码来源:linux_platform.go
示例14: GetInstanceID
func (ms httpMetadataService) GetInstanceID() (string, error) {
err := ms.ensureMinimalNetworkSetup()
if err != nil {
return "", err
}
url := fmt.Sprintf("%s/latest/meta-data/instance-id", ms.metadataHost)
resp, err := http.Get(url)
if err != nil {
return "", bosherr.WrapError(err, "Getting instance id from url")
}
defer func() {
if err := resp.Body.Close(); err != nil {
ms.logger.Warn(ms.logTag, "Failed to close response body when getting instance id: %s", err.Error())
}
}()
bytes, err := ioutil.ReadAll(resp.Body)
if err != nil {
return "", bosherr.WrapError(err, "Reading instance id response body")
}
return string(bytes), nil
}
开发者ID:viovanov,项目名称:bosh-agent,代码行数:25,代码来源:http_metadata_service.go
示例15: getUserData
func (ms httpMetadataService) getUserData() (UserDataContentsType, error) {
var userData UserDataContentsType
err := ms.ensureMinimalNetworkSetup()
if err != nil {
return userData, err
}
userDataURL := fmt.Sprintf("%s/latest/user-data", ms.metadataHost)
userDataResp, err := http.Get(userDataURL)
if err != nil {
return userData, bosherr.WrapError(err, "Getting user data from url")
}
defer func() {
if err := userDataResp.Body.Close(); err != nil {
ms.logger.Warn(ms.logTag, "Failed to close response body when getting user data: %s", err.Error())
}
}()
userDataBytes, err := ioutil.ReadAll(userDataResp.Body)
if err != nil {
return userData, bosherr.WrapError(err, "Reading user data response body")
}
err = json.Unmarshal(userDataBytes, &userData)
if err != nil {
return userData, bosherr.WrapError(err, "Unmarshalling user data")
}
return userData, nil
}
开发者ID:viovanov,项目名称:bosh-agent,代码行数:32,代码来源:http_metadata_service.go
示例16: detectMacAddresses
func (net centosNetManager) detectMacAddresses() (map[string]string, error) {
addresses := map[string]string{}
filePaths, err := net.fs.Glob("/sys/class/net/*")
if err != nil {
return addresses, bosherr.WrapError(err, "Getting file list from /sys/class/net")
}
var macAddress string
for _, filePath := range filePaths {
isPhysicalDevice := net.fs.FileExists(filepath.Join(filePath, "device"))
if isPhysicalDevice {
macAddress, err = net.fs.ReadFileString(filepath.Join(filePath, "address"))
if err != nil {
return addresses, bosherr.WrapError(err, "Reading mac address from file")
}
macAddress = strings.Trim(macAddress, "\n")
interfaceName := filepath.Base(filePath)
addresses[macAddress] = interfaceName
}
}
return addresses, nil
}
开发者ID:viovanov,项目名称:bosh-agent,代码行数:27,代码来源:centos_net_manager.go
示例17: MigratePersistentDisk
func (p linux) MigratePersistentDisk(fromMountPoint, toMountPoint string) (err error) {
p.logger.Debug(logTag, "Migrating persistent disk %v to %v", fromMountPoint, toMountPoint)
err = p.diskManager.GetMounter().RemountAsReadonly(fromMountPoint)
if err != nil {
err = bosherr.WrapError(err, "Remounting persistent disk as readonly")
return
}
// Golang does not implement a file copy that would allow us to preserve dates...
// So we have to shell out to tar to perform the copy instead of delegating to the FileSystem
tarCopy := fmt.Sprintf("(tar -C %s -cf - .) | (tar -C %s -xpf -)", fromMountPoint, toMountPoint)
_, _, _, err = p.cmdRunner.RunCommand("sh", "-c", tarCopy)
if err != nil {
err = bosherr.WrapError(err, "Copying files from old disk to new disk")
return
}
_, err = p.diskManager.GetMounter().Unmount(fromMountPoint)
if err != nil {
err = bosherr.WrapError(err, "Unmounting old persistent disk")
return
}
err = p.diskManager.GetMounter().Remount(toMountPoint, fromMountPoint)
if err != nil {
err = bosherr.WrapError(err, "Remounting new disk on original mountpoint")
}
return
}
开发者ID:tacgomes,项目名称:bosh-agent,代码行数:30,代码来源:linux_platform.go
示例18: Run
func (r concreteRunner) Run(action Action, payloadBytes []byte) (value interface{}, err error) {
payloadArgs, err := r.extractJSONArguments(payloadBytes)
if err != nil {
err = bosherr.WrapError(err, "Extracting json arguments")
return
}
actionValue := reflect.ValueOf(action)
runMethodValue := actionValue.MethodByName("Run")
if runMethodValue.Kind() != reflect.Func {
err = bosherr.Error("Run method not found")
return
}
runMethodType := runMethodValue.Type()
if r.invalidReturnTypes(runMethodType) {
err = bosherr.Error("Run method should return a value and an error")
return
}
methodArgs, err := r.extractMethodArgs(runMethodType, payloadArgs)
if err != nil {
err = bosherr.WrapError(err, "Extracting method arguments from payload")
return
}
values := runMethodValue.Call(methodArgs)
return r.extractReturns(values)
}
开发者ID:viovanov,项目名称:bosh-agent,代码行数:29,代码来源:runner.go
示例19: SetupHostname
func (p linux) SetupHostname(hostname string) (err error) {
_, _, _, err = p.cmdRunner.RunCommand("hostname", hostname)
if err != nil {
err = bosherr.WrapError(err, "Shelling out to hostname")
return
}
err = p.fs.WriteFileString("/etc/hostname", hostname)
if err != nil {
err = bosherr.WrapError(err, "Writing /etc/hostname")
return
}
buffer := bytes.NewBuffer([]byte{})
t := template.Must(template.New("etc-hosts").Parse(etcHostsTemplate))
err = t.Execute(buffer, hostname)
if err != nil {
err = bosherr.WrapError(err, "Generating config from template")
return
}
err = p.fs.WriteFile("/etc/hosts", buffer.Bytes())
if err != nil {
err = bosherr.WrapError(err, "Writing to /etc/hosts")
}
return
}
开发者ID:tacgomes,项目名称:bosh-agent,代码行数:28,代码来源:linux_platform.go
示例20: loadFromDiskPath
func (ms *configDriveMetadataService) loadFromDiskPath(diskPath string) error {
contentPaths := []string{ms.metaDataFilePath, ms.userDataFilePath}
contents, err := ms.platform.GetFilesContentsFromDisk(diskPath, contentPaths)
if err != nil {
return bosherr.WrapError(err, "Reading files on config drive")
}
var metadata MetadataContentsType
err = json.Unmarshal(contents[0], &metadata)
if err != nil {
return bosherr.WrapError(err, "Parsing config drive metadata from meta_data.json")
}
ms.metaDataContents = metadata
var userdata UserDataContentsType
err = json.Unmarshal(contents[1], &userdata)
if err != nil {
return bosherr.WrapError(err, "Parsing config drive metadata from user_data")
}
ms.userDataContents = userdata
return nil
}
开发者ID:viovanov,项目名称:bosh-agent,代码行数:28,代码来源:config_drive_metadata_service.go
注:本文中的github.com/cloudfoundry/bosh-agent/internal/github.com/cloudfoundry/bosh-utils/errors.WrapError函数示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论