本文整理汇总了Golang中github.com/pkg/errors.Wrap函数的典型用法代码示例。如果您正苦于以下问题:Golang Wrap函数的具体用法?Golang Wrap怎么用?Golang Wrap使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了Wrap函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: IssueAndSaveNewCertificates
// IssueAndSaveNewCertificates generates a new key-pair, signs it with the local root-ca, and returns a
// tls certificate
func (rca *RootCA) IssueAndSaveNewCertificates(paths CertPaths, cn, ou, org string) (*tls.Certificate, error) {
csr, key, err := GenerateAndWriteNewKey(paths)
if err != nil {
return nil, errors.Wrap(err, "error when generating new node certs")
}
if !rca.CanSign() {
return nil, ErrNoValidSigner
}
// Obtain a signed Certificate
certChain, err := rca.ParseValidateAndSignCSR(csr, cn, ou, org)
if err != nil {
return nil, errors.Wrap(err, "failed to sign node certificate")
}
// Ensure directory exists
err = os.MkdirAll(filepath.Dir(paths.Cert), 0755)
if err != nil {
return nil, err
}
// Write the chain to disk
if err := ioutils.AtomicWriteFile(paths.Cert, certChain, 0644); err != nil {
return nil, err
}
// Create a valid TLSKeyPair out of the PEM encoded private key and certificate
tlsKeyPair, err := tls.X509KeyPair(certChain, key)
if err != nil {
return nil, err
}
return &tlsKeyPair, nil
}
示例2: handleAddressChange
func (n *Node) handleAddressChange(ctx context.Context, member *membership.Member, reconnectAddr string) error {
newConn, err := n.ConnectToMember(reconnectAddr, 0)
if err != nil {
return errors.Wrapf(err, "could connect to member ID %x at observed address %s", member.RaftID, reconnectAddr)
}
healthCtx, cancelHealth := context.WithTimeout(ctx, time.Duration(n.Config.ElectionTick)*n.opts.TickInterval)
defer cancelHealth()
if err := newConn.HealthCheck(healthCtx); err != nil {
return errors.Wrapf(err, "%x failed health check at observed address %s", member.RaftID, reconnectAddr)
}
if err := n.cluster.ReplaceMemberConnection(member.RaftID, member, newConn, reconnectAddr, false); err != nil {
newConn.Conn.Close()
return errors.Wrap(err, "failed to replace connection to raft member")
}
// If we're the leader, write the address change to raft
updateCtx, cancelUpdate := context.WithTimeout(ctx, time.Duration(n.Config.ElectionTick)*n.opts.TickInterval)
defer cancelUpdate()
if err := n.updateMember(updateCtx, reconnectAddr, member.RaftID, member.NodeID); err != nil {
return errors.Wrap(err, "failed to update member address in raft")
}
return nil
}
示例3: editSubmitPlayerViewHandler
func (s *Site) editSubmitPlayerViewHandler(w http.ResponseWriter, req *http.Request) {
id := mux.Vars(req)["id"]
pid := strToUint(id)
log.Printf("edit player ID: %s", id)
defer func() {
if r := recover(); r != nil {
s.commonEditPlayerViewHandler(w, req,
fmt.Sprintf("%v", r))
}
}()
if err := req.ParseForm(); err != nil {
panic(errors.Wrap(err, "error processing form data"))
}
aliases := req.Form["aliases"]
// expecting name to be 1 element list, aliases a list with
// many aliases
if len(aliases) == 0 {
panic(errors.New("no aliases selected"))
}
log.Printf("claimed aliases: %s", aliases)
err := s.p.UpdatePlayerAliases(pid, aliases)
if err != nil {
panic(errors.Wrap(err, "error updating player"))
}
// redirect to player view
http.Redirect(w, req, s.playerViewURL(pid), http.StatusFound)
}
示例4: migrateSnapshots
func migrateSnapshots(legacySnapDir, snapDir string) error {
// use temporary snaphot directory so initialization appears atomic
tmpdirpath := filepath.Clean(snapDir) + ".tmp"
if fileutil.Exist(tmpdirpath) {
if err := os.RemoveAll(tmpdirpath); err != nil {
return errors.Wrap(err, "could not remove temporary snapshot directory")
}
}
if err := fileutil.CreateDirAll(tmpdirpath); err != nil {
return errors.Wrap(err, "could not create temporary snapshot directory")
}
snapshotNames, err := fileutil.ReadDir(legacySnapDir)
if err != nil {
return errors.Wrapf(err, "could not list snapshot directory %s", legacySnapDir)
}
for _, fname := range snapshotNames {
err := os.Link(filepath.Join(legacySnapDir, fname), filepath.Join(tmpdirpath, fname))
if err != nil {
return errors.Wrap(err, "error linking snapshot file")
}
}
if err := os.Rename(tmpdirpath, snapDir); err != nil {
return err
}
return nil
}
示例5: getDirtyExitFailedJobsFromRedis
func getDirtyExitFailedJobsFromRedis(redisClient *redis.Client) ([]redisWorker, error) {
failedJobsLength, err := redisClient.LLen(resqueFailedQueueKey).Result()
if err != nil {
return []redisWorker{}, errors.Wrap(err, "Failed to get failed resque jobs length")
}
failedJobs, err := redisClient.LRange(resqueFailedQueueKey, 0, failedJobsLength).Result()
if err != nil {
return []redisWorker{}, errors.Wrap(err, "Failed to get failed resque jobs")
}
var failedResqueJobs []redisWorker
for _, failedJob := range failedJobs {
var job failedResqueJob
if err := json.Unmarshal([]byte(failedJob), &job); err != nil {
continue
}
if job.Exception == "Resque::DirtyExit" {
failedResqueJobs = append(failedResqueJobs, redisWorker{failedJob, failedJob})
}
}
return failedResqueJobs, nil
}
示例6: UpdateCluster
func UpdateCluster(h sshAble, d drivers.Driver, config KubernetesConfig) error {
client, err := sshutil.NewSSHClient(d)
if err != nil {
return errors.Wrap(err, "Error creating new ssh client")
}
// transfer localkube from cache/asset to vm
if localkubeURIWasSpecified(config) {
lCacher := localkubeCacher{config}
if err = lCacher.updateLocalkubeFromURI(client); err != nil {
return errors.Wrap(err, "Error updating localkube from uri")
}
} else {
if err = updateLocalkubeFromAsset(client); err != nil {
return errors.Wrap(err, "Error updating localkube from asset")
}
}
fileAssets := []CopyableFile{}
addMinikubeAddonsDirToAssets(&fileAssets)
// merge files to copy
var copyableFiles []CopyableFile
copyableFiles = append(copyableFiles, memoryAssets...)
copyableFiles = append(copyableFiles, fileAssets...)
// transfer files to vm
for _, copyableFile := range copyableFiles {
if err := sshutil.Transfer(copyableFile, copyableFile.GetLength(),
copyableFile.GetTargetDir(), copyableFile.GetTargetName(),
copyableFile.GetPermissions(), client); err != nil {
return err
}
}
return nil
}
示例7: StartHost
// StartHost starts a host VM.
func StartHost(api libmachine.API, config MachineConfig) (*host.Host, error) {
exists, err := api.Exists(constants.MachineName)
if err != nil {
return nil, errors.Wrapf(err, "Error checking if host exists: %s", constants.MachineName)
}
if !exists {
return createHost(api, config)
}
glog.Infoln("Machine exists!")
h, err := api.Load(constants.MachineName)
if err != nil {
return nil, errors.Wrap(err, "Error loading existing host. Please try running [minikube delete], then run [minikube start] again.")
}
s, err := h.Driver.GetState()
glog.Infoln("Machine state: ", s)
if err != nil {
return nil, errors.Wrap(err, "Error getting state for host")
}
if s != state.Running {
if err := h.Driver.Start(); err != nil {
return nil, errors.Wrapf(err, "Error starting stopped host")
}
if err := api.Save(h); err != nil {
return nil, errors.Wrapf(err, "Error saving started host")
}
}
if err := h.ConfigureAuth(); err != nil {
return nil, errors.Wrap(err, "Error configuring auth on host: %s")
}
return h, nil
}
示例8: requestToken
func requestToken(schemeData map[string]string) (string, error) {
maxRetries := samlRequestTimeout(schemeData) - 7
time.Sleep(5 * time.Second)
id := samlRequestId(schemeData)
v := url.Values{}
v.Set("request_id", id)
for count := 0; count <= maxRetries; count += 2 {
u, err := GetURL("/auth/login")
if err != nil {
return "", errors.Wrap(err, "Error in GetURL")
}
resp, err := tsuruNet.Dial5Full300Client.Post(u, "application/x-www-form-urlencoded", strings.NewReader(v.Encode()))
if err != nil {
return "", errors.Wrap(err, "Error during login post")
}
defer resp.Body.Close()
result, err := ioutil.ReadAll(resp.Body)
if err != nil {
return "", errors.Wrap(err, "Error reading body")
}
if strings.TrimSpace(string(result)) == saml.ErrRequestWaitingForCredentials.Message {
if count < maxRetries {
time.Sleep(2 * time.Second)
}
continue
}
data := make(map[string]interface{})
if err = json.Unmarshal(result, &data); err != nil {
return "", errors.Errorf("API response: %s", result)
}
return data["token"].(string), nil
}
// finish when timeout
return "", saml.ErrRequestWaitingForCredentials
}
示例9: fetchArbitraryCard
func (c *Card) fetchArbitraryCard() error {
u, err := CurrentUser()
if err != nil {
return errors.Wrap(err, "No user logged in")
}
if c.db == nil {
db, err := u.DB()
if err != nil {
return errors.Wrap(err, "Error connecting to User DB")
}
c.db = db
}
doc := make(map[string][]*fb.Card)
query := map[string]interface{}{
"selector": map[string]string{"type": "card"},
"limit": 1,
}
if err := c.db.Find(query, &doc); err != nil {
return err
}
if len(doc["docs"]) == 0 {
return errors.New("No cards available")
}
c.Card = doc["docs"][0]
return nil
}
示例10: GetJob
func (s *DatabaseStore) GetJob(inst flux.InstanceID, id JobID) (Job, error) {
var (
queue string
method string
paramsBytes []byte
scheduledAt time.Time
priority int
key string
submittedAt time.Time
claimedAt nullTime
heartbeatAt nullTime
finishedAt nullTime
logStr string
status string
done sql.NullBool
success sql.NullBool
)
if err := s.conn.QueryRow(`
SELECT queue, method, params, scheduled_at, priority, key, submitted_at, claimed_at, heartbeat_at, finished_at, log, status, done, success
FROM jobs
WHERE id = $1
AND instance_id = $2
`, string(id), string(inst)).Scan(
&queue, &method, ¶msBytes, &scheduledAt, &priority, &key, &submittedAt,
&claimedAt, &heartbeatAt, &finishedAt, &logStr, &status, &done, &success,
); err == sql.ErrNoRows {
return Job{}, ErrNoSuchJob
} else if err != nil {
return Job{}, errors.Wrap(err, "error getting job")
}
params, err := s.scanParams(method, paramsBytes)
if err != nil {
return Job{}, errors.Wrap(err, "unmarshaling params")
}
var log []string
if err := json.NewDecoder(strings.NewReader(logStr)).Decode(&log); err != nil {
return Job{}, errors.Wrap(err, "unmarshaling log")
}
return Job{
Instance: inst,
ID: id,
Queue: queue,
Method: method,
Params: params,
ScheduledAt: scheduledAt,
Priority: priority,
Key: key,
Submitted: submittedAt,
Claimed: claimedAt.Time,
Heartbeat: heartbeatAt.Time,
Finished: finishedAt.Time,
Log: log,
Status: status,
Done: done.Bool,
Success: success.Bool,
}, nil
}
示例11: AddStockcollections
// AddStockcollections adds the given related objects to the existing relationships
// of the contact, optionally inserting them as new records.
// Appends related to o.R.Stockcollections.
// Sets related.R.Contact appropriately.
func (o *Contact) AddStockcollections(exec boil.Executor, insert bool, related ...*Stockcollection) error {
var err error
for _, rel := range related {
rel.ContactID.Int = o.ContactID
rel.ContactID.Valid = true
if insert {
if err = rel.Insert(exec); err != nil {
return errors.Wrap(err, "failed to insert into foreign table")
}
} else {
if err = rel.Update(exec, "contact_id"); err != nil {
return errors.Wrap(err, "failed to update foreign table")
}
}
}
if o.R == nil {
o.R = &contactR{
Stockcollections: related,
}
} else {
o.R.Stockcollections = append(o.R.Stockcollections, related...)
}
for _, rel := range related {
if rel.R == nil {
rel.R = &stockcollectionR{
Contact: o,
}
} else {
rel.R.Contact = o
}
}
return nil
}
示例12: writeTargetState
func (pkg *smPackage) writeTargetState(client connection.Client) error {
sess, err := client.NewSession()
if err != nil {
return err
}
defer sess.Close()
stdin, err := sess.StdinPipe()
if err != nil {
return errors.Wrap(err, "failed to receive stdin pipe")
}
tstamp := time.Now().UTC().Format("20060102T150405")
filename := fmt.Sprintf("/var/lib/smutje/%s.%s.log", pkg.ID, tstamp)
cmd := fmt.Sprintf(`bash -c "cat - > %[1]s && ln -sf %[1]s /var/lib/smutje/%[2]s.log"`, filename, pkg.ID)
if err := sess.Start(cmd); err != nil {
return err
}
if _, err := io.WriteString(stdin, strings.Join(pkg.state, "\n")+"\n"); err != nil {
return errors.Wrap(err, "failed to send script to target")
}
stdin.Close()
return sess.Wait()
}
示例13: UnmarshalJSON
// UnmarshalJSON unmarshals a list of conditions from json.
func (cs Conditions) UnmarshalJSON(data []byte) error {
if cs == nil {
return errors.New("Can not be nil")
}
var jcs map[string]jsonCondition
var dc Condition
if err := json.Unmarshal(data, &jcs); err != nil {
return errors.Wrap(err, "")
}
for k, jc := range jcs {
for name, c := range ConditionFactories {
if name == jc.Type {
dc = c()
if len(jc.Options) == 0 {
cs[k] = dc
break
}
if err := json.Unmarshal(jc.Options, dc); err != nil {
return errors.Wrap(err, "")
}
cs[k] = dc
break
}
}
}
return nil
}
示例14: Update
// Update does PATCH workitem
func (c *WorkitemController) Update(ctx *app.UpdateWorkitemContext) error {
return application.Transactional(c.db, func(appl application.Application) error {
if ctx.Payload == nil || ctx.Payload.Data == nil || ctx.Payload.Data.ID == nil {
return jsonapi.JSONErrorResponse(ctx, errors.NewBadParameterError("missing data.ID element in request", nil))
}
wi, err := appl.WorkItems().Load(ctx, *ctx.Payload.Data.ID)
if err != nil {
return jsonapi.JSONErrorResponse(ctx, errs.Wrap(err, fmt.Sprintf("Failed to load work item with id %v", *ctx.Payload.Data.ID)))
}
// Type changes of WI are not allowed which is why we overwrite it the
// type with the old one after the WI has been converted.
oldType := wi.Type
err = ConvertJSONAPIToWorkItem(appl, *ctx.Payload.Data, wi)
if err != nil {
return jsonapi.JSONErrorResponse(ctx, err)
}
wi.Type = oldType
wi, err = appl.WorkItems().Save(ctx, *wi)
if err != nil {
return jsonapi.JSONErrorResponse(ctx, errs.Wrap(err, "Error updating work item"))
}
wi2 := ConvertWorkItem(ctx.RequestData, wi)
resp := &app.WorkItem2Single{
Data: wi2,
Links: &app.WorkItemLinks{
Self: buildAbsoluteURL(ctx.RequestData),
},
}
return ctx.OK(resp)
})
}
示例15: createSockets
// createSockets initializes the sockets for the socket group based on values from zmq.
func createSockets() (*zmq.Context, SocketGroup, error) {
context, err := zmq.NewContext()
if err != nil {
return context, SocketGroup{}, errors.Wrap(err, "Could not create zmq Context")
}
var sg SocketGroup
sg.ShellSocket, err = context.NewSocket(zmq.ROUTER)
if err != nil {
return context, sg, errors.Wrap(err, "Could not get Shell Socket")
}
sg.ControlSocket, err = context.NewSocket(zmq.ROUTER)
if err != nil {
return context, sg, errors.Wrap(err, "Could not get Control Socket")
}
sg.StdinSocket, err = context.NewSocket(zmq.ROUTER)
if err != nil {
return context, sg, errors.Wrap(err, "Could not get Stdin Socket")
}
sg.IOPubSocket, err = context.NewSocket(zmq.PUB)
if err != nil {
return context, sg, errors.Wrap(err, "Could not get IOPub Socket")
}
return context, sg, nil
}