How to use Direction method of toxiproxy Package

Best Toxiproxy code snippet using toxiproxy.Direction

network.go

Source:network.go Github

copy

Full Screen

1// Copyright 2018 The Cockroach Authors.2//3// Use of this software is governed by the Business Source License4// included in the file licenses/BSL.txt.5//6// As of the Change Date specified in that file, in accordance with7// the Business Source License, use of this software will be governed8// by the Apache License, Version 2.0, included in the file9// licenses/APL.txt.10package main11import (12 "bytes"13 "context"14 "fmt"15 "io/ioutil"16 "net/http"17 "time"18 toxiproxy "github.com/Shopify/toxiproxy/client"19 _ "github.com/lib/pq"20)21// runNetworkSanity is just a sanity check to make sure we're setting up toxiproxy22// correctly.23func runNetworkSanity(ctx context.Context, t *test, origC *cluster, nodes int) {24 origC.Put(ctx, cockroach, "./cockroach", origC.All())25 c, err := Toxify(ctx, t.l, origC, origC.All())26 if err != nil {27 t.Fatal(err)28 }29 c.Start(ctx, t, c.All())30 db := c.Conn(ctx, 1) // unaffected by toxiproxy31 defer db.Close()32 waitForFullReplication(t, db)33 // NB: we're generous with latency in this test because we're checking that34 // the upstream connections aren't affected by latency below, but the fixed35 // cost of starting the binary and processing the query is already close to36 // 100ms.37 //38 // NB: last node gets no latency injected, but first node gets cut off below.39 const latency = 300 * time.Millisecond40 for i := 1; i <= nodes; i++ {41 // NB: note that these latencies only apply to connections *to* the node42 // on which the toxic is active. That is, if n1 has a (down or upstream)43 // latency toxic of 100ms, then none of its outbound connections are44 // affected but any connections made to it by other nodes will.45 // In particular, it's difficult to simulate intricate network partitions46 // as there's no way to activate toxics only for certain peers.47 proxy := c.Proxy(i)48 if _, err := proxy.AddToxic("", "latency", "downstream", 1, toxiproxy.Attributes{49 "latency": latency / (2 * time.Millisecond), // ms50 }); err != nil {51 t.Fatal(err)52 }53 if _, err := proxy.AddToxic("", "latency", "upstream", 1, toxiproxy.Attributes{54 "latency": latency / (2 * time.Millisecond), // ms55 }); err != nil {56 t.Fatal(err)57 }58 }59 m := newMonitor(ctx, c.cluster, c.All())60 m.Go(func(ctx context.Context) error {61 c.Measure(ctx, 1, `SET CLUSTER SETTING trace.debug.enable = true`)62 c.Measure(ctx, 1, "CREATE DATABASE test")63 c.Measure(ctx, 1, `CREATE TABLE test.commit (a INT, b INT, v INT, PRIMARY KEY (a, b))`)64 for i := 0; i < 10; i++ {65 duration := c.Measure(ctx, 1, fmt.Sprintf(66 "BEGIN; INSERT INTO test.commit VALUES (2, %[1]d), (1, %[1]d), (3, %[1]d); COMMIT",67 i,68 ))69 c.l.Printf("%s\n", duration)70 }71 c.Measure(ctx, 1, `72set tracing=on;73insert into test.commit values(3,1000), (1,1000), (2,1000);74select age, message from [ show trace for session ];75`)76 for i := 1; i < origC.spec.NodeCount; i++ {77 if dur := c.Measure(ctx, i, `SELECT 1`); dur > latency {78 t.Fatalf("node %d unexpectedly affected by latency: select 1 took %.2fs", i, dur.Seconds())79 }80 }81 return nil82 })83 m.Wait()84}85func runNetworkTPCC(ctx context.Context, t *test, origC *cluster, nodes int) {86 n := origC.spec.NodeCount87 serverNodes, workerNode := origC.Range(1, n-1), origC.Node(n)88 origC.Put(ctx, cockroach, "./cockroach", origC.All())89 origC.Put(ctx, workload, "./workload", origC.All())90 c, err := Toxify(ctx, t.l, origC, serverNodes)91 if err != nil {92 t.Fatal(err)93 }94 const warehouses = 195 c.Start(ctx, t, serverNodes)96 c.Run(ctx, workerNode, fmt.Sprintf(97 `./workload fixtures load tpcc --warehouses=%d {pgurl:1}`, warehouses,98 ))99 db := c.Conn(ctx, 1)100 defer db.Close()101 waitForFullReplication(t, db)102 duration := time.Hour103 if local {104 // NB: this is really just testing the test with this duration, it won't105 // be able to detect slow goroutine leaks.106 duration = 5 * time.Minute107 }108 // Run TPCC, but don't give it the first node (or it basically won't do anything).109 m := newMonitor(ctx, c.cluster, serverNodes)110 m.Go(func(ctx context.Context) error {111 t.WorkerStatus("running tpcc")112 tpccL, err := c.l.ChildLogger("tpcc", quietStdout, quietStderr)113 if err != nil {114 return err115 }116 cmd := fmt.Sprintf(117 "./workload run tpcc --warehouses=%d --wait=false"+118 " --histograms="+perfArtifactsDir+"/stats.json"+119 " --duration=%s {pgurl:2-%d}",120 warehouses, duration, c.spec.NodeCount-1)121 return c.RunL(ctx, tpccL, workerNode, cmd)122 })123 checkGoroutines := func(ctx context.Context) int {124 // NB: at the time of writing, the goroutine count would quickly125 // stabilize near 230 when the network is partitioned, and around 270126 // when it isn't. Experimentally a past "slow" goroutine leak leaked ~3127 // goroutines every minute (though it would likely be more with the tpcc128 // workload above), which over the duration of an hour would easily push129 // us over the threshold.130 const thresh = 350131 uiAddrs := c.ExternalAdminUIAddr(ctx, serverNodes)132 var maxSeen int133 for _, addr := range uiAddrs {134 url := "http://" + addr + "/debug/pprof/goroutine?debug=2"135 resp, err := http.Get(url)136 if err != nil {137 t.Fatal(err)138 }139 content, err := ioutil.ReadAll(resp.Body)140 resp.Body.Close()141 if err != nil {142 t.Fatal(err)143 }144 numGoroutines := bytes.Count(content, []byte("goroutine "))145 if numGoroutines >= thresh {146 t.Fatalf("%s shows %d goroutines (expected <%d)", url, numGoroutines, thresh)147 }148 if maxSeen < numGoroutines {149 maxSeen = numGoroutines150 }151 }152 return maxSeen153 }154 m.Go(func(ctx context.Context) error {155 time.Sleep(10 * time.Second) // give tpcc a head start156 // Give n1 a network partition from the remainder of the cluster. Note that even though it affects157 // both the "upstream" and "downstream" directions, this is in fact an asymmetric partition since158 // it only affects connections *to* the node. n1 itself can connect to the cluster just fine.159 proxy := c.Proxy(1)160 c.l.Printf("letting inbound traffic to first node time out")161 for _, direction := range []string{"upstream", "downstream"} {162 if _, err := proxy.AddToxic("", "timeout", direction, 1, toxiproxy.Attributes{163 "timeout": 0, // forever164 }); err != nil {165 t.Fatal(err)166 }167 }168 t.WorkerStatus("checking goroutines")169 done := time.After(duration)170 var maxSeen int171 for {172 cur := checkGoroutines(ctx)173 if maxSeen < cur {174 c.l.Printf("new goroutine peak: %d", cur)175 maxSeen = cur176 }177 select {178 case <-done:179 c.l.Printf("done checking goroutines, repairing network")180 // Repair the network. Note that the TPCC workload would never181 // finish (despite the duration) without this. In particular,182 // we don't want to m.Wait() before we do this.183 toxics, err := proxy.Toxics()184 if err != nil {185 t.Fatal(err)186 }187 for _, toxic := range toxics {188 if err := proxy.RemoveToxic(toxic.Name); err != nil {189 t.Fatal(err)190 }191 }192 c.l.Printf("network is repaired")193 // Verify that goroutine count doesn't spike.194 for i := 0; i < 20; i++ {195 nowGoroutines := checkGoroutines(ctx)196 c.l.Printf("currently at most %d goroutines per node", nowGoroutines)197 time.Sleep(time.Second)198 }199 return nil200 default:201 time.Sleep(3 * time.Second)202 }203 }204 })205 m.Wait()206}207func registerNetwork(r *testRegistry) {208 const numNodes = 4209 r.Add(testSpec{210 Name: fmt.Sprintf("network/sanity/nodes=%d", numNodes),211 Cluster: makeClusterSpec(numNodes),212 Run: func(ctx context.Context, t *test, c *cluster) {213 runNetworkSanity(ctx, t, c, numNodes)214 },215 })216 r.Add(testSpec{217 Name: fmt.Sprintf("network/tpcc/nodes=%d", numNodes),218 Cluster: makeClusterSpec(numNodes),219 Run: func(ctx context.Context, t *test, c *cluster) {220 runNetworkTPCC(ctx, t, c, numNodes)221 },222 })223}...

