本文整理汇总了Golang中github.com/pkg/errors.WithStack函数的典型用法代码示例。如果您正苦于以下问题:Golang WithStack函数的具体用法?Golang WithStack怎么用?Golang WithStack使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了WithStack函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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
}
开发者ID:yext,项目名称:edward,代码行数:33,代码来源:serviceconfig.go
示例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")
}
开发者ID:yext,项目名称:edward,代码行数:25,代码来源:command.go
示例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)
}
开发者ID:tsuru,项目名称:tsuru,代码行数:31,代码来源:docker.go
示例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
}
开发者ID:Ritsyy,项目名称:almighty-core,代码行数:33,代码来源:search_repository.go
示例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
}
开发者ID:tsuru,项目名称:tsuru,代码行数:27,代码来源:db.go
示例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
}
开发者ID:tsuru,项目名称:tsuru,代码行数:30,代码来源:provisioner.go
示例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
}
开发者ID:Ritsyy,项目名称:almighty-core,代码行数:29,代码来源:token.go
示例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
}
开发者ID:Ritsyy,项目名称:almighty-core,代码行数:30,代码来源:service.go
示例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()
}
开发者ID:yext,项目名称:edward,代码行数:26,代码来源:runner.go
示例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()
}
开发者ID:Ritsyy,项目名称:almighty-core,代码行数:31,代码来源:transaction.go
示例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
}
开发者ID:tsuru,项目名称:tsuru,代码行数:28,代码来源:provisioner.go
示例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
}
开发者ID:Ritsyy,项目名称:almighty-core,代码行数:36,代码来源:link_repository.go
示例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)
}
开发者ID:yext,项目名称:edward,代码行数:25,代码来源:config.go
示例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
}
开发者ID:yext,项目名称:edward,代码行数:28,代码来源:config.go
示例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
}
开发者ID:tsuru,项目名称:tsuru,代码行数:58,代码来源:provisioner.go
示例16: Save
func (c Config) Save(writer io.Writer) error {
c.printf("Saving config")
content, err := json.MarshalIndent(c, "", " ")
if err != nil {
return errors.WithStack(err)
}
_, err = writer.Write(content)
return errors.WithStack(err)
}
开发者ID:yext,项目名称:edward,代码行数:9,代码来源:config.go
示例17: executeSQLFile
// executeSQLFile loads the given filename from the packaged SQL files and
// executes it on the given database
func executeSQLFile(filename string) fn {
return func(db *sql.Tx) error {
data, err := Asset(filename)
if err != nil {
return errs.WithStack(err)
}
_, err = db.Exec(string(data))
return errs.WithStack(err)
}
}
开发者ID:Ritsyy,项目名称:almighty-core,代码行数:12,代码来源:migration.go
示例18: TestConvertExistingWorkItem
func TestConvertExistingWorkItem(t *testing.T) {
resource.Require(t, resource.Database)
// Setting up the dependent tracker query and tracker data in the Database
tr := Tracker{URL: "https://api.github.com/", Type: ProviderGithub}
db = db.Create(&tr)
require.Nil(t, db.Error)
tq := TrackerQuery{Query: "some random query", Schedule: "0 0 0 * * *", TrackerID: tr.ID}
db = db.Create(&tq)
require.Nil(t, db.Error)
defer cleaner.DeleteCreatedEntities(db)()
t.Log("Created Tracker Query and Tracker")
models.Transactional(db, func(tx *gorm.DB) error {
t.Log("Adding a work item which wasn't present.")
remoteItemData := TrackerItemContent{
Content: []byte(`{"title":"linking","url":"http://github.com/sbose/api/testonly/1","state":"closed","body":"body of issue","user.login":"sbose78","assignee.login":"pranav"}`),
ID: "http://github.com/sbose/api/testonly/1",
}
workItem, err := convert(tx, int(tq.ID), remoteItemData, ProviderGithub)
assert.Nil(t, err)
assert.Equal(t, "linking", workItem.Fields[workitem.SystemTitle])
assert.Equal(t, "sbose78", workItem.Fields[workitem.SystemCreator])
assert.Equal(t, "pranav", workItem.Fields[workitem.SystemAssignees].([]interface{})[0])
assert.Equal(t, "closed", workItem.Fields[workitem.SystemState])
return errors.WithStack(err)
})
t.Log("Updating the existing work item when it's reimported.")
models.Transactional(db, func(tx *gorm.DB) error {
remoteItemDataUpdated := TrackerItemContent{
Content: []byte(`{"title":"linking-updated","url":"http://github.com/api/testonly/1","state":"closed","body":"body of issue","user.login":"sbose78","assignee.login":"pranav"}`),
ID: "http://github.com/sbose/api/testonly/1",
}
workItemUpdated, err := convert(tx, int(tq.ID), remoteItemDataUpdated, ProviderGithub)
assert.Nil(t, err)
assert.Equal(t, "linking-updated", workItemUpdated.Fields[workitem.SystemTitle])
assert.Equal(t, "sbose78", workItemUpdated.Fields[workitem.SystemCreator])
assert.Equal(t, "pranav", workItemUpdated.Fields[workitem.SystemAssignees].([]interface{})[0])
assert.Equal(t, "closed", workItemUpdated.Fields[workitem.SystemState])
wir := workitem.NewWorkItemRepository(tx)
wir.Delete(context.Background(), workItemUpdated.ID)
return errors.WithStack(err)
})
}
开发者ID:Ritsyy,项目名称:almighty-core,代码行数:55,代码来源:trackeritem_repository_test.go
示例19: Launch
func (sc *ServiceConfig) Launch(cfg OperationConfig) error {
if cfg.IsExcluded(sc) {
return nil
}
command, err := sc.GetCommand()
if err != nil {
return errors.WithStack(err)
}
return errors.WithStack(command.StartAsync(cfg))
}
开发者ID:yext,项目名称:edward,代码行数:11,代码来源:serviceconfig.go
示例20: Build
func (sc *ServiceConfig) Build(cfg OperationConfig) error {
if cfg.IsExcluded(sc) {
return nil
}
command, err := sc.GetCommand()
if err != nil {
return errors.WithStack(err)
}
return errors.WithStack(command.BuildSync(false))
}
开发者ID:yext,项目名称:edward,代码行数:11,代码来源:serviceconfig.go
注:本文中的github.com/pkg/errors.WithStack函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论