github.com/pingcap/tiflow@v0.0.0-20240520035814-5bf52d54e205/engine/executor/worker/internal/runnables.go (about) 1 // Copyright 2022 PingCAP, Inc. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // See the License for the specific language governing permissions and 12 // limitations under the License. 13 14 package internal 15 16 import ( 17 "context" 18 19 "github.com/pingcap/log" 20 "github.com/pingcap/tiflow/engine/pkg/clock" 21 "go.uber.org/atomic" 22 "go.uber.org/zap" 23 ) 24 25 // RunnableID is a unique id for the runnable 26 type RunnableID = string 27 28 // Runnable defines an interface that can be run in task runner 29 type Runnable interface { 30 Run(ctx context.Context) error 31 ID() RunnableID 32 } 33 34 // RunnableStatus is the runtime container status 35 type RunnableStatus = int32 36 37 // Defines all RunnableStatus 38 const ( 39 TaskSubmitted = RunnableStatus(iota + 1) 40 TaskRunning 41 TaskClosing 42 ) 43 44 // RunnableContainer implements Runnable, and maintains some more running information 45 type RunnableContainer struct { 46 Runnable 47 status atomic.Int32 48 info RuntimeInfo 49 } 50 51 // WrapRunnable creates a new RunnableContainer from a Runnable interface 52 func WrapRunnable(runnable Runnable, submitTime clock.MonotonicTime) *RunnableContainer { 53 return &RunnableContainer{ 54 Runnable: runnable, 55 status: *atomic.NewInt32(TaskSubmitted), 56 info: RuntimeInfo{SubmitTime: submitTime}, 57 } 58 } 59 60 // Status returns the status of RunnableContainer 61 func (c *RunnableContainer) Status() RunnableStatus { 62 return c.status.Load() 63 } 64 65 // Info returns the info of RunnableContainer 66 func (c *RunnableContainer) Info() RuntimeInfo { 67 return c.info 68 } 69 70 // OnLaunched is the callback when the runnable instance is launched. 71 func (c *RunnableContainer) OnLaunched() { 72 oldStatus := c.status.Swap(TaskRunning) 73 if oldStatus != TaskSubmitted { 74 log.Panic("unexpected status", zap.Int32("status", oldStatus)) 75 } 76 } 77 78 // OnStopped is the callback when the runnable instance is stopped 79 func (c *RunnableContainer) OnStopped() { 80 oldStatus := c.status.Swap(TaskClosing) 81 if oldStatus != TaskRunning && oldStatus != TaskSubmitted { 82 log.Panic("unexpected status", zap.Int32("status", oldStatus)) 83 } 84 }