Full Screen

Full Screen

client.go

Source:client.go Github

copy

Full Screen

1// Package Toxiproxy provides a client wrapper around the Toxiproxy HTTP API for2// testing the resiliency of Go applications.3package toxiproxy4import (5 "bytes"6 "encoding/json"7 "fmt"8 "net/http"9)10// Client holds information about where to connect to Toxiproxy.11type Client struct {12 endpoint string13}14type Toxic map[string]interface{}15type Toxics map[string]Toxic16// Proxy represents a Proxy.17type Proxy struct {18 Name string `json:"name"` // The name of the proxy19 Listen string `json:"listen"` // The address the proxy listens on20 Upstream string `json:"upstream"` // The upstream address to proxy to21 Enabled bool `json:"enabled"` // Whether the proxy is enabled22 ToxicsUpstream Toxics `json:"upstream_toxics"` // Toxics in the upstream direction23 ToxicsDownstream Toxics `json:"downstream_toxics"` // Toxics in the downstream direction24 client *Client25}26// NewClient creates a new client which provides the base of all communication27// with Toxiproxy. Endpoint is the address to the proxy (e.g. localhost:8474 if28// not overriden)29func NewClient(endpoint string) *Client {30 return &Client{endpoint: endpoint}31}32// Proxies returns a map with all the proxies and their toxics.33func (client *Client) Proxies() (map[string]*Proxy, error) {34 resp, err := http.Get(client.endpoint + "/proxies")35 if err != nil {36 return nil, err37 }38 err = checkError(resp, http.StatusOK, "Proxies")39 if err != nil {40 return nil, err41 }42 proxies := make(map[string]*Proxy)43 err = json.NewDecoder(resp.Body).Decode(&proxies)44 if err != nil {45 return nil, err46 }47 for _, proxy := range proxies {48 proxy.client = client49 }50 return proxies, nil51}52// NewProxy instantiates a new proxy instance. Note Create() must be called on53// it to create it. The Enabled field must be set to true, otherwise the Proxy54// will not be enabled when created.55func (client *Client) NewProxy(proxy *Proxy) *Proxy {56 if proxy == nil {57 proxy = &Proxy{}58 }59 proxy.client = client60 return proxy61}62// Create creates a new proxy.63func (proxy *Proxy) Create() error {64 request, err := json.Marshal(proxy)65 if err != nil {66 return err67 }68 resp, err := http.Post(proxy.client.endpoint+"/proxies", "application/json", bytes.NewReader(request))69 if err != nil {70 return err71 }72 err = checkError(resp, http.StatusCreated, "Create")73 if err != nil {74 return err75 }76 proxy = new(Proxy)77 err = json.NewDecoder(resp.Body).Decode(&proxy)78 if err != nil {79 return err80 }81 return nil82}83// Proxy returns a proxy by name.84func (client *Client) Proxy(name string) (*Proxy, error) {85 // TODO url encode86 resp, err := http.Get(client.endpoint + "/proxies/" + name)87 if err != nil {88 return nil, err89 }90 err = checkError(resp, http.StatusOK, "Proxy")91 if err != nil {92 return nil, err93 }94 proxy := client.NewProxy(nil)95 err = json.NewDecoder(resp.Body).Decode(proxy)96 if err != nil {97 return nil, err98 }99 return proxy, nil100}101// Save saves changes to a proxy such as its enabled status.102func (proxy *Proxy) Save() error {103 request, err := json.Marshal(proxy)104 if err != nil {105 return err106 }107 resp, err := http.Post(proxy.client.endpoint+"/proxies/"+proxy.Name, "application/json", bytes.NewReader(request))108 if err != nil {109 return err110 }111 err = checkError(resp, http.StatusOK, "Save")112 if err != nil {113 return err114 }115 err = json.NewDecoder(resp.Body).Decode(proxy)116 if err != nil {117 return err118 }119 return nil120}121// Delete a proxy which will cause it to stop listening and delete all122// information associated with it. If you just wish to stop and later enable a123// proxy, set the `Enabled` field to `false` and call `Save()`.124func (proxy *Proxy) Delete() error {125 httpClient := &http.Client{}126 req, err := http.NewRequest("DELETE", proxy.client.endpoint+"/proxies/"+proxy.Name, nil)127 if err != nil {128 return err129 }130 resp, err := httpClient.Do(req)131 if err != nil {132 return err133 }134 return checkError(resp, http.StatusNoContent, "Delete")135}136// Toxics returns a map of all the toxics and their attributes for a direction.137func (proxy *Proxy) Toxics(direction string) (Toxics, error) {138 resp, err := http.Get(proxy.client.endpoint + "/proxies/" + proxy.Name + "/" + direction + "/toxics")139 if err != nil {140 return nil, err141 }142 err = checkError(resp, http.StatusOK, "Toxics")143 if err != nil {144 return nil, err145 }146 toxics := make(Toxics)147 err = json.NewDecoder(resp.Body).Decode(&toxics)148 if err != nil {149 return nil, err150 }151 return toxics, nil152}153// SetToxic sets the parameters for a toxic with a given name in the direction.154// See https://github.com/Shopify/toxiproxy#toxics for a list of all Toxics.155func (proxy *Proxy) SetToxic(name string, direction string, toxic Toxic) (Toxic, error) {156 request, err := json.Marshal(toxic)157 if err != nil {158 return nil, err159 }160 resp, err := http.Post(proxy.client.endpoint+"/proxies/"+proxy.Name+"/"+direction+"/toxics/"+name, "application/json", bytes.NewReader(request))161 if err != nil {162 return nil, err163 }164 err = checkError(resp, http.StatusOK, "SetToxic")165 if err != nil {166 return nil, err167 }168 toxics := make(Toxic)169 err = json.NewDecoder(resp.Body).Decode(&toxics)170 if err != nil {171 return nil, err172 }173 return toxics, nil174}175// ResetState resets the state of all proxies and toxics in Toxiproxy.176func (client *Client) ResetState() error {177 resp, err := http.Get(client.endpoint + "/reset")178 if err != nil {179 return err180 }181 return checkError(resp, http.StatusNoContent, "ResetState")182}183type ApiError struct {184 Title string `json:"title"`185 Status int `json:"status"`186}187func (err *ApiError) Error() string {188 return fmt.Sprintf("HTTP %d: %s", err.Status, err.Title)189}190func checkError(resp *http.Response, expectedCode int, caller string) error {191 if resp.StatusCode != expectedCode {192 apiError := new(ApiError)193 err := json.NewDecoder(resp.Body).Decode(apiError)194 if err != nil {195 apiError.Title = fmt.Sprintf("Unexpected response code, expected %d", expectedCode)196 apiError.Status = resp.StatusCode197 }198 return fmt.Errorf("%s: %v", caller, apiError)199 }200 return nil201}...

