How to use Lock method of toxiproxy Package

Best Toxiproxy code snippet using toxiproxy.Lock

lock_test.go

Source:lock_test.go Github

copy

Full Screen

...47 fmt.Print(print + "-----\n")48}49func TestBehaviorRelease(t *testing.T) {50 logrus.SetLevel(logrus.DebugLevel)51 hasLockCh := make(chan bool, 5)52 defer cleanUp()53 WithToxiProxy(t, func(p *toxiproxy.Proxy, c *api.Client) {54 printKeys("lock-test")55 ctx, cancel := context.WithTimeout(context.Background(), time.Millisecond*500)56 defer cancel()57 name := fmt.Sprintf("lock-test-%d", rand.Int())58 l, err := consul.SpawnLock(ctx, &consul.LockConfig{59 Client: c,60 LockOptions: &api.LockOptions{61 SessionOpts: &api.SessionEntry{62 Name: name,63 LockDelay: time.Second * 10,64 Behavior: api.SessionBehaviorRelease,65 TTL: "10s",66 },67 Value: []byte("lock-value"),68 SessionName: name,69 Key: name,70 },71 OnChange: func(hasLock bool) {72 hasLockCh <- hasLock73 },74 })75 require.NoError(t, err)76 require.NotNil(t, l)77 // Should have lock78 printKeys("lock-test")79 require.True(t, l.HasLock())80 select {81 case is := <-hasLockCh:82 assert.True(t, is)83 default:84 }85 // Interrupt connectivity to consul86 p.Stop()87 // Ensure the connectivity is broken88 _, _, err = c.KV().Get(name, nil)89 assert.Error(t, err)90 // Wait until we notice we lost lock91 is := <-hasLockCh92 assert.False(t, is)93 assert.False(t, l.HasLock())94 printKeys("lock-test")95 // Resume connectivity96 err = p.Start()97 require.NoError(t, err)98 // Wait until we regain lock99 is = <-hasLockCh100 assert.True(t, is)101 assert.True(t, l.HasLock())102 // Unlock the key103 l.Unlock([]byte("this is a test"))104 printKeys("lock-test")105 // Ensure the key is NOT deleted106 list, _, err := c.KV().List("lock-test", nil)107 require.NoError(t, err)108 var found bool109 for _, i := range list {110 if i.Key == name {111 found = true112 assert.Equal(t, i.Value, []byte("this is a test"))113 }114 }115 assert.True(t, found)116 // Delete the key117 _, err = c.KV().Delete(name, nil)118 require.NoError(t, err)119 })120}121func TestBehaviorDeleteOnUnlock(t *testing.T) {122 logrus.SetLevel(logrus.DebugLevel)123 hasLockCh := make(chan bool, 5)124 defer cleanUp()125 WithToxiProxy(t, func(p *toxiproxy.Proxy, c *api.Client) {126 ctx, cancel := context.WithTimeout(context.Background(), time.Millisecond*500)127 defer cancel()128 name := fmt.Sprintf("lock-test-delete-%d", rand.Int())129 l, err := consul.SpawnLock(ctx, &consul.LockConfig{130 Client: c,131 LockOptions: &api.LockOptions{132 SessionOpts: &api.SessionEntry{133 Name: name,134 LockDelay: time.Second * 10,135 // When SessionBehavior is Delete136 Behavior: api.SessionBehaviorDelete,137 TTL: "10s",138 },139 Value: []byte("lock-value"),140 SessionName: name,141 Key: name,142 },143 OnChange: func(hasLock bool) {144 hasLockCh <- hasLock145 },146 })147 require.NoError(t, err)148 require.NotNil(t, l)149 // Should have lock150 require.True(t, l.HasLock())151 select {152 case is := <-hasLockCh:153 assert.True(t, is)154 default:155 }156 // Unlock the key157 l.Unlock(nil)158 printKeys("lock-test")159 // Ensure the key was deleted160 list, _, err := c.KV().List("lock-test", nil)161 require.NoError(t, err)162 var found bool163 for _, i := range list {164 if i.Key == name {165 found = true166 }167 }168 assert.False(t, found)169 })170}171func TestBehaviorDeleteOnDisconnect(t *testing.T) {172 logrus.SetLevel(logrus.DebugLevel)173 defer cleanUp()174 WithToxiProxy(t, func(p *toxiproxy.Proxy, c *api.Client) {175 printKeys("lock-test")176 ctx, cancel := context.WithTimeout(context.Background(), time.Millisecond*500)177 defer cancel()178 name := fmt.Sprintf("lock-test-disconnect%d", rand.Int())179 l, err := consul.SpawnLock(ctx, &consul.LockConfig{180 Client: c,181 LockOptions: &api.LockOptions{182 SessionOpts: &api.SessionEntry{183 Name: name,184 // When SessionBehavior is Delete185 Behavior: api.SessionBehaviorDelete,186 TTL: "10s",187 },188 Value: []byte("lock-value"),189 SessionName: name,190 Key: name,191 },192 })193 require.NoError(t, err)194 require.NotNil(t, l)195 // Should have lock196 printKeys("lock-test")197 require.True(t, l.HasLock())198 // Interrupt connectivity to consul199 p.Stop()200 // Wait for the lock file to disappear201 client, err := api.NewClient(api.DefaultConfig())202 testutil.UntilPass(t, 50, time.Second, func(t testutil.TestingT) {203 kv, _, err := client.KV().Get(name, nil)204 assert.NoError(t, err)205 assert.Nil(t, kv)206 })207 // Resume connectivity208 err = p.Start()209 require.NoError(t, err)210 // Wait until we regain lock211 testutil.UntilPass(t, 50, time.Second, func(t testutil.TestingT) {212 assert.True(t, l.HasLock())213 })214 // Unlock the key215 l.Unlock(nil)216 })217}...

Full Screen

Full Screen

proxy.go

Source:proxy.go Github

copy

Full Screen

...27type ConnectionList struct {28 list map[string]net.Conn29 lock sync.Mutex30}31func (c *ConnectionList) Lock() {32 c.lock.Lock()33}34func (c *ConnectionList) Unlock() {35 c.lock.Unlock()36}37var ErrProxyAlreadyStarted = errors.New("Proxy already started")38func NewProxy() *Proxy {39 proxy := &Proxy{40 started: make(chan error),41 connections: ConnectionList{list: make(map[string]net.Conn)},42 }43 proxy.Toxics = NewToxicCollection(proxy)44 return proxy45}46func (proxy *Proxy) Start() error {47 proxy.Lock()48 defer proxy.Unlock()49 return start(proxy)50}51func (proxy *Proxy) Update(input *Proxy) error {52 proxy.Lock()53 defer proxy.Unlock()54 if input.Listen != proxy.Listen || input.Upstream != proxy.Upstream {55 stop(proxy)56 proxy.Listen = input.Listen57 proxy.Upstream = input.Upstream58 }59 if input.Enabled != proxy.Enabled {60 if input.Enabled {61 return start(proxy)62 }63 stop(proxy)64 }65 return nil66}67func (proxy *Proxy) Stop() {68 proxy.Lock()69 defer proxy.Unlock()70 stop(proxy)71}72// server runs the Proxy server, accepting new clients and creating Links to73// connect them to upstreams.74func (proxy *Proxy) server() {75 ln, err := net.Listen("tcp", proxy.Listen)76 if err != nil {77 proxy.started <- err78 return79 }80 proxy.Listen = ln.Addr().String()81 proxy.started <- nil82 logrus.WithFields(logrus.Fields{83 "name": proxy.Name,84 "proxy": proxy.Listen,85 "upstream": proxy.Upstream,86 }).Info("Started proxy")87 acceptTomb := tomb.Tomb{}88 defer acceptTomb.Done()89 // This channel is to kill the blocking Accept() call below by closing the90 // net.Listener.91 go func() {92 <-proxy.tomb.Dying()93 // Notify ln.Accept() that the shutdown was safe94 acceptTomb.Killf("Shutting down from stop()")95 // Unblock ln.Accept()96 err := ln.Close()97 if err != nil {98 logrus.WithFields(logrus.Fields{99 "proxy": proxy.Name,100 "listen": proxy.Listen,101 "err": err,102 }).Warn("Attempted to close an already closed proxy server")103 }104 // Wait for the accept loop to finish processing105 acceptTomb.Wait()106 proxy.tomb.Done()107 }()108 for {109 client, err := ln.Accept()110 if err != nil {111 // This is to confirm we're being shut down in a legit way. Unfortunately,112 // Go doesn't export the error when it's closed from Close() so we have to113 // sync up with a channel here.114 //115 // See http://zhen.org/blog/graceful-shutdown-of-go-net-dot-listeners/116 select {117 case <-acceptTomb.Dying():118 default:119 logrus.WithFields(logrus.Fields{120 "proxy": proxy.Name,121 "listen": proxy.Listen,122 "err": err,123 }).Warn("Error while accepting client")124 }125 return126 }127 logrus.WithFields(logrus.Fields{128 "name": proxy.Name,129 "client": client.RemoteAddr(),130 "proxy": proxy.Listen,131 "upstream": proxy.Upstream,132 }).Info("Accepted client")133 upstream, err := net.Dial("tcp", proxy.Upstream)134 if err != nil {135 logrus.WithFields(logrus.Fields{136 "name": proxy.Name,137 "client": client.RemoteAddr(),138 "proxy": proxy.Listen,139 "upstream": proxy.Upstream,140 }).Error("Unable to open connection to upstream")141 client.Close()142 continue143 }144 name := client.RemoteAddr().String()145 proxy.connections.Lock()146 proxy.connections.list[name+"upstream"] = upstream147 proxy.connections.list[name+"downstream"] = client148 proxy.connections.Unlock()149 proxy.Toxics.StartLink(name+"upstream", client, upstream, stream.Upstream)150 proxy.Toxics.StartLink(name+"downstream", upstream, client, stream.Downstream)151 }152}153func (proxy *Proxy) RemoveConnection(name string) {154 proxy.connections.Lock()155 defer proxy.connections.Unlock()156 delete(proxy.connections.list, name)157}158// Starts a proxy, assumes the lock has already been taken159func start(proxy *Proxy) error {160 if proxy.Enabled {161 return ErrProxyAlreadyStarted162 }163 proxy.tomb = tomb.Tomb{} // Reset tomb, from previous starts/stops164 go proxy.server()165 err := <-proxy.started166 // Only enable the proxy if it successfully started167 proxy.Enabled = err == nil168 return err169}170// Stops a proxy, assumes the lock has already been taken171func stop(proxy *Proxy) {172 if !proxy.Enabled {173 return174 }175 proxy.Enabled = false176 proxy.tomb.Killf("Shutting down from stop()")177 proxy.tomb.Wait() // Wait until we stop accepting new connections178 proxy.connections.Lock()179 defer proxy.connections.Unlock()180 for _, conn := range proxy.connections.list {181 conn.Close()182 }183 logrus.WithFields(logrus.Fields{184 "name": proxy.Name,185 "proxy": proxy.Listen,186 "upstream": proxy.Upstream,187 }).Info("Terminated proxy")188}...

Full Screen

Full Screen

Lock

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 toxiproxy := client.NewClient("localhost:8474")4 toxiproxy.CreateProxy("redis", "localhost:6379", "localhost:16379")5 toxiproxy.EnableProxy("redis")6 toxiproxy.AddLatency("redis", "downstream", 5000)7 toxiproxy.AddLatency("redis", "upstream", 5000)8 toxiproxy.AddLatency("redis", "downstream", 5000)9 toxiproxy.AddLatency("redis", "upstream", 5000)10 toxiproxy.AddLatency("redis", "downstream", 5000)11 toxiproxy.AddLatency("redis", "upstream", 5000)12 toxiproxy.AddLatency("redis", "downstream", 5000)13 toxiproxy.AddLatency("redis", "upstream", 5000)14 toxiproxy.AddLatency("redis", "downstream", 5000)15 toxiproxy.AddLatency("redis", "upstream", 5000)16 toxiproxy.AddLatency("redis", "downstream", 5000)17 toxiproxy.AddLatency("redis", "upstream", 5000)18 toxiproxy.AddLatency("redis", "downstream", 5000)19 toxiproxy.AddLatency("redis", "upstream", 5000)20 toxiproxy.AddLatency("redis", "downstream", 5000)21 toxiproxy.AddLatency("redis", "upstream", 5000)22 toxiproxy.AddLatency("redis", "downstream", 5000)23 toxiproxy.AddLatency("redis", "upstream", 5000)24 toxiproxy.AddLatency("redis", "downstream", 5000)25 toxiproxy.AddLatency("redis", "upstream", 5000)26 toxiproxy.AddLatency("redis", "downstream", 5000)27 toxiproxy.AddLatency("redis", "upstream", 5000)28 toxiproxy.AddLatency("redis", "downstream", 5000)29 toxiproxy.AddLatency("redis", "upstream

Full Screen

Full Screen

Lock

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 proxy := toxiproxy.NewProxy("test", "localhost:8081", "localhost:8080")4 proxy.Toxics = client.Toxics{5 &client.Toxic{6 Attributes: map[string]string{7 },8 },9 }10 err := proxy.Create()11 if err != nil {12 fmt.Println(err)13 }14 proxies, err := toxiproxy.Proxies()15 if err != nil {16 fmt.Println(err)17 }18 for _, proxy := range proxies {19 fmt.Println(proxy.Name)20 }21 proxy, err = toxiproxy.Get("test")22 if err != nil {23 fmt.Println(err)24 }25 fmt.Println(proxy.Name)26 err = proxy.Update()27 if err != nil {28 fmt.Println(err)29 }30 err = proxy.Delete()31 if err != nil {32 fmt.Println(err)33 }34}35import (36func main() {37 proxy, err := toxiproxy.Get("test")38 if err != nil {39 fmt.Println(err)40 }41 fmt.Println(proxy.Name)42 err = proxy.Update()43 if err != nil {44 fmt.Println(err)45 }46 err = proxy.Delete()47 if err != nil {48 fmt.Println(err)49 }50}51import (

Full Screen

Full Screen

Lock

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 proxy, err := toxiproxy.NewProxy("localhost:6379", "localhost:6380")4 if err != nil {5 fmt.Println("Error creating proxy:", err)6 }7 err = proxy.Start()8 if err != nil {9 fmt.Println("Error starting proxy:", err)10 }11 err = proxy.AddToxic("latency", "latency", "downstream", 1.0, toxiproxy.Attributes{12 })13 if err != nil {14 fmt.Println("Error adding toxic:", err)15 }16 err = proxy.AddToxic("bandwidth", "bandwidth", "downstream", 1.0, toxiproxy.Attributes{17 })18 if err != nil {19 fmt.Println("Error adding toxic:", err)20 }21 err = proxy.AddToxic("slow_close", "slow_close", "downstream", 1.0, toxiproxy.Attributes{22 })23 if err != nil {24 fmt.Println("Error adding toxic:", err)25 }26 err = proxy.AddToxic("timeout", "timeout", "downstream", 1.0, toxiproxy.Attributes{27 })28 if err != nil {29 fmt.Println("Error adding toxic:", err)30 }31 err = proxy.AddToxic("slicer", "slicer", "downstream", 1.0, toxiproxy.Attributes{32 })33 if err != nil {34 fmt.Println("Error adding toxic:", err)35 }36 err = proxy.AddToxic("timeout", "timeout", "downstream", 1.0,

Full Screen

Full Screen

Lock

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 client := toxiproxy.NewClient("localhost:8474")4 proxy, err := client.CreateProxy("test", "localhost:3000", "localhost:3001")5 if err != nil {6 log.Fatalf("Failed to create proxy: %s", err)7 }8 err = proxy.Update()9 if err != nil {10 log.Fatalf("Failed to update proxy: %s", err)11 }12 toxic, err := proxy.AddToxic("latency", "latency", "downstream", 1.0, toxiproxy.Attributes{13 })14 if err != nil {15 log.Fatalf("Failed to add toxic: %s", err)16 }17 err = proxy.UpdateToxic(toxic)18 if err != nil {19 log.Fatalf("Failed to update toxic: %s", err)20 }21 err = proxy.RemoveToxic("latency")22 if err != nil {23 log.Fatalf("Failed to remove toxic: %s", err)24 }25 proxies, err := client.Proxies()26 if err != nil {27 log.Fatalf("Failed to get proxies: %s", err)28 }29 for _, proxy := range proxies {30 fmt.Println(proxy.Name)31 }32 proxy, err = client.Proxy("test")33 if err != nil {34 log.Fatalf("Failed to get proxy: %s", err)35 }36 fmt.Println(proxy.Name)37 err = proxy.Delete()38 if err != nil {39 log.Fatalf("Failed to delete proxy: %s", err)40 }41}

Full Screen

Full Screen

Lock

Using AI Code Generation

copy

Full Screen

1func main() {2 toxiproxy.Reset()3 toxiproxy.CreateProxy("proxy1", "localhost:5000", "localhost:5001")4 toxiproxy.CreateProxy("proxy2", "localhost:5002", "localhost:5003")5 toxiproxy.CreateProxy("proxy3", "localhost:5004", "localhost:5005")6 toxiproxy.CreateProxy("proxy4", "localhost:5006", "localhost:5007")7 toxiproxy.CreateProxy("proxy5", "localhost:5008", "localhost:5009")8 toxiproxy.CreateProxy("proxy6", "localhost:5010", "localhost:5011")9 toxiproxy.CreateProxy("proxy7", "localhost:5012", "localhost:5013")10 toxiproxy.CreateProxy("proxy8", "localhost:5014", "localhost:5015")11 toxiproxy.CreateProxy("proxy9", "localhost:5016", "localhost:5017")12 toxiproxy.CreateProxy("proxy10", "localhost:5018", "localhost:5019")13 toxiproxy.CreateProxy("proxy11", "localhost:5020", "localhost:5021")14 toxiproxy.CreateProxy("proxy12", "localhost:5022", "localhost:5023")15 toxiproxy.CreateProxy("proxy13", "localhost:5024", "localhost:5025")16 toxiproxy.CreateProxy("proxy14", "localhost:5026", "localhost:5027")17 toxiproxy.CreateProxy("proxy15", "localhost:5028", "localhost:5029")18 toxiproxy.CreateProxy("proxy16", "localhost:5030", "localhost:5031")19 toxiproxy.CreateProxy("proxy17", "localhost:5032", "localhost:5033")20 toxiproxy.CreateProxy("proxy18", "localhost:5034", "localhost:5035")21 toxiproxy.CreateProxy("proxy19", "localhost:5036", "localhost:5037")22 toxiproxy.CreateProxy("proxy20", "localhost:5038", "localhost:5039")23 toxiproxy.CreateProxy("proxy21", "localhost:5040", "localhost:5041")24 toxiproxy.CreateProxy("proxy

Full Screen

Full Screen

Lock

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 proxy := toxiproxy.NewProxy("proxy", ":8080", "localhost:80")4 err := proxy.Start()5 if err != nil {6 panic(err)7 }8 fmt.Println("Proxy started")9 proxy.Toxics().Latency("latency", "downstream", 5000)10 proxy.Toxics().Bandwidth("bandwidth", "downstream", 10000)11 proxy.Toxics().SlowClose("slow_close", "downstream", 5000)12 proxy.Toxics().Timeout("timeout", "downstream", 5000)13 proxy.Toxics().Slicer("slicer", "downstream", 1000, 1000, 0)14 proxy.Toxics().LimitData("limit_data", "downstream", 10000)15 proxy.Toxics().Latency("latency", "upstream", 5000)16 proxy.Toxics().Bandwidth("bandwidth", "upstream", 10000)17 proxy.Toxics().SlowClose("slow_close", "upstream", 5000)18 proxy.Toxics().Timeout("timeout", "upstream", 5000)19 proxy.Toxics().Slicer("slicer", "upstream", 1000, 1000, 0)20 proxy.Toxics().LimitData("limit_data", "upstream", 10000)21 proxy.Toxics().Latency("latency", "all", 5000)22 proxy.Toxics().Bandwidth("bandwidth", "all", 10000)23 proxy.Toxics().SlowClose("slow_close", "all", 5000)24 proxy.Toxics().Timeout("timeout", "all", 5000)25 proxy.Toxics().Slicer("slicer", "all", 1000, 1000, 0)26 proxy.Toxics().LimitData("limit_data", "all", 10000)27 err = proxy.Delete()28 if err != nil {29 panic(err)30 }31}

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.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful