當前位置: 首頁>>代碼示例>>Golang>>正文


Golang errors.WrapError函數代碼示例

本文整理匯總了Golang中github.com/cloudfoundry/bosh-agent/internal/github.com/cloudfoundry/bosh-utils/errors.WrapError函數的典型用法代碼示例。如果您正苦於以下問題:Golang WrapError函數的具體用法?Golang WrapError怎麽用?Golang WrapError使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。


在下文中一共展示了WrapError函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的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


注:本文中的github.com/cloudfoundry/bosh-agent/internal/github.com/cloudfoundry/bosh-utils/errors.WrapError函數示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。