How to use Context method of executor Package

Best K6 code snippet using executor.Context

unit.go

Source:unit.go Github

copy

Full Screen

...10 "google.golang.org/grpc"11 "google.golang.org/grpc/metadata"12)13type Unit interface {14 Invoke(context.Context, opentracing.Tracer)15 ExtractIncomingMetadata(context.Context, opentracing.Tracer) (opentracing.SpanContext, error)16 StartContext(opentracing.Tracer, opentracing.SpanContext, context.Context) (opentracing.Span, context.Context)17 EmulateWork()18 AddContextMetadata(opentracing.Span)19 Next(context.Context, opentracing.Span, opentracing.Tracer)20 CloseContext(opentracing.Span)21 GetLoadPercentage() float6422 SetWeight(int64)23 GetWeight() int6424}25type UnitExecutor struct {26 data *api.Unit27 syncCount int28 syncSet map[string]int29 WorkSampler DistributionSampler30 SuccessorClients map[string]*grpc.ClientConn31 Tags map[string]string32 Baggage map[string]string33 Logs map[string]string34 Worker *Worker35 Weight int6436}37func CreateUnitExecutorFromConfig(unitConfig *api.Unit, workerConfig *Worker) (*UnitExecutor, error) {38 dist, err := LookupDistribution(unitConfig.WorkBefore)39 if err != nil {40 //surface error from parsing the distribution41 return nil, err42 }43 // Create TLS credentials for grpc clients that skip root CA verification44 /* creds := credentials.NewTLS(&tls.Config{45 InsecureSkipVerify: true,46 })47 option := grpc.WithTransportCredentials(creds) */48 clientConnections := make(map[string]*grpc.ClientConn)49 for _, successor := range unitConfig.Successors {50 if successor.IsRemote {51 conn, err := grpc.Dial(successor.HostPort, grpc.WithInsecure())52 if err != nil {53 return nil, err54 }55 clientConnections[successor.ServiceId] = conn56 }57 }58 var tags map[string]string59 var baggage map[string]string60 var logs map[string]string61 if unitConfig.Context != nil {62 if unitConfig.Context.Tags != nil {63 tags = generateStringMap(unitConfig.Context.Tags)64 }65 if unitConfig.Context.Baggage != nil {66 baggage = generateStringMap(unitConfig.Context.Baggage)67 }68 if unitConfig.Context.Logs != nil {69 logs = generateStringMap(unitConfig.Context.Logs)70 }71 }72 return &UnitExecutor{73 data: unitConfig,74 syncCount: len(unitConfig.Inputs),75 syncSet: make(map[string]int),76 WorkSampler: dist,77 SuccessorClients: clientConnections,78 Tags: tags,79 Baggage: baggage,80 Logs: logs,81 Worker: workerConfig,82 }, nil83}84func (executor *UnitExecutor) Invoke(ctx context.Context, tracer opentracing.Tracer) {85 //Assumption: at this point we always have a context86 spanCtx, err := executor.ExtractIncomingMetadata(ctx, tracer)87 if err != nil {88 log.Fatalf("Couldn't extract metadata, please check format. Data was: %v", ctx)89 }90 spanStart := time.Now()91 span, ctxNew := executor.StartContext(tracer, spanCtx, ctx)92 executor.AddContextMetadata(span)93 executor.EmulateWork()94 executor.Next(ctxNew, span, tracer)95 sampled := getSampledFlag(span.Context())96 traceID := getTraceIdAsBytes(span.Context())97 spanID := getSpanID(span.Context())98 executor.CloseContext(span)99 finishTimeDelta := time.Since(spanStart)100 executor.Worker.SpanDurationHist.Observe(float64(finishTimeDelta.Nanoseconds() / 1000.0))101 started, err := ptypes.TimestampProto(spanStart)102 finished, err := ptypes.TimestampProto(spanStart.Add(finishTimeDelta))103 if err != nil {104 log.Fatalf("Couldn't convert timestamps to proto format.")105 }106 go executor.Worker.Reporter.Collect(&api.Result{107 TraceId: traceID,108 SpanId: spanID,109 StartTime: started,110 FinishTime: finished,111 Sampled: sampled,112 })113}114func (executor *UnitExecutor) ExtractIncomingMetadata(ctx context.Context, tracer opentracing.Tracer) (opentracing.SpanContext, error) {115 md, ok := metadata.FromIncomingContext(ctx)116 if !ok {117 md = metadata.New(nil)118 }119 remoteContext, err := tracer.Extract(opentracing.HTTPHeaders, metadataReaderWriter{md})120 //if there is no span context to be found in headers, were fine actually, because it means that this is a root span. Could do an additional check for that here.121 if err != nil && err != opentracing.ErrSpanContextNotFound {122 return nil, err123 }124 return remoteContext, nil125}126func (executor *UnitExecutor) StartContext(tracer opentracing.Tracer, spancontext opentracing.SpanContext, ctx context.Context) (opentracing.Span, context.Context) {127 return opentracing.StartSpanFromContextWithTracer(ctx, tracer, executor.data.Identifier, mapOpenTracingRelationshipType(executor.data.RelType, spancontext))128 //var span opentracing.Span129 //spanStart := time.Now() TODO: do local measurements130 //if executor.data.ThroughputRatio != 0.0 {131 //start local "parent" span as root span132 //span = tracer.StartSpan(executor.data.Identifier)133 //} else {134 //start local span with relationship indicator135 // relationshipTypeOption := mapOpenTracingRelationshipType(executor.data.RelType, spanContext)136 // span = tracer.StartSpan(executor.data.Identifier, relationshipTypeOption)137 //}138 //return span139}140func mapOpenTracingRelationshipType(relType api.RelationshipType, spanContext opentracing.SpanContext) opentracing.StartSpanOption {141 switch relType {142 case api.RelationshipType_FOLLOWS:143 return opentracing.FollowsFrom(spanContext)144 default:145 return opentracing.ChildOf(spanContext)146 }147}148func (executor *UnitExecutor) EmulateWork() {149 <-time.NewTimer(executor.WorkSampler.GetNextValue()).C150}151func (executor *UnitExecutor) AddContextMetadata(span opentracing.Span) {152 for k, v := range executor.Tags {153 span.SetTag(k, v)154 }155 for k, v := range executor.Baggage {156 span.SetBaggageItem(k, v)157 }158 for k, v := range executor.Logs {159 //we chose the LogFields method here over logKV160 span.LogFields(161 otlog.String(k, v),162 )163 }164}165func (executor *UnitExecutor) Next(ctx context.Context, span opentracing.Span, tracer opentracing.Tracer) {166 //for each successor we have 4 different cases: remote or local, req-resp or fire and forget167 //var ctxNew context.Context168 for _, successor := range executor.data.Successors {169 localClientSpan, ctxNew := opentracing.StartSpanFromContextWithTracer(ctx, tracer, "invoke-"+successor.UnitId, mapOpenTracingRelationshipType(executor.data.RelType, span.Context()))170 //localClientSpan := tracer.StartSpan("invoke-"+successor.UnitId, mapOpenTracingRelationshipType(api.RelationshipType_CHILD, span.Context()))171 //ctxNew = opentracing.ContextWithSpan(ctx, localClientSpan)172 if successor.IsRemote {173 md, ok := metadata.FromOutgoingContext(ctxNew)174 if !ok {175 md = metadata.New(nil)176 } else {177 md = md.Copy()178 }179 mdWriter := metadataReaderWriter{md}180 //Step 3b: Inject the local span context with HTTP-Header-Format into the metadatawriter.181 err := tracer.Inject(localClientSpan.Context(), opentracing.HTTPHeaders, mdWriter)182 if err != nil {183 log.Printf("Tracer.Inject() failed: %v", err)184 }185 if successor.Sync {186 //Step 3a: Use context ("outgoing" is from the perspective of the calling service!) and create a metadata writer;187 api.NewBenchmarkWorkerClient(executor.SuccessorClients[successor.ServiceId]).Call(metadata.NewOutgoingContext(ctxNew, md), &api.DispatchId{UnitReference: successor.UnitId})188 } else {189 go api.NewBenchmarkWorkerClient(executor.SuccessorClients[successor.ServiceId]).Call(metadata.NewOutgoingContext(ctxNew, md), &api.DispatchId{UnitReference: successor.UnitId})190 }191 } else {192 if successor.Sync {193 executor.Worker.UnitExecutorMap[successor.UnitId].Invoke(ctxNew, tracer)194 } else {195 go executor.Worker.UnitExecutorMap[successor.UnitId].Invoke(ctxNew, tracer)196 }197 }198 localClientSpan.Finish()199 }200}201func (executor *UnitExecutor) CloseContext(span opentracing.Span) {202 span.Finish()203}204//Turns templates for tags and baggage into a map of strings to strings.205func generateStringMap(templates []*api.KeyValueTemplate) map[string]string {206 data := make(map[string]string, len(templates))207 for _, tagTemplate := range templates {208 //Differentiation 0: key is static value, i.e. check for length to be 0 or less209 if tagTemplate.GetKeyLength() <= 0 {210 //Differentiation 1: value is a static value, i.e. check for length to be 0 or less211 if tagTemplate.GetValueLength() <= 0 {212 data[tagTemplate.GetKeyStatic()] = tagTemplate.GetValueStatic()213 } else {214 data[tagTemplate.GetKeyStatic()] = RandStringWithLength(tagTemplate.GetValueLength())215 }...

Full Screen

Full Screen

unbounded_executor.go

Source:unbounded_executor.go Github

copy

Full Screen

...15 return recovered16}17const StopSignal = "STOP!"18type UnboundedExecutor struct {19 ctx context.Context20 cancel context.CancelFunc21 activeGoroutinesMutex *sync.Mutex22 activeGoroutines map[string]int23}24// GlobalUnboundedExecutor has the life cycle of the program itself25// any goroutine want to be shutdown before main exit can be started from this executor26var GlobalUnboundedExecutor = NewUnboundedExecutor()27func NewUnboundedExecutor() *UnboundedExecutor {28 ctx, cancel := context.WithCancel(context.TODO())29 return &UnboundedExecutor{30 ctx: ctx,31 cancel: cancel,32 activeGoroutinesMutex: &sync.Mutex{},33 activeGoroutines: map[string]int{},34 }35}36func (executor *UnboundedExecutor) Go(handler func(ctx context.Context)) {37 _, file, line, _ := runtime.Caller(1)38 executor.activeGoroutinesMutex.Lock()39 defer executor.activeGoroutinesMutex.Unlock()40 startFrom := fmt.Sprintf("%s:%d", file, line)41 executor.activeGoroutines[startFrom] += 142 go func() {43 defer func() {44 recovered := recover()45 if recovered != nil && recovered != StopSignal {46 LogPanic(recovered)47 }48 executor.activeGoroutinesMutex.Lock()49 defer executor.activeGoroutinesMutex.Unlock()50 executor.activeGoroutines[startFrom] -= 151 }()52 handler(executor.ctx)53 }()54}55func (executor *UnboundedExecutor) Stop() {56 executor.cancel()57}58func (executor *UnboundedExecutor) StopAndWaitForever() {59 executor.StopAndWait(context.Background())60}61func (executor *UnboundedExecutor) StopAndWait(ctx context.Context) {62 executor.cancel()63 for {64 fiveSeconds := time.NewTimer(time.Millisecond * 100)65 select {66 case <-fiveSeconds.C:67 case <-ctx.Done():68 return69 }70 if executor.checkGoroutines() {71 return72 }73 }74}75func (executor *UnboundedExecutor) checkGoroutines() bool {...

Full Screen

Full Screen

Context

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 ctx := context.Background()4 ctx, cancel := context.WithTimeout(ctx, 10*time.Second)5 defer cancel()6 go func() {7 time.Sleep(5 * time.Second)8 cancel()9 }()10 select {11 case <-time.After(20 * time.Second):12 fmt.Println("overslept")13 case <-ctx.Done():14 fmt.Println(ctx.Err())15 }16}17ch := make(chan int, 10)18import (19func main() {20 ch := make(chan string, 2)21 go func() {22 fmt.Println("successfully sent steve to channel")23 }()24 time.Sleep(2 * time.Second)25 fmt.Println(<-ch)26 fmt.Println(<-ch)27 fmt.Println(<-ch)28}29import (30func main() {31 ch := make(chan int, 2)32 close(ch)33 for i := range ch {34 fmt.Println(i)35 }36}

Full Screen

Full Screen

Context

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 ctx, cancel := context.WithCancel(context.Background())4 wg := sync.WaitGroup{}5 wg.Add(1)6 go func() {7 defer wg.Done()8 ticker := time.NewTicker(1 * time.Second)9 for {10 select {11 case <-ctx.Done():12 fmt.Println("context is done")13 fmt.Println("counter is incremented to", counter)14 }15 }16 }()17 time.Sleep(5 * time.Second)18 cancel()19 wg.Wait()20}21import (22func main() {23 ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)24 wg := sync.WaitGroup{}25 wg.Add(1)26 go func() {

Full Screen

Full Screen

Context

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 ctx := context.Background()4 ctx, cancel := context.WithCancel(ctx)5 ctx, _ = context.WithDeadline(ctx, time.Now().Add(5*time.Second))6 ctx, _ = context.WithTimeout(ctx, 5*time.Second)7 ctx = context.WithValue(ctx, key, "value")8 ctx = context.WithValue(ctx, key, "value")9 ctx = context.WithValue(ctx, key, "value")10 ctx = context.WithValue(ctx, key, "value")11 ctx = context.WithValue(ctx, key, "value")12 ctx = context.WithValue(ctx, key, "value")13 ctx = context.WithValue(ctx, key, "value")14 ctx = context.WithValue(ctx, key, "value")15 ctx = context.WithValue(ctx, key, "value")16 ctx = context.WithValue(ctx, key, "value")17 ctx = context.WithValue(ctx, key, "value")18 ctx = context.WithValue(ctx, key, "value")19 ctx = context.WithValue(ctx, key, "value")20 ctx = context.WithValue(ctx, key, "value")21 ctx = context.WithValue(ctx, key, "value")22 ctx = context.WithValue(ctx, key, "value")23 ctx = context.WithValue(ctx, key, "value")

Full Screen

Full Screen

Context

Using AI Code Generation

copy

Full Screen

1import java.util.concurrent.*;2class MyThread implements Runnable {3 public void run() {4 System.out.println("Thread is running");5 }6}7class Task implements Runnable {8 public void run() {9 System.out.println("Task is running");10 }11}12class ExecutorDemo {13 public static void main(String[] args) {14 ExecutorService executor = Executors.newFixedThreadPool(5);15 for (int i = 0; i < 5; i++) {16 Runnable worker = new MyThread();17 executor.execute(worker);18 }19 executor.shutdown();20 while (!executor.isTerminated()) {21 }22 System.out.println("Finished all threads");23 ExecutorService executor1 = Executors.newFixedThreadPool(5);24 for (int i = 0; i < 5; i++) {25 Runnable worker = new Task();26 executor1.execute(worker);27 }28 executor1.shutdown();29 while (!executor1.isTerminated()) {30 }31 System.out.println("Finished all threads");32 ExecutorService executor2 = Executors.newFixedThreadPool(5);33 for (int i = 0; i < 5; i++) {34 Runnable worker = new MyThread();35 executor2.execute(worker);36 }37 executor2.shutdown();38 while (!executor2.isTerminated()) {39 }40 System.out.println("Finished all threads");41 ExecutorService executor3 = Executors.newFixedThreadPool(5);42 for (int i = 0; i < 5; i++) {43 Runnable worker = new Task();44 executor3.execute(worker);45 }46 executor3.shutdown();47 while (!executor3.isTerminated()) {48 }49 System.out.println("Finished all threads");50 ExecutorService executor4 = Executors.newFixedThreadPool(5);51 for (int i = 0; i < 5; i++) {52 Runnable worker = new MyThread();53 executor4.execute(worker);54 }55 executor4.shutdown();56 while (!executor4.isTerminated()) {57 }58 System.out.println("Finished all threads");59 ExecutorService executor5 = Executors.newFixedThreadPool(5);60 for (int i = 0; i < 5; i++) {61 Runnable worker = new Task();62 executor5.execute(worker);63 }64 executor5.shutdown();65 while (!executor5.isTerminated()) {66 }67 System.out.println("Finished all threads");

Full Screen

Full Screen

Context

Using AI Code Generation

copy

Full Screen

1func main() {2 executor := NewExecutor()3 ctx := executor.Context()4 fmt.Println(ctx)5}6func (e *Executor) Context() context.Context {7}8func (e *Executor) Deadline() (time.Time, bool) {9 return e.ctx.Deadline()10}11func (e *Executor) Done() <-chan struct{} {12 return e.ctx.Done()13}14func (e *Executor) Err() error {15 return e.ctx.Err()16}

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run K6 automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Most used method in

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful