本文整理汇总了Golang中github.com/pkg/errors.WithStack函数的典型用法代码示例。如果您正苦于以下问题:Golang WithStack函数的具体用法?Golang WithStack怎么用?Golang WithStack使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了WithStack函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: Status
func (sc *ServiceConfig) Status() ([]ServiceStatus, error) {
command, err := sc.GetCommand()
if err != nil {
return nil, errors.WithStack(err)
}
status := ServiceStatus{
Service: sc,
Status: "STOPPED",
}
if command.Pid != 0 {
status.Status = "RUNNING"
status.Pid = command.Pid
proc, err := process.NewProcess(int32(command.Pid))
if err != nil {
return nil, errors.WithStack(err)
}
epochStart, err := proc.CreateTime()
if err != nil {
return nil, errors.WithStack(err)
}
status.StartTime = time.Unix(epochStart/1000, 0)
status.Ports, err = sc.getPorts(proc)
if err != nil {
return nil, errors.WithStack(err)
}
}
return []ServiceStatus{
status,
}, nil
}
示例2: waitForAnyPort
func (sc *ServiceCommand) waitForAnyPort(cancel <-chan struct{}, command *exec.Cmd) error {
for true {
time.Sleep(100 * time.Millisecond)
select {
case <-cancel:
return nil
default:
}
connections, err := net.Connections("all")
if err != nil {
return errors.WithStack(err)
}
proc, err := process.NewProcess(int32(command.Process.Pid))
if err != nil {
return errors.WithStack(err)
}
if hasPort(proc, connections) {
return nil
}
}
return errors.New("exited check loop unexpectedly")
}
示例3: joinSwarm
func joinSwarm(existingClient *docker.Client, newClient *docker.Client, addr string) error {
swarmInfo, err := existingClient.InspectSwarm(nil)
if err != nil {
return errors.WithStack(err)
}
dockerInfo, err := existingClient.Info()
if err != nil {
return errors.WithStack(err)
}
if len(dockerInfo.Swarm.RemoteManagers) == 0 {
return errors.Errorf("no remote managers found in node %#v", dockerInfo)
}
addrs := make([]string, len(dockerInfo.Swarm.RemoteManagers))
for i, peer := range dockerInfo.Swarm.RemoteManagers {
addrs[i] = peer.Addr
}
host := tsuruNet.URLToHost(addr)
opts := docker.JoinSwarmOptions{
JoinRequest: swarm.JoinRequest{
ListenAddr: fmt.Sprintf("0.0.0.0:%d", swarmConfig.swarmPort),
AdvertiseAddr: host,
JoinToken: swarmInfo.JoinTokens.Worker,
RemoteAddrs: addrs,
},
}
err = newClient.JoinSwarm(opts)
if err != nil && err != docker.ErrNodeAlreadyInSwarm {
return errors.WithStack(err)
}
return redistributeManagers(existingClient)
}
示例4: SearchFullText
// SearchFullText Search returns work items for the given query
func (r *GormSearchRepository) SearchFullText(ctx context.Context, rawSearchString string, start *int, limit *int) ([]*app.WorkItem, uint64, error) {
// parse
// generateSearchQuery
// ....
parsedSearchDict, err := parseSearchString(rawSearchString)
if err != nil {
return nil, 0, errs.WithStack(err)
}
sqlSearchQueryParameter := generateSQLSearchInfo(parsedSearchDict)
var rows []workitem.WorkItem
rows, count, err := r.search(ctx, sqlSearchQueryParameter, parsedSearchDict.workItemTypes, start, limit)
if err != nil {
return nil, 0, errs.WithStack(err)
}
result := make([]*app.WorkItem, len(rows))
for index, value := range rows {
var err error
// FIXME: Against best practice http://go-database-sql.org/retrieving.html
wiType, err := r.wir.LoadTypeFromDB(ctx, value.Type)
if err != nil {
return nil, 0, errors.NewInternalError(err.Error())
}
result[index], err = convertFromModel(*wiType, value)
if err != nil {
return nil, 0, errors.NewConversionError(err.Error())
}
}
return result, count, nil
}
示例5: updateDBSwarmNodes
func updateDBSwarmNodes(client *docker.Client) error {
nodes, err := listValidNodes(client)
if err != nil {
return errors.WithStack(err)
}
var addrs []string
for _, n := range nodes {
if n.ManagerStatus == nil {
continue
}
addr := n.Spec.Annotations.Labels[labelNodeDockerAddr.String()]
if addr == "" {
continue
}
addrs = append(addrs, addr)
}
coll, err := nodeAddrCollection()
if err != nil {
return err
}
defer coll.Close()
_, err = coll.UpsertId(uniqueDocumentID, bson.M{"$set": bson.M{"addresses": addrs}})
if err != nil {
return errors.WithStack(err)
}
return nil
}
示例6: Destroy
func (p *swarmProvisioner) Destroy(a provision.App) error {
client, err := chooseDBSwarmNode()
if err != nil {
return err
}
multiErrors := tsuruErrors.NewMultiError()
processes, err := allAppProcesses(a.GetName())
if err != nil {
multiErrors.Add(err)
}
for _, p := range processes {
name := serviceNameForApp(a, p)
err = client.RemoveService(docker.RemoveServiceOptions{
ID: name,
})
if err != nil {
if _, notFound := err.(*docker.NoSuchService); !notFound {
multiErrors.Add(errors.WithStack(err))
}
}
}
err = client.RemoveNetwork(networkNameForApp(a))
if err != nil {
multiErrors.Add(errors.WithStack(err))
}
if multiErrors.Len() > 0 {
return multiErrors
}
return nil
}
示例7: Extract
func (mgm tokenManager) Extract(tokenString string) (*account.Identity, error) {
token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
return mgm.publicKey, nil
})
if err != nil {
return nil, errors.WithStack(err)
}
if !token.Valid {
return nil, errors.New("Token not valid")
}
claimedUUID := token.Claims.(jwt.MapClaims)["sub"]
if claimedUUID == nil {
return nil, errors.New("Subject can not be nil")
}
// in case of nil UUID, below type casting will fail hence we need above check
id, err := uuid.FromString(token.Claims.(jwt.MapClaims)["sub"].(string))
if err != nil {
return nil, errors.WithStack(err)
}
ident := account.Identity{
ID: id,
Username: token.Claims.(jwt.MapClaims)["preferred_username"].(string),
}
return &ident, nil
}
示例8: encodeToken
func encodeToken(referal *url.URL, outhToken *oauth2.Token) error {
str := outhToken.Extra("expires_in")
expiresIn, err := strconv.Atoi(fmt.Sprintf("%v", str))
if err != nil {
return errs.WithStack(errors.New("cant convert expires_in to integer " + err.Error()))
}
str = outhToken.Extra("refresh_expires_in")
refreshExpiresIn, err := strconv.Atoi(fmt.Sprintf("%v", str))
if err != nil {
return errs.WithStack(errors.New("cant convert refresh_expires_in to integer " + err.Error()))
}
tokenData := &app.TokenData{
AccessToken: &outhToken.AccessToken,
RefreshToken: &outhToken.RefreshToken,
TokenType: &outhToken.TokenType,
ExpiresIn: &expiresIn,
RefreshExpiresIn: &refreshExpiresIn,
}
b, err := json.Marshal(tokenData)
if err != nil {
return errs.WithStack(errors.New("cant marshal token data struct " + err.Error()))
}
parameters := url.Values{}
parameters.Add("token", outhToken.AccessToken) // Temporary keep the old "token" param. We will drop this param as soon as UI adopt the new json param.
parameters.Add("token_json", string(b))
referal.RawQuery = parameters.Encode()
return nil
}
示例9: run
func run(c *cli.Context) error {
args := c.Args()
if len(args) < 3 {
return errors.New("a directory, log file and command is required")
}
workingDir := os.ExpandEnv(args[0])
logFile := os.ExpandEnv(args[1])
fullCommand := os.ExpandEnv(args[2])
command, cmdArgs, err := parseCommand(fullCommand)
if err != nil {
return errors.WithStack(err)
}
log, err := os.Create(logFile)
if err != nil {
return errors.WithStack(err)
}
cmd := exec.Command(command, cmdArgs...)
fmt.Println(cmd.Path)
cmd.Dir = workingDir
cmd.Stdout = log
cmd.Stderr = log
return cmd.Run()
}
示例10: Transactional
// Transactional executes the given function in a transaction. If todo returns an error, the transaction is rolled back
func Transactional(db DB, todo func(f Application) error) error {
var tx Transaction
var err error
if tx, err = db.BeginTransaction(); err != nil {
log.Error(nil, map[string]interface{}{
"err": err,
}, "database BeginTransaction failed!")
return errors.WithStack(err)
}
if err := todo(tx); err != nil {
log.Debug(nil, map[string]interface{}{
"pkg": "application",
}, "Rolling back the transaction...")
tx.Rollback()
log.Error(nil, map[string]interface{}{
"err": err,
}, "database transaction failed!")
return errors.WithStack(err)
}
log.Debug(nil, map[string]interface{}{
"pkg": "application",
}, "Commit the transaction!")
return tx.Commit()
}
示例11: ArchiveDeploy
func (p *swarmProvisioner) ArchiveDeploy(a provision.App, archiveURL string, evt *event.Event) (imgID string, err error) {
baseImage := image.GetBuildImage(a)
buildingImage, err := image.AppNewImageName(a.GetName())
if err != nil {
return "", errors.WithStack(err)
}
client, err := chooseDBSwarmNode()
if err != nil {
return "", err
}
cmds := dockercommon.ArchiveDeployCmds(a, archiveURL)
srvID, task, err := runOnceBuildCmds(client, a, cmds, baseImage, buildingImage, evt)
if srvID != "" {
defer removeServiceAndLog(client, srvID)
}
if err != nil {
return "", err
}
_, err = commitPushBuildImage(client, buildingImage, task.Status.ContainerStatus.ContainerID, a)
if err != nil {
return "", err
}
err = deployProcesses(client, a, buildingImage, nil)
if err != nil {
return "", errors.WithStack(err)
}
return buildingImage, nil
}
示例12: ValidateCorrectSourceAndTargetType
// ValidateCorrectSourceAndTargetType returns an error if the Path of
// the source WIT as defined by the work item link type is not part of
// the actual source's WIT; the same applies for the target.
func (r *GormWorkItemLinkRepository) ValidateCorrectSourceAndTargetType(ctx context.Context, sourceID, targetID uint64, linkTypeID satoriuuid.UUID) error {
linkType, err := r.workItemLinkTypeRepo.LoadTypeFromDBByID(ctx, linkTypeID)
if err != nil {
return errs.WithStack(err)
}
// Fetch the source work item
source, err := r.workItemRepo.LoadFromDB(ctx, strconv.FormatUint(sourceID, 10))
if err != nil {
return errs.WithStack(err)
}
// Fetch the target work item
target, err := r.workItemRepo.LoadFromDB(ctx, strconv.FormatUint(targetID, 10))
if err != nil {
return errs.WithStack(err)
}
// Fetch the concrete work item types of the target and the source.
sourceWorkItemType, err := r.workItemTypeRepo.LoadTypeFromDB(ctx, source.Type)
if err != nil {
return errs.WithStack(err)
}
targetWorkItemType, err := r.workItemTypeRepo.LoadTypeFromDB(ctx, target.Type)
if err != nil {
return errs.WithStack(err)
}
// Check type paths
if !sourceWorkItemType.IsTypeOrSubtypeOf(linkType.SourceTypeName) {
return errors.NewBadParameterError("source work item type", source.Type)
}
if !targetWorkItemType.IsTypeOrSubtypeOf(linkType.TargetTypeName) {
return errors.NewBadParameterError("target work item type", target.Type)
}
return nil
}
示例13: LoadConfigWithDir
func LoadConfigWithDir(reader io.Reader, workingDir string, edwardVersion string, logger common.Logger) (Config, error) {
config, err := loadConfigContents(reader, workingDir, logger)
if err != nil {
return Config{}, errors.WithStack(err)
}
if config.MinEdwardVersion != "" && edwardVersion != "" {
// Check that this config is supported by this version
minVersion, err1 := version.NewVersion(config.MinEdwardVersion)
if err1 != nil {
return Config{}, errors.WithStack(err)
}
currentVersion, err2 := version.NewVersion(edwardVersion)
if err2 != nil {
return Config{}, errors.WithStack(err)
}
if currentVersion.LessThan(minVersion) {
return Config{}, errors.New("this config requires at least version " + config.MinEdwardVersion)
}
}
err = config.initMaps()
config.printf("Config loaded with: %d groups and %d services\n", len(config.GroupMap), len(config.ServiceMap))
return config, errors.WithStack(err)
}
示例14: loadImports
func (c *Config) loadImports() error {
c.printf("Loading imports\n")
for _, i := range c.Imports {
var cPath string
if filepath.IsAbs(i) {
cPath = i
} else {
cPath = filepath.Join(c.workingDir, i)
}
c.printf("Loading: %v\n", cPath)
r, err := os.Open(cPath)
if err != nil {
return errors.WithStack(err)
}
cfg, err := loadConfigContents(r, filepath.Dir(cPath), c.Logger)
if err != nil {
return errors.WithStack(err)
}
err = c.importConfig(cfg)
if err != nil {
return errors.WithStack(err)
}
}
return nil
}
示例15: Shell
func (p *swarmProvisioner) Shell(opts provision.ShellOptions) error {
client, err := chooseDBSwarmNode()
if err != nil {
return err
}
tasks, err := runningTasksForApp(client, opts.App, opts.Unit)
if err != nil {
return err
}
if len(tasks) == 0 {
if opts.Unit != "" {
return &provision.UnitNotFoundError{ID: opts.Unit}
}
return provision.ErrEmptyApp
}
nodeClient, err := clientForNode(client, tasks[0].NodeID)
if err != nil {
return err
}
cmds := []string{"/usr/bin/env", "TERM=" + opts.Term, "bash", "-l"}
execCreateOpts := docker.CreateExecOptions{
AttachStdin: true,
AttachStdout: true,
AttachStderr: true,
Cmd: cmds,
Container: tasks[0].Status.ContainerStatus.ContainerID,
Tty: true,
}
exec, err := nodeClient.CreateExec(execCreateOpts)
if err != nil {
return errors.WithStack(err)
}
startExecOptions := docker.StartExecOptions{
InputStream: opts.Conn,
OutputStream: opts.Conn,
ErrorStream: opts.Conn,
Tty: true,
RawTerminal: true,
}
errs := make(chan error, 1)
go func() {
errs <- nodeClient.StartExec(exec.ID, startExecOptions)
}()
execInfo, err := nodeClient.InspectExec(exec.ID)
for !execInfo.Running && err == nil {
select {
case startErr := <-errs:
return startErr
default:
execInfo, err = nodeClient.InspectExec(exec.ID)
}
}
if err != nil {
return errors.WithStack(err)
}
nodeClient.ResizeExecTTY(exec.ID, opts.Height, opts.Width)
return <-errs
}