本文整理汇总了Golang中golang.org/x/net/context.Context.Done方法的典型用法代码示例。如果您正苦于以下问题:Golang Context.Done方法的具体用法?Golang Context.Done怎么用?Golang Context.Done使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类golang.org/x/net/context.Context
的用法示例。
在下文中一共展示了Context.Done方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: backgroundRekeyChecker
func (md *MDServerRemote) backgroundRekeyChecker(ctx context.Context) {
for {
select {
case <-md.rekeyTimer.C:
if !md.conn.IsConnected() {
md.rekeyTimer.Reset(MdServerBackgroundRekeyPeriod)
continue
}
// Assign an ID to this rekey check so we can track it.
logTags := make(logger.CtxLogTags)
logTags[CtxMDSRIDKey] = CtxMDSROpID
newCtx := logger.NewContextWithLogTags(ctx, logTags)
id, err := MakeRandomRequestID()
if err != nil {
md.log.CWarningf(ctx,
"Couldn't generate a random request ID: %v", err)
} else {
newCtx = context.WithValue(newCtx, CtxMDSRIDKey, id)
}
md.log.CDebugf(newCtx, "Checking for rekey folders")
if err := md.getFoldersForRekey(newCtx, md.client); err != nil {
md.log.CWarningf(newCtx, "MDServerRemote: getFoldersForRekey "+
"failed with %v", err)
}
md.rekeyTimer.Reset(MdServerBackgroundRekeyPeriod)
case <-ctx.Done():
return
}
}
}
示例2: blockingLookup
// Waits until a sufficient quorum is assembled
func (ks *Keyserver) blockingLookup(ctx context.Context, req *proto.LookupRequest, epoch uint64) (*proto.LookupProof, error) {
newSignatures := make(chan interface{}, newSignatureBufferSize)
ks.signatureBroadcast.Subscribe(epoch, newSignatures)
defer ks.signatureBroadcast.Unsubscribe(epoch, newSignatures)
verifiersLeft := coname.ListQuorum(req.QuorumRequirement, nil)
ratifications, haveVerifiers, err := ks.findRatificationsForEpoch(epoch, verifiersLeft)
if err != nil {
return nil, err
}
for v := range haveVerifiers {
delete(verifiersLeft, v)
}
for !coname.CheckQuorum(req.QuorumRequirement, haveVerifiers) {
select {
case <-ctx.Done():
return nil, fmt.Errorf("timed out while waiting for ratification")
case v := <-newSignatures:
newSig := v.(*proto.SignedEpochHead)
for id := range newSig.Signatures {
if _, ok := verifiersLeft[id]; ok {
ratifications = append(ratifications, newSig)
delete(verifiersLeft, id)
haveVerifiers[id] = struct{}{}
}
}
}
}
return ks.assembleLookupProof(req, epoch, ratifications)
}
示例3: WebSensorsAgent
func WebSensorsAgent(ctx context.Context, db data.DB, u *models.User) {
// Get the db's changes, then filter by updates, then
// filter by whether this user can read the record
changes := data.Filter(data.FilterKind(db.Changes(), models.EventKind), func(c *data.Change) bool {
ok, _ := access.CanRead(db, u, c.Record)
return ok
})
Run:
for {
select {
case c, ok := <-*changes:
if !ok {
break Run
}
switch c.Record.(*models.Event).Name {
case WEB_SENSOR_LOCATION:
webSensorLocation(db, u, c.Record.(*models.Event).Data)
}
case <-ctx.Done():
break Run
}
}
}
示例4: processInternalRaftRequest
func (s *EtcdServer) processInternalRaftRequest(ctx context.Context, r pb.InternalRaftRequest) (*applyResult, error) {
r.ID = s.reqIDGen.Next()
data, err := r.Marshal()
if err != nil {
return nil, err
}
if len(data) > maxRequestBytes {
return nil, ErrRequestTooLarge
}
ch := s.w.Register(r.ID)
s.r.Propose(ctx, data)
select {
case x := <-ch:
return x.(*applyResult), nil
case <-ctx.Done():
s.w.Trigger(r.ID, nil) // GC wait
return nil, ctx.Err()
case <-s.done:
return nil, ErrStopped
}
}
示例5: Handle
// Handle is the quicklog handle method for processing a log line
func (u *Handler) Handle(ctx context.Context, prev <-chan ql.Line, next chan<- ql.Line, config map[string]interface{}) error {
field := "uuid"
if u.FieldName != "" {
field = u.FieldName
}
ok := true
fieldIface := config["field"]
if fieldIface != nil {
field, ok = fieldIface.(string)
if !ok {
log.Log(ctx).Warn("Could not parse UUID config, using field=uuid")
field = "uuid"
}
}
log.Log(ctx).Debug("Starting filter handler", "handler", "uuid", "field", field)
go func() {
for {
select {
case line := <-prev:
line.Data[field] = uuid.NewV4().String()
next <- line
case <-ctx.Done():
return
}
}
}()
return nil
}
示例6: Upload
// Upload is called to perform the upload.
func (u *mockUploadDescriptor) Upload(ctx context.Context, progressOutput progress.Output) (distribution.Descriptor, error) {
if u.currentUploads != nil {
defer atomic.AddInt32(u.currentUploads, -1)
if atomic.AddInt32(u.currentUploads, 1) > maxUploadConcurrency {
return distribution.Descriptor{}, errors.New("concurrency limit exceeded")
}
}
// Sleep a bit to simulate a time-consuming upload.
for i := int64(0); i <= 10; i++ {
select {
case <-ctx.Done():
return distribution.Descriptor{}, ctx.Err()
case <-time.After(10 * time.Millisecond):
progressOutput.WriteProgress(progress.Progress{ID: u.ID(), Current: i, Total: 10})
}
}
if u.simulateRetries != 0 {
u.simulateRetries--
return distribution.Descriptor{}, errors.New("simulating retry")
}
return distribution.Descriptor{}, nil
}
示例7: waitForStateChange
// waitForStateChange blocks until the state changes to something other than the sourceState.
func (ac *addrConn) waitForStateChange(ctx context.Context, sourceState ConnectivityState) (ConnectivityState, error) {
ac.mu.Lock()
defer ac.mu.Unlock()
if sourceState != ac.state {
return ac.state, nil
}
done := make(chan struct{})
var err error
go func() {
select {
case <-ctx.Done():
ac.mu.Lock()
err = ctx.Err()
ac.stateCV.Broadcast()
ac.mu.Unlock()
case <-done:
}
}()
defer close(done)
for sourceState == ac.state {
ac.stateCV.Wait()
if err != nil {
return ac.state, err
}
}
return ac.state, nil
}
示例8: runExec
func runExec(ctx context.Context, db *sql.DB, query string) error {
done := make(chan struct{})
var (
errMsg error
)
go func() {
for {
if _, err := db.Exec(query); err != nil {
errMsg = err
time.Sleep(time.Second)
continue
} else {
errMsg = nil
done <- struct{}{}
break
}
}
}()
select {
case <-done:
return errMsg
case <-ctx.Done():
return fmt.Errorf("runExec %s timed out with %v / %v", query, ctx.Err(), errMsg)
}
}
示例9: reconnectOnFailure
func (c *Cluster) reconnectOnFailure(ctx context.Context) {
for {
<-ctx.Done()
c.Lock()
if c.stop || c.node != nil {
c.Unlock()
return
}
c.reconnectDelay *= 2
if c.reconnectDelay > maxReconnectDelay {
c.reconnectDelay = maxReconnectDelay
}
logrus.Warnf("Restarting swarm in %.2f seconds", c.reconnectDelay.Seconds())
delayCtx, cancel := context.WithTimeout(context.Background(), c.reconnectDelay)
c.cancelDelay = cancel
c.Unlock()
<-delayCtx.Done()
if delayCtx.Err() != context.DeadlineExceeded {
return
}
c.Lock()
if c.node != nil {
c.Unlock()
return
}
var err error
_, ctx, err = c.startNewNode(false, c.listenAddr, c.getRemoteAddress(), "", "", false)
if err != nil {
c.err = err
ctx = delayCtx
}
c.Unlock()
}
}
示例10: wait
// wait blocks until i) the new transport is up or ii) ctx is done or iii) ac is closed or
// iv) transport is in TransientFailure and the RPC is fail-fast.
func (ac *addrConn) wait(ctx context.Context, failFast bool) (transport.ClientTransport, error) {
for {
ac.mu.Lock()
switch {
case ac.state == Shutdown:
ac.mu.Unlock()
return nil, errConnClosing
case ac.state == Ready:
ct := ac.transport
ac.mu.Unlock()
return ct, nil
case ac.state == TransientFailure && failFast:
ac.mu.Unlock()
return nil, Errorf(codes.Unavailable, "grpc: RPC failed fast due to transport failure")
default:
ready := ac.ready
if ready == nil {
ready = make(chan struct{})
ac.ready = ready
}
ac.mu.Unlock()
select {
case <-ctx.Done():
return nil, toRPCErr(ctx.Err())
// Wait until the new transport is ready or failed.
case <-ready:
}
}
}
}
示例11: runQuery
func runQuery(ctx context.Context, db *sql.DB, query string) (*sql.Rows, error) {
done := make(chan struct{})
var (
rows *sql.Rows
errMsg error
)
go func() {
for {
rs, err := db.Query(query)
if err != nil {
errMsg = err
time.Sleep(time.Second)
continue
} else {
rows = rs
errMsg = nil
done <- struct{}{}
break
}
}
}()
select {
case <-done:
return rows, errMsg
case <-ctx.Done():
return nil, fmt.Errorf("runQuery %s timed out with %v / %v", query, ctx.Err(), errMsg)
}
}
示例12: AcquireTTL
// AcquireTTL acquires the lock as with `Acquire` but places a TTL on it. After the TTL expires the lock is released automatically.
func (l *lock) AcquireTTL(ctx context.Context, ttl time.Duration) error {
var err error
done := make(chan error)
Loop:
for {
acquireCtx, cancel := context.WithCancel(context.Background())
go func() {
done <- l.acquireTry(acquireCtx, ttl)
}()
select {
case err = <-done:
cancel()
if err != ErrExists {
break Loop
}
case <-ctx.Done():
cancel()
<-done
if err != ErrExists {
err = ErrTimeout
}
break Loop
}
}
return err
}
示例13: Handle
func (*hostnameHandler) Handle(ctx context.Context, prev <-chan ql.Line, next chan<- ql.Line, config map[string]interface{}) error {
field := "hostname"
ok := true
fieldIface := config["field"]
if fieldIface != nil {
field, ok = fieldIface.(string)
if !ok {
log.Log(ctx).Warn("Could not parse hostname config, using field=hostname")
field = "hostname"
}
}
log.Log(ctx).Debug("Starting filter handler", "handler", "hostname", "field", field)
hostname, _ := os.Hostname()
go func() {
for {
select {
case line := <-prev:
line.Data[field] = hostname
next <- line
case <-ctx.Done():
return
}
}
}()
return nil
}
示例14: Run
func (n *network) Run(ctx context.Context) {
wg := sync.WaitGroup{}
log.Info("Watching for new subnet leases")
evts := make(chan []subnet.Event)
wg.Add(1)
go func() {
subnet.WatchLeases(ctx, n.sm, n.name, n.lease, evts)
wg.Done()
}()
n.rl = make([]netlink.Route, 0, 10)
wg.Add(1)
go func() {
n.routeCheck(ctx)
wg.Done()
}()
defer wg.Wait()
for {
select {
case evtBatch := <-evts:
n.handleSubnetEvents(evtBatch)
case <-ctx.Done():
return
}
}
}
示例15: wait
// wait blocks until i) the new transport is up or ii) ctx is done or iii) ac is closed.
func (ac *addrConn) wait(ctx context.Context) (transport.ClientTransport, error) {
for {
ac.mu.Lock()
switch {
case ac.state == Shutdown:
ac.mu.Unlock()
return nil, errConnClosing
case ac.state == Ready:
ct := ac.transport
ac.mu.Unlock()
return ct, nil
default:
ready := ac.ready
if ready == nil {
ready = make(chan struct{})
ac.ready = ready
}
ac.mu.Unlock()
select {
case <-ctx.Done():
return nil, transport.ContextErr(ctx.Err())
// Wait until the new transport is ready or failed.
case <-ready:
}
}
}
}