Best K6 code snippet using metrics.GetTags
nginx_plus_api_metrics.go
Source:nginx_plus_api_metrics.go
1package nginx_plus_api2import (3 "encoding/json"4 "errors"5 "fmt"6 "io/ioutil"7 "net"8 "net/http"9 "net/url"10 "strconv"11 "strings"12 "github.com/influxdata/telegraf"13)14var (15 // errNotFound signals that the NGINX API routes does not exist.16 errNotFound = errors.New("not found")17)18func (n *NginxPlusApi) gatherMetrics(addr *url.URL, acc telegraf.Accumulator) {19 addError(acc, n.gatherProcessesMetrics(addr, acc))20 addError(acc, n.gatherConnectionsMetrics(addr, acc))21 addError(acc, n.gatherSslMetrics(addr, acc))22 addError(acc, n.gatherHttpRequestsMetrics(addr, acc))23 addError(acc, n.gatherHttpServerZonesMetrics(addr, acc))24 addError(acc, n.gatherHttpUpstreamsMetrics(addr, acc))25 addError(acc, n.gatherHttpCachesMetrics(addr, acc))26 addError(acc, n.gatherStreamServerZonesMetrics(addr, acc))27 addError(acc, n.gatherStreamUpstreamsMetrics(addr, acc))28}29func addError(acc telegraf.Accumulator, err error) {30 // This plugin has hardcoded API resource paths it checks that may not31 // be in the nginx.conf. Currently, this is to prevent logging of32 // paths that are not configured.33 //34 // The correct solution is to do a GET to /api to get the available paths35 // on the server rather than simply ignore.36 if err != errNotFound {37 acc.AddError(err)38 }39}40func (n *NginxPlusApi) gatherUrl(addr *url.URL, path string) ([]byte, error) {41 url := fmt.Sprintf("%s/%d/%s", addr.String(), n.ApiVersion, path)42 resp, err := n.client.Get(url)43 if err != nil {44 return nil, fmt.Errorf("error making HTTP request to %s: %s", url, err)45 }46 defer resp.Body.Close()47 switch resp.StatusCode {48 case http.StatusOK:49 case http.StatusNotFound:50 // format as special error to catch and ignore as some nginx API51 // features are either optional, or only available in some versions52 return nil, errNotFound53 default:54 return nil, fmt.Errorf("%s returned HTTP status %s", url, resp.Status)55 }56 contentType := strings.Split(resp.Header.Get("Content-Type"), ";")[0]57 switch contentType {58 case "application/json":59 body, err := ioutil.ReadAll(resp.Body)60 if err != nil {61 return nil, err62 }63 return body, nil64 default:65 return nil, fmt.Errorf("%s returned unexpected content type %s", url, contentType)66 }67}68func (n *NginxPlusApi) gatherProcessesMetrics(addr *url.URL, acc telegraf.Accumulator) error {69 body, err := n.gatherUrl(addr, processesPath)70 if err != nil {71 return err72 }73 var processes = &Processes{}74 if err := json.Unmarshal(body, processes); err != nil {75 return err76 }77 acc.AddFields(78 "nginx_plus_api_processes",79 map[string]interface{}{80 "respawned": processes.Respawned,81 },82 getTags(addr),83 )84 return nil85}86func (n *NginxPlusApi) gatherConnectionsMetrics(addr *url.URL, acc telegraf.Accumulator) error {87 body, err := n.gatherUrl(addr, connectionsPath)88 if err != nil {89 return err90 }91 var connections = &Connections{}92 if err := json.Unmarshal(body, connections); err != nil {93 return err94 }95 acc.AddFields(96 "nginx_plus_api_connections",97 map[string]interface{}{98 "accepted": connections.Accepted,99 "dropped": connections.Dropped,100 "active": connections.Active,101 "idle": connections.Idle,102 },103 getTags(addr),104 )105 return nil106}107func (n *NginxPlusApi) gatherSslMetrics(addr *url.URL, acc telegraf.Accumulator) error {108 body, err := n.gatherUrl(addr, sslPath)109 if err != nil {110 return err111 }112 var ssl = &Ssl{}113 if err := json.Unmarshal(body, ssl); err != nil {114 return err115 }116 acc.AddFields(117 "nginx_plus_api_ssl",118 map[string]interface{}{119 "handshakes": ssl.Handshakes,120 "handshakes_failed": ssl.HandshakesFailed,121 "session_reuses": ssl.SessionReuses,122 },123 getTags(addr),124 )125 return nil126}127func (n *NginxPlusApi) gatherHttpRequestsMetrics(addr *url.URL, acc telegraf.Accumulator) error {128 body, err := n.gatherUrl(addr, httpRequestsPath)129 if err != nil {130 return err131 }132 var httpRequests = &HttpRequests{}133 if err := json.Unmarshal(body, httpRequests); err != nil {134 return err135 }136 acc.AddFields(137 "nginx_plus_api_http_requests",138 map[string]interface{}{139 "total": httpRequests.Total,140 "current": httpRequests.Current,141 },142 getTags(addr),143 )144 return nil145}146func (n *NginxPlusApi) gatherHttpServerZonesMetrics(addr *url.URL, acc telegraf.Accumulator) error {147 body, err := n.gatherUrl(addr, httpServerZonesPath)148 if err != nil {149 return err150 }151 var httpServerZones HttpServerZones152 if err := json.Unmarshal(body, &httpServerZones); err != nil {153 return err154 }155 tags := getTags(addr)156 for zoneName, zone := range httpServerZones {157 zoneTags := map[string]string{}158 for k, v := range tags {159 zoneTags[k] = v160 }161 zoneTags["zone"] = zoneName162 acc.AddFields(163 "nginx_plus_api_http_server_zones",164 func() map[string]interface{} {165 result := map[string]interface{}{166 "processing": zone.Processing,167 "requests": zone.Requests,168 "responses_1xx": zone.Responses.Responses1xx,169 "responses_2xx": zone.Responses.Responses2xx,170 "responses_3xx": zone.Responses.Responses3xx,171 "responses_4xx": zone.Responses.Responses4xx,172 "responses_5xx": zone.Responses.Responses5xx,173 "responses_total": zone.Responses.Total,174 "received": zone.Received,175 "sent": zone.Sent,176 }177 if zone.Discarded != nil {178 result["discarded"] = *zone.Discarded179 }180 return result181 }(),182 zoneTags,183 )184 }185 return nil186}187func (n *NginxPlusApi) gatherHttpUpstreamsMetrics(addr *url.URL, acc telegraf.Accumulator) error {188 body, err := n.gatherUrl(addr, httpUpstreamsPath)189 if err != nil {190 return err191 }192 var httpUpstreams HttpUpstreams193 if err := json.Unmarshal(body, &httpUpstreams); err != nil {194 return err195 }196 tags := getTags(addr)197 for upstreamName, upstream := range httpUpstreams {198 upstreamTags := map[string]string{}199 for k, v := range tags {200 upstreamTags[k] = v201 }202 upstreamTags["upstream"] = upstreamName203 upstreamFields := map[string]interface{}{204 "keepalive": upstream.Keepalive,205 "zombies": upstream.Zombies,206 }207 if upstream.Queue != nil {208 upstreamFields["queue_size"] = upstream.Queue.Size209 upstreamFields["queue_max_size"] = upstream.Queue.MaxSize210 upstreamFields["queue_overflows"] = upstream.Queue.Overflows211 }212 acc.AddFields(213 "nginx_plus_api_http_upstreams",214 upstreamFields,215 upstreamTags,216 )217 for _, peer := range upstream.Peers {218 peerFields := map[string]interface{}{219 "backup": peer.Backup,220 "weight": peer.Weight,221 "state": peer.State,222 "active": peer.Active,223 "requests": peer.Requests,224 "responses_1xx": peer.Responses.Responses1xx,225 "responses_2xx": peer.Responses.Responses2xx,226 "responses_3xx": peer.Responses.Responses3xx,227 "responses_4xx": peer.Responses.Responses4xx,228 "responses_5xx": peer.Responses.Responses5xx,229 "responses_total": peer.Responses.Total,230 "sent": peer.Sent,231 "received": peer.Received,232 "fails": peer.Fails,233 "unavail": peer.Unavail,234 "healthchecks_checks": peer.HealthChecks.Checks,235 "healthchecks_fails": peer.HealthChecks.Fails,236 "healthchecks_unhealthy": peer.HealthChecks.Unhealthy,237 "downtime": peer.Downtime,238 //"selected": peer.Selected.toInt64,239 //"downstart": peer.Downstart.toInt64,240 }241 if peer.HealthChecks.LastPassed != nil {242 peerFields["healthchecks_last_passed"] = *peer.HealthChecks.LastPassed243 }244 if peer.HeaderTime != nil {245 peerFields["header_time"] = *peer.HeaderTime246 }247 if peer.ResponseTime != nil {248 peerFields["response_time"] = *peer.ResponseTime249 }250 if peer.MaxConns != nil {251 peerFields["max_conns"] = *peer.MaxConns252 }253 peerTags := map[string]string{}254 for k, v := range upstreamTags {255 peerTags[k] = v256 }257 peerTags["upstream_address"] = peer.Server258 if peer.ID != nil {259 peerTags["id"] = strconv.Itoa(*peer.ID)260 }261 acc.AddFields("nginx_plus_api_http_upstream_peers", peerFields, peerTags)262 }263 }264 return nil265}266func (n *NginxPlusApi) gatherHttpCachesMetrics(addr *url.URL, acc telegraf.Accumulator) error {267 body, err := n.gatherUrl(addr, httpCachesPath)268 if err != nil {269 return err270 }271 var httpCaches HttpCaches272 if err := json.Unmarshal(body, &httpCaches); err != nil {273 return err274 }275 tags := getTags(addr)276 for cacheName, cache := range httpCaches {277 cacheTags := map[string]string{}278 for k, v := range tags {279 cacheTags[k] = v280 }281 cacheTags["cache"] = cacheName282 acc.AddFields(283 "nginx_plus_api_http_caches",284 map[string]interface{}{285 "size": cache.Size,286 "max_size": cache.MaxSize,287 "cold": cache.Cold,288 "hit_responses": cache.Hit.Responses,289 "hit_bytes": cache.Hit.Bytes,290 "stale_responses": cache.Stale.Responses,291 "stale_bytes": cache.Stale.Bytes,292 "updating_responses": cache.Updating.Responses,293 "updating_bytes": cache.Updating.Bytes,294 "revalidated_responses": cache.Revalidated.Responses,295 "revalidated_bytes": cache.Revalidated.Bytes,296 "miss_responses": cache.Miss.Responses,297 "miss_bytes": cache.Miss.Bytes,298 "miss_responses_written": cache.Miss.ResponsesWritten,299 "miss_bytes_written": cache.Miss.BytesWritten,300 "expired_responses": cache.Expired.Responses,301 "expired_bytes": cache.Expired.Bytes,302 "expired_responses_written": cache.Expired.ResponsesWritten,303 "expired_bytes_written": cache.Expired.BytesWritten,304 "bypass_responses": cache.Bypass.Responses,305 "bypass_bytes": cache.Bypass.Bytes,306 "bypass_responses_written": cache.Bypass.ResponsesWritten,307 "bypass_bytes_written": cache.Bypass.BytesWritten,308 },309 cacheTags,310 )311 }312 return nil313}314func (n *NginxPlusApi) gatherStreamServerZonesMetrics(addr *url.URL, acc telegraf.Accumulator) error {315 body, err := n.gatherUrl(addr, streamServerZonesPath)316 if err != nil {317 return err318 }319 var streamServerZones StreamServerZones320 if err := json.Unmarshal(body, &streamServerZones); err != nil {321 return err322 }323 tags := getTags(addr)324 for zoneName, zone := range streamServerZones {325 zoneTags := map[string]string{}326 for k, v := range tags {327 zoneTags[k] = v328 }329 zoneTags["zone"] = zoneName330 acc.AddFields(331 "nginx_plus_api_stream_server_zones",332 map[string]interface{}{333 "processing": zone.Processing,334 "connections": zone.Connections,335 "received": zone.Received,336 "sent": zone.Sent,337 },338 zoneTags,339 )340 }341 return nil342}343func (n *NginxPlusApi) gatherStreamUpstreamsMetrics(addr *url.URL, acc telegraf.Accumulator) error {344 body, err := n.gatherUrl(addr, streamUpstreamsPath)345 if err != nil {346 return err347 }348 var streamUpstreams StreamUpstreams349 if err := json.Unmarshal(body, &streamUpstreams); err != nil {350 return err351 }352 tags := getTags(addr)353 for upstreamName, upstream := range streamUpstreams {354 upstreamTags := map[string]string{}355 for k, v := range tags {356 upstreamTags[k] = v357 }358 upstreamTags["upstream"] = upstreamName359 acc.AddFields(360 "nginx_plus_api_stream_upstreams",361 map[string]interface{}{362 "zombies": upstream.Zombies,363 },364 upstreamTags,365 )366 for _, peer := range upstream.Peers {367 peerFields := map[string]interface{}{368 "backup": peer.Backup,369 "weight": peer.Weight,370 "state": peer.State,371 "active": peer.Active,372 "connections": peer.Connections,373 "sent": peer.Sent,374 "received": peer.Received,375 "fails": peer.Fails,376 "unavail": peer.Unavail,377 "healthchecks_checks": peer.HealthChecks.Checks,378 "healthchecks_fails": peer.HealthChecks.Fails,379 "healthchecks_unhealthy": peer.HealthChecks.Unhealthy,380 "downtime": peer.Downtime,381 }382 if peer.HealthChecks.LastPassed != nil {383 peerFields["healthchecks_last_passed"] = *peer.HealthChecks.LastPassed384 }385 if peer.ConnectTime != nil {386 peerFields["connect_time"] = *peer.ConnectTime387 }388 if peer.FirstByteTime != nil {389 peerFields["first_byte_time"] = *peer.FirstByteTime390 }391 if peer.ResponseTime != nil {392 peerFields["response_time"] = *peer.ResponseTime393 }394 peerTags := map[string]string{}395 for k, v := range upstreamTags {396 peerTags[k] = v397 }398 peerTags["upstream_address"] = peer.Server399 peerTags["id"] = strconv.Itoa(peer.ID)400 acc.AddFields("nginx_plus_api_stream_upstream_peers", peerFields, peerTags)401 }402 }403 return nil404}405func getTags(addr *url.URL) map[string]string {406 h := addr.Host407 host, port, err := net.SplitHostPort(h)408 if err != nil {409 host = addr.Host410 if addr.Scheme == "http" {411 port = "80"412 } else if addr.Scheme == "https" {413 port = "443"414 } else {415 port = ""416 }417 }418 return map[string]string{"source": host, "port": port}419}...
GetTags
Using AI Code Generation
1import (2func main() {3 lc := logger.NewClient("test", false, "./test.log", "DEBUG")4 mdc := metadata.NewDeviceClient(5 clients.Endpoints{6 clients.CoreMetaDataServiceKey: {7 Protocol: "http"},8 },9 tags, err := mdc.GetTags()10 if err != nil {11 fmt.Println("Error getting all tags from metadata: ", err.Error())12 }13 for _, tag := range tags {14 fmt.Println("Tag: ", tag)15 }16}17import (18func main() {19 lc := logger.NewClient("test", false, "./test.log", "DEBUG")20 mdc := metadata.NewDeviceClient(21 clients.Endpoints{22 clients.CoreMetaDataServiceKey: {23 Protocol: "http"},24 },25 devices, err := mdc.GetDevicesByTag("test")26 if err != nil {27 fmt.Println("Error getting all devices by tag from metadata: ", err.Error())28 }
GetTags
Using AI Code Generation
1import (2func main() {3 tags := metrics.GetTags()4 fmt.Println(tags)5}6import (7func main() {8 tags := metrics.GetTags()9 fmt.Println(tags)10}11import (12func main() {13 tags := metrics.GetTags()14 fmt.Println(tags)15}16import (17func main() {18 tags := metrics.GetTags()19 fmt.Println(tags)20}21import (22func main() {23 tags := metrics.GetTags()24 fmt.Println(tags)25}26import (27func main() {28 tags := metrics.GetTags()29 fmt.Println(tags)30}31import (32func main() {33 tags := metrics.GetTags()34 fmt.Println(tags)35}36import (37func main() {38 tags := metrics.GetTags()39 fmt.Println(tags)40}41import (42func main() {43 tags := metrics.GetTags()
GetTags
Using AI Code Generation
1import (2func main() {3 metrics.GetTags()4 fmt.Println("Tags are: ", metrics.GetTags())5}6import (7func main() {8 metrics.GetTags()9 fmt.Println("Tags are: ", metrics.GetTags())10}11import (12func main() {13 metrics.GetTags()14 fmt.Println("Tags are: ", metrics.GetTags())15}16import (17func main() {18 metrics.GetTags()19 fmt.Println("Tags are: ", metrics.GetTags())20}21import (22func main() {23 metrics.GetTags()24 fmt.Println("Tags are: ", metrics.GetTags())25}26import (27func main() {28 metrics.GetTags()29 fmt.Println("Tags are: ", metrics.GetTags
GetTags
Using AI Code Generation
1import (2func main() {3 m := metrics.New("test.metric", metrics.CounterType, []metrics.Tag{4 metrics.NewTag("tag1", "value1"),5 metrics.NewTag("tag2", "value2"),6 })7 fmt.Println(m.GetTags())8}9[Tag{key: tag1, value: value1} Tag{key: tag2, value: value2}]10import (11func main() {12 m := metrics.New("test.metric", metrics.CounterType, []metrics.Tag{13 metrics.NewTag("tag1", "value1"),14 metrics.NewTag("tag2", "value2"),15 })16 fmt.Println(m.GetHost())17}18import (19func main() {20 m := metrics.New("test.metric", metrics.CounterType, []metrics.Tag{21 metrics.NewTag("tag1", "value1"),22 metrics.NewTag("tag2", "value2"),23 })24 fmt.Println(m.GetHostname())25}26import (27func main() {28 m := metrics.New("test.metric", metrics.CounterType, []metrics.Tag{29 metrics.NewTag("tag1", "value1"),30 metrics.NewTag("tag2", "value2"),31 })32 fmt.Println(m.GetDeviceName())33}
GetTags
Using AI Code Generation
1import (2func main() {3 tags := metrics.GetTags("test.metric")4 fmt.Println(tags)5}6import (7func main() {8 metricStats := metrics.GetMetricStats("test.metric")9 fmt.Println(metricStats)10}11import (12func main() {13 metricSamples := metrics.GetMetricSamples("test.metric")14 fmt.Println(metricSamples)15}16import (17func main() {18 metricSample := metrics.GetMetricSample("test.metric", []string{"tag1", "tag2"})19 fmt.Println(metricSample)20}21import (22func main() {23 metricSamples := metrics.GetMetricSamplesByTags("test.metric", []string{"tag1", "tag2"})24 fmt.Println(metricSamples)25}26import (27func main() {28 metricSamples := metrics.GetMetricSamplesByTags("test.metric", []string{"tag1", "tag2"})
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.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!