How to use NewMetric method of v1 Package

Best K6 code snippet using v1.NewMetric

exporter.go

Source:exporter.go Github

copy

Full Screen

1package main2import (3 "encoding/json"4 "errors"5 "fmt"6 "io/ioutil"7 "net"8 "os"9 "sort"10 "strings"11 "time"12 "github.com/go-kit/kit/log"13 "github.com/go-kit/kit/log/level"14 "github.com/mslocrian/avi_exporter/pkg/models"15 "github.com/avinetworks/sdk/go/clients"16 "github.com/avinetworks/sdk/go/session"17 "github.com/prometheus/client_golang/prometheus"18 // "github.com/prometheus/common/log"19 "github.com/tidwall/pretty"20)21func formatAviRef(in string) string {22 uriArr := strings.SplitAfter(in, "/")23 return uriArr[len(uriArr)-1]24}25// Exporter describes the prometheus exporter.26type Exporter struct {27 GaugeOptsMap models.GaugeOptsMap28 AviClient *clients.AviClient29 connectionOpts models.ConnectionOpts30 userMetricString string31 gauges models.Gauges32 logger log.Logger33 ses *models.SeInventory34 vsinv []models.VirtualServiceInventory35 metrics []prometheus.Metric36 tenants *models.TenantInventory37 clouds *models.CloudInventory38 segroups *models.SeGroupInventory39}40func fromJSONFile(path string, ob interface{}) (err error) {41 toReturn := ob42 openedFile, err := os.Open(path)43 defer openedFile.Close()44 if err != nil {45 return err46 }47 byteValue, err := ioutil.ReadAll(openedFile)48 if err != nil {49 return err50 }51 err = json.Unmarshal(byteValue, &toReturn)52 if err != nil {53 return err54 }55 return nil56}57func (o Exporter) getDefaultMetrics(entityType string) (r models.DefaultMetrics, err error) {58 var path string59 r = models.DefaultMetrics{}60 switch entityType {61 case "virtualservice":62 path = "lib/virtualservice_metrics.json"63 case "serviceengine":64 path = "lib/serviceengine_metrics.json"65 case "controller":66 path = "lib/controller_metrics.json"67 default:68 err = errors.New("entity type must be either: virtualserver, servicengine or controller")69 return r, err70 }71 err = fromJSONFile(path, &r)72 if err != nil {73 return r, err74 }75 return r, nil76}77func (o *Exporter) setAllMetricsMap() (r models.GaugeOptsMap, err error) {78 r = make(models.GaugeOptsMap)79 //////////////////////////////////////////////////////////////////////////////80 // Get default metrics.81 //////////////////////////////////////////////////////////////////////////////82 vsDefaultMetrics, err := o.getDefaultMetrics("virtualservice")83 if err != nil {84 return r, err85 }86 seDefaultMetrics, err := o.getDefaultMetrics("serviceengine")87 if err != nil {88 return r, err89 }90 controllerDefaultMetrics, err := o.getDefaultMetrics("controller")91 if err != nil {92 return r, err93 }94 //////////////////////////////////////////////////////////////////////////////95 // Populating default metrics. Leaving these as separate functions96 // in the event we want different GaugeOpts in the future.97 //////////////////////////////////////////////////////////////////////////////98 for _, v := range vsDefaultMetrics {99 fName := strings.ReplaceAll(v.Metric, ".", "_")100 r[v.Metric] = models.GaugeOpts{CustomLabels: []string{"name", "fqdn", "ipaddress", "pool", "tenant_uuid", "tenant", "units", "controller"}, Type: "virtualservice", GaugeOpts: prometheus.GaugeOpts{Name: fName, Help: v.Help}}101 }102 for _, v := range seDefaultMetrics {103 fName := strings.ReplaceAll(v.Metric, ".", "_")104 r[v.Metric] = models.GaugeOpts{CustomLabels: []string{"name", "entity_uuid", "fqdn", "ipaddress", "tenant_uuid", "tenant", "units", "controller"}, Type: "serviceengine", GaugeOpts: prometheus.GaugeOpts{Name: fName, Help: v.Help}}105 }106 for _, v := range controllerDefaultMetrics {107 fName := strings.ReplaceAll(v.Metric, ".", "_")108 r[v.Metric] = models.GaugeOpts{CustomLabels: []string{"name", "entity_uuid", "fqdn", "ipaddress", "tenant_uuid", "tenant", "units", "controller"}, Type: "controller", GaugeOpts: prometheus.GaugeOpts{Name: fName, Help: v.Help}}109 }110 //////////////////////////////////////////////////////////////////////////////111 return r, nil112}113func (o *Exporter) setPromMetricsMap() (r models.GaugeOptsMap) {114 r = make(models.GaugeOptsMap)115 all, _ := o.setAllMetricsMap()116 if o.userMetricString == "" {117 r = all118 return119 }120 /////////////////////////////////////////////////////////121 // User provided metrics list122 /////////////////////////////////////////////////////////123 metrics := strings.Split(o.userMetricString, ",")124 for _, v := range metrics {125 r[v] = all[v]126 }127 return128}129func (o *Exporter) setUserMetrics() (r string) {130 r = os.Getenv("AVI_METRICS")131 return132}133// NewExporter constructor.134func NewExporter(username, password string, logger log.Logger) (r *Exporter) {135 r = new(Exporter)136 r.userMetricString = r.setUserMetrics()137 r.connectionOpts = r.setConnectionOpts()138 r.GaugeOptsMap = r.setPromMetricsMap()139 r.logger = logger140 return141}142// func (o *Exporter) setConnectionOpts(username, password string) (r connectionOpts) {143func (o *Exporter) setConnectionOpts() (r models.ConnectionOpts) {144 r.Username = os.Getenv("AVI_USERNAME")145 r.Password = os.Getenv("AVI_PASSWORD")146 return147}148func (o *Exporter) setController(controller string) {149 o.connectionOpts.Controller = controller150}151// connect establishes the avi connection.152func (o *Exporter) connect(cluster, tenant, api_version string) (r *clients.AviClient, err error) {153 o.setController(cluster)154 // simplify avi connection155 r, err = clients.NewAviClient(cluster, o.connectionOpts.Username,156 session.SetPassword(o.connectionOpts.Password),157 session.SetTenant(tenant),158 session.SetInsecure,159 session.SetVersion(api_version))160 return161}162func (o *Exporter) registerGauges() {163 o.gauges = make(map[string]*prometheus.GaugeVec)164 for k, v := range o.GaugeOptsMap {165 g := prometheus.NewGaugeVec(v.GaugeOpts, v.CustomLabels)166 o.gauges[k] = g167 }168}169// sortUniqueKeys sorts unique keys within a string array.170func sortUniqueKeys(in []string) ([]string, error) {171 var err error172 var resp []string173 respMap := make(map[string]string)174 for _, v := range in {175 respMap[v] = v176 }177 for _, v := range respMap {178 resp = append(resp, v)179 }180 sort.Strings(resp)181 return resp, err182}183func (o *Exporter) getVirtualServices() (r map[string]models.VirtualServiceDef, err error) {184 vs, err := o.AviClient.VirtualService.GetAll()185 var pooluuid string186 if err != nil {187 return r, err188 }189 r = make(map[string]models.VirtualServiceDef)190 for _, v := range vs {191 if v.Vip == nil {192 continue193 }194 vip := v.Vip[0]195 address := *vip.IPAddress.Addr196 dns, _ := net.LookupAddr(address)197 for k, v := range dns {198 dns[k] = strings.TrimSuffix(v, ".")199 }200 dns, err = sortUniqueKeys(dns)201 if v.PoolRef != nil {202 pooluuid = formatAviRef(*v.PoolRef)203 }204 r[*v.UUID] = models.VirtualServiceDef{Name: *v.Name, IPAddress: address, FQDN: strings.Join(dns, ","), PoolUUID: pooluuid}205 }206 return r, nil207}208func (o *Exporter) getClusterRuntime() (r map[string]models.ClusterDef, err error) {209 resp := new(models.Cluster)210 err = o.AviClient.AviSession.Get("/api/cluster", &resp)211 if err != nil {212 return r, err213 }214 r = make(map[string]models.ClusterDef)215 for _, v := range resp.Nodes {216 address := v.IP.Addr217 dns, _ := net.LookupAddr(address)218 r[v.VMUUID] = models.ClusterDef{Name: v.Name, IPAddress: address, FQDN: strings.Join(dns, ",")}219 }220 return r, nil221}222func (o *Exporter) getServiceEngines() (r map[string]models.SeDef, err error) {223 se, err := o.AviClient.ServiceEngine.GetAll()224 if err != nil {225 return r, err226 }227 r = make(map[string]models.SeDef)228 for _, v := range se {229 address := *v.MgmtVnic.VnicNetworks[0].IP.IPAddr.Addr230 dns, _ := net.LookupAddr(address)231 for k, v := range dns {232 dns[k] = strings.TrimSuffix(v, ".")233 }234 r[*v.UUID] = models.SeDef{Name: *v.Name, IPAddress: address, FQDN: strings.Join(dns, ",")}235 }236 return r, nil237}238func (o *Exporter) getPools() (r map[string]models.PoolDef, err error) {239 vs, err := o.AviClient.Pool.GetAll()240 r = make(map[string]models.PoolDef)241 if err != nil {242 return r, err243 }244 for _, v := range vs {245 r[*v.UUID] = models.PoolDef{Name: *v.Name}246 }247 return r, nil248}249// toPrettyJSON formats json output.250func toPrettyJSON(p interface{}) []byte {251 bytes, err := json.Marshal(p)252 if err != nil {253 // log.Infoln(err.Error())254 }255 return pretty.Pretty(bytes)256}257func CollectTarget(controller, username, password, tenant, api_version string, logger log.Logger) (metrics []prometheus.Metric, err error) {258 e := NewExporter(username, password, logger)259 e.registerGauges()260 metrics, err = e.Collect(controller, tenant, api_version)261 return metrics, err262}263// Collect retrieves metrics for Avi.264func (o *Exporter) Collect(controller, tenant, api_version string) (metrics []prometheus.Metric, err error) {265 /*266 Connect to the cluster.267 */268 o.AviClient, err = o.connect(controller, tenant, api_version)269 if err != nil {270 return metrics, err271 }272 err = o.AviClient.AviSession.Get("api/serviceengine-inventory?page_size=200", &o.ses)273 if err != nil {274 return metrics, err275 }276 err = o.AviClient.AviSession.Get("api/tenant?page_size=200", &o.tenants)277 if err != nil {278 return metrics, err279 }280 err = o.AviClient.AviSession.Get("api/cloud?page_size=200", &o.clouds)281 if err != nil {282 return metrics, err283 }284 err = o.AviClient.AviSession.Get("api/serviceenginegroup?page_size=200", &o.segroups)285 if err != nil {286 return metrics, err287 }288 // We need to pull un-exposed VS Faults (asymmetric vs's)289 page_iter := 1290 for {291 res := &models.VsInventory{}292 uri := fmt.Sprintf("api/virtualservice-inventory?page_size=200&page=%v", page_iter)293 err = o.AviClient.AviSession.Get(uri, res)294 count := res.Count295 for _, result := range res.Results {296 o.vsinv = append(o.vsinv, result)297 }298 if len(o.vsinv) >= int(count) {299 break300 }301 page_iter += 1302 }303 err = o.setVirtualServiceFaultMetrics()304 if err != nil {305 return metrics, err306 }307 /*308 Set promMetrics.309 */310 /*311 stegen - fix this312 " value:"" > label:<name:"pool" value:"" > label:<name:"tenant_uuid" value:"tenant-0a01a6d4-b3e0-4ffb-bd0d-73b30f2bf4b2" > label:<name:"units" value:"BITS_PER_SECOND" > gauge:<value:0 > } was collected before with the same name and label values313 * collected metric "avi_virtual_l4_server_avg_goodput" { label:<name:"controller" value:"lb-ctrl2-pub.or1.ne.adobe.net" > label:<name:"fqdn" value:"" > label:<name:"ipaddress" value:"" > label:<name:"name" value:"" > label:<name:"pool" value:"" > label:<name:"tenant_uuid" value:"tenant-0a01a6d4-b3e0-4ffb-bd0d-73b30f2bf4b2" > label:<name:"units" value:"BYTES_PER_SECOND" > gauge:<value:0 > } was collected before with the same name and label values314 */315 /*316 err = o.setVirtualServiceMetrics()317 if err != nil {318 return metrics, err319 }320 */321 err = o.setServiceEngineMetrics()322 if err != nil {323 return metrics, err324 }325 err = o.setControllerMetrics()326 if err != nil {327 return metrics, err328 }329 err = o.seMemDist()330 if err != nil {331 return metrics, err332 }333 err = o.seShMalloc()334 if err != nil {335 return metrics, err336 }337 // We may not have BGP Metrics on each controller338 err = o.seBgpPeerState()339 err = o.seVnicPortGroup()340 if err != nil {341 return metrics, err342 }343 err = o.seMissedHeartBeats()344 if err != nil {345 return metrics, err346 }347 err = o.getLicenseUsage()348 if err != nil {349 return metrics, err350 }351 err = o.getLicenseExpiration()352 if err != nil {353 return metrics, err354 }355 return o.metrics, err356}357func (o *Exporter) getVirtualServiceMetrics() (r [][]models.CollectionResponse, err error) {358 req := models.Metrics{}359 for k, v := range o.GaugeOptsMap {360 if v.Type == "virtualservice" {361 reqMetric := models.MetricRequest{}362 reqMetric.EntityUUID = "*"363 reqMetric.MetricEntity = "VSERVER_METRICS_ENTITY"364 reqMetric.Limit = 1365 reqMetric.MetricID = k366 reqMetric.Step = 5367 req.MetricRequests = append(req.MetricRequests, reqMetric)368 }369 }370 resp := make(map[string]map[string][]models.CollectionResponse)371 err = o.AviClient.AviSession.Post("api/analytics/metrics/collection", req, &resp)372 if err != nil {373 return r, err374 }375 for _, s := range resp["series"] {376 r = append(r, s)377 }378 return r, nil379}380func (o *Exporter) getServiceEngineMetrics() (r [][]models.CollectionResponse, err error) {381 req := models.Metrics{}382 for k, v := range o.GaugeOptsMap {383 if v.Type == "serviceengine" {384 reqMetric := models.MetricRequest{}385 reqMetric.EntityUUID = "*"386 reqMetric.MetricEntity = "SE_METRICS_ENTITY"387 reqMetric.Limit = 1388 reqMetric.MetricID = k389 reqMetric.Step = 5390 req.MetricRequests = append(req.MetricRequests, reqMetric)391 }392 }393 resp := make(map[string]map[string][]models.CollectionResponse)394 err = o.AviClient.AviSession.Post("api/analytics/metrics/collection", req, &resp)395 if err != nil {396 return r, err397 }398 for _, s := range resp["series"] {399 r = append(r, s)400 }401 return r, err402}403func (o *Exporter) getControllerMetrics() (r [][]models.CollectionResponse, err error) {404 req := models.Metrics{}405 for k, v := range o.GaugeOptsMap {406 if v.Type == "controller" {407 reqMetric := models.MetricRequest{}408 reqMetric.EntityUUID = "*"409 reqMetric.MetricEntity = "CONTROLLER_METRICS_ENTITY"410 reqMetric.Limit = 1411 reqMetric.MetricID = k412 reqMetric.Step = 5413 req.MetricRequests = append(req.MetricRequests, reqMetric)414 }415 }416 resp := make(map[string]map[string][]models.CollectionResponse)417 err = o.AviClient.AviSession.Post("api/analytics/metrics/collection", req, &resp)418 if err != nil {419 return r, err420 }421 for _, s := range resp["series"] {422 r = append(r, s)423 }424 return r, nil425}426func (o *Exporter) setVirtualServiceMetrics() (err error) {427 /*428 Get lb objects for mapping.429 */430 vs, _ := o.getVirtualServices()431 pools, _ := o.getPools()432 results, err := o.getVirtualServiceMetrics()433 if err != nil {434 return err435 }436 for _, v := range results {437 for _, v1 := range v {438 var labelNames = []string{"name", "pool", "tenant_uuid", "tenant", "controller", "units", "fqdn", "ipaddress"}439 var labelValues = []string{vs[v1.Header.EntityUUID].Name, pools[vs[v1.Header.EntityUUID].PoolUUID].Name, v1.Header.TenantUUID, o.getTenantNameFromUUID(v1.Header.TenantUUID), o.connectionOpts.Controller, v1.Header.Units, vs[v1.Header.EntityUUID].FQDN, vs[v1.Header.EntityUUID].IPAddress}440 newMetric, err := prometheus.NewConstMetric(prometheus.NewDesc("avi_virtual_"+strings.Replace(v1.Header.Name, ".", "_", -1), "Virtual Service Metrics", labelNames, nil),441 prometheus.GaugeValue, v1.Data[len(v1.Data)-1].Value, labelValues...)442 if err != nil {443 return err444 }445 o.metrics = append(o.metrics, newMetric)446 }447 }448 return nil449}450func (o *Exporter) setServiceEngineMetrics() (err error) {451 results, err := o.getServiceEngineMetrics()452 ses, _ := o.getServiceEngines()453 if err != nil {454 return err455 }456 for _, v := range results {457 for _, v1 := range v {458 var labelNames = []string{"tenant_uuid", "tenant", "entity_uuid", "controller", "units", "name", "fqdn", "ipaddress"}459 var labelValues = []string{v1.Header.TenantUUID, o.getTenantNameFromUUID(v1.Header.TenantUUID), v1.Header.EntityUUID, o.connectionOpts.Controller, v1.Header.Units, ses[v1.Header.EntityUUID].Name, ses[v1.Header.EntityUUID].FQDN, ses[v1.Header.EntityUUID].IPAddress}460 newMetric, err := prometheus.NewConstMetric(prometheus.NewDesc("avi_"+strings.Replace(v1.Header.Name, ".", "_", -1), "Service Engine Metrics", labelNames, nil),461 prometheus.GaugeValue, v1.Data[len(v1.Data)-1].Value, labelValues...)462 if err != nil {463 return err464 }465 o.metrics = append(o.metrics, newMetric)466 }467 }468 return nil469}470func (o *Exporter) setVirtualServiceFaultMetrics() (err error) {471 for _, vs := range o.vsinv {472 faults := vs.Faults.(map[string]interface{})473 if _, found := faults["shared_vip"]; found {474 tenantSplit := strings.Split(vs.Config.TenantRef, "/")475 cloudSplit := strings.Split(vs.Config.CloudRef, "/")476 seGroupSplit := strings.Split(vs.Config.SEGroupRef, "/")477 var labelNames = []string{"name", "uuid", "tenant", "cloud", "se_group", "controller"}478 var labelValues = []string{vs.Config.Name, vs.Config.UUID, o.getTenantNameFromUUID(tenantSplit[len(tenantSplit)-1]), o.getCloudNameFromUUID(cloudSplit[len(cloudSplit)-1]), o.getSEGroupNameFromUUID(seGroupSplit[len(seGroupSplit)-1]), o.connectionOpts.Controller}479 newMetric, err := prometheus.NewConstMetric(prometheus.NewDesc("avi_vs_fault_shared_vip", "Virtual Service Shared VIP Fault Metrics", labelNames, nil),480 prometheus.GaugeValue, 1, labelValues...)481 if err != nil {482 return err483 }484 o.metrics = append(o.metrics, newMetric)485 }486 }487 return nil488}489func (o *Exporter) setControllerMetrics() (err error) {490 results, err := o.getControllerMetrics()491 runtime, _ := o.getClusterRuntime()492 if err != nil {493 return err494 }495 for _, v := range results {496 for _, v1 := range v {497 var labelNames = []string{"tenant_uuid", "tenant", "entity_uuid", "controller", "units", "name", "fqdn", "ipaddress"}498 var labelValues = []string{v1.Header.TenantUUID, o.getTenantNameFromUUID(v1.Header.TenantUUID), v1.Header.EntityUUID, o.connectionOpts.Controller, v1.Header.Units, runtime[v1.Header.EntityUUID].Name, runtime[v1.Header.EntityUUID].FQDN, runtime[v1.Header.EntityUUID].IPAddress}499 newMetric, err := prometheus.NewConstMetric(prometheus.NewDesc("avi_"+strings.ReplaceAll(v1.Header.Name, ".", "_"), "Controller Metrics", labelNames, nil),500 prometheus.GaugeValue, v1.Data[len(v1.Data)-1].Value, labelValues...)501 if err != nil {502 return err503 }504 o.metrics = append(o.metrics, newMetric)505 }506 }507 return nil508}509func (o *Exporter) seMemDist() (err error) {510 for _, se := range o.ses.Results {511 var memDist []models.ServiceEngineMemDist512 err = o.AviClient.AviSession.Get("api/serviceengine/"+se.UUID+"/memdist", &memDist)513 if err != nil {514 e := err.(session.AviError)515 if e.HttpStatusCode == 500 {516 level.Error(o.logger).Log("msg", "There was an error collecting se memdist stats", "error", fmt.Sprintf("%#v", err))517 continue518 } else {519 return err520 }521 }522 for _, dist := range memDist {523 var labelNames = []string{"controller", "uuid", "ip", "proc_id"}524 var labelValues = []string{o.connectionOpts.Controller, se.UUID, se.Config.MgmtIpAddress.Addr, dist.ProcID}525 newMetric, err := prometheus.NewConstMetric(prometheus.NewDesc("avi_se_mem_dist_shm_memory_mb", "AVI SE Memory Distribution Shared Memory MB", labelNames, nil),526 prometheus.GaugeValue, float64(dist.ShmMemoryMB), labelValues...)527 if err != nil {528 return err529 }530 o.metrics = append(o.metrics, newMetric)531 newMetric, err = prometheus.NewConstMetric(prometheus.NewDesc("avi_se_mem_dist_app_learning_memory_mb", "AVI SE Memory Distribution App Learning Memory MB", labelNames, nil),532 prometheus.GaugeValue, float64(dist.AppLearningMemoryMB), labelValues...)533 if err != nil {534 return err535 }536 o.metrics = append(o.metrics, newMetric)537 newMetric, err = prometheus.NewConstMetric(prometheus.NewDesc("avi_se_mem_dist_clusters", "AVI SE Memory Distribution Clusters", labelNames, nil),538 prometheus.GaugeValue, float64(dist.Clusters), labelValues...)539 if err != nil {540 return err541 }542 o.metrics = append(o.metrics, newMetric)543 newMetric, err = prometheus.NewConstMetric(prometheus.NewDesc("avi_se_mem_config_memory_mb", "AVI SE Memory Distribution Config Memory MB", labelNames, nil),544 prometheus.GaugeValue, float64(dist.ConfigMemoryMB), labelValues...)545 if err != nil {546 return err547 }548 o.metrics = append(o.metrics, newMetric)549 newMetric, err = prometheus.NewConstMetric(prometheus.NewDesc("avi_se_mem_conn_memory_mb", "AVI SE Memory Distribution Connection Memory MB", labelNames, nil),550 prometheus.GaugeValue, float64(dist.ConnMemoryMB), labelValues...)551 if err != nil {552 return err553 }554 o.metrics = append(o.metrics, newMetric)555 newMetric, err = prometheus.NewConstMetric(prometheus.NewDesc("avi_se_mem_conn_memory_per_core_mb", "AVI SE Memory Distribution Connection Memory Per Core MB", labelNames, nil),556 prometheus.GaugeValue, float64(dist.ConnMemoryMBPerCore), labelValues...)557 if err != nil {558 return err559 }560 o.metrics = append(o.metrics, newMetric)561 newMetric, err = prometheus.NewConstMetric(prometheus.NewDesc("avi_se_mem_huge_pages", "AVI SE Memory Distribution Huge Pages", labelNames, nil),562 prometheus.GaugeValue, float64(dist.HugePages), labelValues...)563 if err != nil {564 return err565 }566 o.metrics = append(o.metrics, newMetric)567 newMetric, err = prometheus.NewConstMetric(prometheus.NewDesc("avi_se_mem_hypervisor_type", "AVI SE Memory Distribution Hypervisor Type", labelNames, nil),568 prometheus.GaugeValue, float64(dist.HugePages), labelValues...)569 if err != nil {570 return err571 }572 o.metrics = append(o.metrics, newMetric)573 newMetric, err = prometheus.NewConstMetric(prometheus.NewDesc("avi_se_mem_num_queues", "AVI SE Memory Distribution Num Queues", labelNames, nil),574 prometheus.GaugeValue, float64(dist.NumQueues), labelValues...)575 if err != nil {576 return err577 }578 o.metrics = append(o.metrics, newMetric)579 newMetric, err = prometheus.NewConstMetric(prometheus.NewDesc("avi_se_mem_num_recv", "AVI SE Memory Distribution Num Received", labelNames, nil),580 prometheus.GaugeValue, float64(dist.NumRXd), labelValues...)581 if err != nil {582 return err583 }584 o.metrics = append(o.metrics, newMetric)585 newMetric, err = prometheus.NewConstMetric(prometheus.NewDesc("avi_se_mem_num_xmit", "AVI SE Memory Distribution Num Transmitted", labelNames, nil),586 prometheus.GaugeValue, float64(dist.NumTXd), labelValues...)587 if err != nil {588 return err589 }590 o.metrics = append(o.metrics, newMetric)591 newMetric, err = prometheus.NewConstMetric(prometheus.NewDesc("avi_se_mem_num_os_reserved_memory_mb", "AVI SE Memory Distribution OS Reserved Memory MB", labelNames, nil),592 prometheus.GaugeValue, float64(dist.OSReservedMemoryMB), labelValues...)593 if err != nil {594 return err595 }596 o.metrics = append(o.metrics, newMetric)597 newMetric, err = prometheus.NewConstMetric(prometheus.NewDesc("avi_se_mem_shm_config_memory_mb", "AVI SE Memory Distribution Shared Config Memory MB", labelNames, nil),598 prometheus.GaugeValue, float64(dist.ShmConfigMemoryMB), labelValues...)599 if err != nil {600 return err601 }602 o.metrics = append(o.metrics, newMetric)603 newMetric, err = prometheus.NewConstMetric(prometheus.NewDesc("avi_se_mem_shm_conn_memory_mb", "AVI SE Memory Distribution Shared Connection Memory MB", labelNames, nil),604 prometheus.GaugeValue, float64(dist.ShmConnMemoryMB), labelValues...)605 if err != nil {606 return err607 }608 o.metrics = append(o.metrics, newMetric)609 }610 }611 return err612}613func (o *Exporter) seShMalloc() (err error) {614 for _, se := range o.ses.Results {615 var shMalloc []models.ServiceEngineSHMallocStats616 err = o.AviClient.AviSession.Get("api/serviceengine/"+se.UUID+"/shmallocstats", &shMalloc)617 if err != nil {618 e := err.(session.AviError)619 if e.HttpStatusCode == 500 {620 level.Error(o.logger).Log("msg", "There was an error collecting se shmalloc stats", "error", fmt.Sprintf("%#v", err))621 continue622 } else {623 return err624 }625 }626 for _, outerStats := range shMalloc {627 for _, shMallocStat := range outerStats.ShMallocStatEntry {628 var labelNames = []string{"controller", "uuid", "ip"}629 var labelValues = []string{o.connectionOpts.Controller, se.UUID, se.Config.MgmtIpAddress.Addr}630 shMallocMetricName := strings.ToLower(shMallocStat.ShMallocTypeName)631 metricNameSize := fmt.Sprintf("avi_%s_size", shMallocMetricName)632 metricNameFail := fmt.Sprintf("avi_%s_fail", shMallocMetricName)633 metricNameCount := fmt.Sprintf("avi_%s_count", shMallocMetricName)634 newMetricSize, err := prometheus.NewConstMetric(prometheus.NewDesc(metricNameSize, "AVI SE Shared Malloc Size Entry", labelNames, nil),635 prometheus.GaugeValue, float64(shMallocStat.ShMallocTypeSize), labelValues...)636 if err != nil {637 return err638 }639 newMetricFail, err := prometheus.NewConstMetric(prometheus.NewDesc(metricNameFail, "AVI SE Shared Malloc Fail Entry", labelNames, nil),640 prometheus.GaugeValue, float64(shMallocStat.ShMallocTypeFail), labelValues...)641 if err != nil {642 return err643 }644 newMetricCount, err := prometheus.NewConstMetric(prometheus.NewDesc(metricNameCount, "AVI SE Shared Malloc Count Entry", labelNames, nil),645 prometheus.GaugeValue, float64(shMallocStat.ShMallocTypeCnt), labelValues...)646 if err != nil {647 return err648 }649 o.metrics = append(o.metrics, newMetricSize)650 o.metrics = append(o.metrics, newMetricFail)651 o.metrics = append(o.metrics, newMetricCount)652 }653 }654 }655 return err656}657func (o *Exporter) seBgpPeerState() (err error) {658 for _, se := range o.ses.Results {659 var seBGP []models.SeBGP660 err = o.AviClient.AviSession.Get("api/serviceengine/"+se.UUID+"/bgp", &seBGP)661 if err != nil {662 e := err.(session.AviError)663 if e.HttpStatusCode == 500 {664 level.Error(o.logger).Log("msg", "There was an error collecting se bgp stats", "error", fmt.Sprintf("%#v", err))665 continue666 } else {667 return err668 }669 }670 for _, peer := range seBGP {671 var labelNames = []string{"controller", "uuid", "ip", "vrf"}672 var labelValues = []string{o.connectionOpts.Controller, se.UUID, se.Config.MgmtIpAddress.Addr, peer.Name}673 newMetric, err := prometheus.NewConstMetric(prometheus.NewDesc("avi_se_bgp_peer_count", "AVI SE BGP Peer Count", labelNames, nil),674 prometheus.GaugeValue, float64(len(peer.Peers)), labelValues...)675 if err != nil {676 return err677 }678 o.metrics = append(o.metrics, newMetric)679 newMetric, err = prometheus.NewConstMetric(prometheus.NewDesc("avi_se_bgp_vs_count", "AVI SE BGP Peer VS Count", labelNames, nil),680 prometheus.GaugeValue, float64(len(peer.VSNames)), labelValues...)681 if err != nil {682 return err683 }684 o.metrics = append(o.metrics, newMetric)685 newMetric, err = prometheus.NewConstMetric(prometheus.NewDesc("avi_se_bgp_route_count", "AVI SE BGP Peer Route Count", labelNames, nil),686 prometheus.GaugeValue, float64(len(peer.Routes)), labelValues...)687 if err != nil {688 return err689 }690 o.metrics = append(o.metrics, newMetric)691 for _, p := range peer.Peers {692 var labelNames = []string{"controller", "uuid", "ip", "vrf", "peer_ip", "peer_state", "remote_as"}693 var labelValues = []string{o.connectionOpts.Controller, se.UUID, se.Config.MgmtIpAddress.Addr, peer.Name, p.PeerIP, p.PeerState, fmt.Sprintf("%v", p.RemoteAS)}694 newMetric, err = prometheus.NewConstMetric(prometheus.NewDesc("avi_se_bgp_peer_state", "AVI SE BGP Peer State", labelNames, nil),695 prometheus.GaugeValue, float64(p.Active), labelValues...)696 if err != nil {697 return err698 }699 o.metrics = append(o.metrics, newMetric)700 }701 }702 }703 return err704}705func (o *Exporter) seVnicPortGroup() (err error) {706 return err707}708func (o *Exporter) seMissedHeartBeats() (err error) {709 for _, se := range o.ses.Results {710 // TODO(stegen) add the timestamps?711 var labelNames = []string{"controller", "uuid", "ip"}712 var labelValues = []string{o.connectionOpts.Controller, se.UUID, se.Config.MgmtIpAddress.Addr}713 newMetric, err := prometheus.NewConstMetric(prometheus.NewDesc("avi_se_missed_heartbeats", "AVI Number SE Heartbeat Misses", labelNames, nil),714 prometheus.GaugeValue, float64(se.RunTime.HbStatus.NumHbMisses), labelValues...)715 if err != nil {716 return err717 }718 o.metrics = append(o.metrics, newMetric)719 newMetric, err = prometheus.NewConstMetric(prometheus.NewDesc("avi_se_outstanding_heartbeats", "AVI Number SE Outstanding Heartbeat", labelNames, nil),720 prometheus.GaugeValue, float64(se.RunTime.HbStatus.NumOutstandingHb), labelValues...)721 if err != nil {722 return err723 }724 o.metrics = append(o.metrics, newMetric)725 }726 return err727}728func (o *Exporter) getLicenseUsage() (err error) {729 var res interface{}730 err = o.AviClient.AviSession.Get("api/licenseusage?limit=365&step=86400", &res)731 if err != nil {732 return err733 }734 licensing := res.(map[string]interface{})735 var labelNames = []string{"controller"}736 var labelValues = []string{o.connectionOpts.Controller}737 if _, ok := licensing["licensed_ses"]; ok {738 newMetric, err := prometheus.NewConstMetric(prometheus.NewDesc("avi_license_licensed_ses_total", "AVI Total Licensed Service Engines", labelNames, nil),739 prometheus.GaugeValue, licensing["licensed_ses"].(float64), labelValues...)740 if err != nil {741 return err742 }743 o.metrics = append(o.metrics, newMetric)744 }745 if _, ok := licensing["num_ses"]; ok {746 newMetric, err := prometheus.NewConstMetric(prometheus.NewDesc("avi_license_licensed_ses_used", "AVI Total Used Service Engines", labelNames, nil),747 prometheus.GaugeValue, licensing["num_ses"].(float64), labelValues...)748 if err != nil {749 return err750 }751 o.metrics = append(o.metrics, newMetric)752 }753 if _, ok := licensing["licensed_cores"]; ok {754 newMetric, err := prometheus.NewConstMetric(prometheus.NewDesc("avi_license_licensed_cores_total", "AVI Total Licensed Cores", labelNames, nil),755 prometheus.GaugeValue, licensing["licensed_cores"].(float64), labelValues...)756 if err != nil {757 return err758 }759 o.metrics = append(o.metrics, newMetric)760 }761 if _, ok := licensing["licensed_service_cores"]; ok {762 newMetric, err := prometheus.NewConstMetric(prometheus.NewDesc("avi_license_licensed_service_cores_total", "AVI Total Licensed Cores", labelNames, nil),763 prometheus.GaugeValue, licensing["licensed_service_cores"].(float64), labelValues...)764 if err != nil {765 return err766 }767 o.metrics = append(o.metrics, newMetric)768 }769 if _, ok := licensing["consumed_service_cores"]; ok {770 newMetric, err := prometheus.NewConstMetric(prometheus.NewDesc("avi_license_consumed_service_cores_total", "AVI Total Licensed Cores", labelNames, nil),771 prometheus.GaugeValue, licensing["consumed_service_cores"].(float64), labelValues...)772 if err != nil {773 return err774 }775 o.metrics = append(o.metrics, newMetric)776 }777 if _, ok := licensing["num_se_vcpus"]; ok {778 newMetric, err := prometheus.NewConstMetric(prometheus.NewDesc("avi_license_licensed_cores_used", "AVI Total Used Cores", labelNames, nil),779 prometheus.GaugeValue, licensing["num_se_vcpus"].(float64), labelValues...)780 if err != nil {781 return err782 }783 o.metrics = append(o.metrics, newMetric)784 }785 if _, ok := licensing["licensed_sockets"]; ok {786 newMetric, err := prometheus.NewConstMetric(prometheus.NewDesc("avi_license_licensed_sockets_total", "AVI Total Licensed Sockets", labelNames, nil),787 prometheus.GaugeValue, licensing["licensed_sockets"].(float64), labelValues...)788 if err != nil {789 return err790 }791 o.metrics = append(o.metrics, newMetric)792 }793 if _, ok := licensing["num_sockets"]; ok {794 newMetric, err := prometheus.NewConstMetric(prometheus.NewDesc("avi_license_licensed_sockets_used", "AVI Total Used Sockets", labelNames, nil),795 prometheus.GaugeValue, licensing["num_sockets"].(float64), labelValues...)796 if err != nil {797 return err798 }799 o.metrics = append(o.metrics, newMetric)800 }801 return err802}803func (o *Exporter) getLicenseExpiration() (err error) {804 var licenses models.BaseLicense805 timeLayout := "2006-01-02T15:04:05"806 err = o.AviClient.AviSession.Get("api/license", &licenses)807 if err != nil {808 return err809 }810 for _, l := range licenses.Licenses {811 var labelNames = []string{"controller", "license_id"}812 var labelValues = []string{o.connectionOpts.Controller, l.LicenseId}813 validUntil, err := time.Parse(timeLayout, l.ValidUntil)814 if err != nil {815 return err816 }817 expires := validUntil.Sub(time.Now())818 newMetric, err := prometheus.NewConstMetric(prometheus.NewDesc("avi_license_expiration_days", "AVI License Expiration", labelNames, nil),819 prometheus.GaugeValue, expires.Hours()/24, labelValues...)820 if err != nil {821 return err822 }823 o.metrics = append(o.metrics, newMetric)824 }825 return nil826}827func (o *Exporter) getTenantNameFromUUID(uuid string) string {828 for _, tenant := range o.tenants.Results {829 tenantMap := tenant.(map[string]interface{})830 if tenantMap["uuid"] == uuid {831 return tenantMap["name"].(string)832 }833 }834 return "unknown"835}836func (o *Exporter) getCloudNameFromUUID(uuid string) string {837 for _, cloud := range o.clouds.Results {838 cloudMap := cloud.(map[string]interface{})839 if cloudMap["uuid"] == uuid {840 return cloudMap["name"].(string)841 }842 }843 return "unknown"844}845func (o *Exporter) getSEGroupNameFromUUID(uuid string) string {846 for _, seg := range o.segroups.Results {847 segMap := seg.(map[string]interface{})848 if segMap["uuid"] == uuid {849 return segMap["name"].(string)850 }851 }852 return "unknown"853}...

Full Screen

Full Screen

command.go

Source:command.go Github

copy

Full Screen

...10type Metrics struct {11 Metrics []*Metric12}1314func NewMetric(level int, id string, batch string, text string) *Metric {15 metric := &Metric{16 Level: level,17 Id: id,18 Batch: batch,19 Text: text,20 }21 return metric22}2324var metrics = []*Metric{25 NewMetric(0, "overview", "",26 "/redfish/v1/"),27 NewMetric(0, "firmware", "",28 "/redfish/v1/Systems/0/Oem/ts_fujitsu/FirmwareInventory"),29 NewMetric(0, "nic", "",30 "/redfish/v1/Systems/0/Oem/ts_fujitsu/FirmwareInventory/NIC"),31 NewMetric(0, "ntp0", "",32 "/redfish/v1/Managers/iRMC/Oem/ts_fujitsu/iRMCConfiguration/Time/NtpServers/0"),33 NewMetric(0, "ntp1", "",34 "/redfish/v1/Managers/iRMC/Oem/ts_fujitsu/iRMCConfiguration/Time/NtpServers/1"),35 NewMetric(0, "network", "",36 "/redfish/v1/Managers/iRMC/EthernetInterfaces/0"),37 NewMetric(0, "disk",38 "/rest/v1/Oem/eLCM/ProfileManagement/RAIDAdapter",39 "/rest/v1/Oem/eLCM/ProfileManagement/get?PARAM_PATH=Server/HWConfigurationIrmc/Adapters/RAIDAdapter"),40 NewMetric(0, "snmp",41 "/rest/v1/Oem/eLCM/ProfileManagement/NetworkServices",42 "/rest/v1/Oem/eLCM/ProfileManagement/get?PARAM_PATH=Server/SystemConfig/IrmcConfig/NetworkServices"),43} ...

Full Screen

Full Screen

NewMetric

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 http.Handle("/metrics", promhttp.Handler())4 go func() {5 log.Fatal(http.ListenAndServe(":2112", nil))6 }()7 inProgressGaugeVec := promauto.NewGaugeVec(prometheus.GaugeOpts{8 }, []string{"method"})9 inProgressGaugeVec.WithLabelValues("query").Inc()10 fmt.Println("hello world")11 inProgressGaugeVec.WithLabelValues("query").Dec()12}13myapp_inprogress_requests{method="query"} 014import (15func main() {16 http.Handle("/metrics", promhttp.Handler())17 go func() {18 log.Fatal(http.ListenAndServe(":2112", nil))19 }()20 histogramVec := promauto.NewHistogramVec(prometheus.HistogramOpts{

Full Screen

Full Screen

NewMetric

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 http.Handle("/metrics", promhttp.Handler())4 go func() {5 for {6 time.Sleep(5 * time.Second)7 metric := promauto.NewCounter(prometheus.CounterOpt

Full Screen

Full Screen

NewMetric

Using AI Code Generation

copy

Full Screen

1func main() {2 var v1 = v1.NewMetric()3 v1.Add(2, 3)4 fmt.Println(v1.Result())5}6type Metric struct {7}8func NewMetric() *Metric {9 return &Metric{result: 0}10}11func (m *Metric) Add(x, y int) {12}13func (m *Metric) Result() int {14}15type Metric struct {16}17func NewMetric() *Metric {18 return &Metric{result: 0}19}20func (m *Metric) Add(x, y int) {21}22func (m *Metric) Result() int {23}24type Metric struct {25}26func NewMetric() *Metric {27 return &Metric{result: 0}28}29func (m *Metric) Add(x, y int) {30}31func (m *Metric) Result() int {32}33type Metric struct {34}35func NewMetric() *Metric {36 return &Metric{result: 0}37}38func (m *Metric) Add(x, y int) {39}40func (m *Metric) Result() int {41}42type Metric struct {43}44func NewMetric() *Metric {45 return &Metric{result: 0}46}47func (m *Metric) Add(x, y int) {48}49func (m *Metric) Result() int {50}51type Metric struct {52}53func NewMetric() *Metric {54 return &Metric{result: 0}55}56func (m *Metric) Add(x, y int) {57}58func (m *Metric) Result() int {

Full Screen

Full Screen

NewMetric

Using AI Code Generation

copy

Full Screen

1func main() {2 m := v1.NewMetric()3 m.SetName("myMetric")4 m.SetDescription("myMetric description")5 m.SetUnit("myMetric unit")6 m.SetType(v1.MetricType_GAUGE)7 m.SetFloatVal(1.0)8 fmt.Println(m)9}

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