Full Screen

Full Screen

Direction

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 client := toxiproxy.NewClient("localhost:8474")4 toxics, err := client.Toxics("redis")5 if err != nil {6 panic(err)7 }8 for _, toxic := range toxics {9 fmt.Println(toxic.Name)10 fmt.Println(toxic.Stream)11 fmt.Println(toxic.Type)12 fmt.Println(toxic.Direction)13 fmt.Println(toxic.Toxicity)14 fmt.Println(toxic.Attributes)15 fmt.Println(toxic.CreatedAt)16 }17}18import (19func main() {20 client := toxiproxy.NewClient("localhost:8474")21 toxics, err := client.Toxics("redis")22 if err != nil {23 panic(err)24 }25 for _, toxic := range toxics {26 fmt.Println(toxic.Name)27 fmt.Println(toxic.Stream)28 fmt.Println(toxic.Type)29 fmt.Println(toxic.Direction())30 fmt.Println(toxic.Toxicity)31 fmt.Println(toxic.Attributes)32 fmt.Println(toxic.CreatedAt)33 }34}

Full Screen

Full Screen

Direction

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 client := toxiproxy.NewClient("localhost:8474")4 toxics, err := client.Toxics("redis-master")5 if err != nil {6 fmt.Printf("error: %s7 }8 fmt.Printf("toxics: %v9}10import (11func main() {12 client := toxiproxy.NewClient("localhost:8474")13 toxics, err := client.Toxics("redis-master")14 if err != nil {15 fmt.Printf("error: %s16 }17 fmt.Printf("toxics: %v18}19import (20func main() {21 client := toxiproxy.NewClient("localhost:8474")22 toxics, err := client.Toxics("redis-master")23 if err != nil {24 fmt.Printf("error: %s25 }26 fmt.Printf("toxics: %v27}28import (29func main() {30 client := toxiproxy.NewClient("localhost:8474")31 toxics, err := client.Toxics("redis-master")32 if err != nil {33 fmt.Printf("error: %s34 }35 fmt.Printf("toxics: %v36}37import (38func main() {39 client := toxiproxy.NewClient("localhost:8474")

Full Screen

Full Screen

Direction

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 client := toxiproxy.NewClient("localhost:8474")4 client.CreateProxy("redis", "localhost:6379", "localhost:16379")5 client.CreateProxy("mysql", "localhost:3306", "localhost:13306")6 client.CreateProxy("http", "localhost:80", "localhost:8080")7 client.CreateProxy("https", "localhost:443", "localhost:8443")8 client.CreateProxy("memcache", "localhost:11211", "localhost:11111")9 client.CreateProxy("tcp", "localhost:9999", "localhost:9998")10 client.CreateProxy("dns", "localhost:53", "localhost:5353")11 client.CreateProxy("test", "localhost:3000", "localhost:3001")12 client.CreateProxy("test2", "localhost:3000", "localhost:3002")13 client.CreateProxy("test3", "localhost:3000", "localhost:3003")14 client.CreateProxy("test4", "localhost:3000", "localhost:3004")15 client.CreateProxy("test5", "localhost:3000", "localhost:3005")16 client.CreateProxy("test6", "localhost:3000", "localhost:3006")17 client.CreateProxy("test7", "localhost:3000", "localhost:3007")18 client.CreateProxy("test8", "localhost:3000", "localhost:3008")19 client.CreateProxy("test9", "localhost:3000", "localhost:3009")20 proxies, err := client.Proxies()21 if err != nil {22 panic(err)23 }24 fmt.Println(proxies)25 proxy, err := client.Proxy("test")26 if err != nil {27 panic(err)28 }29 fmt.Println(proxy)30 proxy.Enable()31 proxy.Disable()32 proxy.Save()33 proxy.Delete()34 toxic := toxiproxy.Toxic{

Full Screen

Full Screen

Direction

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 proxy, _ := toxiproxy.NewClient("localhost:8474")4 direction, _ := proxy.Direction("redis")5 fmt.Println(direction)6}7[{"name":"redis","listen":"localhost:6379","upstream":"localhost:6378","enabled":true}]8{"name":"redis","listen":"localhost:6379","upstream":"localhost:6378","enabled":true}9{"name":"latency","type":"latency","stream":"upstream","toxicity":1,"attributes":{"latency":0,"jitter":0}}10{"name":"latency","type":"latency","stream":"upstream","toxicity":1,"attributes":{"latency":0,"jitter":0}}11{"name":"latency","type":"latency","stream":"downstream","toxicity":1,"attributes":{"latency":0,"jitter":0}}12{"name":"latency","type":"latency","stream":"downstream","toxicity":1,"attributes":{"latency":0,"jitter":0}}13{"name":"latency","type":"latency","stream":"upstream","toxicity":1,"attributes":{"latency":0,"jitter":0}}14{"name":"redis","listen":"localhost:6379","upstream":"localhost:6378","enabled":true}15{"name":"slow_close","type":"slow_close","stream":"up

Full Screen

Full Screen

Direction

Using AI Code Generation

copy

Full Screen

1toxiproxy.Direction("upstream")2toxiproxy.Direction("downstream")3toxiproxy.Enable()4toxiproxy.Enable()5toxiproxy.Disable()6toxiproxy.Disable()7toxiproxy.Latency(100)8toxiproxy.Latency(100)9toxiproxy.LatencyJitter(10)10toxiproxy.LatencyJitter(10)11toxiproxy.LatencyJitter(10)12toxiproxy.LatencyJitter(10)13toxiproxy.Bandwidth(100)14toxiproxy.Bandwidth(100)15toxiproxy.Slicer(100)16toxiproxy.Slicer(100)

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