本文整理汇总了Golang中github.com/juju/errors.Wrap函数的典型用法代码示例。如果您正苦于以下问题:Golang Wrap函数的具体用法?Golang Wrap怎么用?Golang Wrap使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了Wrap函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: Start
// Start implements Machine.
func (m *machine) Start(args StartArgs) error {
params := NewURLParams()
params.MaybeAdd("user_data", args.UserData)
params.MaybeAdd("distro_series", args.DistroSeries)
params.MaybeAdd("hwe_kernel", args.Kernel)
params.MaybeAdd("comment", args.Comment)
result, err := m.controller.post(m.resourceURI, "deploy", params.Values)
if err != nil {
if svrErr, ok := errors.Cause(err).(ServerError); ok {
switch svrErr.StatusCode {
case http.StatusNotFound, http.StatusConflict:
return errors.Wrap(err, NewBadRequestError(svrErr.BodyMessage))
case http.StatusForbidden:
return errors.Wrap(err, NewPermissionError(svrErr.BodyMessage))
case http.StatusServiceUnavailable:
return errors.Wrap(err, NewCannotCompleteError(svrErr.BodyMessage))
}
}
return NewUnexpectedError(err)
}
machine, err := readMachine(m.controller.apiVersion, result)
if err != nil {
return errors.Trace(err)
}
m.updateFrom(machine)
return nil
}
示例2: translateControllerError
func translateControllerError(store jujuclient.ClientStore, err error) error {
if !errors.IsNotFound(err) {
return err
}
controllers, err2 := store.AllControllers()
if err2 != nil {
return err2
}
if len(controllers) == 0 {
return errors.Wrap(err, ErrNoControllersDefined)
}
return errors.Wrap(err, ErrNoCurrentController)
}
示例3: Delete
// Delete implements File.
func (f *file) Delete() error {
err := f.controller.delete(f.resourceURI)
if err != nil {
if svrErr, ok := errors.Cause(err).(ServerError); ok {
switch svrErr.StatusCode {
case http.StatusNotFound:
return errors.Wrap(err, NewNoMatchError(svrErr.BodyMessage))
case http.StatusForbidden:
return errors.Wrap(err, NewPermissionError(svrErr.BodyMessage))
}
}
return NewUnexpectedError(err)
}
return nil
}
示例4: validateModelUUID
// validateModelUUID is the common validator for the various
// apiserver components that need to check for a valid model
// UUID. An empty modelUUID means that the connection has come in at
// the root of the URL space and refers to the controller
// model.
//
// It returns the validated model UUID.
func validateModelUUID(args validateArgs) (string, error) {
ssState := args.statePool.SystemState()
if args.modelUUID == "" {
// We allow the modelUUID to be empty so that:
// TODO: server a limited API at the root (empty modelUUID)
// just the user manager and model manager are able to accept
// requests that don't require a modelUUID, like add-model.
if args.strict {
return "", errors.Trace(common.UnknownModelError(args.modelUUID))
}
return ssState.ModelUUID(), nil
}
if args.modelUUID == ssState.ModelUUID() {
return args.modelUUID, nil
}
if args.controllerModelOnly {
return "", errors.Unauthorizedf("requested model %q is not the controller model", args.modelUUID)
}
if !names.IsValidModel(args.modelUUID) {
return "", errors.Trace(common.UnknownModelError(args.modelUUID))
}
modelTag := names.NewModelTag(args.modelUUID)
if _, err := ssState.GetModel(modelTag); err != nil {
return "", errors.Wrap(err, common.UnknownModelError(args.modelUUID))
}
return args.modelUUID, nil
}
示例5: validateModelUUID
// validateModelUUID is the common validator for the various
// apiserver components that need to check for a valid model
// UUID. An empty modelUUID means that the connection has come in at
// the root of the URL space and refers to the controller
// model.
//
// It returns the validated model UUID.
func validateModelUUID(args validateArgs) (string, error) {
ssState := args.statePool.SystemState()
if args.modelUUID == "" {
// We allow the modelUUID to be empty for 2 cases
// 1) Compatibility with older clients
// 2) TODO: server a limited API at the root (empty modelUUID)
// with just the user manager and model manager
// if the connection comes over a sufficiently up to date
// login command.
if args.strict {
return "", errors.Trace(common.UnknownModelError(args.modelUUID))
}
logger.Debugf("validate model uuid: empty modelUUID")
return ssState.ModelUUID(), nil
}
if args.modelUUID == ssState.ModelUUID() {
logger.Debugf("validate model uuid: controller model - %s", args.modelUUID)
return args.modelUUID, nil
}
if args.controllerModelOnly {
return "", errors.Unauthorizedf("requested model %q is not the controller model", args.modelUUID)
}
if !names.IsValidModel(args.modelUUID) {
return "", errors.Trace(common.UnknownModelError(args.modelUUID))
}
modelTag := names.NewModelTag(args.modelUUID)
if _, err := ssState.GetModel(modelTag); err != nil {
return "", errors.Wrap(err, common.UnknownModelError(args.modelUUID))
}
logger.Debugf("validate model uuid: %s", args.modelUUID)
return args.modelUUID, nil
}
示例6: CreateDevice
// Devices implements Controller.
func (c *controller) CreateDevice(args CreateDeviceArgs) (Device, error) {
// There must be at least one mac address.
if len(args.MACAddresses) == 0 {
return nil, NewBadRequestError("at least one MAC address must be specified")
}
params := NewURLParams()
params.MaybeAdd("hostname", args.Hostname)
params.MaybeAdd("domain", args.Domain)
params.MaybeAddMany("mac_addresses", args.MACAddresses)
params.MaybeAdd("parent", args.Parent)
result, err := c.post("devices", "", params.Values)
if err != nil {
if svrErr, ok := errors.Cause(err).(ServerError); ok {
if svrErr.StatusCode == http.StatusBadRequest {
return nil, errors.Wrap(err, NewBadRequestError(svrErr.BodyMessage))
}
}
// Translate http errors.
return nil, NewUnexpectedError(err)
}
device, err := readDevice(c.apiVersion, result)
if err != nil {
return nil, errors.Trace(err)
}
device.controller = c
return device, nil
}
示例7: AddUser
// AddUser adds a user.
func (api *UserManagerAPI) AddUser(args params.AddUsers) (params.AddUserResults, error) {
result := params.AddUserResults{
Results: make([]params.AddUserResult, len(args.Users)),
}
if err := api.check.ChangeAllowed(); err != nil {
return result, errors.Trace(err)
}
if len(args.Users) == 0 {
return result, nil
}
loggedInUser, err := api.getLoggedInUser()
if err != nil {
return result, errors.Wrap(err, common.ErrPerm)
}
// TODO(thumper): PERMISSIONS Change this permission check when we have
// real permissions. For now, only the owner of the initial environment is
// able to add users.
if err := api.permissionCheck(loggedInUser); err != nil {
return result, errors.Trace(err)
}
for i, arg := range args.Users {
user, err := api.state.AddUser(arg.Username, arg.DisplayName, arg.Password, loggedInUser.Id())
if err != nil {
err = errors.Annotate(err, "failed to create user")
result.Results[i].Error = common.ServerError(err)
} else {
result.Results[i].Tag = user.Tag().String()
}
}
return result, nil
}
示例8: versionInitSystem
func versionInitSystem(ser string) (string, error) {
seriesos, err := series.GetOSFromSeries(ser)
if err != nil {
notFound := errors.NotFoundf("init system for series %q", ser)
return "", errors.Wrap(err, notFound)
}
switch seriesos {
case os.Windows:
return InitSystemWindows, nil
case os.Ubuntu:
switch ser {
case "precise", "quantal", "raring", "saucy", "trusty", "utopic":
return InitSystemUpstart, nil
default:
// vivid and later
if featureflag.Enabled(feature.LegacyUpstart) {
return InitSystemUpstart, nil
}
return InitSystemSystemd, nil
}
case os.CentOS:
return InitSystemSystemd, nil
}
return "", errors.NotFoundf("unknown os %q (from series %q), init system", seriesos, ser)
}
示例9: createContainer
func createContainer(
lxcContainer golxc.Container,
directory string,
networkConfig *container.NetworkConfig,
extraCreateArgs, templateParams []string,
caCert []byte,
) error {
// Generate initial lxc.conf with networking settings.
netConfig := generateNetworkConfig(networkConfig)
configPath := filepath.Join(directory, "lxc.conf")
if err := ioutil.WriteFile(configPath, []byte(netConfig), 0644); err != nil {
return errors.Annotatef(err, "failed to write container config %q", configPath)
}
logger.Tracef("wrote initial config %q for container %q", configPath, lxcContainer.Name())
var err error
var execEnv []string = nil
var closer func()
if caCert != nil {
execEnv, closer, err = wgetEnvironment(caCert)
if err != nil {
return errors.Annotatef(err, "failed to get environment for wget execution")
}
defer closer()
}
// Create the container.
logger.Debugf("creating lxc container %q", lxcContainer.Name())
logger.Debugf("lxc-create template params: %v", templateParams)
if err := lxcContainer.Create(configPath, defaultTemplate, extraCreateArgs, templateParams, execEnv); err != nil {
return errors.Wrap(err, instance.NewRetryableCreationError("lxc container creation failed: "+lxcContainer.Name()))
}
return nil
}
示例10: TestWrapOfNil
func (*functionSuite) TestWrapOfNil(c *gc.C) {
detailed := errors.New("detailed")
err := errors.Wrap(nil, detailed) //err nilWrapTest
c.Assert(err.Error(), gc.Equals, "detailed")
c.Assert(errors.Cause(err), gc.Equals, detailed)
c.Assert(errors.Details(err), jc.Contains, tagToLocation["nilWrapTest"].String())
}
示例11: Call
// Call will repeatedly execute the Func until either the function returns no
// error, the retry count is exceeded or the stop channel is closed.
func Call(args CallArgs) error {
err := args.Validate()
if err != nil {
return errors.Trace(err)
}
for i := 1; args.Attempts < 0 || i <= args.Attempts; i++ {
err = args.Func()
if err == nil {
return nil
}
if args.IsFatalError != nil && args.IsFatalError(err) {
return errors.Trace(err)
}
if args.NotifyFunc != nil {
args.NotifyFunc(err, i)
}
if i == args.Attempts && args.Attempts > 0 {
break // don't wait before returning the error
}
// Wait for the delay, and retry
select {
case <-args.Clock.After(args.Delay):
case <-args.Stop:
return RetryStopped
}
args.Delay = ScaleDuration(args.Delay, args.MaxDelay, args.BackoffFactor)
}
return errors.Wrap(err, &AttemptsExceeded{err})
}
示例12: validateEnvironUUID
// validateEnvironUUID is the common validator for the various
// apiserver components that need to check for a valid environment
// UUID. An empty envUUID means that the connection has come in at
// the root of the URL space and refers to the state server
// environment.
//
// It returns the validated environment UUID.
func validateEnvironUUID(args validateArgs) (string, error) {
ssState := args.statePool.SystemState()
if args.envUUID == "" {
// We allow the environUUID to be empty for 2 cases
// 1) Compatibility with older clients
// 2) TODO: server a limited API at the root (empty envUUID)
// with just the user manager and environment manager
// if the connection comes over a sufficiently up to date
// login command.
if args.strict {
return "", errors.Trace(common.UnknownEnvironmentError(args.envUUID))
}
logger.Debugf("validate env uuid: empty envUUID")
return ssState.EnvironUUID(), nil
}
if args.envUUID == ssState.EnvironUUID() {
logger.Debugf("validate env uuid: state server environment - %s", args.envUUID)
return args.envUUID, nil
}
if args.stateServerEnvOnly {
return "", errors.Unauthorizedf("requested environment %q is not the state server environment", args.envUUID)
}
if !names.IsValidEnvironment(args.envUUID) {
return "", errors.Trace(common.UnknownEnvironmentError(args.envUUID))
}
envTag := names.NewEnvironTag(args.envUUID)
if _, err := ssState.GetEnvironment(envTag); err != nil {
return "", errors.Wrap(err, common.UnknownEnvironmentError(args.envUUID))
}
logger.Debugf("validate env uuid: %s", args.envUUID)
return args.envUUID, nil
}
示例13: finalizeAction
// finalizeAction passes back the final status of an Action hook to state.
// It wraps any errors which occurred in normal behavior of the Action run;
// only errors passed in unhandledErr will be returned.
func (ctx *HookContext) finalizeAction(err, unhandledErr error) error {
// TODO (binary132): synchronize with gsamfira's reboot logic
message := ctx.actionData.ResultsMessage
results := ctx.actionData.ResultsMap
tag := ctx.actionData.Tag
status := params.ActionCompleted
if ctx.actionData.Failed {
status = params.ActionFailed
}
// If we had an action error, we'll simply encapsulate it in the response
// and discard the error state. Actions should not error the uniter.
if err != nil {
message = err.Error()
if IsMissingHookError(err) {
message = fmt.Sprintf("action not implemented on unit %q", ctx.unitName)
}
status = params.ActionFailed
}
callErr := ctx.state.ActionFinish(tag, status, results, message)
if callErr != nil {
unhandledErr = errors.Wrap(unhandledErr, callErr)
}
return unhandledErr
}
示例14: checkCreds
// checkCreds validates the entities credentials in the current environment.
// If the entity is a user, and lookForEnvUser is true, an env user must exist
// for the environment. In the case of a user logging in to the server, but
// not an environment, there is no env user needed. While we have the env
// user, if we do have it, update the last login time.
func checkCreds(st *state.State, req params.LoginRequest, lookForEnvUser bool) (state.Entity, *time.Time, error) {
tag, err := names.ParseTag(req.AuthTag)
if err != nil {
return nil, nil, err
}
entity, err := st.FindEntity(tag)
if errors.IsNotFound(err) {
// We return the same error when an entity does not exist as for a bad
// password, so that we don't allow unauthenticated users to find
// information about existing entities.
logger.Debugf("entity %q not found", tag)
return nil, nil, common.ErrBadCreds
}
if err != nil {
return nil, nil, errors.Trace(err)
}
authenticator, err := authentication.FindEntityAuthenticator(entity)
if err != nil {
return nil, nil, err
}
if err = authenticator.Authenticate(entity, req.Credentials, req.Nonce); err != nil {
logger.Debugf("bad credentials")
return nil, nil, err
}
// For user logins, update the last login time.
// NOTE: this code path is only for local users. When we support remote
// user logins with bearer tokens, we will need to make sure that we also
// update the last connection times for the environment users there.
var lastLogin *time.Time
if user, ok := entity.(*state.User); ok {
userLastLogin, err := user.LastLogin()
if err != nil && !state.IsNeverLoggedInError(err) {
return nil, nil, errors.Trace(err)
}
if lookForEnvUser {
envUser, err := st.EnvironmentUser(user.UserTag())
if err != nil {
return nil, nil, errors.Wrap(err, common.ErrBadCreds)
}
// The last connection for the environment takes precedence over
// the local user last login time.
userLastLogin, err = envUser.LastConnection()
if err != nil && !state.IsNeverConnectedError(err) {
return nil, nil, errors.Trace(err)
}
envUser.UpdateLastConnection()
}
// Only update the user's last login time if it is a successful
// login, meaning that if we are logging into an environment, make
// sure that there is an environment user in that environment for
// this user.
user.UpdateLastLogin()
lastLogin = &userLastLogin
}
return entity, lastLogin, nil
}
示例15: Next
// Next implements plan.Plan Next interface.
func (r *SelectFinalPlan) Next(ctx context.Context) (row *plan.Row, err error) {
// push a new rowStackItem into RowStack
pushRowStack(ctx, r.SelectList.ResultFields, r.SelectList.FromFields)
row, err = r.Src.Next(ctx)
// pop the rowStackItem
if errPop := popRowStack(ctx); errPop != nil {
return nil, errors.Wrap(err, errPop)
}
if row == nil || err != nil {
return nil, errors.Trace(err)
}
// we should not output hidden fields to client.
row.Data = row.Data[:r.HiddenFieldOffset]
for i, o := range row.Data {
switch v := o.(type) {
case bool:
// Convert bool field to int
if v {
row.Data[i] = uint8(1)
} else {
row.Data[i] = uint8(0)
}
}
}
if !r.infered {
setResultFieldInfo(r.ResultFields[0:r.HiddenFieldOffset], row.Data)
r.infered = true
}
return
}