From 99aa9b8667b5981892ab178e9227ca50d5c5ba7f Mon Sep 17 00:00:00 2001 From: Toberd Date: Wed, 10 Mar 2021 10:24:09 +0100 Subject: [PATCH 01/12] Updated swagger documentation --- core/device/device.go | 168 +++- core/network/connection_data.go | 6 +- doc/api_doc.json | 1402 +++++++++++++++++++++++++++---- 3 files changed, 1363 insertions(+), 213 deletions(-) diff --git a/core/device/device.go b/core/device/device.go index 8f1eec6..26e562f 100644 --- a/core/device/device.go +++ b/core/device/device.go @@ -9,7 +9,7 @@ type ctxKey int const devicePropertiesKey ctxKey = iota + 1 -// Status represents an interface status +// Status represents an interface status. type Status string // All status codes with the corresponding label @@ -30,43 +30,47 @@ const ( // // swagger:model type Device struct { - // The os of the device + // Class of the device. // // example: routerOS Class string `yaml:"class" json:"class" xml:"class"` - // The properties of the device + // Properties of the device. Properties Properties `yaml:"properties" json:"properties" xml:"properties"` } // Properties // -// Properties are properties that can be determined for a device +// Properties are properties that can be determined for a device. // // swagger:model type Properties struct { - // Vendor of the device + // Vendor of the device. // // example: Mikrotik Vendor *string `yaml:"vendor" json:"vendor" xml:"vendor"` - // Model of the device + // Model of the device. // // example: CHR Model *string `yaml:"model" json:"model" xml:"model"` - // ModelSeries of the device + // ModelSeries of the device. // // example: null ModelSeries *string `yaml:"model_series" json:"model_series" xml:"model_series"` - // SerialNumber of the device + // SerialNumber of the device. // // example: null SerialNumber *string `yaml:"serial_number" json:"serial_number" xml:"serial_number"` - // OSVersion of the device + // OSVersion of the device. // // example: 6.44.6 OSVersion *string `yaml:"os_version" json:"os_version" xml:"os_version"` } -// Interface represents all interface values which can be read +// Interface +// +// Interface represents all interface values which can be read. +// +// swagger:model type Interface struct { IfIndex *uint64 `yaml:"ifIndex" json:"ifIndex" xml:"ifIndex"` IfDescr *string `yaml:"ifDescr" json:"ifDescr" xml:"ifDescr"` @@ -118,7 +122,15 @@ type Interface struct { OpticalOPM *OpticalOPMInterface `yaml:"optical_opm,omitempty" json:"optical_opm,omitempty" xml:"optical_opm,omitempty"` } -// EthernetLikeInterface represents an ethernet like interface +// +// Special interface types are defined here. +// + +// EthernetLikeInterface +// +// EthernetLikeInterface represents an ethernet like interface. +// +// swagger:model type EthernetLikeInterface struct { Dot3StatsAlignmentErrors *uint64 `yaml:"dot3StatsAlignmentErrors,omitempty" json:"dot3StatsAlignmentErrors,omitempty" xml:"dot3StatsAlignmentErrors,omitempty"` Dot3StatsFCSErrors *uint64 `yaml:"dot3StatsFCSErrors,omitempty" json:"dot3StatsFCSErrors,omitempty" xml:"dot3StatsFCSErrors,omitempty"` @@ -136,7 +148,11 @@ type EthernetLikeInterface struct { EtherStatsCRCAlignErrors *uint64 `yaml:"etherStatsCRCAlignErrors ,omitempty" json:"etherStatsCRCAlignErrors,omitempty" xml:"etherStatsCRCAlignErrors,omitempty"` } -// RadioInterface represents a radio interface +// RadioInterface +// +// RadioInterface represents a radio interface. +// +// swagger:model type RadioInterface struct { LevelOut *int64 `yaml:"level_out,omitempty" json:"level_out,omitempty" xml:"level_out,omitempty" mapstructure:"level_out"` LevelIn *int64 `yaml:"level_in,omitempty" json:"level_in,omitempty" xml:"level_in,omitempty" mapstructure:"level_in"` @@ -144,12 +160,21 @@ type RadioInterface struct { MaxbitrateIn *uint64 `yaml:"maxbitrate_in,omitempty" json:"maxbitrate_in,omitempty" xml:"maxbitrate_in,omitempty" mapstructure:"maxbitrate_in"` } -// DWDMInterface represents a DWDM interface +// DWDMInterface +// +// DWDMInterface represents a DWDM interface. +// +// swagger:model type DWDMInterface struct { RXLevel *float64 `yaml:"rx_level,omitempty" json:"rx_level,omitempty" xml:"rx_level,omitempty" mapstructure:"rx_level"` TXLevel *float64 `yaml:"tx_level,omitempty" json:"tx_level,omitempty" xml:"tx_level,omitempty" mapstructure:"tx_level"` } +// OpticalTransponderInterface +// +// OpticalTransponderInterface represents an optical transponder interface. +// +// swagger:model type OpticalTransponderInterface struct { Identifier *string `yaml:"identifier,omitempty" json:"identifier,omitempty" xml:"identifier,omitempty" mapstructure:"identifier"` Label *string `yaml:"label,omitempty" json:"label,omitempty" xml:"label,omitempty" mapstructure:"label"` @@ -159,6 +184,11 @@ type OpticalTransponderInterface struct { UncorrectedFEC *uint64 `yaml:"uncorrected_fec,omitempty" json:"uncorrected_fec,omitempty" xml:"uncorrected_fec,omitempty" mapstructure:"uncorrected_fec"` } +// OpticalAmplifierInterface +// +// OpticalAmplifierInterface represents an optical amplifier interface. +// +// swagger:model type OpticalAmplifierInterface struct { Identifier *string `yaml:"identifier,omitempty" json:"identifier,omitempty" xml:"identifier,omitempty" mapstructure:"identifier"` Label *string `yaml:"label,omitempty" json:"label,omitempty" xml:"label,omitempty" mapstructure:"label"` @@ -167,6 +197,11 @@ type OpticalAmplifierInterface struct { Gain *float64 `yaml:"gain,omitempty" json:"gain,omitempty" xml:"gain,omitempty" mapstructure:"gain"` } +// OpticalOPMInterface +// +// OpticalOPMInterface represents an optical opm interface. +// +// swagger:model type OpticalOPMInterface struct { Identifier *string `yaml:"identifier,omitempty" json:"identifier,omitempty" xml:"identifier,omitempty" mapstructure:"identifier"` Label *string `yaml:"label,omitempty" json:"label,omitempty" xml:"label,omitempty" mapstructure:"label"` @@ -174,12 +209,56 @@ type OpticalOPMInterface struct { Channels []OpticalOPMChannel `yaml:"channels,omitempty" json:"channels,omitempty" xml:"channels,omitempty" mapstructure:"channels"` } +// OpticalOPMChannel +// +// OpticalOPMChannel represents an optical opm channel of an optical opm interface. +// +// swagger:model type OpticalOPMChannel struct { Channel string `yaml:"channel,omitempty" json:"channel,omitempty" xml:"channel,omitempty" mapstructure:"channel"` RXPower *float64 `yaml:"rx_power,omitempty" json:"rx_power,omitempty" xml:"rx_power,omitempty" mapstructure:"rx_power"` } -// UPSComponent represents a UPS component +// +// Special device components are defined here. +// + +// CPUComponent +// +// CPUComponent represents a CPU component. +// +// swagger:model +type CPUComponent struct { + Load []float64 `yaml:"load" json:"load" xml:"load"` + Temperature []float64 `yaml:"temperature" json:"temperature" xml:"temperature"` +} + +// DiskComponent +// +// DiskComponent represents a disk component. +// +// swagger:model +type DiskComponent struct { + Storages []DiskComponentStorage `yaml:"storages" json:"storages" xml:"storages"` +} + +// DiskComponentStorage +// +// DiskComponentStorage contains information per storage. +// +// swagger:model +type DiskComponentStorage struct { + Type *string `yaml:"type" json:"type" xml:"type"` + Description *string `yaml:"description" json:"description" xml:"description"` + Available *int `yaml:"available" json:"available" xml:"available"` + Used *int `yaml:"used" json:"used" xml:"used"` +} + +// UPSComponent +// +// UPSComponent represents a UPS component. +// +// swagger:model type UPSComponent struct { AlarmLowVoltageDisconnect *int `yaml:"alarm_low_voltage_disconnect" json:"alarm_low_voltage_disconnect" xml:"alarm_low_voltage_disconnect"` BatteryAmperage *float64 `yaml:"battery_amperage " json:"battery_amperage " xml:"battery_amperage"` @@ -194,26 +273,21 @@ type UPSComponent struct { SystemVoltage *float64 `yaml:"system_voltage" json:"system_voltage" xml:"system_voltage"` } -// ServerComponent represents a server component +// ServerComponent +// +// ServerComponent represents a server component. +// +// swagger:model type ServerComponent struct { Procs *int `yaml:"procs" json:"procs" xml:"procs"` Users *int `yaml:"users" json:"users" xml:"users"` } -// DiskComponent represents a disk component -type DiskComponent struct { - Storages []DiskComponentStorage `yaml:"storages" json:"storages" xml:"storages"` -} - -// DiskComponentStorage contains information per storage. -type DiskComponentStorage struct { - Type *string `yaml:"type" json:"type" xml:"type"` - Description *string `yaml:"description" json:"description" xml:"description"` - Available *int `yaml:"available" json:"available" xml:"available"` - Used *int `yaml:"used" json:"used" xml:"used"` -} - -// SBCComponent represents a SBC component +// SBCComponent +// +// SBCComponent represents a SBC component. +// +// swagger:model type SBCComponent struct { Agents []SBCComponentAgent `yaml:"agents" json:"agents" xml:"agents"` Realms []SBCComponentRealm `yaml:"realms" json:"realms" xml:"realms"` @@ -226,7 +300,11 @@ type SBCComponent struct { SystemHealthScore *int `yaml:"system_health_score" json:"system_health_score" xml:"system_health_score"` } +// SBCComponentAgent +// // SBCComponentAgent contains information per agent. (Voice) +// +// swagger:model type SBCComponentAgent struct { Hostname string `yaml:"hostname" json:"hostname" xml:"hostname" mapstructure:"hostname"` CurrentActiveSessionsInbound *int `yaml:"current_active_sessions_inbound" json:"current_active_sessions_inbound" xml:"current_active_sessions_inbound" mapstructure:"current_active_sessions_inbound"` @@ -237,7 +315,11 @@ type SBCComponentAgent struct { Status *int `yaml:"status" json:"status" xml:"status" mapstructure:"status"` } +// SBCComponentRealm +// // SBCComponentRealm contains information per realm. (Voice) +// +// swagger:model type SBCComponentRealm struct { Name string `yaml:"name" json:"name" xml:"name"` CurrentActiveSessionsInbound *int `yaml:"current_active_sessions_inbound" json:"current_active_sessions_inbound" xml:"current_active_sessions_inbound" mapstructure:"current_active_sessions_inbound"` @@ -249,41 +331,49 @@ type SBCComponentRealm struct { Status *int `yaml:"status" json:"status" xml:"status" mapstructure:"status"` } -// CPUComponent represents a CPU component -type CPUComponent struct { - Load []float64 `yaml:"load" json:"load" xml:"load"` - Temperature []float64 `yaml:"temperature" json:"temperature" xml:"temperature"` -} - -// HardwareHealthComponent represents hardware health information of a device +// HardwareHealthComponent +// +// HardwareHealthComponent represents hardware health information of a device. +// +// swagger:model type HardwareHealthComponent struct { EnvironmentMonitorState *int `yaml:"environment_monitor_state" json:"environment_monitor_state" xml:"environment_monitor_state"` Fans []HardwareHealthComponentFan `yaml:"fans" json:"fans" xml:"fans"` PowerSupply []HardwareHealthComponentPowerSupply `yaml:"power_supply" json:"power_supply" xml:"power_supply"` } +// HardwareHealthComponentFan +// +// HardwareHealthComponentFan represents one fan of a device. +// +// swagger:model type HardwareHealthComponentFan struct { Description *string `yaml:"description" json:"description" xml:"description"` State *int `yaml:"state" json:"state" xml:"state"` } +// HardwareHealthComponentPowerSupply +// +// HardwareHealthComponentPowerSupply represents one power supply of a device. +// +// swagger:model type HardwareHealthComponentPowerSupply struct { Description *string `yaml:"description" json:"description" xml:"description"` State *int `yaml:"state" json:"state" xml:"state"` } -// NewContextWithDeviceProperties returns a new context with the device properties +// NewContextWithDeviceProperties returns a new context with the device properties. func NewContextWithDeviceProperties(ctx context.Context, properties Device) context.Context { return context.WithValue(ctx, devicePropertiesKey, properties) } -// DevicePropertiesFromContext returns the device properties from the context +// DevicePropertiesFromContext returns the device properties from the context. func DevicePropertiesFromContext(ctx context.Context) (Device, bool) { properties, ok := ctx.Value(devicePropertiesKey).(Device) return properties, ok } -// ToStatusCode returns the status as a code +// ToStatusCode returns the status as a code. func (s Status) ToStatusCode() (int, error) { switch s { case StatusUp: diff --git a/core/network/connection_data.go b/core/network/connection_data.go index 7226c82..c6129bc 100644 --- a/core/network/connection_data.go +++ b/core/network/connection_data.go @@ -2,7 +2,7 @@ package network // ConnectionData // -// ConnectionData includes all connection data for a device +// ConnectionData includes all connection data for a device. // // swagger:model type ConnectionData struct { @@ -14,7 +14,7 @@ type ConnectionData struct { // SNMPConnectionData // -// SNMPConnectionData includes all snmp connection data for a device +// SNMPConnectionData includes all snmp connection data for a device. // // swagger:model type SNMPConnectionData struct { @@ -53,7 +53,7 @@ type SNMPCredentials struct { // HTTPConnectionData // -// HTTPConnectionData includes all http connection data for a device +// HTTPConnectionData includes all http connection data for a device. // // swagger:model type HTTPConnectionData struct { diff --git a/doc/api_doc.json b/doc/api_doc.json index a136982..e42f614 100644 --- a/doc/api_doc.json +++ b/doc/api_doc.json @@ -23,6 +23,132 @@ }, "host": "localhost:8237", "paths": { + "/check/cpu-load": { + "post": { + "consumes": [ + "application/json", + "application/xml" + ], + "produces": [ + "application/json", + "application/xml" + ], + "tags": [ + "check" + ], + "summary": "Check the cpu load of a device.", + "operationId": "checkCpuLoad", + "parameters": [ + { + "description": "Request to process.", + "name": "body", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/CheckCpuLoadRequest" + } + } + ], + "responses": { + "200": { + "description": "Returns the response.", + "schema": { + "$ref": "#/definitions/CheckCpuLoadResponse" + } + }, + "400": { + "description": "Returns an error with more details in the body.", + "schema": { + "$ref": "#/definitions/OutputError" + } + } + } + } + }, + "/check/disk": { + "post": { + "consumes": [ + "application/json", + "application/xml" + ], + "produces": [ + "application/json", + "application/xml" + ], + "tags": [ + "check" + ], + "summary": "Check the disk of a device.", + "operationId": "checkDisk", + "parameters": [ + { + "description": "Request to process.", + "name": "body", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/CheckDiskRequest" + } + } + ], + "responses": { + "200": { + "description": "Returns the response.", + "schema": { + "$ref": "#/definitions/CheckDiskResponse" + } + }, + "400": { + "description": "Returns an error with more details in the body.", + "schema": { + "$ref": "#/definitions/OutputError" + } + } + } + } + }, + "/check/hardware-health": { + "post": { + "consumes": [ + "application/json", + "application/xml" + ], + "produces": [ + "application/json", + "application/xml" + ], + "tags": [ + "check" + ], + "summary": "Check an hardware health of an device.", + "operationId": "checkSBC", + "parameters": [ + { + "description": "Request to process.", + "name": "body", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/CheckHardwareHealthRequest" + } + } + ], + "responses": { + "200": { + "description": "Returns the response.", + "schema": { + "$ref": "#/definitions/CheckHardwareHealthResponse" + } + }, + "400": { + "description": "Returns an error with more details in the body.", + "schema": { + "$ref": "#/definitions/OutputError" + } + } + } + } + }, "/check/identify": { "post": { "consumes": [ @@ -120,7 +246,7 @@ "tags": [ "check" ], - "summary": "Read out the memory usage of a device.", + "summary": "Check the memory usage of a device.", "operationId": "checkMemoryUsage", "parameters": [ { @@ -149,7 +275,7 @@ } } }, - "/check/metrics": { + "/check/sbc": { "post": { "consumes": [ "application/json", @@ -162,8 +288,8 @@ "tags": [ "check" ], - "summary": "Prints all available metrics for a device as performance data.", - "operationId": "checkMetrics", + "summary": "Check an sbc device.", + "operationId": "checkSBC", "parameters": [ { "description": "Request to process.", @@ -171,7 +297,7 @@ "in": "body", "required": true, "schema": { - "$ref": "#/definitions/CheckMetricsRequest" + "$ref": "#/definitions/CheckSBCRequest" } } ], @@ -179,7 +305,49 @@ "200": { "description": "Returns the response.", "schema": { - "$ref": "#/definitions/CheckResponse" + "$ref": "#/definitions/CheckSBCResponse" + } + }, + "400": { + "description": "Returns an error with more details in the body.", + "schema": { + "$ref": "#/definitions/OutputError" + } + } + } + } + }, + "/check/server": { + "post": { + "consumes": [ + "application/json", + "application/xml" + ], + "produces": [ + "application/json", + "application/xml" + ], + "tags": [ + "check" + ], + "summary": "Check a linux server.", + "operationId": "checkServer", + "parameters": [ + { + "description": "Request to process.", + "name": "body", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/CheckServerRequest" + } + } + ], + "responses": { + "200": { + "description": "Returns the response.", + "schema": { + "$ref": "#/definitions/CheckServerResponse" } }, "400": { @@ -485,6 +653,91 @@ } } }, + "/read/disk": { + "post": { + "consumes": [ + "application/json", + "application/xml" + ], + "produces": [ + "application/json", + "application/xml" + ], + "tags": [ + "read" + ], + "summary": "Reads out disk data of a device.", + "operationId": "readDisk", + "parameters": [ + { + "description": "Request to process.", + "name": "body", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/ReadDiskRequest" + } + } + ], + "responses": { + "200": { + "description": "Returns the response.", + "schema": { + "$ref": "#/definitions/ReadDiskResponse" + } + }, + "400": { + "description": "Returns an error with more details in the body.", + "schema": { + "$ref": "#/definitions/OutputError" + } + } + } + } + }, + "/read/hardware-health": { + "post": { + "consumes": [ + "application/json", + "application/xml" + ], + "produces": [ + "application/json", + "application/xml" + ], + "tags": [ + "read", + "hardware" + ], + "summary": "Reads out hardware health data of a device.", + "operationId": "health", + "parameters": [ + { + "description": "Request to process.", + "name": "body", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/ReadHardwareHealthRequest" + } + } + ], + "responses": { + "200": { + "description": "Returns the response.", + "schema": { + "$ref": "#/definitions/ReadHardwareHealthResponse" + } + }, + "400": { + "description": "Returns an error with more details in the body.", + "schema": { + "$ref": "#/definitions/OutputError" + } + } + } + } + }, "/read/interfaces": { "post": { "consumes": [ @@ -569,7 +822,7 @@ } } }, - "/read/ups": { + "/read/sbc": { "post": { "consumes": [ "application/json", @@ -582,8 +835,8 @@ "tags": [ "read" ], - "summary": "Reads out UPS data of a device.", - "operationId": "readUPS", + "summary": "Reads out SBC data of a device.", + "operationId": "readSBC", "parameters": [ { "description": "Request to process.", @@ -591,7 +844,7 @@ "in": "body", "required": true, "schema": { - "$ref": "#/definitions/ReadUPSRequest" + "$ref": "#/definitions/ReadSBCRequest" } } ], @@ -599,7 +852,7 @@ "200": { "description": "Returns the response.", "schema": { - "$ref": "#/definitions/ReadUPSResponse" + "$ref": "#/definitions/ReadSBCResponse" } }, "400": { @@ -610,35 +863,224 @@ } } } - } - }, - "definitions": { - "BaseRequest": { - "description": "BaseRequest is a generic request that is processed by thola", - "type": "object", - "properties": { - "device_data": { - "$ref": "#/definitions/DeviceData" - }, - "timeout": { - "description": "Timeout for the request (0 =\u003e no timeout)", - "type": "integer", - "format": "int64", - "x-go-name": "Timeout" - } - }, - "x-go-package": "github.com/inexio/thola/core/request" - }, - "BaseResponse": { - "description": "BaseResponse defines attributes every response has.", - "type": "object", - "title": "BaseResponse", - "x-go-package": "github.com/inexio/thola/core/request" }, - "CheckDeviceRequest": { - "description": "CheckDeviceRequest is a the request struct for the check device request.", - "type": "object", - "title": "CheckDeviceRequest", + "/read/server": { + "post": { + "consumes": [ + "application/json", + "application/xml" + ], + "produces": [ + "application/json", + "application/xml" + ], + "tags": [ + "read" + ], + "summary": "Reads out server data of a device.", + "operationId": "readServer", + "parameters": [ + { + "description": "Request to process.", + "name": "body", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/ReadServerRequest" + } + } + ], + "responses": { + "200": { + "description": "Returns the response.", + "schema": { + "$ref": "#/definitions/ReadServerResponse" + } + }, + "400": { + "description": "Returns an error with more details in the body.", + "schema": { + "$ref": "#/definitions/OutputError" + } + } + } + } + }, + "/read/ups": { + "post": { + "consumes": [ + "application/json", + "application/xml" + ], + "produces": [ + "application/json", + "application/xml" + ], + "tags": [ + "read" + ], + "summary": "Reads out UPS data of a device.", + "operationId": "readUPS", + "parameters": [ + { + "description": "Request to process.", + "name": "body", + "in": "body", + "required": true, + "schema": { + "$ref": "#/definitions/ReadUPSRequest" + } + } + ], + "responses": { + "200": { + "description": "Returns the response.", + "schema": { + "$ref": "#/definitions/ReadUPSResponse" + } + }, + "400": { + "description": "Returns an error with more details in the body.", + "schema": { + "$ref": "#/definitions/OutputError" + } + } + } + } + } + }, + "definitions": { + "BaseRequest": { + "description": "BaseRequest is a generic request that is processed by thola", + "type": "object", + "properties": { + "device_data": { + "$ref": "#/definitions/DeviceData" + }, + "timeout": { + "description": "Timeout for the request (0 =\u003e no timeout)", + "type": "integer", + "format": "int64", + "x-go-name": "Timeout" + } + }, + "x-go-package": "github.com/inexio/thola/core/request" + }, + "BaseResponse": { + "description": "BaseResponse defines attributes every response has.", + "type": "object", + "title": "BaseResponse", + "x-go-package": "github.com/inexio/thola/core/request" + }, + "CPUComponent": { + "description": "CPUComponent represents a CPU component.", + "type": "object", + "title": "CPUComponent", + "properties": { + "load": { + "type": "array", + "items": { + "type": "number", + "format": "double" + }, + "x-go-name": "Load" + }, + "temperature": { + "type": "array", + "items": { + "type": "number", + "format": "double" + }, + "x-go-name": "Temperature" + } + }, + "x-go-package": "github.com/inexio/thola/core/device" + }, + "CheckCPULoadRequest": { + "description": "CheckCPULoadRequest is a the request struct for the check cpu load request.", + "type": "object", + "title": "CheckCPULoadRequest", + "properties": { + "cpuLoadThresholds": { + "$ref": "#/definitions/CheckThresholds" + }, + "device_data": { + "$ref": "#/definitions/DeviceData" + }, + "json_metrics": { + "type": "boolean", + "x-go-name": "JSONMetrics" + }, + "print_performance_data": { + "type": "boolean", + "x-go-name": "PrintPerformanceData" + }, + "timeout": { + "description": "Timeout for the request (0 =\u003e no timeout)", + "type": "integer", + "format": "int64", + "x-go-name": "Timeout" + } + }, + "x-go-package": "github.com/inexio/thola/core/request" + }, + "CheckDeviceRequest": { + "description": "CheckDeviceRequest is a the request struct for the check device request.", + "type": "object", + "title": "CheckDeviceRequest", + "properties": { + "device_data": { + "$ref": "#/definitions/DeviceData" + }, + "json_metrics": { + "type": "boolean", + "x-go-name": "JSONMetrics" + }, + "print_performance_data": { + "type": "boolean", + "x-go-name": "PrintPerformanceData" + }, + "timeout": { + "description": "Timeout for the request (0 =\u003e no timeout)", + "type": "integer", + "format": "int64", + "x-go-name": "Timeout" + } + }, + "x-go-package": "github.com/inexio/thola/core/request" + }, + "CheckDiskRequest": { + "description": "CheckDiskRequest is a the request struct for the check disk request.", + "type": "object", + "title": "CheckDiskRequest", + "properties": { + "device_data": { + "$ref": "#/definitions/DeviceData" + }, + "diskThresholds": { + "$ref": "#/definitions/CheckThresholds" + }, + "json_metrics": { + "type": "boolean", + "x-go-name": "JSONMetrics" + }, + "print_performance_data": { + "type": "boolean", + "x-go-name": "PrintPerformanceData" + }, + "timeout": { + "description": "Timeout for the request (0 =\u003e no timeout)", + "type": "integer", + "format": "int64", + "x-go-name": "Timeout" + } + }, + "x-go-package": "github.com/inexio/thola/core/request" + }, + "CheckHardwareHealthRequest": { + "description": "CheckHardwareHealthRequest is a the request struct for the check sbc request.", + "type": "object", + "title": "CheckHardwareHealthRequest", "properties": { "device_data": { "$ref": "#/definitions/DeviceData" @@ -720,12 +1162,19 @@ "device_data": { "$ref": "#/definitions/DeviceData" }, - "filter": { + "ifName_filter": { "type": "array", "items": { "type": "string" }, - "x-go-name": "Filter" + "x-go-name": "IfNameFilter" + }, + "ifType_filter": { + "type": "array", + "items": { + "type": "string" + }, + "x-go-name": "IfTypeFilter" }, "json_metrics": { "type": "boolean", @@ -776,38 +1225,6 @@ }, "x-go-package": "github.com/inexio/thola/core/request" }, - "CheckMetricsRequest": { - "description": "CheckRequest is a the request struct for the check metrics request.", - "type": "object", - "title": "CheckMetricsRequest", - "properties": { - "device_data": { - "$ref": "#/definitions/DeviceData" - }, - "interface_filter": { - "type": "array", - "items": { - "type": "string" - }, - "x-go-name": "InterfaceFilter" - }, - "json_metrics": { - "type": "boolean", - "x-go-name": "JSONMetrics" - }, - "print_performance_data": { - "type": "boolean", - "x-go-name": "PrintPerformanceData" - }, - "timeout": { - "description": "Timeout for the request (0 =\u003e no timeout)", - "type": "integer", - "format": "int64", - "x-go-name": "Timeout" - } - }, - "x-go-package": "github.com/inexio/thola/core/request" - }, "CheckRequest": { "description": "CheckRequest is a generic response struct for the check request.", "type": "object", @@ -855,6 +1272,34 @@ }, "x-go-package": "github.com/inexio/thola/core/request" }, + "CheckSBCRequest": { + "description": "CheckSBCRequest is a the request struct for the check sbc request.", + "type": "object", + "title": "CheckSBCRequest", + "properties": { + "SystemHealthScoreThresholds": { + "$ref": "#/definitions/CheckThresholds" + }, + "device_data": { + "$ref": "#/definitions/DeviceData" + }, + "json_metrics": { + "type": "boolean", + "x-go-name": "JSONMetrics" + }, + "print_performance_data": { + "type": "boolean", + "x-go-name": "PrintPerformanceData" + }, + "timeout": { + "description": "Timeout for the request (0 =\u003e no timeout)", + "type": "integer", + "format": "int64", + "x-go-name": "Timeout" + } + }, + "x-go-package": "github.com/inexio/thola/core/request" + }, "CheckSNMPRequest": { "description": "CheckSNMPRequest is a the request struct for the check snmp request.", "type": "object", @@ -880,6 +1325,34 @@ }, "x-go-package": "github.com/inexio/thola/core/request" }, + "CheckServerRequest": { + "description": "CheckServerRequest is a the request struct for the check server request.", + "type": "object", + "title": "CheckServerRequest", + "properties": { + "device_data": { + "$ref": "#/definitions/DeviceData" + }, + "json_metrics": { + "type": "boolean", + "x-go-name": "JSONMetrics" + }, + "print_performance_data": { + "type": "boolean", + "x-go-name": "PrintPerformanceData" + }, + "serverThresholds": { + "$ref": "#/definitions/CheckThresholds" + }, + "timeout": { + "description": "Timeout for the request (0 =\u003e no timeout)", + "type": "integer", + "format": "int64", + "x-go-name": "Timeout" + } + }, + "x-go-package": "github.com/inexio/thola/core/request" + }, "CheckTholaServerRequest": { "description": "CheckTholaServerRequest is the request struct for the check thola server request.", "type": "object", @@ -905,16 +1378,24 @@ "type": "object", "properties": { "criticalMax": { - "$ref": "#/definitions/Value" + "type": "number", + "format": "double", + "x-go-name": "CriticalMax" }, "criticalMin": { - "$ref": "#/definitions/Value" + "type": "number", + "format": "double", + "x-go-name": "CriticalMin" }, "warningMax": { - "$ref": "#/definitions/Value" + "type": "number", + "format": "double", + "x-go-name": "WarningMax" }, "warningMin": { - "$ref": "#/definitions/Value" + "type": "number", + "format": "double", + "x-go-name": "WarningMin" } }, "x-go-package": "github.com/inexio/thola/core/request" @@ -971,7 +1452,25 @@ "$ref": "#/definitions/SNMPConnectionData" } }, - "x-go-package": "github.com/inexio/thola/core/network" + "x-go-package": "github.com/inexio/thola/core/network" + }, + "DWDMInterface": { + "description": "DWDMInterface represents a DWDM interface.", + "type": "object", + "title": "DWDMInterface", + "properties": { + "rx_level": { + "type": "number", + "format": "double", + "x-go-name": "RXLevel" + }, + "tx_level": { + "type": "number", + "format": "double", + "x-go-name": "TXLevel" + } + }, + "x-go-package": "github.com/inexio/thola/core/device" }, "Device": { "description": "Device represents a device and has the same structure as Response.\nResponse can possibly be removed and replaced by Device.", @@ -979,7 +1478,7 @@ "title": "Device", "properties": { "class": { - "description": "The os of the device", + "description": "Class of the device.", "type": "string", "x-go-name": "Class", "example": "routerOS" @@ -1007,83 +1506,51 @@ }, "x-go-package": "github.com/inexio/thola/core/request" }, - "HTTPConnectionData": { - "description": "HTTPConnectionData includes all http connection data for a device", + "DiskComponent": { + "description": "DiskComponent represents a disk component.", "type": "object", - "title": "HTTPConnectionData", + "title": "DiskComponent", "properties": { - "auth_password": { - "description": "The password for authorization on the device", - "type": "string", - "x-go-name": "AuthPassword", - "example": "password" - }, - "auth_username": { - "description": "The username for authorization on the device", - "type": "string", - "x-go-name": "AuthUsername", - "example": "username" - }, - "http_ports": { - "description": "The http port(s) of the device", - "type": "array", - "items": { - "type": "integer", - "format": "int64" - }, - "x-go-name": "HTTPPorts", - "example": "80" - }, - "https_ports": { - "description": "The https port(s) of the device", + "storages": { "type": "array", "items": { - "type": "integer", - "format": "int64" + "$ref": "#/definitions/DiskComponentStorage" }, - "x-go-name": "HTTPSPorts", - "example": "443" + "x-go-name": "Storages" } }, - "x-go-package": "github.com/inexio/thola/core/network" + "x-go-package": "github.com/inexio/thola/core/device" }, - "IdentifyRequest": { - "description": "IdentifyRequest is a the request struct for the identify request.", + "DiskComponentStorage": { + "description": "DiskComponentStorage contains information per storage.", "type": "object", - "title": "IdentifyRequest", + "title": "DiskComponentStorage", "properties": { - "device_data": { - "$ref": "#/definitions/DeviceData" - }, - "timeout": { - "description": "Timeout for the request (0 =\u003e no timeout)", + "available": { "type": "integer", "format": "int64", - "x-go-name": "Timeout" - } - }, - "x-go-package": "github.com/inexio/thola/core/request" - }, - "IdentifyResponse": { - "description": "IdentifyResponse is the response struct that is for identify requests.", - "type": "object", - "title": "IdentifyResponse", - "properties": { - "class": { - "description": "The os of the device", + "x-go-name": "Available" + }, + "description": { "type": "string", - "x-go-name": "Class", - "example": "routerOS" + "x-go-name": "Description" }, - "properties": { - "$ref": "#/definitions/Properties" + "type": { + "type": "string", + "x-go-name": "Type" + }, + "used": { + "type": "integer", + "format": "int64", + "x-go-name": "Used" } }, - "x-go-package": "github.com/inexio/thola/core/request" + "x-go-package": "github.com/inexio/thola/core/device" }, - "Interface": { - "description": "Interface represents all interface values which can be read", + "EthernetLikeInterface": { + "description": "EthernetLikeInterface represents an ethernet like interface.", "type": "object", + "title": "EthernetLikeInterface", "properties": { "dot3HCStatsFCSErrors": { "type": "integer", @@ -1154,6 +1621,155 @@ "type": "integer", "format": "uint64", "x-go-name": "EtherStatsCRCAlignErrors" + } + }, + "x-go-package": "github.com/inexio/thola/core/device" + }, + "HTTPConnectionData": { + "description": "HTTPConnectionData includes all http connection data for a device", + "type": "object", + "title": "HTTPConnectionData", + "properties": { + "auth_password": { + "description": "The password for authorization on the device", + "type": "string", + "x-go-name": "AuthPassword", + "example": "password" + }, + "auth_username": { + "description": "The username for authorization on the device", + "type": "string", + "x-go-name": "AuthUsername", + "example": "username" + }, + "http_ports": { + "description": "The http port(s) of the device", + "type": "array", + "items": { + "type": "integer", + "format": "int64" + }, + "x-go-name": "HTTPPorts", + "example": "80" + }, + "https_ports": { + "description": "The https port(s) of the device", + "type": "array", + "items": { + "type": "integer", + "format": "int64" + }, + "x-go-name": "HTTPSPorts", + "example": "443" + } + }, + "x-go-package": "github.com/inexio/thola/core/network" + }, + "HardwareHealthComponent": { + "description": "HardwareHealthComponent represents hardware health information of a device.", + "type": "object", + "title": "HardwareHealthComponent", + "properties": { + "environment_monitor_state": { + "type": "integer", + "format": "int64", + "x-go-name": "EnvironmentMonitorState" + }, + "fans": { + "type": "array", + "items": { + "$ref": "#/definitions/HardwareHealthComponentFan" + }, + "x-go-name": "Fans" + }, + "power_supply": { + "type": "array", + "items": { + "$ref": "#/definitions/HardwareHealthComponentPowerSupply" + }, + "x-go-name": "PowerSupply" + } + }, + "x-go-package": "github.com/inexio/thola/core/device" + }, + "HardwareHealthComponentFan": { + "description": "HardwareHealthComponentFan represents one fan of a device.", + "type": "object", + "title": "HardwareHealthComponentFan", + "properties": { + "description": { + "type": "string", + "x-go-name": "Description" + }, + "state": { + "type": "integer", + "format": "int64", + "x-go-name": "State" + } + }, + "x-go-package": "github.com/inexio/thola/core/device" + }, + "HardwareHealthComponentPowerSupply": { + "description": "HardwareHealthComponentPowerSupply represents one power supply of a device.", + "type": "object", + "title": "HardwareHealthComponentPowerSupply", + "properties": { + "description": { + "type": "string", + "x-go-name": "Description" + }, + "state": { + "type": "integer", + "format": "int64", + "x-go-name": "State" + } + }, + "x-go-package": "github.com/inexio/thola/core/device" + }, + "IdentifyRequest": { + "description": "IdentifyRequest is a the request struct for the identify request.", + "type": "object", + "title": "IdentifyRequest", + "properties": { + "device_data": { + "$ref": "#/definitions/DeviceData" + }, + "timeout": { + "description": "Timeout for the request (0 =\u003e no timeout)", + "type": "integer", + "format": "int64", + "x-go-name": "Timeout" + } + }, + "x-go-package": "github.com/inexio/thola/core/request" + }, + "IdentifyResponse": { + "description": "IdentifyResponse is the response struct that is for identify requests.", + "type": "object", + "title": "IdentifyResponse", + "properties": { + "class": { + "description": "Class of the device.", + "type": "string", + "x-go-name": "Class", + "example": "routerOS" + }, + "properties": { + "$ref": "#/definitions/Properties" + } + }, + "x-go-package": "github.com/inexio/thola/core/request" + }, + "Interface": { + "description": "Interface represents all interface values which can be read.", + "type": "object", + "title": "Interface", + "properties": { + "dwdm": { + "$ref": "#/definitions/DWDMInterface" + }, + "ethernet_like": { + "$ref": "#/definitions/EthernetLikeInterface" }, "ifAdminStatus": { "$ref": "#/definitions/Status" @@ -1330,35 +1946,129 @@ "type": "string", "x-go-name": "IfType" }, - "level_in": { - "type": "integer", - "format": "int64", - "x-go-name": "LevelIn" + "optical_amplifier": { + "$ref": "#/definitions/OpticalAmplifierInterface" }, - "level_out": { - "type": "integer", - "format": "int64", - "x-go-name": "LevelOut" + "optical_opm": { + "$ref": "#/definitions/OpticalOPMInterface" }, - "maxbitrate_in": { - "type": "integer", - "format": "uint64", - "x-go-name": "MaxbitrateIn" + "optical_transponder": { + "$ref": "#/definitions/OpticalTransponderInterface" }, - "maxbitrate_out": { + "radio": { + "$ref": "#/definitions/RadioInterface" + } + }, + "x-go-package": "github.com/inexio/thola/core/device" + }, + "OpticalAmplifierInterface": { + "description": "OpticalAmplifierInterface represents an optical amplifier interface.", + "type": "object", + "title": "OpticalAmplifierInterface", + "properties": { + "gain": { + "type": "number", + "format": "double", + "x-go-name": "Gain" + }, + "identifier": { + "type": "string", + "x-go-name": "Identifier" + }, + "label": { + "type": "string", + "x-go-name": "Label" + }, + "rx_power": { + "type": "number", + "format": "double", + "x-go-name": "RXPower" + }, + "tx_power": { + "type": "number", + "format": "double", + "x-go-name": "TXPower" + } + }, + "x-go-package": "github.com/inexio/thola/core/device" + }, + "OpticalOPMChannel": { + "description": "OpticalOPMChannel represents an optical opm channel of an optical opm interface.", + "type": "object", + "title": "OpticalOPMChannel", + "properties": { + "channel": { + "type": "string", + "x-go-name": "Channel" + }, + "rx_power": { + "type": "number", + "format": "double", + "x-go-name": "RXPower" + } + }, + "x-go-package": "github.com/inexio/thola/core/device" + }, + "OpticalOPMInterface": { + "description": "OpticalOPMInterface represents an optical opm interface.", + "type": "object", + "title": "OpticalOPMInterface", + "properties": { + "channels": { + "type": "array", + "items": { + "$ref": "#/definitions/OpticalOPMChannel" + }, + "x-go-name": "Channels" + }, + "identifier": { + "type": "string", + "x-go-name": "Identifier" + }, + "label": { + "type": "string", + "x-go-name": "Label" + }, + "rx_power": { + "type": "number", + "format": "double", + "x-go-name": "RXPower" + } + }, + "x-go-package": "github.com/inexio/thola/core/device" + }, + "OpticalTransponderInterface": { + "description": "OpticalTransponderInterface represents an optical transponder interface.", + "type": "object", + "title": "OpticalTransponderInterface", + "properties": { + "corrected_fec": { "type": "integer", "format": "uint64", - "x-go-name": "MaxbitrateOut" + "x-go-name": "CorrectedFEC" + }, + "identifier": { + "type": "string", + "x-go-name": "Identifier" }, - "rx_level": { + "label": { + "type": "string", + "x-go-name": "Label" + }, + "rx_power": { "type": "number", "format": "double", - "x-go-name": "RXLevel" + "x-go-name": "RXPower" }, - "tx_level": { + "tx_power": { "type": "number", "format": "double", - "x-go-name": "TXLevel" + "x-go-name": "TXPower" + }, + "uncorrected_fec": { + "type": "integer", + "format": "uint64", + "x-go-name": "UncorrectedFEC" } }, "x-go-package": "github.com/inexio/thola/core/device" @@ -1377,8 +2087,7 @@ }, "OutputMessage": { "type": "object", - "description": "OutputMessage represents a message of the response. It contains a message and a status code.", - "title": "OutputMessage", + "title": "OutputMessage represents a message of the response. It contains a message and a status code.", "properties": { "message": { "type": "string", @@ -1432,36 +2141,36 @@ "x-go-package": "github.com/inexio/go-monitoringplugin" }, "Properties": { - "description": "Properties are properties that can be determined for a device", + "description": "Properties are properties that can be determined for a device.", "type": "object", "title": "Properties", "properties": { "model": { - "description": "Model of the device", + "description": "Model of the device.", "type": "string", "x-go-name": "Model", "example": "CHR" }, "model_series": { - "description": "ModelSeries of the device", + "description": "ModelSeries of the device.", "type": "string", "x-go-name": "ModelSeries", "example": "null" }, "os_version": { - "description": "OSVersion of the device", + "description": "OSVersion of the device.", "type": "string", "x-go-name": "OSVersion", "example": "6.44.6" }, "serial_number": { - "description": "SerialNumber of the device", + "description": "SerialNumber of the device.", "type": "string", "x-go-name": "SerialNumber", "example": "null" }, "vendor": { - "description": "Vendor of the device", + "description": "Vendor of the device.", "type": "string", "x-go-name": "Vendor", "example": "Mikrotik" @@ -1469,6 +2178,34 @@ }, "x-go-package": "github.com/inexio/thola/core/device" }, + "RadioInterface": { + "description": "RadioInterface represents a radio interface.", + "type": "object", + "title": "RadioInterface", + "properties": { + "level_in": { + "type": "integer", + "format": "int64", + "x-go-name": "LevelIn" + }, + "level_out": { + "type": "integer", + "format": "int64", + "x-go-name": "LevelOut" + }, + "maxbitrate_in": { + "type": "integer", + "format": "uint64", + "x-go-name": "MaxbitrateIn" + }, + "maxbitrate_out": { + "type": "integer", + "format": "uint64", + "x-go-name": "MaxbitrateOut" + } + }, + "x-go-package": "github.com/inexio/thola/core/device" + }, "ReadAvailableComponentsRequest": { "description": "ReadAvailableComponentsRequest is a the request struct for the read available-components request.", "type": "object", @@ -1564,6 +2301,78 @@ }, "x-go-package": "github.com/inexio/thola/core/request" }, + "ReadDiskRequest": { + "description": "ReadDiskRequest is a the request struct for the read disk request.", + "type": "object", + "title": "ReadDiskRequest", + "properties": { + "device_data": { + "$ref": "#/definitions/DeviceData" + }, + "timeout": { + "description": "Timeout for the request (0 =\u003e no timeout)", + "type": "integer", + "format": "int64", + "x-go-name": "Timeout" + } + }, + "x-go-package": "github.com/inexio/thola/core/request" + }, + "ReadDiskResponse": { + "description": "ReadDiskResponse is a the response struct for the read disk response.", + "type": "object", + "title": "ReadDiskResponse", + "properties": { + "disk": { + "$ref": "#/definitions/DiskComponent" + } + }, + "x-go-package": "github.com/inexio/thola/core/request" + }, + "ReadHardwareHealthRequest": { + "description": "ReadHardwareHealthRequest is a the request struct for the read hardware health request.", + "type": "object", + "title": "ReadHardwareHealthRequest", + "properties": { + "device_data": { + "$ref": "#/definitions/DeviceData" + }, + "timeout": { + "description": "Timeout for the request (0 =\u003e no timeout)", + "type": "integer", + "format": "int64", + "x-go-name": "Timeout" + } + }, + "x-go-package": "github.com/inexio/thola/core/request" + }, + "ReadHardwareHealthResponse": { + "description": "ReadHardwareHealthResponse is a the response struct for the read hardware health request.", + "type": "object", + "title": "ReadHardwareHealthResponse", + "properties": { + "environment_monitor_state": { + "type": "integer", + "format": "int64", + "x-go-name": "EnvironmentMonitorState" + }, + "fans": { + "type": "array", + "items": { + "$ref": "#/definitions/HardwareHealthComponentFan" + }, + "x-go-name": "Fans" + }, + "power_supply": { + "type": "array", + "items": { + "$ref": "#/definitions/HardwareHealthComponentPowerSupply" + }, + "x-go-name": "PowerSupply" + } + }, + "x-go-package": "github.com/inexio/thola/core/request" + }, "ReadInterfacesRequest": { "description": "ReadInterfacesRequest is a the request struct for the read interfaces request.", "type": "object", @@ -1614,7 +2423,7 @@ "x-go-package": "github.com/inexio/thola/core/request" }, "ReadMemoryUsageResponse": { - "description": "ReadMemoryUsageResponse is a the response struct for the read memory usage response.", + "description": "ReadMemoryUsageResponse is a the response struct for the read memory usage request.", "type": "object", "title": "ReadMemoryUsageResponse", "properties": { @@ -1649,6 +2458,62 @@ "title": "ReadResponse", "x-go-package": "github.com/inexio/thola/core/request" }, + "ReadSBCRequest": { + "description": "ReadSBCRequest is a the request struct for the read sbc request.", + "type": "object", + "title": "ReadSBCRequest", + "properties": { + "device_data": { + "$ref": "#/definitions/DeviceData" + }, + "timeout": { + "description": "Timeout for the request (0 =\u003e no timeout)", + "type": "integer", + "format": "int64", + "x-go-name": "Timeout" + } + }, + "x-go-package": "github.com/inexio/thola/core/request" + }, + "ReadSBCResponse": { + "description": "ReadSBCResponse is a the response struct for the read sbc response.", + "type": "object", + "title": "ReadSBCResponse", + "properties": { + "sbc": { + "$ref": "#/definitions/SBCComponent" + } + }, + "x-go-package": "github.com/inexio/thola/core/request" + }, + "ReadServerRequest": { + "description": "ReadServerRequest is a the request struct for the read server request.", + "type": "object", + "title": "ReadServerRequest", + "properties": { + "device_data": { + "$ref": "#/definitions/DeviceData" + }, + "timeout": { + "description": "Timeout for the request (0 =\u003e no timeout)", + "type": "integer", + "format": "int64", + "x-go-name": "Timeout" + } + }, + "x-go-package": "github.com/inexio/thola/core/request" + }, + "ReadServerResponse": { + "description": "ReadServerResponse is a the response struct for the read server response.", + "type": "object", + "title": "ReadServerResponse", + "properties": { + "server": { + "$ref": "#/definitions/ServerComponent" + } + }, + "x-go-package": "github.com/inexio/thola/core/request" + }, "ReadUPSRequest": { "description": "ReadUPSRequest is a the request struct for the read ups request.", "type": "object", @@ -1677,6 +2542,182 @@ }, "x-go-package": "github.com/inexio/thola/core/request" }, + "ResponseInfo": { + "type": "object", + "title": "ResponseInfo has all available information for a response. It also contains the RawOutput.", + "properties": { + "messages": { + "type": "array", + "items": { + "$ref": "#/definitions/OutputMessage" + }, + "x-go-name": "Messages" + }, + "performance_data": { + "type": "array", + "items": { + "$ref": "#/definitions/PerformanceDataPointInfo" + }, + "x-go-name": "PerformanceData" + }, + "raw_output": { + "type": "string", + "x-go-name": "RawOutput" + }, + "status_code": { + "type": "integer", + "format": "int64", + "x-go-name": "StatusCode" + } + }, + "x-go-package": "github.com/inexio/go-monitoringplugin" + }, + "SBCComponent": { + "description": "SBCComponent represents a SBC component.", + "type": "object", + "title": "SBCComponent", + "properties": { + "active_local_contacts": { + "type": "integer", + "format": "int64", + "x-go-name": "ActiveLocalContacts" + }, + "agents": { + "type": "array", + "items": { + "$ref": "#/definitions/SBCComponentAgent" + }, + "x-go-name": "Agents" + }, + "global_call_per_second": { + "type": "integer", + "format": "int64", + "x-go-name": "GlobalCallPerSecond" + }, + "global_concurrent_sessions ": { + "type": "integer", + "format": "int64", + "x-go-name": "GlobalConcurrentSessions" + }, + "license_capacity": { + "type": "integer", + "format": "int64", + "x-go-name": "LicenseCapacity" + }, + "realms": { + "type": "array", + "items": { + "$ref": "#/definitions/SBCComponentRealm" + }, + "x-go-name": "Realms" + }, + "system_health_score": { + "type": "integer", + "format": "int64", + "x-go-name": "SystemHealthScore" + }, + "system_redundancy": { + "type": "integer", + "format": "int64", + "x-go-name": "SystemRedundancy" + }, + "transcoding_capacity": { + "type": "integer", + "format": "int64", + "x-go-name": "TranscodingCapacity" + } + }, + "x-go-package": "github.com/inexio/thola/core/device" + }, + "SBCComponentAgent": { + "description": "SBCComponentAgent contains information per agent. (Voice)", + "type": "object", + "title": "SBCComponentAgent", + "properties": { + "current_active_sessions_inbound": { + "type": "integer", + "format": "int64", + "x-go-name": "CurrentActiveSessionsInbound" + }, + "current_active_sessions_outbound": { + "type": "integer", + "format": "int64", + "x-go-name": "CurrentActiveSessionsOutbound" + }, + "current_session_rate_inbound": { + "type": "integer", + "format": "int64", + "x-go-name": "CurrentSessionRateInbound" + }, + "current_session_rate_outbound": { + "type": "integer", + "format": "int64", + "x-go-name": "CurrentSessionRateOutbound" + }, + "hostname": { + "type": "string", + "x-go-name": "Hostname" + }, + "period_asr": { + "type": "integer", + "format": "int64", + "x-go-name": "PeriodASR" + }, + "status": { + "type": "integer", + "format": "int64", + "x-go-name": "Status" + } + }, + "x-go-package": "github.com/inexio/thola/core/device" + }, + "SBCComponentRealm": { + "description": "SBCComponentRealm contains information per realm. (Voice)", + "type": "object", + "title": "SBCComponentRealm", + "properties": { + "active_local_contacts": { + "type": "integer", + "format": "int64", + "x-go-name": "ActiveLocalContacts" + }, + "current_active_sessions_inbound": { + "type": "integer", + "format": "int64", + "x-go-name": "CurrentActiveSessionsInbound" + }, + "current_active_sessions_outbound": { + "type": "integer", + "format": "int64", + "x-go-name": "CurrentActiveSessionsOutbound" + }, + "current_session_rate_inbound": { + "type": "integer", + "format": "int64", + "x-go-name": "CurrentSessionRateInbound" + }, + "current_session_rate_outbound": { + "type": "integer", + "format": "int64", + "x-go-name": "CurrentSessionRateOutbound" + }, + "name": { + "type": "string", + "x-go-name": "Name" + }, + "period_asr": { + "type": "integer", + "format": "int64", + "x-go-name": "PeriodASR" + }, + "status": { + "type": "integer", + "format": "int64", + "x-go-name": "Status" + } + }, + "x-go-package": "github.com/inexio/thola/core/device" + }, "SNMPConnectionData": { "description": "SNMPConnectionData includes all snmp connection data for a device", "type": "object", @@ -1734,14 +2775,33 @@ }, "x-go-package": "github.com/inexio/thola/core/network" }, + "ServerComponent": { + "description": "ServerComponent represents a server component.", + "type": "object", + "title": "ServerComponent", + "properties": { + "procs": { + "type": "integer", + "format": "int64", + "x-go-name": "Procs" + }, + "users": { + "type": "integer", + "format": "int64", + "x-go-name": "Users" + } + }, + "x-go-package": "github.com/inexio/thola/core/device" + }, "Status": { - "description": "Status represents an interface status", "type": "string", + "title": "Status represents an interface status.", "x-go-package": "github.com/inexio/thola/core/device" }, "UPSComponent": { - "description": "UPSComponent represents a UPS component", + "description": "UPSComponent represents a UPS component.", "type": "object", + "title": "UPSComponent", "properties": { "alarm_low_voltage_disconnect": { "type": "integer", @@ -1800,10 +2860,10 @@ }, "x-go-package": "github.com/inexio/thola/core/device" }, - "Value": { - "description": "Value represents a value that was read out from a device.", + "value": { + "description": "value represents a value that was read out from a device.", "type": "string", - "title": "Value", + "title": "value", "x-go-package": "github.com/inexio/thola/core/value" } }, @@ -1817,4 +2877,4 @@ "basicAuth": [] } ] -} \ No newline at end of file +} From 04865cec9af2959ded9917efd7ce64530d702c53 Mon Sep 17 00:00:00 2001 From: Toberd Date: Wed, 10 Mar 2021 11:41:09 +0100 Subject: [PATCH 02/12] Updated swagger documentation again --- api/request_handler.go | 18 ++++++------ core/network/connection_data.go | 20 +++++++------- doc/api_doc.json | 49 ++++++++++++++++----------------- 3 files changed, 43 insertions(+), 44 deletions(-) diff --git a/api/request_handler.go b/api/request_handler.go index 37d78b8..8a5cabe 100644 --- a/api/request_handler.go +++ b/api/request_handler.go @@ -251,7 +251,7 @@ func StartAPI() { // 200: // description: Returns the response. // schema: - // $ref: '#/definitions/CheckMemoryUsageResponse' + // $ref: '#/definitions/CheckResponse' // 400: // description: Returns an error with more details in the body. // schema: @@ -273,12 +273,12 @@ func StartAPI() { // description: Request to process. // required: true // schema: - // $ref: '#/definitions/CheckCpuLoadRequest' + // $ref: '#/definitions/CheckCPULoadRequest' // responses: // 200: // description: Returns the response. // schema: - // $ref: '#/definitions/CheckCpuLoadResponse' + // $ref: '#/definitions/CheckResponse' // 400: // description: Returns an error with more details in the body. // schema: @@ -305,7 +305,7 @@ func StartAPI() { // 200: // description: Returns the response. // schema: - // $ref: '#/definitions/CheckSBCResponse' + // $ref: '#/definitions/CheckResponse' // 400: // description: Returns an error with more details in the body. // schema: @@ -332,7 +332,7 @@ func StartAPI() { // 200: // description: Returns the response. // schema: - // $ref: '#/definitions/CheckServerResponse' + // $ref: '#/definitions/CheckResponse' // 400: // description: Returns an error with more details in the body. // schema: @@ -359,14 +359,14 @@ func StartAPI() { // 200: // description: Returns the response. // schema: - // $ref: '#/definitions/CheckDiskResponse' + // $ref: '#/definitions/CheckResponse' // 400: // description: Returns an error with more details in the body. // schema: // $ref: '#/definitions/OutputError' e.POST("/check/disk", checkDisk) - // swagger:operation POST /check/hardware-health check checkSBC + // swagger:operation POST /check/hardware-health check checkHardwareHealth // --- // summary: Check an hardware health of an device. // consumes: @@ -386,7 +386,7 @@ func StartAPI() { // 200: // description: Returns the response. // schema: - // $ref: '#/definitions/CheckHardwareHealthResponse' + // $ref: '#/definitions/CheckResponse' // 400: // description: Returns an error with more details in the body. // schema: @@ -609,7 +609,7 @@ func StartAPI() { // $ref: '#/definitions/OutputError' e.POST("/read/disk", readDisk) - // swagger:operation POST /read/hardware-health read hardware health + // swagger:operation POST /read/hardware-health read hardware-health // --- // summary: Reads out hardware health data of a device. // consumes: diff --git a/core/network/connection_data.go b/core/network/connection_data.go index c6129bc..311165f 100644 --- a/core/network/connection_data.go +++ b/core/network/connection_data.go @@ -18,27 +18,27 @@ type ConnectionData struct { // // swagger:model type SNMPConnectionData struct { - // The snmp community string(s) for the device + // The snmp community string(s) for the device. // // example: public Communities []string `json:"communities" xml:"communities" yaml:"communities"` - // The snmp version(s) of the device + // The snmp version(s) of the device. // // example: 2c Versions []string `json:"versions" xml:"versions" yaml:"versions"` - // The snmp port(s) of the device + // The snmp port(s) of the device. // // example: 161 Ports []int `json:"ports" xml:"ports" yaml:"ports"` - // The amount of parallel connection requests used while trying to get a valid SNMP connection + // The amount of parallel connection requests used while trying to get a valid SNMP connection. // // example: 5 DiscoverParallelRequests *int `json:"discoverParallelRequests" xml:"discoverParallelRequests" yaml:"discoverParallelRequests"` - // The timeout in seconds used while trying to get a valid SNMP connection + // The timeout in seconds used while trying to get a valid SNMP connection. // // example: 2 DiscoverTimeout *int `json:"discoverTimeout" xml:"discoverTimeout" yaml:"discoverTimeout"` - // The retries used while trying to get a valid SNMP connection + // The retries used while trying to get a valid SNMP connection. // // example: 0 DiscoverRetries *int `json:"discoverRetries" xml:"discoverRetries" yaml:"discoverRetries"` @@ -57,19 +57,19 @@ type SNMPCredentials struct { // // swagger:model type HTTPConnectionData struct { - // The http port(s) of the device + // The http port(s) of the device. // // example: 80 HTTPPorts []int `json:"http_ports" xml:"http_ports" yaml:"http_ports"` - // The https port(s) of the device + // The https port(s) of the device. // // example: 443 HTTPSPorts []int `json:"https_ports" xml:"https_ports" yaml:"https_ports"` - // The username for authorization on the device + // The username for authorization on the device. // // example: username AuthUsername *string `json:"auth_username" xml:"auth_username" yaml:"auth_username"` - // The password for authorization on the device + // The password for authorization on the device. // // example: password AuthPassword *string `json:"auth_password" xml:"auth_password" yaml:"auth_password"` diff --git a/doc/api_doc.json b/doc/api_doc.json index e42f614..36e602f 100644 --- a/doc/api_doc.json +++ b/doc/api_doc.json @@ -45,7 +45,7 @@ "in": "body", "required": true, "schema": { - "$ref": "#/definitions/CheckCpuLoadRequest" + "$ref": "#/definitions/CheckCPULoadRequest" } } ], @@ -53,7 +53,7 @@ "200": { "description": "Returns the response.", "schema": { - "$ref": "#/definitions/CheckCpuLoadResponse" + "$ref": "#/definitions/CheckResponse" } }, "400": { @@ -95,7 +95,7 @@ "200": { "description": "Returns the response.", "schema": { - "$ref": "#/definitions/CheckDiskResponse" + "$ref": "#/definitions/CheckResponse" } }, "400": { @@ -121,7 +121,7 @@ "check" ], "summary": "Check an hardware health of an device.", - "operationId": "checkSBC", + "operationId": "checkHardwareHealth", "parameters": [ { "description": "Request to process.", @@ -137,7 +137,7 @@ "200": { "description": "Returns the response.", "schema": { - "$ref": "#/definitions/CheckHardwareHealthResponse" + "$ref": "#/definitions/CheckResponse" } }, "400": { @@ -263,7 +263,7 @@ "200": { "description": "Returns the response.", "schema": { - "$ref": "#/definitions/CheckMemoryUsageResponse" + "$ref": "#/definitions/CheckResponse" } }, "400": { @@ -305,7 +305,7 @@ "200": { "description": "Returns the response.", "schema": { - "$ref": "#/definitions/CheckSBCResponse" + "$ref": "#/definitions/CheckResponse" } }, "400": { @@ -347,7 +347,7 @@ "200": { "description": "Returns the response.", "schema": { - "$ref": "#/definitions/CheckServerResponse" + "$ref": "#/definitions/CheckResponse" } }, "400": { @@ -706,11 +706,10 @@ "application/xml" ], "tags": [ - "read", - "hardware" + "read" ], "summary": "Reads out hardware health data of a device.", - "operationId": "health", + "operationId": "hardware-health", "parameters": [ { "description": "Request to process.", @@ -1441,7 +1440,7 @@ "x-go-package": "github.com/inexio/thola/core/request" }, "ConnectionData": { - "description": "ConnectionData includes all connection data for a device", + "description": "ConnectionData includes all connection data for a device.", "type": "object", "title": "ConnectionData", "properties": { @@ -1626,24 +1625,24 @@ "x-go-package": "github.com/inexio/thola/core/device" }, "HTTPConnectionData": { - "description": "HTTPConnectionData includes all http connection data for a device", + "description": "HTTPConnectionData includes all http connection data for a device.", "type": "object", "title": "HTTPConnectionData", "properties": { "auth_password": { - "description": "The password for authorization on the device", + "description": "The password for authorization on the device.", "type": "string", "x-go-name": "AuthPassword", "example": "password" }, "auth_username": { - "description": "The username for authorization on the device", + "description": "The username for authorization on the device.", "type": "string", "x-go-name": "AuthUsername", "example": "username" }, "http_ports": { - "description": "The http port(s) of the device", + "description": "The http port(s) of the device.", "type": "array", "items": { "type": "integer", @@ -1653,7 +1652,7 @@ "example": "80" }, "https_ports": { - "description": "The https port(s) of the device", + "description": "The https port(s) of the device.", "type": "array", "items": { "type": "integer", @@ -2719,12 +2718,12 @@ "x-go-package": "github.com/inexio/thola/core/device" }, "SNMPConnectionData": { - "description": "SNMPConnectionData includes all snmp connection data for a device", + "description": "SNMPConnectionData includes all snmp connection data for a device.", "type": "object", "title": "SNMPConnectionData", "properties": { "communities": { - "description": "The snmp community string(s) for the device", + "description": "The snmp community string(s) for the device.", "type": "array", "items": { "type": "string" @@ -2733,28 +2732,28 @@ "example": "public" }, "discoverParallelRequests": { - "description": "The amount of parallel connection requests used while trying to get a valid SNMP connection", + "description": "The amount of parallel connection requests used while trying to get a valid SNMP connection.", "type": "integer", "format": "int64", "x-go-name": "DiscoverParallelRequests", "example": 5 }, "discoverRetries": { - "description": "The retries used while trying to get a valid SNMP connection", + "description": "The retries used while trying to get a valid SNMP connection.", "type": "integer", "format": "int64", "x-go-name": "DiscoverRetries", "example": 0 }, "discoverTimeout": { - "description": "The timeout in seconds used while trying to get a valid SNMP connection", + "description": "The timeout in seconds used while trying to get a valid SNMP connection.", "type": "integer", "format": "int64", "x-go-name": "DiscoverTimeout", "example": 2 }, "ports": { - "description": "The snmp port(s) of the device", + "description": "The snmp port(s) of the device.", "type": "array", "items": { "type": "integer", @@ -2764,7 +2763,7 @@ "example": "161" }, "versions": { - "description": "The snmp version(s) of the device", + "description": "The snmp version(s) of the device.", "type": "array", "items": { "type": "string" @@ -2877,4 +2876,4 @@ "basicAuth": [] } ] -} +} \ No newline at end of file From c81ef63a388e13194dafa66d91287400fb7e7cfc Mon Sep 17 00:00:00 2001 From: mikameyer Date: Wed, 10 Mar 2021 12:19:43 +0100 Subject: [PATCH 03/12] changed ekinops metrics --- .../check_interface_metrics_request_process.go | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/core/request/check_interface_metrics_request_process.go b/core/request/check_interface_metrics_request_process.go index 98f645a..fd5e3d7 100644 --- a/core/request/check_interface_metrics_request_process.go +++ b/core/request/check_interface_metrics_request_process.go @@ -540,12 +540,12 @@ func addCheckInterfacePerformanceData(interfaces []device.Interface, r *monitori if err != nil { return err } - for _, channel := range i.OpticalOPM.Channels { - if channel.RXPower != nil { - err := r.AddPerformanceDataPoint(monitoringplugin.NewPerformanceDataPoint("rx_power", *channel.RXPower, "").SetLabel(*i.IfDescr + "_" + channel.Channel)) - if err != nil { - return err - } + } + for _, channel := range i.OpticalOPM.Channels { + if channel.RXPower != nil { + err := r.AddPerformanceDataPoint(monitoringplugin.NewPerformanceDataPoint("rx_power", *channel.RXPower, "").SetLabel(*i.IfDescr + "_" + channel.Channel)) + if err != nil { + return err } } } From 1bad9107a2fd1935e34caaf9fbac8af905f6d77d Mon Sep 17 00:00:00 2001 From: Toberd Date: Fri, 12 Mar 2021 12:59:03 +0100 Subject: [PATCH 04/12] Adjusted human_readable_parser.go --- core/parser/human_readable_parser.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/core/parser/human_readable_parser.go b/core/parser/human_readable_parser.go index e0970a0..fbbfe47 100644 --- a/core/parser/human_readable_parser.go +++ b/core/parser/human_readable_parser.go @@ -12,7 +12,7 @@ func toHumanReadable(value reflect.Value, insertion int) string { switch kind { case reflect.Struct: - output := "\n" + var output string for i := 0; i < value.NumField(); i++ { fieldValue := toHumanReadable(value.Field(i), insertion+1) if strings.TrimSpace(fieldValue) == "" { @@ -23,7 +23,7 @@ func toHumanReadable(value reflect.Value, insertion int) string { output += fieldValue output += "\n" } - return output + return "\n" + strings.Repeat(" ", insertion) + strings.TrimSpace(output) + "\n" case reflect.Slice: if value.IsNil() { return "" From dd42e15d078807416a7e0d043a83d586781cf2f1 Mon Sep 17 00:00:00 2001 From: mikameyer Date: Fri, 12 Mar 2021 15:50:03 +0100 Subject: [PATCH 05/12] added warning/critical values in performance data --- cmd/check.go | 23 ++- cmd/check_cpu_load.go | 2 +- cmd/check_disk.go | 2 +- cmd/check_memory_usage.go | 2 +- cmd/check_sbc.go | 2 +- cmd/check_ups.go | 10 +- .../network_device_communicator.go | 2 +- core/request/check_cpu_load.go | 9 +- core/request/check_cpu_load_process.go | 24 +-- core/request/check_disk_request.go | 9 +- core/request/check_disk_request_process.go | 14 +- core/request/check_hardware_health_process.go | 10 +- ...check_interface_metrics_request_process.go | 106 +++++----- core/request/check_memory_usage.go | 9 +- core/request/check_memory_usage_process.go | 12 +- core/request/check_sbc_request.go | 9 +- core/request/check_sbc_request_process.go | 51 +++-- core/request/check_server_request.go | 9 +- core/request/check_server_request_process.go | 4 +- .../check_thola_server_request_process.go | 8 +- core/request/check_ups.go | 25 +-- core/request/check_ups_process.go | 183 +++++++----------- .../read_hardware_health_request_process.go | 2 +- go.mod | 2 +- go.sum | 4 +- test/integration_test.go | 6 +- .../devices/ios/7206VXR/test_data.json | 2 +- 27 files changed, 261 insertions(+), 280 deletions(-) diff --git a/cmd/check.go b/cmd/check.go index 0d95fcd..8637090 100644 --- a/cmd/check.go +++ b/cmd/check.go @@ -2,6 +2,7 @@ package cmd import ( "fmt" + "github.com/inexio/go-monitoringplugin" "github.com/inexio/thola/core/request" "github.com/rs/zerolog" "github.com/rs/zerolog/log" @@ -64,35 +65,45 @@ func getCheckRequest() request.CheckRequest { } } -func generateCheckThresholds(cmd *cobra.Command, warningMin, warningMax, criticalMin, criticalMax string) request.CheckThresholds { - var thresholds request.CheckThresholds +func generateCheckThresholds(cmd *cobra.Command, warningMin, warningMax, criticalMin, criticalMax string, setMinToZeroIfEmpty bool) monitoringplugin.Thresholds { + var thresholds monitoringplugin.Thresholds if flagName := warningMin; flagName != "" && cmd.Flags().Changed(flagName) { v, err := cmd.Flags().GetFloat64(flagName) if err != nil { log.Fatal().Err(err).Msgf("flag '%s' is not a float64", flagName) } - thresholds.WarningMin = &v + thresholds.WarningMin = v } if flagName := warningMax; flagName != "" && cmd.Flags().Changed(flagName) { v, err := cmd.Flags().GetFloat64(flagName) if err != nil { log.Fatal().Err(err).Msgf("flag '%s' is not a float64", flagName) } - thresholds.WarningMax = &v + thresholds.WarningMax = v } if flagName := criticalMin; flagName != "" && cmd.Flags().Changed(flagName) { v, err := cmd.Flags().GetFloat64(flagName) if err != nil { log.Fatal().Err(err).Msgf("flag '%s' is not a float64", flagName) } - thresholds.CriticalMin = &v + thresholds.CriticalMin = v } if flagName := criticalMax; flagName != "" && cmd.Flags().Changed(flagName) { v, err := cmd.Flags().GetFloat64(flagName) if err != nil { log.Fatal().Err(err).Msgf("flag '%s' is not a float64", flagName) } - thresholds.CriticalMax = &v + thresholds.CriticalMax = v } + + if setMinToZeroIfEmpty { + if thresholds.HasWarning() && thresholds.WarningMin == nil { + thresholds.WarningMin = 0 + } + if thresholds.HasCritical() && thresholds.CriticalMin == nil { + thresholds.CriticalMin = 0 + } + } + return thresholds } diff --git a/cmd/check_cpu_load.go b/cmd/check_cpu_load.go index 97d69e7..56cd507 100644 --- a/cmd/check_cpu_load.go +++ b/cmd/check_cpu_load.go @@ -21,7 +21,7 @@ var checkCpuLoad = &cobra.Command{ Run: func(cmd *cobra.Command, args []string) { r := request.CheckCPULoadRequest{ CheckDeviceRequest: getCheckDeviceRequest(args[0]), - CPULoadThresholds: generateCheckThresholds(cmd, "", "warning", "", "critical"), + CPULoadThresholds: generateCheckThresholds(cmd, "", "warning", "", "critical", true), } handleRequest(&r) }, diff --git a/cmd/check_disk.go b/cmd/check_disk.go index a4ed148..d195405 100644 --- a/cmd/check_disk.go +++ b/cmd/check_disk.go @@ -21,7 +21,7 @@ var checkDiskCMD = &cobra.Command{ Run: func(cmd *cobra.Command, args []string) { r := request.CheckDiskRequest{ CheckDeviceRequest: getCheckDeviceRequest(args[0]), - DiskThresholds: generateCheckThresholds(cmd, "warning", "", "critical", ""), + DiskThresholds: generateCheckThresholds(cmd, "warning", "", "critical", "", false), } handleRequest(&r) }, diff --git a/cmd/check_memory_usage.go b/cmd/check_memory_usage.go index a69265e..0fe5436 100644 --- a/cmd/check_memory_usage.go +++ b/cmd/check_memory_usage.go @@ -21,7 +21,7 @@ var checkMemoryUsage = &cobra.Command{ Run: func(cmd *cobra.Command, args []string) { r := request.CheckMemoryUsageRequest{ CheckDeviceRequest: getCheckDeviceRequest(args[0]), - MemoryUsageThresholds: generateCheckThresholds(cmd, "", "warning", "", "critical"), + MemoryUsageThresholds: generateCheckThresholds(cmd, "", "warning", "", "critical", true), } handleRequest(&r) }, diff --git a/cmd/check_sbc.go b/cmd/check_sbc.go index ec7f35d..c638eae 100644 --- a/cmd/check_sbc.go +++ b/cmd/check_sbc.go @@ -20,7 +20,7 @@ var checkSBCCMD = &cobra.Command{ Run: func(cmd *cobra.Command, args []string) { r := request.CheckSBCRequest{ CheckDeviceRequest: getCheckDeviceRequest(args[0]), - SystemHealthScoreThresholds: generateCheckThresholds(cmd, "system-health-score-warning", "", "system-health-score-critical", ""), + SystemHealthScoreThresholds: generateCheckThresholds(cmd, "system-health-score-warning", "", "system-health-score-critical", "", false), } handleRequest(&r) }, diff --git a/cmd/check_ups.go b/cmd/check_ups.go index 273f1fe..20b2972 100644 --- a/cmd/check_ups.go +++ b/cmd/check_ups.go @@ -43,11 +43,11 @@ var checkUPSCMD = &cobra.Command{ Run: func(cmd *cobra.Command, args []string) { r := request.CheckUPSRequest{ CheckDeviceRequest: getCheckDeviceRequest(args[0]), - BatteryCurrentThresholds: generateCheckThresholds(cmd, "batt-current-warning-min", "batt-current-warning-max", "batt-current-critical-min", "batt-current-critical-max"), - BatteryTemperatureThresholds: generateCheckThresholds(cmd, "batt-temperature-warning-min", "batt-temperature-warning-max", "batt-temperature-critical-min", "batt-temperature-critical-max"), - CurrentLoadThresholds: generateCheckThresholds(cmd, "current-load-warning-min", "current-load-warning-max", "current-load-warning-max", "current-load-warning-max"), - RectifierCurrentThresholds: generateCheckThresholds(cmd, "rectifier-current-warning-min", "rectifier-current-warning-max", "rectifier-current-critical-min", "rectifier-current-critical-max"), - SystemVoltageThresholds: generateCheckThresholds(cmd, "system-voltage-warning-min", "system-voltage-warning-max", "system-voltage-critical-min", "system-voltage-critical-max"), + BatteryCurrentThresholds: generateCheckThresholds(cmd, "batt-current-warning-min", "batt-current-warning-max", "batt-current-critical-min", "batt-current-critical-max", false), + BatteryTemperatureThresholds: generateCheckThresholds(cmd, "batt-temperature-warning-min", "batt-temperature-warning-max", "batt-temperature-critical-min", "batt-temperature-critical-max", false), + CurrentLoadThresholds: generateCheckThresholds(cmd, "current-load-warning-min", "current-load-warning-max", "current-load-warning-max", "current-load-warning-max", false), + RectifierCurrentThresholds: generateCheckThresholds(cmd, "rectifier-current-warning-min", "rectifier-current-warning-max", "rectifier-current-critical-min", "rectifier-current-critical-max", false), + SystemVoltageThresholds: generateCheckThresholds(cmd, "system-voltage-warning-min", "system-voltage-warning-max", "system-voltage-critical-min", "system-voltage-critical-max", false), } handleRequest(&r) }, diff --git a/core/communicator/network_device_communicator.go b/core/communicator/network_device_communicator.go index 0ec246e..e5934cc 100644 --- a/core/communicator/network_device_communicator.go +++ b/core/communicator/network_device_communicator.go @@ -542,7 +542,7 @@ func (c *networkDeviceCommunicator) GetDiskComponent(ctx context.Context) (devic func (c *networkDeviceCommunicator) GetHardwareHealthComponent(ctx context.Context) (device.HardwareHealthComponent, error) { if !c.deviceClassCommunicator.hasAvailableComponent(hardwareHealthComponent) { - return device.HardwareHealthComponent{}, tholaerr.NewComponentNotFoundError("no sbc component available for this device") + return device.HardwareHealthComponent{}, tholaerr.NewComponentNotFoundError("no hardware health component available for this device") } var hardwareHealth device.HardwareHealthComponent diff --git a/core/request/check_cpu_load.go b/core/request/check_cpu_load.go index b84b44b..9644bce 100644 --- a/core/request/check_cpu_load.go +++ b/core/request/check_cpu_load.go @@ -1,6 +1,9 @@ package request -import "context" +import ( + "context" + "github.com/inexio/go-monitoringplugin" +) // CheckCPULoadRequest // @@ -9,11 +12,11 @@ import "context" // swagger:model type CheckCPULoadRequest struct { CheckDeviceRequest - CPULoadThresholds CheckThresholds `json:"cpuLoadThresholds" xml:"cpuLoadThresholds"` + CPULoadThresholds monitoringplugin.Thresholds `json:"cpuLoadThresholds" xml:"cpuLoadThresholds"` } func (r *CheckCPULoadRequest) validate(ctx context.Context) error { - if err := r.CPULoadThresholds.validate(); err != nil { + if err := r.CPULoadThresholds.Validate(); err != nil { return err } return r.CheckDeviceRequest.validate(ctx) diff --git a/core/request/check_cpu_load_process.go b/core/request/check_cpu_load_process.go index b380812..f4dbbe8 100644 --- a/core/request/check_cpu_load_process.go +++ b/core/request/check_cpu_load_process.go @@ -6,7 +6,6 @@ import ( "context" "fmt" "github.com/inexio/go-monitoringplugin" - "github.com/inexio/thola/core/value" "strconv" ) @@ -23,30 +22,27 @@ func (r *CheckCPULoadRequest) process(ctx context.Context) (Response, error) { for k, cpuLoad := range response.(*ReadCPULoadResponse).CPULoad { cpuSum += cpuLoad - val := value.New(cpuLoad) performanceDataLabel := "cpu_load" if cpuAmount > 1 { performanceDataLabel += "_" + strconv.Itoa(k) } - err = r.mon.AddPerformanceDataPoint(monitoringplugin.NewPerformanceDataPoint(performanceDataLabel, val.String(), "%")) + point := monitoringplugin.NewPerformanceDataPoint(performanceDataLabel, cpuLoad).SetUnit("%") + if cpuAmount == 1 { + point.SetThresholds(r.CPULoadThresholds) + } + err = r.mon.AddPerformanceDataPoint(point) if r.mon.UpdateStatusOnError(err, monitoringplugin.UNKNOWN, "error while adding performance data point", true) { return &CheckResponse{r.mon.GetInfo()}, nil } } - val := value.New(cpuSum / float64(cpuAmount)) - if !r.CPULoadThresholds.isEmpty() { - code := r.CPULoadThresholds.checkValue(val) - r.mon.UpdateStatusIf(code != monitoringplugin.OK, code, fmt.Sprintf("average cpu load is %s%%", val)) - } - if cpuAmount > 1 { - fl, err := val.Float64() - if r.mon.UpdateStatusOnError(err, monitoringplugin.UNKNOWN, "can't parse value to error", true) { - return &CheckResponse{r.mon.GetInfo()}, nil - } - err = r.mon.AddPerformanceDataPoint(monitoringplugin.NewPerformanceDataPoint("cpu_load_average", fmt.Sprintf("%.3f", fl), "%")) + val := cpuSum / float64(cpuAmount) + err = r.mon.AddPerformanceDataPoint( + monitoringplugin.NewPerformanceDataPoint("cpu_load_average", fmt.Sprintf("%.3f", val)). + SetUnit("%"). + SetThresholds(r.CPULoadThresholds)) if r.mon.UpdateStatusOnError(err, monitoringplugin.UNKNOWN, "error while adding performance data point", true) { return &CheckResponse{r.mon.GetInfo()}, nil } diff --git a/core/request/check_disk_request.go b/core/request/check_disk_request.go index 93ba9e5..520faa9 100644 --- a/core/request/check_disk_request.go +++ b/core/request/check_disk_request.go @@ -1,6 +1,9 @@ package request -import "context" +import ( + "context" + "github.com/inexio/go-monitoringplugin" +) // CheckDiskRequest // @@ -9,11 +12,11 @@ import "context" // swagger:model type CheckDiskRequest struct { CheckDeviceRequest - DiskThresholds CheckThresholds `json:"diskThresholds" xml:"diskThresholds"` + DiskThresholds monitoringplugin.Thresholds `json:"diskThresholds" xml:"diskThresholds"` } func (r *CheckDiskRequest) validate(ctx context.Context) error { - if err := r.DiskThresholds.validate(); err != nil { + if err := r.DiskThresholds.Validate(); err != nil { return err } return r.CheckDeviceRequest.validate(ctx) diff --git a/core/request/check_disk_request_process.go b/core/request/check_disk_request_process.go index a9ecb3e..d61664a 100644 --- a/core/request/check_disk_request_process.go +++ b/core/request/check_disk_request_process.go @@ -6,7 +6,6 @@ import ( "context" "fmt" "github.com/inexio/go-monitoringplugin" - "github.com/inexio/thola/core/value" ) func (r *CheckDiskRequest) process(ctx context.Context) (Response, error) { @@ -21,14 +20,14 @@ func (r *CheckDiskRequest) process(ctx context.Context) (Response, error) { for _, storage := range disk.Storages { if storage.Type != nil && storage.Description != nil && storage.Available != nil && storage.Used != nil { - p := monitoringplugin.NewPerformanceDataPoint("disk_available", *storage.Available, "KB").SetLabel(*storage.Description) + p := monitoringplugin.NewPerformanceDataPoint("disk_available", *storage.Available).SetUnit("KB").SetLabel(*storage.Description) err = r.mon.AddPerformanceDataPoint(p) if r.mon.UpdateStatusOnError(err, monitoringplugin.UNKNOWN, "error while adding performance data point", true) { r.mon.PrintPerformanceData(false) return &CheckResponse{r.mon.GetInfo()}, nil } - p = monitoringplugin.NewPerformanceDataPoint("disk_used", *storage.Used, "KB").SetLabel(*storage.Description) + p = monitoringplugin.NewPerformanceDataPoint("disk_used", *storage.Used).SetUnit("KB").SetLabel(*storage.Description) err = r.mon.AddPerformanceDataPoint(p) if r.mon.UpdateStatusOnError(err, monitoringplugin.UNKNOWN, "error while adding performance data point", true) { r.mon.PrintPerformanceData(false) @@ -37,17 +36,14 @@ func (r *CheckDiskRequest) process(ctx context.Context) (Response, error) { // get percentage of free part on the storage free := fmt.Sprintf("%.2f", 100-float64(*storage.Used)/float64(*storage.Available)*100) - p = monitoringplugin.NewPerformanceDataPoint("disk_free", free, "%").SetLabel(*storage.Description) + p = monitoringplugin.NewPerformanceDataPoint("disk_free", free).SetUnit("%"). + SetLabel(*storage.Description). + SetThresholds(r.DiskThresholds) err = r.mon.AddPerformanceDataPoint(p) if r.mon.UpdateStatusOnError(err, monitoringplugin.UNKNOWN, "error while adding performance data point", true) { r.mon.PrintPerformanceData(false) return &CheckResponse{r.mon.GetInfo()}, nil } - val := value.New(free) - if !r.DiskThresholds.isEmpty() { - code := r.DiskThresholds.checkValue(val) - r.mon.UpdateStatusIf(code != monitoringplugin.OK, code, fmt.Sprintf("disk usage at %s is %s%%", *storage.Description, val)) - } } } diff --git a/core/request/check_hardware_health_process.go b/core/request/check_hardware_health_process.go index 92bce2e..1e647fb 100644 --- a/core/request/check_hardware_health_process.go +++ b/core/request/check_hardware_health_process.go @@ -12,19 +12,19 @@ func (r *CheckHardwareHealthRequest) process(ctx context.Context) (Response, err hhRequest := ReadHardwareHealthRequest{ReadRequest{r.BaseRequest}} response, err := hhRequest.process(ctx) - if r.mon.UpdateStatusOnError(err, monitoringplugin.UNKNOWN, "error while processing read sbc request", true) { + if r.mon.UpdateStatusOnError(err, monitoringplugin.UNKNOWN, "error while processing read hardware health request", true) { return &CheckResponse{r.mon.GetInfo()}, nil } res := response.(*ReadHardwareHealthResponse) if res.EnvironmentMonitorState != nil { - err = r.mon.AddPerformanceDataPoint(monitoringplugin.NewPerformanceDataPoint("environment_monitor_state", *res.EnvironmentMonitorState, "")) + err = r.mon.AddPerformanceDataPoint(monitoringplugin.NewPerformanceDataPoint("environment_monitor_state", *res.EnvironmentMonitorState)) if r.mon.UpdateStatusOnError(err, monitoringplugin.UNKNOWN, "error while adding performance data point", true) { r.mon.PrintPerformanceData(false) return &CheckResponse{r.mon.GetInfo()}, nil } - // state 2 only works for oracle-acme sbs, this needs to be generalized once check hardware health is made for all device classes + // state 2 only works for oracle-acme sbcs, this needs to be generalized once check hardware health is made for all device classes r.mon.UpdateStatusIf(*res.EnvironmentMonitorState != 2, monitoringplugin.CRITICAL, "environment monitor state is critical") } @@ -33,7 +33,7 @@ func (r *CheckHardwareHealthRequest) process(ctx context.Context) (Response, err r.mon.PrintPerformanceData(false) return &CheckResponse{r.mon.GetInfo()}, nil } - p := monitoringplugin.NewPerformanceDataPoint("fan_state", *fan.State, "").SetLabel(*fan.Description) + p := monitoringplugin.NewPerformanceDataPoint("fan_state", *fan.State).SetLabel(*fan.Description) err = r.mon.AddPerformanceDataPoint(p) if r.mon.UpdateStatusOnError(err, monitoringplugin.UNKNOWN, "error while adding performance data point", true) { r.mon.PrintPerformanceData(false) @@ -46,7 +46,7 @@ func (r *CheckHardwareHealthRequest) process(ctx context.Context) (Response, err r.mon.PrintPerformanceData(false) return &CheckResponse{r.mon.GetInfo()}, nil } - p := monitoringplugin.NewPerformanceDataPoint("power_supply_state", *powerSupply.State, "").SetLabel(*powerSupply.Description) + p := monitoringplugin.NewPerformanceDataPoint("power_supply_state", *powerSupply.State).SetLabel(*powerSupply.Description) err = r.mon.AddPerformanceDataPoint(p) if r.mon.UpdateStatusOnError(err, monitoringplugin.UNKNOWN, "error while adding performance data point", true) { r.mon.PrintPerformanceData(false) diff --git a/core/request/check_interface_metrics_request_process.go b/core/request/check_interface_metrics_request_process.go index fd5e3d7..224b71a 100644 --- a/core/request/check_interface_metrics_request_process.go +++ b/core/request/check_interface_metrics_request_process.go @@ -163,7 +163,7 @@ func addCheckInterfacePerformanceData(interfaces []device.Interface, r *monitori for _, i := range interfaces { //error_counter_in if i.IfInErrors != nil { - err := r.AddPerformanceDataPoint(monitoringplugin.NewPerformanceDataPoint("error_counter_in", *i.IfInErrors, "c").SetLabel(*i.IfDescr)) + err := r.AddPerformanceDataPoint(monitoringplugin.NewPerformanceDataPoint("error_counter_in", *i.IfInErrors).SetUnit("c").SetLabel(*i.IfDescr)) if err != nil { return err } @@ -171,7 +171,7 @@ func addCheckInterfacePerformanceData(interfaces []device.Interface, r *monitori //error_counter_out if i.IfOutErrors != nil { - err := r.AddPerformanceDataPoint(monitoringplugin.NewPerformanceDataPoint("error_counter_out", *i.IfOutErrors, "c").SetLabel(*i.IfDescr)) + err := r.AddPerformanceDataPoint(monitoringplugin.NewPerformanceDataPoint("error_counter_out", *i.IfOutErrors).SetUnit("c").SetLabel(*i.IfDescr)) if err != nil { return err } @@ -179,7 +179,7 @@ func addCheckInterfacePerformanceData(interfaces []device.Interface, r *monitori //packet_counter_discard_in if i.IfInDiscards != nil { - err := r.AddPerformanceDataPoint(monitoringplugin.NewPerformanceDataPoint("packet_counter_discard_in", *i.IfInDiscards, "c").SetLabel(*i.IfDescr)) + err := r.AddPerformanceDataPoint(monitoringplugin.NewPerformanceDataPoint("packet_counter_discard_in", *i.IfInDiscards).SetUnit("c").SetLabel(*i.IfDescr)) if err != nil { return err } @@ -187,7 +187,7 @@ func addCheckInterfacePerformanceData(interfaces []device.Interface, r *monitori //packet_counter_discard_out if i.IfOutDiscards != nil { - err := r.AddPerformanceDataPoint(monitoringplugin.NewPerformanceDataPoint("packet_counter_discard_out", *i.IfOutDiscards, "c").SetLabel(*i.IfDescr)) + err := r.AddPerformanceDataPoint(monitoringplugin.NewPerformanceDataPoint("packet_counter_discard_out", *i.IfOutDiscards).SetUnit("c").SetLabel(*i.IfDescr)) if err != nil { return err } @@ -199,7 +199,7 @@ func addCheckInterfacePerformanceData(interfaces []device.Interface, r *monitori if err != nil { return errors.Wrap(err, "failed to convert admin status") } - err = r.AddPerformanceDataPoint(monitoringplugin.NewPerformanceDataPoint("interface_admin_status", value, "").SetLabel(*i.IfDescr)) + err = r.AddPerformanceDataPoint(monitoringplugin.NewPerformanceDataPoint("interface_admin_status", value).SetLabel(*i.IfDescr)) if err != nil { return err } @@ -211,7 +211,7 @@ func addCheckInterfacePerformanceData(interfaces []device.Interface, r *monitori if err != nil { return errors.Wrap(err, "failed to convert oper status") } - err = r.AddPerformanceDataPoint(monitoringplugin.NewPerformanceDataPoint("interface_oper_status", value, "").SetLabel(*i.IfDescr)) + err = r.AddPerformanceDataPoint(monitoringplugin.NewPerformanceDataPoint("interface_oper_status", value).SetLabel(*i.IfDescr)) if err != nil { return err } @@ -219,12 +219,12 @@ func addCheckInterfacePerformanceData(interfaces []device.Interface, r *monitori //traffic_counter_in if i.IfHCInOctets != nil { - err := r.AddPerformanceDataPoint(monitoringplugin.NewPerformanceDataPoint("traffic_counter_in", *i.IfHCInOctets, "B").SetLabel(*i.IfDescr)) + err := r.AddPerformanceDataPoint(monitoringplugin.NewPerformanceDataPoint("traffic_counter_in", *i.IfHCInOctets).SetUnit("B").SetLabel(*i.IfDescr)) if err != nil { return err } } else if i.IfInOctets != nil { - err := r.AddPerformanceDataPoint(monitoringplugin.NewPerformanceDataPoint("traffic_counter_in", *i.IfInOctets, "B").SetLabel(*i.IfDescr)) + err := r.AddPerformanceDataPoint(monitoringplugin.NewPerformanceDataPoint("traffic_counter_in", *i.IfInOctets).SetUnit("B").SetLabel(*i.IfDescr)) if err != nil { return err } @@ -232,12 +232,12 @@ func addCheckInterfacePerformanceData(interfaces []device.Interface, r *monitori //traffic_counter_out if i.IfHCOutOctets != nil { - err := r.AddPerformanceDataPoint(monitoringplugin.NewPerformanceDataPoint("traffic_counter_out", *i.IfHCOutOctets, "B").SetLabel(*i.IfDescr)) + err := r.AddPerformanceDataPoint(monitoringplugin.NewPerformanceDataPoint("traffic_counter_out", *i.IfHCOutOctets).SetUnit("B").SetLabel(*i.IfDescr)) if err != nil { return err } } else if i.IfOutOctets != nil { - err := r.AddPerformanceDataPoint(monitoringplugin.NewPerformanceDataPoint("traffic_counter_out", *i.IfOutOctets, "B").SetLabel(*i.IfDescr)) + err := r.AddPerformanceDataPoint(monitoringplugin.NewPerformanceDataPoint("traffic_counter_out", *i.IfOutOctets).SetUnit("B").SetLabel(*i.IfDescr)) if err != nil { return err } @@ -245,12 +245,12 @@ func addCheckInterfacePerformanceData(interfaces []device.Interface, r *monitori //packet_counter_unicast_in if i.IfHCInUcastPkts != nil { - err := r.AddPerformanceDataPoint(monitoringplugin.NewPerformanceDataPoint("packet_counter_unicast_in", *i.IfHCInUcastPkts, "c").SetLabel(*i.IfDescr)) + err := r.AddPerformanceDataPoint(monitoringplugin.NewPerformanceDataPoint("packet_counter_unicast_in", *i.IfHCInUcastPkts).SetUnit("c").SetLabel(*i.IfDescr)) if err != nil { return err } } else if i.IfInUcastPkts != nil { - err := r.AddPerformanceDataPoint(monitoringplugin.NewPerformanceDataPoint("packet_counter_unicast_in", *i.IfInUcastPkts, "c").SetLabel(*i.IfDescr)) + err := r.AddPerformanceDataPoint(monitoringplugin.NewPerformanceDataPoint("packet_counter_unicast_in", *i.IfInUcastPkts).SetUnit("c").SetLabel(*i.IfDescr)) if err != nil { return err } @@ -258,12 +258,12 @@ func addCheckInterfacePerformanceData(interfaces []device.Interface, r *monitori //packet_counter_unicast_out if i.IfHCOutUcastPkts != nil { - err := r.AddPerformanceDataPoint(monitoringplugin.NewPerformanceDataPoint("packet_counter_unicast_out", *i.IfHCOutUcastPkts, "c").SetLabel(*i.IfDescr)) + err := r.AddPerformanceDataPoint(monitoringplugin.NewPerformanceDataPoint("packet_counter_unicast_out", *i.IfHCOutUcastPkts).SetUnit("c").SetLabel(*i.IfDescr)) if err != nil { return err } } else if i.IfOutUcastPkts != nil { - err := r.AddPerformanceDataPoint(monitoringplugin.NewPerformanceDataPoint("packet_counter_unicast_out", *i.IfOutUcastPkts, "c").SetLabel(*i.IfDescr)) + err := r.AddPerformanceDataPoint(monitoringplugin.NewPerformanceDataPoint("packet_counter_unicast_out", *i.IfOutUcastPkts).SetUnit("c").SetLabel(*i.IfDescr)) if err != nil { return err } @@ -271,12 +271,12 @@ func addCheckInterfacePerformanceData(interfaces []device.Interface, r *monitori //packet_counter_multicast_in if i.IfHCInMulticastPkts != nil { - err := r.AddPerformanceDataPoint(monitoringplugin.NewPerformanceDataPoint("packet_counter_multicast_in", *i.IfHCInMulticastPkts, "c").SetLabel(*i.IfDescr)) + err := r.AddPerformanceDataPoint(monitoringplugin.NewPerformanceDataPoint("packet_counter_multicast_in", *i.IfHCInMulticastPkts).SetUnit("c").SetLabel(*i.IfDescr)) if err != nil { return err } } else if i.IfInMulticastPkts != nil { - err := r.AddPerformanceDataPoint(monitoringplugin.NewPerformanceDataPoint("packet_counter_multicast_in", *i.IfInMulticastPkts, "c").SetLabel(*i.IfDescr)) + err := r.AddPerformanceDataPoint(monitoringplugin.NewPerformanceDataPoint("packet_counter_multicast_in", *i.IfInMulticastPkts).SetUnit("c").SetLabel(*i.IfDescr)) if err != nil { return err } @@ -284,12 +284,12 @@ func addCheckInterfacePerformanceData(interfaces []device.Interface, r *monitori //packet_counter_multicast_out if i.IfHCOutMulticastPkts != nil { - err := r.AddPerformanceDataPoint(monitoringplugin.NewPerformanceDataPoint("packet_counter_multicast_out", *i.IfHCOutMulticastPkts, "c").SetLabel(*i.IfDescr)) + err := r.AddPerformanceDataPoint(monitoringplugin.NewPerformanceDataPoint("packet_counter_multicast_out", *i.IfHCOutMulticastPkts).SetUnit("c").SetLabel(*i.IfDescr)) if err != nil { return err } } else if i.IfOutMulticastPkts != nil { - err := r.AddPerformanceDataPoint(monitoringplugin.NewPerformanceDataPoint("packet_counter_multicast_out", *i.IfOutMulticastPkts, "c").SetLabel(*i.IfDescr)) + err := r.AddPerformanceDataPoint(monitoringplugin.NewPerformanceDataPoint("packet_counter_multicast_out", *i.IfOutMulticastPkts).SetUnit("c").SetLabel(*i.IfDescr)) if err != nil { return err } @@ -297,12 +297,12 @@ func addCheckInterfacePerformanceData(interfaces []device.Interface, r *monitori //packet_counter_broadcast_in if i.IfHCInBroadcastPkts != nil { - err := r.AddPerformanceDataPoint(monitoringplugin.NewPerformanceDataPoint("packet_counter_broadcast_in", *i.IfHCInBroadcastPkts, "c").SetLabel(*i.IfDescr)) + err := r.AddPerformanceDataPoint(monitoringplugin.NewPerformanceDataPoint("packet_counter_broadcast_in", *i.IfHCInBroadcastPkts).SetUnit("c").SetLabel(*i.IfDescr)) if err != nil { return err } } else if i.IfInBroadcastPkts != nil { - err := r.AddPerformanceDataPoint(monitoringplugin.NewPerformanceDataPoint("packet_counter_broadcast_in", *i.IfInBroadcastPkts, "c").SetLabel(*i.IfDescr)) + err := r.AddPerformanceDataPoint(monitoringplugin.NewPerformanceDataPoint("packet_counter_broadcast_in", *i.IfInBroadcastPkts).SetUnit("c").SetLabel(*i.IfDescr)) if err != nil { return err } @@ -310,12 +310,12 @@ func addCheckInterfacePerformanceData(interfaces []device.Interface, r *monitori //packet_counter_broadcast_out if i.IfHCOutBroadcastPkts != nil { - err := r.AddPerformanceDataPoint(monitoringplugin.NewPerformanceDataPoint("packet_counter_broadcast_out", *i.IfHCOutBroadcastPkts, "c").SetLabel(*i.IfDescr)) + err := r.AddPerformanceDataPoint(monitoringplugin.NewPerformanceDataPoint("packet_counter_broadcast_out", *i.IfHCOutBroadcastPkts).SetUnit("c").SetLabel(*i.IfDescr)) if err != nil { return err } } else if i.IfOutBroadcastPkts != nil { - err := r.AddPerformanceDataPoint(monitoringplugin.NewPerformanceDataPoint("packet_counter_broadcast_out", *i.IfOutBroadcastPkts, "c").SetLabel(*i.IfDescr)) + err := r.AddPerformanceDataPoint(monitoringplugin.NewPerformanceDataPoint("packet_counter_broadcast_out", *i.IfOutBroadcastPkts).SetUnit("c").SetLabel(*i.IfDescr)) if err != nil { return err } @@ -324,11 +324,11 @@ func addCheckInterfacePerformanceData(interfaces []device.Interface, r *monitori //interface_maxspeed_in //interface_maxspeed_out if i.IfSpeed != nil { - err := r.AddPerformanceDataPoint(monitoringplugin.NewPerformanceDataPoint("interface_maxspeed_in", *i.IfSpeed, "B").SetLabel(*i.IfDescr)) + err := r.AddPerformanceDataPoint(monitoringplugin.NewPerformanceDataPoint("interface_maxspeed_in", *i.IfSpeed).SetUnit("B").SetLabel(*i.IfDescr)) if err != nil { return err } - err = r.AddPerformanceDataPoint(monitoringplugin.NewPerformanceDataPoint("interface_maxspeed_out", *i.IfSpeed, "B").SetLabel(*i.IfDescr)) + err = r.AddPerformanceDataPoint(monitoringplugin.NewPerformanceDataPoint("interface_maxspeed_out", *i.IfSpeed).SetUnit("B").SetLabel(*i.IfDescr)) if err != nil { return err } @@ -337,98 +337,98 @@ func addCheckInterfacePerformanceData(interfaces []device.Interface, r *monitori //ethernet like interface metrics if i.EthernetLike != nil { if i.EthernetLike.Dot3StatsAlignmentErrors != nil { - err := r.AddPerformanceDataPoint(monitoringplugin.NewPerformanceDataPoint("error_counter_alignment_errors", *i.EthernetLike.Dot3StatsAlignmentErrors, "c").SetLabel(*i.IfDescr)) + err := r.AddPerformanceDataPoint(monitoringplugin.NewPerformanceDataPoint("error_counter_alignment_errors", *i.EthernetLike.Dot3StatsAlignmentErrors).SetUnit("c").SetLabel(*i.IfDescr)) if err != nil { return err } } if i.EthernetLike.Dot3StatsFCSErrors != nil { - err := r.AddPerformanceDataPoint(monitoringplugin.NewPerformanceDataPoint("error_counter_FCSErrors", *i.EthernetLike.Dot3StatsFCSErrors, "c").SetLabel(*i.IfDescr)) + err := r.AddPerformanceDataPoint(monitoringplugin.NewPerformanceDataPoint("error_counter_FCSErrors", *i.EthernetLike.Dot3StatsFCSErrors).SetUnit("c").SetLabel(*i.IfDescr)) if err != nil { return err } } if i.EthernetLike.Dot3StatsSingleCollisionFrames != nil { - err := r.AddPerformanceDataPoint(monitoringplugin.NewPerformanceDataPoint("error_counter_single_collision_frames", *i.EthernetLike.Dot3StatsSingleCollisionFrames, "c").SetLabel(*i.IfDescr)) + err := r.AddPerformanceDataPoint(monitoringplugin.NewPerformanceDataPoint("error_counter_single_collision_frames", *i.EthernetLike.Dot3StatsSingleCollisionFrames).SetUnit("c").SetLabel(*i.IfDescr)) if err != nil { return err } } if i.EthernetLike.Dot3StatsMultipleCollisionFrames != nil { - err := r.AddPerformanceDataPoint(monitoringplugin.NewPerformanceDataPoint("error_counter_multiple_collision_frames", *i.EthernetLike.Dot3StatsMultipleCollisionFrames, "c").SetLabel(*i.IfDescr)) + err := r.AddPerformanceDataPoint(monitoringplugin.NewPerformanceDataPoint("error_counter_multiple_collision_frames", *i.EthernetLike.Dot3StatsMultipleCollisionFrames).SetUnit("c").SetLabel(*i.IfDescr)) if err != nil { return err } } if i.EthernetLike.Dot3StatsSQETestErrors != nil { - err := r.AddPerformanceDataPoint(monitoringplugin.NewPerformanceDataPoint("error_counter_SQETest_errors", *i.EthernetLike.Dot3StatsSQETestErrors, "c").SetLabel(*i.IfDescr)) + err := r.AddPerformanceDataPoint(monitoringplugin.NewPerformanceDataPoint("error_counter_SQETest_errors", *i.EthernetLike.Dot3StatsSQETestErrors).SetUnit("c").SetLabel(*i.IfDescr)) if err != nil { return err } } if i.EthernetLike.Dot3StatsDeferredTransmissions != nil { - err := r.AddPerformanceDataPoint(monitoringplugin.NewPerformanceDataPoint("error_counter_deferred_transmissions", *i.EthernetLike.Dot3StatsDeferredTransmissions, "c").SetLabel(*i.IfDescr)) + err := r.AddPerformanceDataPoint(monitoringplugin.NewPerformanceDataPoint("error_counter_deferred_transmissions", *i.EthernetLike.Dot3StatsDeferredTransmissions).SetUnit("c").SetLabel(*i.IfDescr)) if err != nil { return err } } if i.EthernetLike.Dot3StatsLateCollisions != nil { - err := r.AddPerformanceDataPoint(monitoringplugin.NewPerformanceDataPoint("error_counter_late_collisions", *i.EthernetLike.Dot3StatsLateCollisions, "c").SetLabel(*i.IfDescr)) + err := r.AddPerformanceDataPoint(monitoringplugin.NewPerformanceDataPoint("error_counter_late_collisions", *i.EthernetLike.Dot3StatsLateCollisions).SetUnit("c").SetLabel(*i.IfDescr)) if err != nil { return err } } if i.EthernetLike.Dot3StatsExcessiveCollisions != nil { - err := r.AddPerformanceDataPoint(monitoringplugin.NewPerformanceDataPoint("error_counter_excessive_collisions", *i.EthernetLike.Dot3StatsExcessiveCollisions, "c").SetLabel(*i.IfDescr)) + err := r.AddPerformanceDataPoint(monitoringplugin.NewPerformanceDataPoint("error_counter_excessive_collisions", *i.EthernetLike.Dot3StatsExcessiveCollisions).SetUnit("c").SetLabel(*i.IfDescr)) if err != nil { return err } } if i.EthernetLike.Dot3StatsInternalMacTransmitErrors != nil { - err := r.AddPerformanceDataPoint(monitoringplugin.NewPerformanceDataPoint("error_counter_internal_mac_transmit_errors", *i.EthernetLike.Dot3StatsInternalMacTransmitErrors, "c").SetLabel(*i.IfDescr)) + err := r.AddPerformanceDataPoint(monitoringplugin.NewPerformanceDataPoint("error_counter_internal_mac_transmit_errors", *i.EthernetLike.Dot3StatsInternalMacTransmitErrors).SetUnit("c").SetLabel(*i.IfDescr)) if err != nil { return err } } if i.EthernetLike.Dot3StatsCarrierSenseErrors != nil { - err := r.AddPerformanceDataPoint(monitoringplugin.NewPerformanceDataPoint("error_counter_carrier_sense_errors", *i.EthernetLike.Dot3StatsCarrierSenseErrors, "c").SetLabel(*i.IfDescr)) + err := r.AddPerformanceDataPoint(monitoringplugin.NewPerformanceDataPoint("error_counter_carrier_sense_errors", *i.EthernetLike.Dot3StatsCarrierSenseErrors).SetUnit("c").SetLabel(*i.IfDescr)) if err != nil { return err } } if i.EthernetLike.Dot3StatsFrameTooLongs != nil { - err := r.AddPerformanceDataPoint(monitoringplugin.NewPerformanceDataPoint("error_counter_frame_too_longs", *i.EthernetLike.Dot3StatsFrameTooLongs, "c").SetLabel(*i.IfDescr)) + err := r.AddPerformanceDataPoint(monitoringplugin.NewPerformanceDataPoint("error_counter_frame_too_longs", *i.EthernetLike.Dot3StatsFrameTooLongs).SetUnit("c").SetLabel(*i.IfDescr)) if err != nil { return err } } if i.EthernetLike.Dot3StatsInternalMacReceiveErrors != nil { - err := r.AddPerformanceDataPoint(monitoringplugin.NewPerformanceDataPoint("error_counter_internal_mac_receive_errors", *i.EthernetLike.Dot3StatsInternalMacReceiveErrors, "c").SetLabel(*i.IfDescr)) + err := r.AddPerformanceDataPoint(monitoringplugin.NewPerformanceDataPoint("error_counter_internal_mac_receive_errors", *i.EthernetLike.Dot3StatsInternalMacReceiveErrors).SetUnit("c").SetLabel(*i.IfDescr)) if err != nil { return err } } if i.EthernetLike.Dot3HCStatsFCSErrors != nil { - err := r.AddPerformanceDataPoint(monitoringplugin.NewPerformanceDataPoint("error_counter_dot3HCStatsFCSErrors", *i.EthernetLike.Dot3HCStatsFCSErrors, "c").SetLabel(*i.IfDescr)) + err := r.AddPerformanceDataPoint(monitoringplugin.NewPerformanceDataPoint("error_counter_dot3HCStatsFCSErrors", *i.EthernetLike.Dot3HCStatsFCSErrors).SetUnit("c").SetLabel(*i.IfDescr)) if err != nil { return err } } if i.EthernetLike.EtherStatsCRCAlignErrors != nil { - err := r.AddPerformanceDataPoint(monitoringplugin.NewPerformanceDataPoint("error_counter_CRCAlign_errors", *i.EthernetLike.EtherStatsCRCAlignErrors, "c").SetLabel(*i.IfDescr)) + err := r.AddPerformanceDataPoint(monitoringplugin.NewPerformanceDataPoint("error_counter_CRCAlign_errors", *i.EthernetLike.EtherStatsCRCAlignErrors).SetUnit("c").SetLabel(*i.IfDescr)) if err != nil { return err } @@ -438,28 +438,28 @@ func addCheckInterfacePerformanceData(interfaces []device.Interface, r *monitori //radio interface metrics if i.Radio != nil { if i.Radio.LevelOut != nil { - err := r.AddPerformanceDataPoint(monitoringplugin.NewPerformanceDataPoint("interface_level_out", *i.Radio.LevelOut, "").SetLabel(*i.IfDescr)) + err := r.AddPerformanceDataPoint(monitoringplugin.NewPerformanceDataPoint("interface_level_out", *i.Radio.LevelOut).SetLabel(*i.IfDescr)) if err != nil { return err } } if i.Radio.LevelIn != nil { - err := r.AddPerformanceDataPoint(monitoringplugin.NewPerformanceDataPoint("interface_level_in", *i.Radio.LevelIn, "").SetLabel(*i.IfDescr)) + err := r.AddPerformanceDataPoint(monitoringplugin.NewPerformanceDataPoint("interface_level_in", *i.Radio.LevelIn).SetLabel(*i.IfDescr)) if err != nil { return err } } if i.Radio.MaxbitrateOut != nil { - err := r.AddPerformanceDataPoint(monitoringplugin.NewPerformanceDataPoint("interface_maxbitrate_out", *i.Radio.MaxbitrateOut, "B").SetLabel(*i.IfDescr)) + err := r.AddPerformanceDataPoint(monitoringplugin.NewPerformanceDataPoint("interface_maxbitrate_out", *i.Radio.MaxbitrateOut).SetUnit("B").SetLabel(*i.IfDescr)) if err != nil { return err } } if i.Radio.MaxbitrateIn != nil { - err := r.AddPerformanceDataPoint(monitoringplugin.NewPerformanceDataPoint("interface_maxbitrate_in", *i.Radio.MaxbitrateIn, "B").SetLabel(*i.IfDescr)) + err := r.AddPerformanceDataPoint(monitoringplugin.NewPerformanceDataPoint("interface_maxbitrate_in", *i.Radio.MaxbitrateIn).SetUnit("B").SetLabel(*i.IfDescr)) if err != nil { return err } @@ -469,14 +469,14 @@ func addCheckInterfacePerformanceData(interfaces []device.Interface, r *monitori //DWDM interface metrics if i.DWDM != nil { if i.DWDM.RXLevel != nil { - err := r.AddPerformanceDataPoint(monitoringplugin.NewPerformanceDataPoint("rx_level", *i.DWDM.RXLevel, "").SetLabel(*i.IfDescr)) + err := r.AddPerformanceDataPoint(monitoringplugin.NewPerformanceDataPoint("rx_level", *i.DWDM.RXLevel).SetLabel(*i.IfDescr)) if err != nil { return err } } if i.DWDM.TXLevel != nil { - err := r.AddPerformanceDataPoint(monitoringplugin.NewPerformanceDataPoint("tx_level", *i.DWDM.TXLevel, "").SetLabel(*i.IfDescr)) + err := r.AddPerformanceDataPoint(monitoringplugin.NewPerformanceDataPoint("tx_level", *i.DWDM.TXLevel).SetLabel(*i.IfDescr)) if err != nil { return err } @@ -486,19 +486,19 @@ func addCheckInterfacePerformanceData(interfaces []device.Interface, r *monitori //OpticalAmplifier if i.OpticalAmplifier != nil { if i.OpticalAmplifier.RXPower != nil { - err := r.AddPerformanceDataPoint(monitoringplugin.NewPerformanceDataPoint("rx_power", *i.OpticalAmplifier.RXPower, "").SetLabel(*i.IfDescr)) + err := r.AddPerformanceDataPoint(monitoringplugin.NewPerformanceDataPoint("rx_power", *i.OpticalAmplifier.RXPower).SetLabel(*i.IfDescr)) if err != nil { return err } } if i.OpticalAmplifier.TXPower != nil { - err := r.AddPerformanceDataPoint(monitoringplugin.NewPerformanceDataPoint("tx_power", *i.OpticalAmplifier.TXPower, "").SetLabel(*i.IfDescr)) + err := r.AddPerformanceDataPoint(monitoringplugin.NewPerformanceDataPoint("tx_power", *i.OpticalAmplifier.TXPower).SetLabel(*i.IfDescr)) if err != nil { return err } } if i.OpticalAmplifier.Gain != nil { - err := r.AddPerformanceDataPoint(monitoringplugin.NewPerformanceDataPoint("gain", *i.OpticalAmplifier.Gain, "").SetLabel(*i.IfDescr)) + err := r.AddPerformanceDataPoint(monitoringplugin.NewPerformanceDataPoint("gain", *i.OpticalAmplifier.Gain).SetLabel(*i.IfDescr)) if err != nil { return err } @@ -508,25 +508,25 @@ func addCheckInterfacePerformanceData(interfaces []device.Interface, r *monitori //OpticalTransponder if i.OpticalTransponder != nil { if i.OpticalTransponder.RXPower != nil { - err := r.AddPerformanceDataPoint(monitoringplugin.NewPerformanceDataPoint("rx_power", *i.OpticalTransponder.RXPower, "").SetLabel(*i.IfDescr)) + err := r.AddPerformanceDataPoint(monitoringplugin.NewPerformanceDataPoint("rx_power", *i.OpticalTransponder.RXPower).SetLabel(*i.IfDescr)) if err != nil { return err } } if i.OpticalTransponder.TXPower != nil { - err := r.AddPerformanceDataPoint(monitoringplugin.NewPerformanceDataPoint("tx_power", *i.OpticalTransponder.TXPower, "").SetLabel(*i.IfDescr)) + err := r.AddPerformanceDataPoint(monitoringplugin.NewPerformanceDataPoint("tx_power", *i.OpticalTransponder.TXPower).SetLabel(*i.IfDescr)) if err != nil { return err } } if i.OpticalTransponder.CorrectedFEC != nil { - err := r.AddPerformanceDataPoint(monitoringplugin.NewPerformanceDataPoint("corrected_fec_counter", *i.OpticalTransponder.CorrectedFEC, "c").SetLabel(*i.IfDescr)) + err := r.AddPerformanceDataPoint(monitoringplugin.NewPerformanceDataPoint("corrected_fec_counter", *i.OpticalTransponder.CorrectedFEC).SetUnit("c").SetLabel(*i.IfDescr)) if err != nil { return err } } if i.OpticalTransponder.UncorrectedFEC != nil { - err := r.AddPerformanceDataPoint(monitoringplugin.NewPerformanceDataPoint("uncorrected_fec_counter", *i.OpticalTransponder.UncorrectedFEC, "c").SetLabel(*i.IfDescr)) + err := r.AddPerformanceDataPoint(monitoringplugin.NewPerformanceDataPoint("uncorrected_fec_counter", *i.OpticalTransponder.UncorrectedFEC).SetUnit("c").SetLabel(*i.IfDescr)) if err != nil { return err } @@ -536,14 +536,14 @@ func addCheckInterfacePerformanceData(interfaces []device.Interface, r *monitori //OpticalOPM if i.OpticalOPM != nil { if i.OpticalOPM.RXPower != nil { - err := r.AddPerformanceDataPoint(monitoringplugin.NewPerformanceDataPoint("rx_power", *i.OpticalOPM.RXPower, "").SetLabel(*i.IfDescr)) + err := r.AddPerformanceDataPoint(monitoringplugin.NewPerformanceDataPoint("rx_power", *i.OpticalOPM.RXPower).SetLabel(*i.IfDescr)) if err != nil { return err } } for _, channel := range i.OpticalOPM.Channels { if channel.RXPower != nil { - err := r.AddPerformanceDataPoint(monitoringplugin.NewPerformanceDataPoint("rx_power", *channel.RXPower, "").SetLabel(*i.IfDescr + "_" + channel.Channel)) + err := r.AddPerformanceDataPoint(monitoringplugin.NewPerformanceDataPoint("rx_power", *channel.RXPower).SetLabel(*i.IfDescr + "_" + channel.Channel)) if err != nil { return err } diff --git a/core/request/check_memory_usage.go b/core/request/check_memory_usage.go index a3d5704..39d29b4 100644 --- a/core/request/check_memory_usage.go +++ b/core/request/check_memory_usage.go @@ -1,6 +1,9 @@ package request -import "context" +import ( + "context" + "github.com/inexio/go-monitoringplugin" +) // CheckMemoryUsageRequest // @@ -9,11 +12,11 @@ import "context" // swagger:model type CheckMemoryUsageRequest struct { CheckDeviceRequest - MemoryUsageThresholds CheckThresholds `json:"memoryUsageThresholds" xml:"memoryUsageThresholds"` + MemoryUsageThresholds monitoringplugin.Thresholds `json:"memoryUsageThresholds" xml:"memoryUsageThresholds"` } func (r *CheckMemoryUsageRequest) validate(ctx context.Context) error { - if err := r.MemoryUsageThresholds.validate(); err != nil { + if err := r.MemoryUsageThresholds.Validate(); err != nil { return err } return r.CheckDeviceRequest.validate(ctx) diff --git a/core/request/check_memory_usage_process.go b/core/request/check_memory_usage_process.go index f64c1d2..be6d836 100644 --- a/core/request/check_memory_usage_process.go +++ b/core/request/check_memory_usage_process.go @@ -4,9 +4,7 @@ package request import ( "context" - "fmt" "github.com/inexio/go-monitoringplugin" - "github.com/inexio/thola/core/value" ) func (r *CheckMemoryUsageRequest) process(ctx context.Context) (Response, error) { @@ -17,16 +15,14 @@ func (r *CheckMemoryUsageRequest) process(ctx context.Context) (Response, error) if r.mon.UpdateStatusOnError(err, monitoringplugin.UNKNOWN, "error while processing read memory-usage request", true) { return &CheckResponse{r.mon.GetInfo()}, nil } - val := value.New(response.(*ReadMemoryUsageResponse).MemoryUsage) + memUsage := response.(*ReadMemoryUsageResponse).MemoryUsage - err = r.mon.AddPerformanceDataPoint(monitoringplugin.NewPerformanceDataPoint("memory_usage", val.String(), "%")) + err = r.mon.AddPerformanceDataPoint(monitoringplugin.NewPerformanceDataPoint("memory_usage", memUsage). + SetUnit("%"). + SetThresholds(r.MemoryUsageThresholds)) if r.mon.UpdateStatusOnError(err, monitoringplugin.UNKNOWN, "error while adding performance data point", true) { return &CheckResponse{r.mon.GetInfo()}, nil } - if !r.MemoryUsageThresholds.isEmpty() { - code := r.MemoryUsageThresholds.checkValue(val) - r.mon.UpdateStatusIf(code != monitoringplugin.OK, code, fmt.Sprintf("memory usage is %s%%", val)) - } return &CheckResponse{r.mon.GetInfo()}, nil } diff --git a/core/request/check_sbc_request.go b/core/request/check_sbc_request.go index c21232b..114cdde 100644 --- a/core/request/check_sbc_request.go +++ b/core/request/check_sbc_request.go @@ -1,6 +1,9 @@ package request -import "context" +import ( + "context" + "github.com/inexio/go-monitoringplugin" +) // CheckSBCRequest // @@ -9,11 +12,11 @@ import "context" // swagger:model type CheckSBCRequest struct { CheckDeviceRequest - SystemHealthScoreThresholds CheckThresholds + SystemHealthScoreThresholds monitoringplugin.Thresholds } func (r *CheckSBCRequest) validate(ctx context.Context) error { - if err := r.SystemHealthScoreThresholds.validate(); err != nil { + if err := r.SystemHealthScoreThresholds.Validate(); err != nil { return err } return r.CheckDeviceRequest.validate(ctx) diff --git a/core/request/check_sbc_request_process.go b/core/request/check_sbc_request_process.go index 7b4b6ea..ab3dadc 100644 --- a/core/request/check_sbc_request_process.go +++ b/core/request/check_sbc_request_process.go @@ -4,9 +4,7 @@ package request import ( "context" - "fmt" "github.com/inexio/go-monitoringplugin" - "github.com/inexio/thola/core/value" ) func (r *CheckSBCRequest) process(ctx context.Context) (Response, error) { @@ -20,7 +18,7 @@ func (r *CheckSBCRequest) process(ctx context.Context) (Response, error) { sbc := response.(*ReadSBCResponse).SBC if sbc.GlobalCallPerSecond != nil { - err = r.mon.AddPerformanceDataPoint(monitoringplugin.NewPerformanceDataPoint("global_call_per_second", *sbc.GlobalCallPerSecond, "")) + err = r.mon.AddPerformanceDataPoint(monitoringplugin.NewPerformanceDataPoint("global_call_per_second", *sbc.GlobalCallPerSecond)) if r.mon.UpdateStatusOnError(err, monitoringplugin.UNKNOWN, "error while adding performance data point", true) { r.mon.PrintPerformanceData(false) return &CheckResponse{r.mon.GetInfo()}, nil @@ -28,7 +26,7 @@ func (r *CheckSBCRequest) process(ctx context.Context) (Response, error) { } if sbc.GlobalConcurrentSessions != nil { - err = r.mon.AddPerformanceDataPoint(monitoringplugin.NewPerformanceDataPoint("global_concurrent_sessions", *sbc.GlobalConcurrentSessions, "")) + err = r.mon.AddPerformanceDataPoint(monitoringplugin.NewPerformanceDataPoint("global_concurrent_sessions", *sbc.GlobalConcurrentSessions)) if r.mon.UpdateStatusOnError(err, monitoringplugin.UNKNOWN, "error while adding performance data point", true) { r.mon.PrintPerformanceData(false) return &CheckResponse{r.mon.GetInfo()}, nil @@ -36,7 +34,7 @@ func (r *CheckSBCRequest) process(ctx context.Context) (Response, error) { } if sbc.ActiveLocalContacts != nil { - err = r.mon.AddPerformanceDataPoint(monitoringplugin.NewPerformanceDataPoint("active_local_contacts", *sbc.ActiveLocalContacts, "")) + err = r.mon.AddPerformanceDataPoint(monitoringplugin.NewPerformanceDataPoint("active_local_contacts", *sbc.ActiveLocalContacts)) if r.mon.UpdateStatusOnError(err, monitoringplugin.UNKNOWN, "error while adding performance data point", true) { r.mon.PrintPerformanceData(false) return &CheckResponse{r.mon.GetInfo()}, nil @@ -44,7 +42,7 @@ func (r *CheckSBCRequest) process(ctx context.Context) (Response, error) { } if sbc.TranscodingCapacity != nil { - err = r.mon.AddPerformanceDataPoint(monitoringplugin.NewPerformanceDataPoint("transcoding_capacity", *sbc.TranscodingCapacity, "")) + err = r.mon.AddPerformanceDataPoint(monitoringplugin.NewPerformanceDataPoint("transcoding_capacity", *sbc.TranscodingCapacity)) if r.mon.UpdateStatusOnError(err, monitoringplugin.UNKNOWN, "error while adding performance data point", true) { r.mon.PrintPerformanceData(false) return &CheckResponse{r.mon.GetInfo()}, nil @@ -52,14 +50,14 @@ func (r *CheckSBCRequest) process(ctx context.Context) (Response, error) { } if sbc.LicenseCapacity != nil { - err = r.mon.AddPerformanceDataPoint(monitoringplugin.NewPerformanceDataPoint("license_capacity", *sbc.LicenseCapacity, "")) + err = r.mon.AddPerformanceDataPoint(monitoringplugin.NewPerformanceDataPoint("license_capacity", *sbc.LicenseCapacity)) if r.mon.UpdateStatusOnError(err, monitoringplugin.UNKNOWN, "error while adding performance data point", true) { return &CheckResponse{r.mon.GetInfo()}, nil } } if sbc.SystemRedundancy != nil { - err = r.mon.AddPerformanceDataPoint(monitoringplugin.NewPerformanceDataPoint("system_redundancy", *sbc.SystemRedundancy, "")) + err = r.mon.AddPerformanceDataPoint(monitoringplugin.NewPerformanceDataPoint("system_redundancy", *sbc.SystemRedundancy)) if r.mon.UpdateStatusOnError(err, monitoringplugin.UNKNOWN, "error while adding performance data point", true) { return &CheckResponse{r.mon.GetInfo()}, nil } @@ -68,20 +66,19 @@ func (r *CheckSBCRequest) process(ctx context.Context) (Response, error) { } if sbc.SystemHealthScore != nil { - err = r.mon.AddPerformanceDataPoint(monitoringplugin.NewPerformanceDataPoint("system_health_score", *sbc.SystemHealthScore, "")) + err = r.mon.AddPerformanceDataPoint( + monitoringplugin.NewPerformanceDataPoint("system_health_score", *sbc.SystemHealthScore). + SetThresholds(r.SystemHealthScoreThresholds). + SetMin(0). + SetMax(100)) if r.mon.UpdateStatusOnError(err, monitoringplugin.UNKNOWN, "error while adding performance data point", true) { return &CheckResponse{r.mon.GetInfo()}, nil } - val := value.New(*sbc.SystemHealthScore) - if !r.SystemHealthScoreThresholds.isEmpty() { - code := r.SystemHealthScoreThresholds.checkValue(val) - r.mon.UpdateStatusIf(code != monitoringplugin.OK, code, fmt.Sprintf("system health score is %s%%", val)) - } } for _, agent := range sbc.Agents { if agent.CurrentActiveSessionsInbound != nil { - p := monitoringplugin.NewPerformanceDataPoint("current_active_sessions_inbound", *agent.CurrentActiveSessionsInbound, "").SetLabel(agent.Hostname) + p := monitoringplugin.NewPerformanceDataPoint("current_active_sessions_inbound", *agent.CurrentActiveSessionsInbound).SetLabel(agent.Hostname) err = r.mon.AddPerformanceDataPoint(p) if r.mon.UpdateStatusOnError(err, monitoringplugin.UNKNOWN, "error while adding performance data point", true) { r.mon.PrintPerformanceData(false) @@ -90,7 +87,7 @@ func (r *CheckSBCRequest) process(ctx context.Context) (Response, error) { } if agent.CurrentSessionRateInbound != nil { - p := monitoringplugin.NewPerformanceDataPoint("current_session_rate_inbound", *agent.CurrentSessionRateInbound, "").SetLabel(agent.Hostname) + p := monitoringplugin.NewPerformanceDataPoint("current_session_rate_inbound", *agent.CurrentSessionRateInbound).SetLabel(agent.Hostname) err = r.mon.AddPerformanceDataPoint(p) if r.mon.UpdateStatusOnError(err, monitoringplugin.UNKNOWN, "error while adding performance data point", true) { r.mon.PrintPerformanceData(false) @@ -99,7 +96,7 @@ func (r *CheckSBCRequest) process(ctx context.Context) (Response, error) { } if agent.CurrentActiveSessionsOutbound != nil { - p := monitoringplugin.NewPerformanceDataPoint("current_active_sessions_outbound", *agent.CurrentActiveSessionsOutbound, "").SetLabel(agent.Hostname) + p := monitoringplugin.NewPerformanceDataPoint("current_active_sessions_outbound", *agent.CurrentActiveSessionsOutbound).SetLabel(agent.Hostname) err = r.mon.AddPerformanceDataPoint(p) if r.mon.UpdateStatusOnError(err, monitoringplugin.UNKNOWN, "error while adding performance data point", true) { r.mon.PrintPerformanceData(false) @@ -108,7 +105,7 @@ func (r *CheckSBCRequest) process(ctx context.Context) (Response, error) { } if agent.CurrentSessionRateOutbound != nil { - p := monitoringplugin.NewPerformanceDataPoint("current_session_rate_outbound", *agent.CurrentSessionRateOutbound, "").SetLabel(agent.Hostname) + p := monitoringplugin.NewPerformanceDataPoint("current_session_rate_outbound", *agent.CurrentSessionRateOutbound).SetLabel(agent.Hostname) err = r.mon.AddPerformanceDataPoint(p) if r.mon.UpdateStatusOnError(err, monitoringplugin.UNKNOWN, "error while adding performance data point", true) { r.mon.PrintPerformanceData(false) @@ -117,7 +114,7 @@ func (r *CheckSBCRequest) process(ctx context.Context) (Response, error) { } if agent.PeriodASR != nil { - p := monitoringplugin.NewPerformanceDataPoint("period_asr", *agent.PeriodASR, "").SetLabel(agent.Hostname) + p := monitoringplugin.NewPerformanceDataPoint("period_asr", *agent.PeriodASR).SetLabel(agent.Hostname) err = r.mon.AddPerformanceDataPoint(p) if r.mon.UpdateStatusOnError(err, monitoringplugin.UNKNOWN, "error while adding performance data point", true) { r.mon.PrintPerformanceData(false) @@ -126,7 +123,7 @@ func (r *CheckSBCRequest) process(ctx context.Context) (Response, error) { } if agent.Status != nil { - p := monitoringplugin.NewPerformanceDataPoint("status", *agent.Status, "").SetLabel(agent.Hostname) + p := monitoringplugin.NewPerformanceDataPoint("status", *agent.Status).SetLabel(agent.Hostname) err = r.mon.AddPerformanceDataPoint(p) if r.mon.UpdateStatusOnError(err, monitoringplugin.UNKNOWN, "error while adding performance data point", true) { r.mon.PrintPerformanceData(false) @@ -137,7 +134,7 @@ func (r *CheckSBCRequest) process(ctx context.Context) (Response, error) { for _, realm := range sbc.Realms { if realm.CurrentActiveSessionsInbound != nil { - p := monitoringplugin.NewPerformanceDataPoint("current_active_sessions_inbound", *realm.CurrentActiveSessionsInbound, "").SetLabel(realm.Name) + p := monitoringplugin.NewPerformanceDataPoint("current_active_sessions_inbound", *realm.CurrentActiveSessionsInbound).SetLabel(realm.Name) err = r.mon.AddPerformanceDataPoint(p) if r.mon.UpdateStatusOnError(err, monitoringplugin.UNKNOWN, "error while adding performance data point", true) { r.mon.PrintPerformanceData(false) @@ -146,7 +143,7 @@ func (r *CheckSBCRequest) process(ctx context.Context) (Response, error) { } if realm.CurrentSessionRateInbound != nil { - p := monitoringplugin.NewPerformanceDataPoint("current_session_rate_inbound", *realm.CurrentSessionRateInbound, "").SetLabel(realm.Name) + p := monitoringplugin.NewPerformanceDataPoint("current_session_rate_inbound", *realm.CurrentSessionRateInbound).SetLabel(realm.Name) err = r.mon.AddPerformanceDataPoint(p) if r.mon.UpdateStatusOnError(err, monitoringplugin.UNKNOWN, "error while adding performance data point", true) { r.mon.PrintPerformanceData(false) @@ -155,7 +152,7 @@ func (r *CheckSBCRequest) process(ctx context.Context) (Response, error) { } if realm.CurrentActiveSessionsOutbound != nil { - p := monitoringplugin.NewPerformanceDataPoint("current_active_sessions_outbound", *realm.CurrentActiveSessionsOutbound, "").SetLabel(realm.Name) + p := monitoringplugin.NewPerformanceDataPoint("current_active_sessions_outbound", *realm.CurrentActiveSessionsOutbound).SetLabel(realm.Name) err = r.mon.AddPerformanceDataPoint(p) if r.mon.UpdateStatusOnError(err, monitoringplugin.UNKNOWN, "error while adding performance data point", true) { r.mon.PrintPerformanceData(false) @@ -164,7 +161,7 @@ func (r *CheckSBCRequest) process(ctx context.Context) (Response, error) { } if realm.CurrentSessionRateOutbound != nil { - p := monitoringplugin.NewPerformanceDataPoint("current_session_rate_outbound", *realm.CurrentSessionRateOutbound, "").SetLabel(realm.Name) + p := monitoringplugin.NewPerformanceDataPoint("current_session_rate_outbound", *realm.CurrentSessionRateOutbound).SetLabel(realm.Name) err = r.mon.AddPerformanceDataPoint(p) if r.mon.UpdateStatusOnError(err, monitoringplugin.UNKNOWN, "error while adding performance data point", true) { r.mon.PrintPerformanceData(false) @@ -173,7 +170,7 @@ func (r *CheckSBCRequest) process(ctx context.Context) (Response, error) { } if realm.PeriodASR != nil { - p := monitoringplugin.NewPerformanceDataPoint("period_asr", *realm.PeriodASR, "").SetLabel(realm.Name) + p := monitoringplugin.NewPerformanceDataPoint("period_asr", *realm.PeriodASR).SetLabel(realm.Name) err = r.mon.AddPerformanceDataPoint(p) if r.mon.UpdateStatusOnError(err, monitoringplugin.UNKNOWN, "error while adding performance data point", true) { r.mon.PrintPerformanceData(false) @@ -182,7 +179,7 @@ func (r *CheckSBCRequest) process(ctx context.Context) (Response, error) { } if realm.Status != nil { - p := monitoringplugin.NewPerformanceDataPoint("status", *realm.Status, "").SetLabel(realm.Name) + p := monitoringplugin.NewPerformanceDataPoint("status", *realm.Status).SetLabel(realm.Name) err = r.mon.AddPerformanceDataPoint(p) if r.mon.UpdateStatusOnError(err, monitoringplugin.UNKNOWN, "error while adding performance data point", true) { r.mon.PrintPerformanceData(false) @@ -191,7 +188,7 @@ func (r *CheckSBCRequest) process(ctx context.Context) (Response, error) { } if realm.ActiveLocalContacts != nil { - p := monitoringplugin.NewPerformanceDataPoint("active_local_contacts", *realm.ActiveLocalContacts, "").SetLabel(realm.Name) + p := monitoringplugin.NewPerformanceDataPoint("active_local_contacts", *realm.ActiveLocalContacts).SetLabel(realm.Name) err = r.mon.AddPerformanceDataPoint(p) if r.mon.UpdateStatusOnError(err, monitoringplugin.UNKNOWN, "error while adding performance data point", true) { r.mon.PrintPerformanceData(false) diff --git a/core/request/check_server_request.go b/core/request/check_server_request.go index 2f0442a..0acdf1c 100644 --- a/core/request/check_server_request.go +++ b/core/request/check_server_request.go @@ -1,6 +1,9 @@ package request -import "context" +import ( + "context" + "github.com/inexio/go-monitoringplugin" +) // CheckServerRequest // @@ -9,11 +12,11 @@ import "context" // swagger:model type CheckServerRequest struct { CheckDeviceRequest - ServerThresholds CheckThresholds `json:"serverThresholds" xml:"serverThresholds"` + ServerThresholds monitoringplugin.Thresholds `json:"serverThresholds" xml:"serverThresholds"` } func (r *CheckServerRequest) validate(ctx context.Context) error { - if err := r.ServerThresholds.validate(); err != nil { + if err := r.ServerThresholds.Validate(); err != nil { return err } return r.CheckDeviceRequest.validate(ctx) diff --git a/core/request/check_server_request_process.go b/core/request/check_server_request_process.go index 3a2b466..b9f6599 100644 --- a/core/request/check_server_request_process.go +++ b/core/request/check_server_request_process.go @@ -18,14 +18,14 @@ func (r *CheckServerRequest) process(ctx context.Context) (Response, error) { server := response.(*ReadServerResponse) if server.Server.Procs != nil { - err = r.mon.AddPerformanceDataPoint(monitoringplugin.NewPerformanceDataPoint("procs", *server.Server.Procs, "")) + err = r.mon.AddPerformanceDataPoint(monitoringplugin.NewPerformanceDataPoint("procs", *server.Server.Procs)) if r.mon.UpdateStatusOnError(err, monitoringplugin.UNKNOWN, "error while adding performance data point", true) { r.mon.PrintPerformanceData(false) return &CheckResponse{r.mon.GetInfo()}, nil } } if server.Server.Users != nil { - err = r.mon.AddPerformanceDataPoint(monitoringplugin.NewPerformanceDataPoint("users", *server.Server.Users, "")) + err = r.mon.AddPerformanceDataPoint(monitoringplugin.NewPerformanceDataPoint("users", *server.Server.Users)) if r.mon.UpdateStatusOnError(err, monitoringplugin.UNKNOWN, "error while adding performance data point", true) { r.mon.PrintPerformanceData(false) return &CheckResponse{r.mon.GetInfo()}, nil diff --git a/core/request/check_thola_server_request_process.go b/core/request/check_thola_server_request_process.go index 5d31769..166425c 100644 --- a/core/request/check_thola_server_request_process.go +++ b/core/request/check_thola_server_request_process.go @@ -33,25 +33,25 @@ func (r *CheckTholaServerRequest) process(ctx context.Context) (Response, error) return &CheckResponse{r.mon.GetInfo()}, nil } - err = r.mon.AddPerformanceDataPoint(monitoringplugin.NewPerformanceDataPoint("total_request_counter", stats.TotalCount, "c")) + err = r.mon.AddPerformanceDataPoint(monitoringplugin.NewPerformanceDataPoint("total_request_counter", stats.TotalCount).SetUnit("c")) if r.mon.UpdateStatusOnError(err, monitoringplugin.UNKNOWN, "error while adding performance data point", true) { r.mon.PrintPerformanceData(false) return &CheckResponse{r.mon.GetInfo()}, nil } - err = r.mon.AddPerformanceDataPoint(monitoringplugin.NewPerformanceDataPoint("successful_request_counter", stats.SuccessfulCounter, "c")) + err = r.mon.AddPerformanceDataPoint(monitoringplugin.NewPerformanceDataPoint("successful_request_counter", stats.SuccessfulCounter).SetUnit("c")) if r.mon.UpdateStatusOnError(err, monitoringplugin.UNKNOWN, "error while adding performance data point", true) { r.mon.PrintPerformanceData(false) return &CheckResponse{r.mon.GetInfo()}, nil } - err = r.mon.AddPerformanceDataPoint(monitoringplugin.NewPerformanceDataPoint("failed_request_counter", stats.FailedCounter, "c")) + err = r.mon.AddPerformanceDataPoint(monitoringplugin.NewPerformanceDataPoint("failed_request_counter", stats.FailedCounter).SetUnit("c")) if r.mon.UpdateStatusOnError(err, monitoringplugin.UNKNOWN, "error while adding performance data point", true) { r.mon.PrintPerformanceData(false) return &CheckResponse{r.mon.GetInfo()}, nil } - err = r.mon.AddPerformanceDataPoint(monitoringplugin.NewPerformanceDataPoint("average_response_time", stats.AverageResponseTime, "s")) + err = r.mon.AddPerformanceDataPoint(monitoringplugin.NewPerformanceDataPoint("average_response_time", stats.AverageResponseTime).SetUnit("s")) if r.mon.UpdateStatusOnError(err, monitoringplugin.UNKNOWN, "error while adding performance data point", true) { r.mon.PrintPerformanceData(false) return &CheckResponse{r.mon.GetInfo()}, nil diff --git a/core/request/check_ups.go b/core/request/check_ups.go index 7c476f1..09789b1 100644 --- a/core/request/check_ups.go +++ b/core/request/check_ups.go @@ -1,6 +1,9 @@ package request -import "context" +import ( + "context" + "github.com/inexio/go-monitoringplugin" +) // CheckUPSRequest // @@ -9,31 +12,31 @@ import "context" // swagger:model type CheckUPSRequest struct { CheckDeviceRequest - BatteryCurrentThresholds CheckThresholds `json:"batteryCurrentThresholds" xml:"batteryCurrentThresholds"` - BatteryTemperatureThresholds CheckThresholds `json:"batteryTemperatureThresholds" xml:"batteryTemperatureThresholds"` - CurrentLoadThresholds CheckThresholds `json:"currentLoadThresholds" xml:"currentLoadThresholds"` - RectifierCurrentThresholds CheckThresholds `json:"rectifierCurrentThresholds" xml:"rectifierCurrentThresholds"` - SystemVoltageThresholds CheckThresholds `json:"systemVoltageThresholds" xml:"systemVoltageThresholds"` + BatteryCurrentThresholds monitoringplugin.Thresholds `json:"batteryCurrentThresholds" xml:"batteryCurrentThresholds"` + BatteryTemperatureThresholds monitoringplugin.Thresholds `json:"batteryTemperatureThresholds" xml:"batteryTemperatureThresholds"` + CurrentLoadThresholds monitoringplugin.Thresholds `json:"currentLoadThresholds" xml:"currentLoadThresholds"` + RectifierCurrentThresholds monitoringplugin.Thresholds `json:"rectifierCurrentThresholds" xml:"rectifierCurrentThresholds"` + SystemVoltageThresholds monitoringplugin.Thresholds `json:"systemVoltageThresholds" xml:"systemVoltageThresholds"` } func (r *CheckUPSRequest) validate(ctx context.Context) error { - if err := r.BatteryCurrentThresholds.validate(); err != nil { + if err := r.BatteryCurrentThresholds.Validate(); err != nil { return err } - if err := r.BatteryTemperatureThresholds.validate(); err != nil { + if err := r.BatteryTemperatureThresholds.Validate(); err != nil { return err } - if err := r.CurrentLoadThresholds.validate(); err != nil { + if err := r.CurrentLoadThresholds.Validate(); err != nil { return err } - if err := r.RectifierCurrentThresholds.validate(); err != nil { + if err := r.RectifierCurrentThresholds.Validate(); err != nil { return err } - if err := r.SystemVoltageThresholds.validate(); err != nil { + if err := r.SystemVoltageThresholds.Validate(); err != nil { return err } diff --git a/core/request/check_ups_process.go b/core/request/check_ups_process.go index a599e7c..995707f 100644 --- a/core/request/check_ups_process.go +++ b/core/request/check_ups_process.go @@ -5,9 +5,7 @@ package request import ( "context" "github.com/inexio/go-monitoringplugin" - "github.com/inexio/thola/core/device" "github.com/inexio/thola/core/utility" - "github.com/inexio/thola/core/value" ) func (r *CheckUPSRequest) process(ctx context.Context) (Response, error) { @@ -19,146 +17,115 @@ func (r *CheckUPSRequest) process(ctx context.Context) (Response, error) { return &CheckResponse{r.mon.GetInfo()}, nil } - err = addCheckUPSPerformanceData(readUPSResponse.UPS, r.mon) - if r.mon.UpdateStatusOnError(err, monitoringplugin.UNKNOWN, "error while adding performance data", true) { - r.mon.PrintPerformanceData(false) - return &CheckResponse{r.mon.GetInfo()}, nil - } - - if readUPSResponse.UPS.MainsVoltageApplied != nil { - r.mon.UpdateStatusIfNot(*readUPSResponse.UPS.MainsVoltageApplied, monitoringplugin.CRITICAL, "Mains voltage is not applied") - } - - if !r.BatteryCurrentThresholds.isEmpty() { - if readUPSResponse.UPS.BatteryCurrent == nil { - r.mon.UpdateStatus(monitoringplugin.UNKNOWN, "battery current value is empty") - } else if status := r.BatteryCurrentThresholds.checkValue(value.New(*readUPSResponse.UPS.BatteryCurrent)); status != monitoringplugin.OK { - r.mon.UpdateStatus(status, "battery current is outside of threshold") - } - } - - if !r.BatteryTemperatureThresholds.isEmpty() { - if readUPSResponse.UPS.BatteryTemperature == nil { - r.mon.UpdateStatus(monitoringplugin.UNKNOWN, "battery temperature value is empty") - } else if status := r.BatteryTemperatureThresholds.checkValue(value.New(*readUPSResponse.UPS.BatteryTemperature)); status != monitoringplugin.OK { - r.mon.UpdateStatus(status, "battery temperature is outside of threshold") + if readUPSResponse.UPS.AlarmLowVoltageDisconnect != nil { + err := r.mon.AddPerformanceDataPoint(monitoringplugin.NewPerformanceDataPoint("alarm_low_voltage_disconnect", *readUPSResponse.UPS.AlarmLowVoltageDisconnect)) + if r.mon.UpdateStatusOnError(err, monitoringplugin.UNKNOWN, "error while adding performance data point", true) { + r.mon.PrintPerformanceData(false) + return &CheckResponse{r.mon.GetInfo()}, nil } } - if !r.CurrentLoadThresholds.isEmpty() { - if readUPSResponse.UPS.CurrentLoad == nil { - r.mon.UpdateStatus(monitoringplugin.UNKNOWN, "current load value is empty") - } else if status := r.CurrentLoadThresholds.checkValue(value.New(*readUPSResponse.UPS.CurrentLoad)); status != monitoringplugin.OK { - r.mon.UpdateStatus(status, "current load is outside of threshold") + if readUPSResponse.UPS.BatteryAmperage != nil { + err := r.mon.AddPerformanceDataPoint(monitoringplugin.NewPerformanceDataPoint("batt_amperage", *readUPSResponse.UPS.BatteryAmperage)) + if r.mon.UpdateStatusOnError(err, monitoringplugin.UNKNOWN, "error while adding performance data point", true) { + r.mon.PrintPerformanceData(false) + return &CheckResponse{r.mon.GetInfo()}, nil } } - if !r.RectifierCurrentThresholds.isEmpty() { - if readUPSResponse.UPS.RectifierCurrent == nil { - r.mon.UpdateStatus(monitoringplugin.UNKNOWN, "rectifier current value is empty") - } else if status := r.RectifierCurrentThresholds.checkValue(value.New(*readUPSResponse.UPS.RectifierCurrent)); status != monitoringplugin.OK { - r.mon.UpdateStatus(status, "rectifier current is outside of threshold") + if readUPSResponse.UPS.BatteryRemainingTime != nil { + err := r.mon.AddPerformanceDataPoint(monitoringplugin.NewPerformanceDataPoint("batt_remaining_time", *readUPSResponse.UPS.BatteryRemainingTime)) + if r.mon.UpdateStatusOnError(err, monitoringplugin.UNKNOWN, "error while adding performance data point", true) { + r.mon.PrintPerformanceData(false) + return &CheckResponse{r.mon.GetInfo()}, nil } } - if !r.SystemVoltageThresholds.isEmpty() { - if readUPSResponse.UPS.SystemVoltage == nil { - r.mon.UpdateStatus(monitoringplugin.UNKNOWN, "system voltage value is empty") - } else if status := r.SystemVoltageThresholds.checkValue(value.New(*readUPSResponse.UPS.SystemVoltage)); status != monitoringplugin.OK { - r.mon.UpdateStatus(status, "system voltage is outside of threshold") - } - } - - return &CheckResponse{r.mon.GetInfo()}, nil -} - -func (r *CheckUPSRequest) getData(ctx context.Context) (*ReadUPSResponse, error) { - readUPSRequest := ReadUPSRequest{ReadRequest{r.BaseRequest}} - response, err := readUPSRequest.process(ctx) - if err != nil { - return nil, err - } - - readUPSResponse := response.(*ReadUPSResponse) - return readUPSResponse, nil -} - -func addCheckUPSPerformanceData(ups device.UPSComponent, r *monitoringplugin.Response) error { - if ups.AlarmLowVoltageDisconnect != nil { - err := r.AddPerformanceDataPoint(monitoringplugin.NewPerformanceDataPoint("alarm_low_voltage_disconnect", *ups.AlarmLowVoltageDisconnect, "")) - if err != nil { - return err + if readUPSResponse.UPS.BatteryCapacity != nil { + err := r.mon.AddPerformanceDataPoint(monitoringplugin.NewPerformanceDataPoint("batt_capacity", *readUPSResponse.UPS.BatteryCapacity)) + if r.mon.UpdateStatusOnError(err, monitoringplugin.UNKNOWN, "error while adding performance data point", true) { + r.mon.PrintPerformanceData(false) + return &CheckResponse{r.mon.GetInfo()}, nil } } - if ups.BatteryAmperage != nil { - err := r.AddPerformanceDataPoint(monitoringplugin.NewPerformanceDataPoint("batt_amperage", *ups.BatteryAmperage, "")) - if err != nil { - return err + if readUPSResponse.UPS.BatteryCurrent != nil { + err := r.mon.AddPerformanceDataPoint( + monitoringplugin.NewPerformanceDataPoint("batt_current", *readUPSResponse.UPS.BatteryCurrent). + SetThresholds(r.BatteryCurrentThresholds)) + if r.mon.UpdateStatusOnError(err, monitoringplugin.UNKNOWN, "error while adding performance data point", true) { + r.mon.PrintPerformanceData(false) + return &CheckResponse{r.mon.GetInfo()}, nil } } - if ups.BatteryRemainingTime != nil { - err := r.AddPerformanceDataPoint(monitoringplugin.NewPerformanceDataPoint("batt_remaining_time", *ups.BatteryRemainingTime, "")) - if err != nil { - return err + if readUPSResponse.UPS.BatteryTemperature != nil { + err := r.mon.AddPerformanceDataPoint( + monitoringplugin.NewPerformanceDataPoint("batt_temperature", *readUPSResponse.UPS.BatteryTemperature). + SetThresholds(r.BatteryTemperatureThresholds)) + if r.mon.UpdateStatusOnError(err, monitoringplugin.UNKNOWN, "error while adding performance data point", true) { + r.mon.PrintPerformanceData(false) + return &CheckResponse{r.mon.GetInfo()}, nil } } - if ups.BatteryCapacity != nil { - err := r.AddPerformanceDataPoint(monitoringplugin.NewPerformanceDataPoint("batt_capacity", *ups.BatteryCapacity, "")) - if err != nil { - return err + if readUPSResponse.UPS.BatteryVoltage != nil { + err := r.mon.AddPerformanceDataPoint(monitoringplugin.NewPerformanceDataPoint("batt_voltage", *readUPSResponse.UPS.BatteryVoltage)) + if r.mon.UpdateStatusOnError(err, monitoringplugin.UNKNOWN, "error while adding performance data point", true) { + r.mon.PrintPerformanceData(false) + return &CheckResponse{r.mon.GetInfo()}, nil } } - if ups.BatteryCurrent != nil { - err := r.AddPerformanceDataPoint(monitoringplugin.NewPerformanceDataPoint("batt_current", *ups.BatteryCurrent, "")) - if err != nil { - return err + if readUPSResponse.UPS.CurrentLoad != nil { + err := r.mon.AddPerformanceDataPoint( + monitoringplugin.NewPerformanceDataPoint("current_load", *readUPSResponse.UPS.CurrentLoad). + SetThresholds(r.CurrentLoadThresholds)) + if r.mon.UpdateStatusOnError(err, monitoringplugin.UNKNOWN, "error while adding performance data point", true) { + r.mon.PrintPerformanceData(false) + return &CheckResponse{r.mon.GetInfo()}, nil } } - if ups.BatteryTemperature != nil { - err := r.AddPerformanceDataPoint(monitoringplugin.NewPerformanceDataPoint("batt_temperature", *ups.BatteryTemperature, "")) - if err != nil { - return err + if readUPSResponse.UPS.MainsVoltageApplied != nil { + err := r.mon.AddPerformanceDataPoint(monitoringplugin.NewPerformanceDataPoint("mains_voltage_applied", utility.IfThenElse(*readUPSResponse.UPS.MainsVoltageApplied, 1, 0))) + if r.mon.UpdateStatusOnError(err, monitoringplugin.UNKNOWN, "error while adding performance data point", true) { + r.mon.PrintPerformanceData(false) + return &CheckResponse{r.mon.GetInfo()}, nil } + r.mon.UpdateStatusIfNot(*readUPSResponse.UPS.MainsVoltageApplied, monitoringplugin.CRITICAL, "Mains voltage is not applied") } - if ups.BatteryVoltage != nil { - err := r.AddPerformanceDataPoint(monitoringplugin.NewPerformanceDataPoint("batt_voltage", *ups.BatteryVoltage, "")) - if err != nil { - return err + if readUPSResponse.UPS.RectifierCurrent != nil { + err := r.mon.AddPerformanceDataPoint( + monitoringplugin.NewPerformanceDataPoint("rectifier_current", *readUPSResponse.UPS.RectifierCurrent). + SetThresholds(r.RectifierCurrentThresholds)) + if r.mon.UpdateStatusOnError(err, monitoringplugin.UNKNOWN, "error while adding performance data point", true) { + r.mon.PrintPerformanceData(false) + return &CheckResponse{r.mon.GetInfo()}, nil } } - if ups.CurrentLoad != nil { - err := r.AddPerformanceDataPoint(monitoringplugin.NewPerformanceDataPoint("current_load", *ups.CurrentLoad, "")) - if err != nil { - return err + if readUPSResponse.UPS.SystemVoltage != nil { + err := r.mon.AddPerformanceDataPoint( + monitoringplugin.NewPerformanceDataPoint("sys_voltage", *readUPSResponse.UPS.SystemVoltage). + SetThresholds(r.SystemVoltageThresholds)) + if r.mon.UpdateStatusOnError(err, monitoringplugin.UNKNOWN, "error while adding performance data point", true) { + r.mon.PrintPerformanceData(false) + return &CheckResponse{r.mon.GetInfo()}, nil } } - if ups.MainsVoltageApplied != nil { - err := r.AddPerformanceDataPoint(monitoringplugin.NewPerformanceDataPoint("mains_voltage_applied", utility.IfThenElse(*ups.MainsVoltageApplied, 1, 0), "")) - if err != nil { - return err - } - } + return &CheckResponse{r.mon.GetInfo()}, nil +} - if ups.RectifierCurrent != nil { - err := r.AddPerformanceDataPoint(monitoringplugin.NewPerformanceDataPoint("rectifier_current", *ups.RectifierCurrent, "")) - if err != nil { - return err - } +func (r *CheckUPSRequest) getData(ctx context.Context) (*ReadUPSResponse, error) { + readUPSRequest := ReadUPSRequest{ReadRequest{r.BaseRequest}} + response, err := readUPSRequest.process(ctx) + if err != nil { + return nil, err } - if ups.SystemVoltage != nil { - err := r.AddPerformanceDataPoint(monitoringplugin.NewPerformanceDataPoint("sys_voltage", *ups.SystemVoltage, "")) - if err != nil { - return err - } - } - return nil + readUPSResponse := response.(*ReadUPSResponse) + return readUPSResponse, nil } diff --git a/core/request/read_hardware_health_request_process.go b/core/request/read_hardware_health_request_process.go index 8bfcfb8..019da7f 100644 --- a/core/request/read_hardware_health_request_process.go +++ b/core/request/read_hardware_health_request_process.go @@ -15,7 +15,7 @@ func (r *ReadHardwareHealthRequest) process(ctx context.Context) (Response, erro result, err := com.GetHardwareHealthComponent(ctx) if err != nil { - return nil, errors.Wrap(err, "can't get cpu load") + return nil, errors.Wrap(err, "failed to get hardware health component") } return &ReadHardwareHealthResponse{ diff --git a/go.mod b/go.mod index de27bd9..bccc9db 100644 --- a/go.mod +++ b/go.mod @@ -10,7 +10,7 @@ require ( github.com/google/go-cmp v0.5.4 github.com/gosnmp/gosnmp v1.30.0 github.com/huandu/go-sqlbuilder v1.8.0 - github.com/inexio/go-monitoringplugin v1.0.2 + github.com/inexio/go-monitoringplugin v1.0.4 github.com/jmoiron/sqlx v1.2.0 github.com/labstack/echo/v4 v4.2.0 github.com/mitchellh/colorstring v0.0.0-20190213212951-d06e56a500db diff --git a/go.sum b/go.sum index 8ebe6ec..92bd235 100644 --- a/go.sum +++ b/go.sum @@ -154,8 +154,8 @@ github.com/huandu/go-sqlbuilder v1.8.0 h1:1KP21dzROt03II0aoX/rD2Y6TX1VCIixSX5mvk github.com/huandu/go-sqlbuilder v1.8.0/go.mod h1:cM38aLPrMXaGxsUkHFh1e2skthPnQRPK7h8//X5LQMc= github.com/inconshreveable/mousetrap v1.0.0 h1:Z8tu5sraLXCXIcARxBp/8cbvlwVa7Z1NHg9XEKhtSvM= github.com/inconshreveable/mousetrap v1.0.0/go.mod h1:PxqpIevigyE2G7u3NXJIT2ANytuPF1OarO4DADm73n8= -github.com/inexio/go-monitoringplugin v1.0.2 h1:jhVHjshrJHC6cjyqomaReqmPIhkJTNJM1ztw3ltx65k= -github.com/inexio/go-monitoringplugin v1.0.2/go.mod h1:kzHRJGZ2iE/0IElB4NYI38h3h0HM5wqTTH7KyUCjkM8= +github.com/inexio/go-monitoringplugin v1.0.4 h1:szt6siVww0dtgkeuUGofOPGFMdLGEeTWWpbJIRI3rlg= +github.com/inexio/go-monitoringplugin v1.0.4/go.mod h1:kzHRJGZ2iE/0IElB4NYI38h3h0HM5wqTTH7KyUCjkM8= github.com/jmoiron/sqlx v1.2.0 h1:41Ip0zITnmWNR/vHV+S4m+VoUivnWY5E4OJfLZjCJMA= github.com/jmoiron/sqlx v1.2.0/go.mod h1:1FEQNm3xlJgrMD+FBdI9+xvCksHtbpVBBw5dYhBSsks= github.com/jonboulle/clockwork v0.1.0/go.mod h1:Ii8DK3G1RaLaWxj9trq07+26W01tbo22gdxWY5EU2bo= diff --git a/test/integration_test.go b/test/integration_test.go index dd31ae1..9d8481b 100644 --- a/test/integration_test.go +++ b/test/integration_test.go @@ -491,8 +491,8 @@ func metricsRawOutputFilter() cmp.Option { } func metricsTransformer() cmp.Option { - return cmp.Transformer("Sort", func(in []monitoringplugin.PerformanceDataPointInfo) []monitoringplugin.PerformanceDataPointInfo { - out := make([]monitoringplugin.PerformanceDataPointInfo, len(in)) + return cmp.Transformer("Sort", func(in []monitoringplugin.PerformanceDataPoint) []monitoringplugin.PerformanceDataPoint { + out := make([]monitoringplugin.PerformanceDataPoint, len(in)) copy(out, in) sort.Slice(out, func(i, j int) bool { return out[i].Label+out[i].Metric < out[j].Label+out[j].Metric @@ -502,7 +502,7 @@ func metricsTransformer() cmp.Option { } func performanceDataPointComparer() cmp.Option { - return cmp.Comparer(func(x, y monitoringplugin.PerformanceDataPointInfo) bool { + return cmp.Comparer(func(x, y monitoringplugin.PerformanceDataPoint) bool { return fmt.Sprint(x) == fmt.Sprint(y) }) } diff --git a/test/testdata/devices/ios/7206VXR/test_data.json b/test/testdata/devices/ios/7206VXR/test_data.json index 300f61c..229dbef 100644 --- a/test/testdata/devices/ios/7206VXR/test_data.json +++ b/test/testdata/devices/ios/7206VXR/test_data.json @@ -633,7 +633,7 @@ { "metric": "cpu_load", "label": "", - "value": "5", + "value": 5, "unit": "%", "warn": null, "crit": null, From 36b4331f7e0dbc2e19175073d67f5dd8454b791e Mon Sep 17 00:00:00 2001 From: Toberd Date: Fri, 12 Mar 2021 16:06:58 +0100 Subject: [PATCH 06/12] Added tests for human_readable_parser.go --- core/parser/human_readable_parser.go | 4 +- core/parser/human_readable_parser_test.go | 71 +++++++++++++++++++++++ 2 files changed, 73 insertions(+), 2 deletions(-) create mode 100644 core/parser/human_readable_parser_test.go diff --git a/core/parser/human_readable_parser.go b/core/parser/human_readable_parser.go index fbbfe47..ce8ff3b 100644 --- a/core/parser/human_readable_parser.go +++ b/core/parser/human_readable_parser.go @@ -39,11 +39,11 @@ func toHumanReadable(value reflect.Value, insertion int) string { output := "(" + strconv.Itoa(value.Len()) + ") \n" for _, key := range value.MapKeys() { output += strings.Repeat(" ", insertion) - output += key.String() + ": " + output += toHumanReadable(key, insertion+1) + ": " output += toHumanReadable(value.MapIndex(key), insertion+1) output += "\n" } - return output + return "\n" + strings.Repeat(" ", insertion) + strings.TrimSpace(output) + "\n" case reflect.String: return value.String() case reflect.Int: diff --git a/core/parser/human_readable_parser_test.go b/core/parser/human_readable_parser_test.go new file mode 100644 index 0000000..81e771b --- /dev/null +++ b/core/parser/human_readable_parser_test.go @@ -0,0 +1,71 @@ +package parser + +import ( + "github.com/stretchr/testify/assert" + "testing" +) + +type TestStruct struct { + Number uint + Name string + Array []float64 +} + +func TestToHumanReadableString(t *testing.T) { + output, err := ToHumanReadable("foobla") + assert.Nil(t, err) + assert.Equal(t, "foobla", string(output)) +} + +func TestToHumanReadableFloat(t *testing.T) { + output, err := ToHumanReadable(0.1) + assert.Nil(t, err) + assert.Equal(t, "0.1", string(output)) +} + +func TestToHumanReadablePointer1(t *testing.T) { + var i uint64 + i = 2 + output, err := ToHumanReadable(&i) + assert.Nil(t, err) + assert.Equal(t, "2", string(output)) +} + +func TestToHumanReadablePointer2(t *testing.T) { + var str []string + str = nil + output, err := ToHumanReadable(&str) + assert.Nil(t, err) + assert.Equal(t, "", string(output)) +} + +func TestToHumanReadableArray(t *testing.T) { + output, err := ToHumanReadable([]string{"a", "b", "c"}) + assert.Nil(t, err) + assert.Equal(t, "[3] a b c", string(output)) +} + +func TestToHumanReadableMap1(t *testing.T) { + output, err := ToHumanReadable(map[int]string{1: "one"}) + assert.Nil(t, err) + assert.Equal(t, "(1) \n"+ + "1: one", string(output)) +} + +func TestToHumanReadableMap2(t *testing.T) { + output, err := ToHumanReadable(map[int]TestStruct{ + 1: {Number: 5}}) + assert.Nil(t, err) + assert.Equal(t, "(1) \n"+ + "1: \n"+ + " Number: 5", string(output)) +} + +func TestToHumanReadableStruct(t *testing.T) { + mystruct := TestStruct{Number: 5, Name: "MyName", Array: []float64{0.1, 0.2}} + output, err := ToHumanReadable(mystruct) + assert.Nil(t, err) + assert.Equal(t, "Number: 5\n"+ + "Name: MyName\n"+ + "Array: [2] 0.1 0.2", string(output)) +} From dee26b708ff44d7630bbd9186b0542ff283d9d2d Mon Sep 17 00:00:00 2001 From: mikameyer Date: Tue, 16 Mar 2021 10:18:54 +0100 Subject: [PATCH 07/12] added golangci and linter fixes --- .github/workflows/lint.yml | 14 ++--- .github/workflows/release.yml | 2 +- core/communicator/base.go | 3 +- core/communicator/ceraos-ip10.go | 24 ++++---- core/communicator/device_class.go | 7 +-- core/communicator/ekinops.go | 8 ++- core/network/http_client.go | 4 -- core/request/check_identify_request.go | 2 - .../request/check_identify_request_process.go | 59 +++++++++---------- test/create_testdata/script.go | 12 ++-- test/integration_test.go | 12 ++-- 11 files changed, 74 insertions(+), 73 deletions(-) diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml index 5354d9b..a61aa1b 100644 --- a/.github/workflows/lint.yml +++ b/.github/workflows/lint.yml @@ -6,13 +6,13 @@ on: - '*' jobs: - fmt: - name: fmt + golangci: + name: Lint runs-on: ubuntu-latest steps: - - uses: actions/checkout@master - - name: check - uses: grandcolline/golang-github-actions@v1.1.0 + - uses: actions/checkout@v2 + + - name: golangci-lint + uses: golangci/golangci-lint-action@v2 with: - run: fmt - token: ${{ secrets.GITHUB_TOKEN }} \ No newline at end of file + args: --disable unused \ No newline at end of file diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index b9cc733..da83e09 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -1,4 +1,4 @@ -name: GoReleaser +name: Release on: push: diff --git a/core/communicator/base.go b/core/communicator/base.go index 97bdaad..0b320cb 100644 --- a/core/communicator/base.go +++ b/core/communicator/base.go @@ -12,7 +12,8 @@ type baseCommunicator struct { type relatedNetworkDeviceCommunicators struct { head NetworkDeviceCommunicator - sub NetworkDeviceCommunicator + //nolint + sub NetworkDeviceCommunicator } func (c *baseCommunicator) GetVendor(_ context.Context) (string, error) { diff --git a/core/communicator/ceraos-ip10.go b/core/communicator/ceraos-ip10.go index f1a2f88..fa67a7a 100644 --- a/core/communicator/ceraos-ip10.go +++ b/core/communicator/ceraos-ip10.go @@ -19,13 +19,13 @@ func (c *ceraosIP10Communicator) GetIfTable(ctx context.Context) ([]device.Inter var targetInterface device.Interface - for i, inter := range subInterfaces { - ok, err := regexp.MatchString("^Ethernet #8$", *inter.IfDescr) - if err != nil { - return nil, errors.Wrap(err, "an unexpected error occurred while trying to match a regexp") - } + regex, err := regexp.Compile("^Ethernet #8$") + if err != nil { + return nil, errors.Wrap(err, "failed to build regex") + } - if ok { + for i, inter := range subInterfaces { + if regex.MatchString(*inter.IfDescr) { targetInterface = inter copy(subInterfaces[i:], subInterfaces[i+1:]) subInterfaces = subInterfaces[:len(subInterfaces)-1] @@ -33,13 +33,13 @@ func (c *ceraosIP10Communicator) GetIfTable(ctx context.Context) ([]device.Inter } } - for i := range subInterfaces { - ok, err := regexp.MatchString("^Radio Interface #[0-9]+$", *subInterfaces[i].IfDescr) - if err != nil { - return nil, errors.Wrap(err, "an unexpected error occurred while trying to match a regexp") - } + regex, err = regexp.Compile("^Radio Interface #[0-9]+$") + if err != nil { + return nil, errors.Wrap(err, "failed to build regex") + } - if ok { + for i := range subInterfaces { + if regex.MatchString(*subInterfaces[i].IfDescr) { subInterfaces[i].IfHCInOctets = targetInterface.IfHCInOctets subInterfaces[i].IfHCOutOctets = targetInterface.IfHCOutOctets subInterfaces[i].IfOperStatus = targetInterface.IfOperStatus diff --git a/core/communicator/device_class.go b/core/communicator/device_class.go index 16c304d..f262ce9 100644 --- a/core/communicator/device_class.go +++ b/core/communicator/device_class.go @@ -47,7 +47,6 @@ type deviceClass struct { config deviceClassConfig identify deviceClassIdentify components deviceClassComponents - yamlFile string parentDeviceClass *deviceClass subDeviceClasses map[string]*deviceClass tryToMatchLast bool @@ -838,15 +837,15 @@ func (d *deviceClassOIDs) validate() error { } func conditionContainsUniqueRequest(c condition) bool { - switch c.(type) { + switch c := c.(type) { case *SnmpCondition: - if c.(*SnmpCondition).Type == "snmpget" { + if c.Type == "snmpget" { return true } case *HTTPCondition: return true case *ConditionSet: - for _, con := range c.(*ConditionSet).Conditions { + for _, con := range c.Conditions { if conditionContainsUniqueRequest(con) { return true } diff --git a/core/communicator/ekinops.go b/core/communicator/ekinops.go index 698ff2e..4d1469d 100644 --- a/core/communicator/ekinops.go +++ b/core/communicator/ekinops.go @@ -76,8 +76,14 @@ func (c *ekinopsCommunicator) GetIfTable(ctx context.Context) ([]device.Interfac reader := *genericDeviceClass.components.interfaces.IfTable.(*snmpGroupPropertyReader) oids := make(deviceClassOIDs) + + regex, err := regexp.Compile("(ifIndex|ifDescr|ifType|ifName|ifAdminStatus|ifOperStatus|ifPhysAddress)") + if err != nil { + return nil, errors.Wrap(err, "failed to build regex") + } + for oid, value := range reader.oids { - if ok, err := regexp.MatchString("(ifIndex|ifDescr|ifType|ifName|ifAdminStatus|ifOperStatus|ifPhysAddress)", oid); err == nil && ok { + if regex.MatchString(oid) { oids[oid] = value } } diff --git a/core/network/http_client.go b/core/network/http_client.go index 12e65c9..76163fe 100644 --- a/core/network/http_client.go +++ b/core/network/http_client.go @@ -157,10 +157,6 @@ func (h *HTTPClient) Request(ctx context.Context, method, path, body string, hea } var response *resty.Response - response = nil - - var err error - err = nil URLStr := "https" if !h.useHTTPS { diff --git a/core/request/check_identify_request.go b/core/request/check_identify_request.go index b940ae0..cb13261 100644 --- a/core/request/check_identify_request.go +++ b/core/request/check_identify_request.go @@ -13,8 +13,6 @@ type CheckIdentifyRequest struct { CheckDeviceRequest Expectations device.Device `yaml:"expectations" json:"expectations" xml:"expectations"` - failedExpectations map[string]IdentifyExpectationResult - OsDiffWarning bool `yaml:"os_diff_warning" json:"os_diff_warning" xml:"os_diff_warning"` VendorDiffWarning bool `yaml:"vendor_diff_warning" json:"vendor_diff_warning" xml:"vendor_diff_warning"` ModelDiffWarning bool `yaml:"model_diff_warning" json:"model_diff_warning" xml:"model_diff_warning"` diff --git a/core/request/check_identify_request_process.go b/core/request/check_identify_request_process.go index eb82776..3bd4b68 100644 --- a/core/request/check_identify_request_process.go +++ b/core/request/check_identify_request_process.go @@ -13,7 +13,7 @@ import ( func (r *CheckIdentifyRequest) process(ctx context.Context) (Response, error) { r.init() - r.failedExpectations = make(map[string]IdentifyExpectationResult) + failedExpectations := make(map[string]IdentifyExpectationResult) identifyRequest := IdentifyRequest{r.BaseRequest} response, err := identifyRequest.process(ctx) @@ -25,33 +25,24 @@ func (r *CheckIdentifyRequest) process(ctx context.Context) (Response, error) { } identifyResponse := response.(*IdentifyResponse) - r.compareExpectations(identifyResponse) - return &CheckIdentifyResponse{ - CheckResponse: CheckResponse{r.mon.GetInfo()}, - IdentifyResult: &identifyResponse.Device, - FailedExpectations: r.failedExpectations, - }, nil -} - -func (r *CheckIdentifyRequest) compareExpectations(response *IdentifyResponse) { if r.Expectations.Class != "" { - r.mon.UpdateStatusIf(response.Class != r.Expectations.Class, utility.IfThenElseInt(r.OsDiffWarning, monitoringplugin.WARNING, monitoringplugin.CRITICAL), fmt.Sprintf("OS: expected: \"%s\", got: \"%s\"", r.Expectations.Class, response.Class)) + r.mon.UpdateStatusIf(identifyResponse.Class != r.Expectations.Class, utility.IfThenElseInt(r.OsDiffWarning, monitoringplugin.WARNING, monitoringplugin.CRITICAL), fmt.Sprintf("OS: expected: \"%s\", got: \"%s\"", r.Expectations.Class, identifyResponse.Class)) } if r.Expectations.Properties.Vendor != nil { var failed bool var empty bool var got string - if response.Properties.Vendor == nil { + if identifyResponse.Properties.Vendor == nil { failed = true empty = true got = "no result" - } else if *response.Properties.Vendor != *r.Expectations.Properties.Vendor { + } else if *identifyResponse.Properties.Vendor != *r.Expectations.Properties.Vendor { failed = true - got = *response.Properties.Vendor + got = *identifyResponse.Properties.Vendor } if r.mon.UpdateStatusIf(failed, utility.IfThenElseInt(r.VendorDiffWarning, monitoringplugin.WARNING, monitoringplugin.CRITICAL), fmt.Sprintf("Vendor: expected: \"%s\", got: %s", *r.Expectations.Properties.Vendor, utility.IfThenElseString(empty, got, "\""+got+"\""))) { - r.failedExpectations["vendor"] = IdentifyExpectationResult{ + failedExpectations["vendor"] = IdentifyExpectationResult{ Expected: *r.Expectations.Properties.Vendor, Got: got, } @@ -61,16 +52,16 @@ func (r *CheckIdentifyRequest) compareExpectations(response *IdentifyResponse) { var failed bool var empty bool var got string - if response.Properties.Model == nil { + if identifyResponse.Properties.Model == nil { failed = true empty = true got = "no result" - } else if *response.Properties.Model != *r.Expectations.Properties.Model { + } else if *identifyResponse.Properties.Model != *r.Expectations.Properties.Model { failed = true - got = *response.Properties.Model + got = *identifyResponse.Properties.Model } if r.mon.UpdateStatusIf(failed, utility.IfThenElseInt(r.ModelDiffWarning, monitoringplugin.WARNING, monitoringplugin.CRITICAL), fmt.Sprintf("Model: expected: \"%s\", got: %s", *r.Expectations.Properties.Model, utility.IfThenElseString(empty, got, "\""+got+"\""))) { - r.failedExpectations["model"] = IdentifyExpectationResult{ + failedExpectations["model"] = IdentifyExpectationResult{ Expected: *r.Expectations.Properties.Model, Got: got, } @@ -80,16 +71,16 @@ func (r *CheckIdentifyRequest) compareExpectations(response *IdentifyResponse) { var failed bool var empty bool var got string - if response.Properties.ModelSeries == nil { + if identifyResponse.Properties.ModelSeries == nil { failed = true empty = true got = "no result" - } else if *response.Properties.ModelSeries != *r.Expectations.Properties.ModelSeries { + } else if *identifyResponse.Properties.ModelSeries != *r.Expectations.Properties.ModelSeries { failed = true - got = *response.Properties.ModelSeries + got = *identifyResponse.Properties.ModelSeries } if r.mon.UpdateStatusIf(failed, utility.IfThenElseInt(r.ModelSeriesDiffWarning, monitoringplugin.WARNING, monitoringplugin.CRITICAL), fmt.Sprintf("ModelSeries: expected: \"%s\", got: %s", *r.Expectations.Properties.ModelSeries, utility.IfThenElseString(empty, got, "\""+got+"\""))) { - r.failedExpectations["model_series"] = IdentifyExpectationResult{ + failedExpectations["model_series"] = IdentifyExpectationResult{ Expected: *r.Expectations.Properties.ModelSeries, Got: got, } @@ -99,16 +90,16 @@ func (r *CheckIdentifyRequest) compareExpectations(response *IdentifyResponse) { var failed bool var empty bool var got string - if response.Properties.SerialNumber == nil { + if identifyResponse.Properties.SerialNumber == nil { failed = true empty = true got = "no result" - } else if *response.Properties.SerialNumber != *r.Expectations.Properties.SerialNumber { + } else if *identifyResponse.Properties.SerialNumber != *r.Expectations.Properties.SerialNumber { failed = true - got = *response.Properties.SerialNumber + got = *identifyResponse.Properties.SerialNumber } if r.mon.UpdateStatusIf(failed, utility.IfThenElseInt(r.SerialNumberDiffWarning, monitoringplugin.WARNING, monitoringplugin.CRITICAL), fmt.Sprintf("SerialNumber: expected: \"%s\", got: %s", *r.Expectations.Properties.SerialNumber, utility.IfThenElseString(empty, got, "\""+got+"\""))) { - r.failedExpectations["serial_number"] = IdentifyExpectationResult{ + failedExpectations["serial_number"] = IdentifyExpectationResult{ Expected: *r.Expectations.Properties.SerialNumber, Got: got, } @@ -118,21 +109,27 @@ func (r *CheckIdentifyRequest) compareExpectations(response *IdentifyResponse) { var failed bool var empty bool var got string - if response.Properties.OSVersion == nil { + if identifyResponse.Properties.OSVersion == nil { failed = true empty = true got = "no result" - } else if *response.Properties.OSVersion != *r.Expectations.Properties.OSVersion { + } else if *identifyResponse.Properties.OSVersion != *r.Expectations.Properties.OSVersion { failed = true - got = *response.Properties.OSVersion + got = *identifyResponse.Properties.OSVersion } if r.mon.UpdateStatusIf(failed, utility.IfThenElseInt(r.OsVersionDiffWarning, monitoringplugin.WARNING, monitoringplugin.CRITICAL), fmt.Sprintf("OSVersion: expected: \"%s\", got: %s", *r.Expectations.Properties.OSVersion, utility.IfThenElseString(empty, got, "\""+got+"\""))) { - r.failedExpectations["version"] = IdentifyExpectationResult{ + failedExpectations["version"] = IdentifyExpectationResult{ Expected: *r.Expectations.Properties.OSVersion, Got: got, } } } + + return &CheckIdentifyResponse{ + CheckResponse: CheckResponse{r.mon.GetInfo()}, + IdentifyResult: &identifyResponse.Device, + FailedExpectations: failedExpectations, + }, nil } func (r *CheckIdentifyRequest) handlePreProcessError(err error) (Response, error) { diff --git a/test/create_testdata/script.go b/test/create_testdata/script.go index 56f2787..e96c7b1 100644 --- a/test/create_testdata/script.go +++ b/test/create_testdata/script.go @@ -89,12 +89,14 @@ func buildRecursiveTestDevices(dir, relativePath string) ([]string, error) { } var subDirs []os.FileInfo files := make(map[string]string) + + regex, err := regexp.Compile(`^\..*`) + if err != nil { + return nil, errors.Wrap(err, "failed to build regex") + } + for _, f := range fileDir { - res, err := regexp.MatchString("^\\..*", f.Name()) - if err != nil { - return nil, errors.Wrap(err, "failed to match regex") - } - if !res { + if !regex.MatchString(f.Name()) { if f.IsDir() { subDirs = append(subDirs, f) } else { diff --git a/test/integration_test.go b/test/integration_test.go index 9d8481b..c8e5366 100644 --- a/test/integration_test.go +++ b/test/integration_test.go @@ -368,12 +368,14 @@ func buildRecursiveTestDevices(dir, relativePath string) ([]testDevice, error) { } var subDirs []os.FileInfo files := make(map[string]string) + + regex, err := regexp.Compile(`^\..*`) + if err != nil { + return nil, errors.Wrap(err, "failed to build regex") + } + for _, f := range fileDir { - res, err := regexp.MatchString("^\\..*", f.Name()) - if err != nil { - return nil, errors.Wrap(err, "failed to match regex") - } - if !res { + if !regex.MatchString(f.Name()) { if f.IsDir() { subDirs = append(subDirs, f) } else { From ffeac8d172921991f41e1bea6c3453dbe7fb6381 Mon Sep 17 00:00:00 2001 From: mikameyer Date: Tue, 16 Mar 2021 11:15:56 +0100 Subject: [PATCH 08/12] fix ekinops different descriptions --- core/communicator/ekinops.go | 2 +- core/communicator/ekinops_module_reader_amplifier.go | 3 ++- core/communicator/ekinops_module_reader_opm.go | 2 +- core/communicator/ekinops_module_reader_transponder.go | 2 +- 4 files changed, 5 insertions(+), 4 deletions(-) diff --git a/core/communicator/ekinops.go b/core/communicator/ekinops.go index 4d1469d..9d8df78 100644 --- a/core/communicator/ekinops.go +++ b/core/communicator/ekinops.go @@ -103,7 +103,7 @@ func ekinopsInterfacesIfIdentifierToSliceIndex(interfaces []device.Interface) (m if interf.IfName == nil { return nil, fmt.Errorf("no ifName set for interface ifIndex: `%d`", *interf.IfIndex) } - identifier := strings.Join(strings.Split(*interf.IfName, "/")[2:], "/") + identifier := strings.Split(strings.Join(strings.Split(*interf.IfName, "/")[2:], "/"), "(")[0] if _, ok := m[identifier]; ok { return nil, fmt.Errorf("interface identifier `%s` exists multiple times", *interf.IfName) diff --git a/core/communicator/ekinops_module_reader_amplifier.go b/core/communicator/ekinops_module_reader_amplifier.go index 90fc6e0..8a3db1e 100644 --- a/core/communicator/ekinops_module_reader_amplifier.go +++ b/core/communicator/ekinops_module_reader_amplifier.go @@ -7,6 +7,7 @@ import ( "github.com/inexio/thola/core/network" "github.com/pkg/errors" "strconv" + "strings" ) type ekinopsModuleReaderAmplifier struct { @@ -48,7 +49,7 @@ func (m *ekinopsModuleReaderAmplifier) readModuleMetrics(ctx context.Context, in } for i, opticalAmplifierInterface := range opticalAmplifierInterfaces { - identifier := m.slotIdentifier + "/" + m.moduleName + "/" + *opticalAmplifierInterface.Identifier + identifier := m.slotIdentifier + "/" + m.moduleName + "/" + strings.Split(*opticalAmplifierInterface.Identifier, "(")[0] idx, ok := mappings[identifier] if !ok { return nil, fmt.Errorf("interface for identifier '%s' not found", identifier) diff --git a/core/communicator/ekinops_module_reader_opm.go b/core/communicator/ekinops_module_reader_opm.go index 4496e69..dd788b0 100644 --- a/core/communicator/ekinops_module_reader_opm.go +++ b/core/communicator/ekinops_module_reader_opm.go @@ -36,7 +36,7 @@ func (m *ekinopsModuleReaderOPM8) readModuleMetrics(ctx context.Context, interfa } for i, opticalOPMInterface := range opticalOPMInterfaces { - identifier := m.slotIdentifier + "/" + m.moduleName + "/" + *opticalOPMInterface.Identifier + identifier := m.slotIdentifier + "/" + m.moduleName + "/" + strings.Split(*opticalOPMInterface.Identifier, "(")[0] idx, ok := mappings[identifier] if !ok { return nil, fmt.Errorf("interface for identifier '%s' not found", identifier) diff --git a/core/communicator/ekinops_module_reader_transponder.go b/core/communicator/ekinops_module_reader_transponder.go index 3fc9efd..ccd3a8b 100644 --- a/core/communicator/ekinops_module_reader_transponder.go +++ b/core/communicator/ekinops_module_reader_transponder.go @@ -50,7 +50,7 @@ func (m *ekinopsModuleReaderTransponder) readModuleMetrics(ctx context.Context, } for i, opticalTransponderInterface := range OpticalTransponderInterfaces { - identifier := m.slotIdentifier + "/" + m.moduleName + "/" + *opticalTransponderInterface.Identifier + identifier := m.slotIdentifier + "/" + m.moduleName + "/" + strings.Split(*opticalTransponderInterface.Identifier, "(")[0] idx, ok := mappings[identifier] if !ok { return nil, fmt.Errorf("interface for identifier '%s' not found", identifier) From b10688e0f5af05b224d7505d8353b5f608703653 Mon Sep 17 00:00:00 2001 From: mikameyer Date: Tue, 16 Mar 2021 11:18:36 +0100 Subject: [PATCH 09/12] fix lint --- core/parser/human_readable_parser_test.go | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/core/parser/human_readable_parser_test.go b/core/parser/human_readable_parser_test.go index 81e771b..6283798 100644 --- a/core/parser/human_readable_parser_test.go +++ b/core/parser/human_readable_parser_test.go @@ -24,16 +24,14 @@ func TestToHumanReadableFloat(t *testing.T) { } func TestToHumanReadablePointer1(t *testing.T) { - var i uint64 - i = 2 + var i uint64 = 2 output, err := ToHumanReadable(&i) assert.Nil(t, err) assert.Equal(t, "2", string(output)) } func TestToHumanReadablePointer2(t *testing.T) { - var str []string - str = nil + var str []string = nil output, err := ToHumanReadable(&str) assert.Nil(t, err) assert.Equal(t, "", string(output)) From c58da6f25fb4cecb8418b2a2e91f4b9dcf66683b Mon Sep 17 00:00:00 2001 From: Toberd Date: Tue, 16 Mar 2021 12:22:53 +0100 Subject: [PATCH 10/12] Added comments and changed file structure --- api/statistics/statistics.go | 6 +- core/communicator/ceraos-ip10.go | 2 + core/communicator/create.go | 4 +- core/communicator/ekinops.go | 3 + core/communicator/ios.go | 1 + core/communicator/ironware.go | 1 + .../network_device_communicator.go | 1036 ++++++++++------- core/communicator/powerone.go | 2 + 8 files changed, 598 insertions(+), 457 deletions(-) diff --git a/api/statistics/statistics.go b/api/statistics/statistics.go index e53edcf..f0a5a95 100644 --- a/api/statistics/statistics.go +++ b/api/statistics/statistics.go @@ -20,7 +20,7 @@ type statistics struct { totalResponseTime time.Duration } -// Statistics includes stats of all requests handled by the api +// Statistics includes stats of all requests handled by the api. type Statistics struct { UpSince time.Time TotalCount int @@ -41,7 +41,7 @@ func handlerFunc(h http.Handler) http.Handler { }) } -// Middleware represents an API middleware +// Middleware represents an API middleware. func Middleware() echo.MiddlewareFunc { stats.Do(func() { stats.init() @@ -66,7 +66,7 @@ func (s *statistics) add(startTime time.Time, statusCode int) { } } -// GetStatistics returns the current statistics +// GetStatistics returns the current statistics. func GetStatistics() (Statistics, error) { stats.RLock() defer stats.RUnlock() diff --git a/core/communicator/ceraos-ip10.go b/core/communicator/ceraos-ip10.go index fa67a7a..61231d1 100644 --- a/core/communicator/ceraos-ip10.go +++ b/core/communicator/ceraos-ip10.go @@ -11,6 +11,8 @@ type ceraosIP10Communicator struct { baseCommunicator } +// GetIfTable returns the ifTable of ceraos/ip10 devices. +// These devices need special behavior radio and ethernet interfaces. func (c *ceraosIP10Communicator) GetIfTable(ctx context.Context) ([]device.Interface, error) { subInterfaces, err := c.sub.GetIfTable(ctx) if err != nil { diff --git a/core/communicator/create.go b/core/communicator/create.go index 410b74d..aa9aa17 100644 --- a/core/communicator/create.go +++ b/core/communicator/create.go @@ -18,7 +18,7 @@ func CreateNetworkDeviceCommunicator(ctx context.Context, deviceClassIdentifier return createCommunicatorByDeviceClass(ctx, deviceClass) } -// IdentifyNetworkDeviceCommunicator identifies a devices and creates a network device communicator +// IdentifyNetworkDeviceCommunicator identifies a devices and creates a network device communicator. func IdentifyNetworkDeviceCommunicator(ctx context.Context) (NetworkDeviceCommunicator, error) { deviceClass, err := identifyDeviceClass(ctx) if err != nil { @@ -32,7 +32,7 @@ func IdentifyNetworkDeviceCommunicator(ctx context.Context) (NetworkDeviceCommun return com, nil } -// MatchDeviceClass checks if the device class in the context matches the given identifier +// MatchDeviceClass checks if the device class in the context matches the given identifier. func MatchDeviceClass(ctx context.Context, identifier string) (bool, error) { deviceClass, err := getDeviceClass(identifier) if err != nil { diff --git a/core/communicator/ekinops.go b/core/communicator/ekinops.go index 9d8df78..cbece41 100644 --- a/core/communicator/ekinops.go +++ b/core/communicator/ekinops.go @@ -15,6 +15,7 @@ type ekinopsCommunicator struct { baseCommunicator } +// GetInterfaces returns the interfaces of ekinops devices. func (c *ekinopsCommunicator) GetInterfaces(ctx context.Context) ([]device.Interface, error) { interfaces, err := c.GetIfTable(ctx) if err != nil { @@ -69,6 +70,8 @@ func (c *ekinopsCommunicator) GetInterfaces(ctx context.Context) ([]device.Inter return normalizeEkinopsInterfaces(interfaces) } +// GetInterfaces returns the interfaces of ekinops devices. +// For ekinops devices, only a few interface values are required. func (c *ekinopsCommunicator) GetIfTable(ctx context.Context) ([]device.Interface, error) { if genericDeviceClass.components.interfaces.IfTable == nil { return nil, errors.New("ifTable information is empty") diff --git a/core/communicator/ios.go b/core/communicator/ios.go index 612a0a4..d5a5801 100644 --- a/core/communicator/ios.go +++ b/core/communicator/ios.go @@ -11,6 +11,7 @@ type iosCommunicator struct { baseCommunicator } +// GetCPUComponentCPULoad returns the cpu load of ios devices. func (c *iosCommunicator) GetCPUComponentCPULoad(ctx context.Context) ([]float64, error) { con, ok := network.DeviceConnectionFromContext(ctx) if !ok || con.SNMP == nil { diff --git a/core/communicator/ironware.go b/core/communicator/ironware.go index 6848770..fcb766e 100644 --- a/core/communicator/ironware.go +++ b/core/communicator/ironware.go @@ -12,6 +12,7 @@ type ironwareCommunicator struct { baseCommunicator } +// GetCPUComponentCPULoad returns the cpu load of ironware devices. func (c *ironwareCommunicator) GetCPUComponentCPULoad(ctx context.Context) ([]float64, error) { con, ok := network.DeviceConnectionFromContext(ctx) if !ok || con.SNMP == nil { diff --git a/core/communicator/network_device_communicator.go b/core/communicator/network_device_communicator.go index e5934cc..9b3126a 100644 --- a/core/communicator/network_device_communicator.go +++ b/core/communicator/network_device_communicator.go @@ -9,29 +9,67 @@ import ( "math" ) -// NetworkDeviceCommunicator represents a communicator for a device +// NetworkDeviceCommunicator represents a communicator for a device. type NetworkDeviceCommunicator interface { + + // GetDeviceClass returns the device class of a network device. GetDeviceClass() string + + // GetAvailableComponents returns the components available for a network device. GetAvailableComponents() []string + + // GetIdentifyProperties returns the identify properties of a device like vendor, model... GetIdentifyProperties(ctx context.Context) (device.Properties, error) + + // GetCPUComponent returns the cpu component of a device if available. GetCPUComponent(ctx context.Context) (device.CPUComponent, error) + + // GetUPSComponent returns the ups component of a device if available. GetUPSComponent(ctx context.Context) (device.UPSComponent, error) + + // GetSBCComponent returns the sbc component of a device if available. GetSBCComponent(ctx context.Context) (device.SBCComponent, error) + + // GetServerComponent returns the sbc component of a device if available. GetServerComponent(ctx context.Context) (device.ServerComponent, error) + + // GetDiskComponent returns the disk component of a device if available. GetDiskComponent(ctx context.Context) (device.DiskComponent, error) + + // GetHardwareHealthComponent returns the hardware health component of a device if available. GetHardwareHealthComponent(ctx context.Context) (device.HardwareHealthComponent, error) + availableCommunicatorFunctions } type availableCommunicatorFunctions interface { + + // GetVendor returns the vendor of a device. GetVendor(ctx context.Context) (string, error) + + // GetModel returns the model of a device. GetModel(ctx context.Context) (string, error) + + // GetModelSeries returns the model series of a device. GetModelSeries(ctx context.Context) (string, error) + + // GetSerialNumber returns the serial number of a device. GetSerialNumber(ctx context.Context) (string, error) + + // GetOSVersion returns the os version of a device. GetOSVersion(ctx context.Context) (string, error) + + // GetIfTable returns the ifTable of a device. + // This only contains the standard ifTable values. GetIfTable(ctx context.Context) ([]device.Interface, error) + + // GetInterfaces returns the interfaces of a device. + // This includes special interface values. GetInterfaces(ctx context.Context) ([]device.Interface, error) + + // GetCountInterfaces returns the count of interfaces of a device. GetCountInterfaces(ctx context.Context) (int, error) + availableCPUCommunicatorFunctions availableMemoryCommunicatorFunctions availableUPSCommunicatorFunctions @@ -42,52 +80,110 @@ type availableCommunicatorFunctions interface { } type availableCPUCommunicatorFunctions interface { + + // GetCPUComponentCPULoad returns the cpu load of the device. GetCPUComponentCPULoad(ctx context.Context) ([]float64, error) + + // GetCPUComponentCPUTemperature returns the cpu temperature of the device. GetCPUComponentCPUTemperature(ctx context.Context) ([]float64, error) } type availableMemoryCommunicatorFunctions interface { + + // GetMemoryComponentMemoryUsage returns the memory usage of the device. GetMemoryComponentMemoryUsage(ctx context.Context) (float64, error) } +type availableDiskCommunicatorFunctions interface { + + // GetDiskComponentStorages returns the storages of the device. + GetDiskComponentStorages(ctx context.Context) ([]device.DiskComponentStorage, error) +} + type availableUPSCommunicatorFunctions interface { + + // GetUPSComponentAlarmLowVoltageDisconnect returns the low voltage disconnect alarm of the ups device. GetUPSComponentAlarmLowVoltageDisconnect(ctx context.Context) (int, error) + + // GetUPSComponentBatteryAmperage returns the battery amperage of the ups device. GetUPSComponentBatteryAmperage(ctx context.Context) (float64, error) + + // GetUPSComponentBatteryCapacity returns the battery capacity of the ups device. GetUPSComponentBatteryCapacity(ctx context.Context) (float64, error) + + // GetUPSComponentBatteryCurrent returns the current battery of the ups device. GetUPSComponentBatteryCurrent(ctx context.Context) (float64, error) + + // GetUPSComponentBatteryRemainingTime returns the battery remaining time of the ups device. GetUPSComponentBatteryRemainingTime(ctx context.Context) (float64, error) + + // GetUPSComponentBatteryTemperature returns the battery temperature of the ups device. GetUPSComponentBatteryTemperature(ctx context.Context) (float64, error) + + // GetUPSComponentBatteryVoltage returns the battery voltage of the ups device. GetUPSComponentBatteryVoltage(ctx context.Context) (float64, error) + + // GetUPSComponentCurrentLoad returns the current load of the ups device. GetUPSComponentCurrentLoad(ctx context.Context) (float64, error) + + // GetUPSComponentMainsVoltageApplied returns if the main voltage of the ups device is applied. GetUPSComponentMainsVoltageApplied(ctx context.Context) (bool, error) + + // GetUPSComponentRectifierCurrent returns the current rectifier of the ups device. GetUPSComponentRectifierCurrent(ctx context.Context) (float64, error) + + // GetUPSComponentSystemVoltage returns the system voltage of the ups device. GetUPSComponentSystemVoltage(ctx context.Context) (float64, error) } +type availableServerCommunicatorFunctions interface { + + // GetServerComponentProcs returns the process count of the device. + GetServerComponentProcs(ctx context.Context) (int, error) + + // GetServerComponentUsers returns the user count of the device. + GetServerComponentUsers(ctx context.Context) (int, error) +} + type availableSBCCommunicatorFunctions interface { + + // GetSBCComponentAgents returns the agents of the sbc device. GetSBCComponentAgents(ctx context.Context) ([]device.SBCComponentAgent, error) + + // GetSBCComponentRealms returns the realms of the sbc device. GetSBCComponentRealms(ctx context.Context) ([]device.SBCComponentRealm, error) + + // GetSBCComponentGlobalCallPerSecond returns the global calls per second of the sbc device. GetSBCComponentGlobalCallPerSecond(ctx context.Context) (int, error) + + // GetSBCComponentGlobalConcurrentSessions returns the global concurrent sessions of the sbc device. GetSBCComponentGlobalConcurrentSessions(ctx context.Context) (int, error) + + // GetSBCComponentActiveLocalContacts returns the active local contacts of the sbc device. GetSBCComponentActiveLocalContacts(ctx context.Context) (int, error) + + // GetSBCComponentTranscodingCapacity returns the transcoding capacity of the sbc device. GetSBCComponentTranscodingCapacity(ctx context.Context) (int, error) + + // GetSBCComponentLicenseCapacity returns the license capacity of the sbc device. GetSBCComponentLicenseCapacity(ctx context.Context) (int, error) - GetSBCComponentSystemRedundancy(ctx context.Context) (int, error) - GetSBCComponentSystemHealthScore(ctx context.Context) (int, error) -} -type availableServerCommunicatorFunctions interface { - GetServerComponentProcs(ctx context.Context) (int, error) - GetServerComponentUsers(ctx context.Context) (int, error) -} + // GetSBCComponentSystemRedundancy returns the system redundancy of the sbc device. + GetSBCComponentSystemRedundancy(ctx context.Context) (int, error) -type availableDiskCommunicatorFunctions interface { - GetDiskComponentStorages(ctx context.Context) ([]device.DiskComponentStorage, error) + // GetSBCComponentSystemHealthScore returns the system health score of the sbc device. + GetSBCComponentSystemHealthScore(ctx context.Context) (int, error) } type availableHardwareHealthCommunicatorFunctions interface { + + // GetHardwareHealthComponentFans returns the fans of the device. GetHardwareHealthComponentFans(ctx context.Context) ([]device.HardwareHealthComponentFan, error) + + // GetHardwareHealthComponentPowerSupply returns the power supply of the device. GetHardwareHealthComponentPowerSupply(ctx context.Context) ([]device.HardwareHealthComponentPowerSupply, error) + + // GetHardwareHealthComponentEnvironmentMonitorState returns the environment monitoring state of the device. GetHardwareHealthComponentEnvironmentMonitorState(ctx context.Context) (int, error) } @@ -156,6 +252,10 @@ func (c *networkDeviceCommunicator) executeWithRecursion(fClass, fCom, fSub adap return nil, tholaerr.NewNotFoundError("failed to get information through any device class") } +// +// Identify properties functions are defined here. +// + func (c *networkDeviceCommunicator) GetIdentifyProperties(ctx context.Context) (device.Properties, error) { dev := device.Device{ Class: c.head.GetDeviceClass(), @@ -214,6 +314,141 @@ func (c *networkDeviceCommunicator) GetIdentifyProperties(ctx context.Context) ( return dev.Properties, nil } +func (c *networkDeviceCommunicator) GetVendor(ctx context.Context) (string, error) { + fClass := newCommunicatorAdapter(c.deviceClassCommunicator).getVendor + fCom := utility.IfThenElse(c.codeCommunicator != nil, adapterFunc(newCommunicatorAdapter(c.codeCommunicator).getVendor), emptyAdapterFunc).(adapterFunc) + fSub := utility.IfThenElse(c.sub != nil, adapterFunc(newCommunicatorAdapter(c.sub).getVendor), emptyAdapterFunc).(adapterFunc) + res, err := c.executeWithRecursion(fClass, fCom, fSub, ctx) + if err != nil { + return "", err + } + s := res.(string) + if s == "" { + return "", tholaerr.NewNotFoundError("empty string returned") + } + return s, err +} + +func (c *networkDeviceCommunicator) GetModel(ctx context.Context) (string, error) { + fClass := newCommunicatorAdapter(c.deviceClassCommunicator).getModel + fCom := utility.IfThenElse(c.codeCommunicator != nil, adapterFunc(newCommunicatorAdapter(c.codeCommunicator).getModel), emptyAdapterFunc).(adapterFunc) + fSub := utility.IfThenElse(c.sub != nil, adapterFunc(newCommunicatorAdapter(c.sub).getModel), emptyAdapterFunc).(adapterFunc) + res, err := c.executeWithRecursion(fClass, fCom, fSub, ctx) + if err != nil { + return "", err + } + s := res.(string) + if s == "" { + return "", tholaerr.NewNotFoundError("empty string returned") + } + return s, err +} + +func (c *networkDeviceCommunicator) GetModelSeries(ctx context.Context) (string, error) { + fClass := newCommunicatorAdapter(c.deviceClassCommunicator).getModelSeries + fCom := utility.IfThenElse(c.codeCommunicator != nil, adapterFunc(newCommunicatorAdapter(c.codeCommunicator).getModelSeries), emptyAdapterFunc).(adapterFunc) + fSub := utility.IfThenElse(c.sub != nil, adapterFunc(newCommunicatorAdapter(c.sub).getModelSeries), emptyAdapterFunc).(adapterFunc) + res, err := c.executeWithRecursion(fClass, fCom, fSub, ctx) + if err != nil { + return "", err + } + s := res.(string) + if s == "" { + return "", tholaerr.NewNotFoundError("empty string returned") + } + return s, err +} + +func (c *networkDeviceCommunicator) GetSerialNumber(ctx context.Context) (string, error) { + fClass := newCommunicatorAdapter(c.deviceClassCommunicator).getSerialNumber + fCom := utility.IfThenElse(c.codeCommunicator != nil, adapterFunc(newCommunicatorAdapter(c.codeCommunicator).getSerialNumber), emptyAdapterFunc).(adapterFunc) + fSub := utility.IfThenElse(c.sub != nil, adapterFunc(newCommunicatorAdapter(c.sub).getSerialNumber), emptyAdapterFunc).(adapterFunc) + res, err := c.executeWithRecursion(fClass, fCom, fSub, ctx) + if err != nil { + return "", err + } + s := res.(string) + if s == "" { + return "", tholaerr.NewNotFoundError("empty string returned") + } + return s, err +} + +func (c *networkDeviceCommunicator) GetOSVersion(ctx context.Context) (string, error) { + fClass := newCommunicatorAdapter(c.deviceClassCommunicator).getOSVersion + fCom := utility.IfThenElse(c.codeCommunicator != nil, adapterFunc(newCommunicatorAdapter(c.codeCommunicator).getOSVersion), emptyAdapterFunc).(adapterFunc) + fSub := utility.IfThenElse(c.sub != nil, adapterFunc(newCommunicatorAdapter(c.sub).getOSVersion), emptyAdapterFunc).(adapterFunc) + res, err := c.executeWithRecursion(fClass, fCom, fSub, ctx) + if err != nil { + return "", err + } + s := res.(string) + if s == "" { + return "", tholaerr.NewNotFoundError("empty string returned") + } + return s, err +} + +// +// Interface component functions are defined here. +// + +func (c *networkDeviceCommunicator) GetInterfaces(ctx context.Context) ([]device.Interface, error) { + if c.isHead() && !c.deviceClassCommunicator.hasAvailableComponent(interfacesComponent) { + return []device.Interface{}, tholaerr.NewComponentNotFoundError("no interfaces component available for this device") + } + fClass := newCommunicatorAdapter(c.deviceClassCommunicator).getInterfaces + fCom := utility.IfThenElse(c.codeCommunicator != nil, adapterFunc(newCommunicatorAdapter(c.codeCommunicator).getInterfaces), emptyAdapterFunc).(adapterFunc) + fSub := utility.IfThenElse(c.sub != nil, adapterFunc(newCommunicatorAdapter(c.sub).getInterfaces), emptyAdapterFunc).(adapterFunc) + res, err := c.executeWithRecursion(fClass, fCom, fSub, ctx) + if err != nil { + return []device.Interface{}, err + } + if c.isHead() { + res = normalizeInterfaces(res.([]device.Interface)) + } + return res.([]device.Interface), err +} + +func (c *networkDeviceCommunicator) GetIfTable(ctx context.Context) ([]device.Interface, error) { + if c.isHead() && !c.deviceClassCommunicator.hasAvailableComponent(interfacesComponent) { + return []device.Interface{}, tholaerr.NewComponentNotFoundError("no interfaces component available for this device") + } + fClass := newCommunicatorAdapter(c.deviceClassCommunicator).getIfTable + fCom := utility.IfThenElse(c.codeCommunicator != nil, adapterFunc(newCommunicatorAdapter(c.codeCommunicator).getIfTable), emptyAdapterFunc).(adapterFunc) + fSub := utility.IfThenElse(c.sub != nil, adapterFunc(newCommunicatorAdapter(c.sub).getIfTable), emptyAdapterFunc).(adapterFunc) + res, err := c.executeWithRecursion(fClass, fCom, fSub, ctx) + if err != nil { + return []device.Interface{}, err + } + return res.([]device.Interface), err +} + +func (c *networkDeviceCommunicator) GetCountInterfaces(ctx context.Context) (int, error) { + fClass := newCommunicatorAdapter(c.deviceClassCommunicator).getCountInterfaces + fCom := utility.IfThenElse(c.codeCommunicator != nil, adapterFunc(newCommunicatorAdapter(c.codeCommunicator).getCountInterfaces), emptyAdapterFunc).(adapterFunc) + fSub := utility.IfThenElse(c.sub != nil, adapterFunc(newCommunicatorAdapter(c.sub).getCountInterfaces), emptyAdapterFunc).(adapterFunc) + res, err := c.executeWithRecursion(fClass, fCom, fSub, ctx) + if err != nil { + return 0, err + } + return res.(int), err +} + +func normalizeInterfaces(interfaces []device.Interface) []device.Interface { + for i, interf := range interfaces { + if interf.IfSpeed != nil && interf.IfHighSpeed != nil && *interf.IfSpeed == math.MaxUint32 { + ifSpeed := *interf.IfHighSpeed * 1000000 + interfaces[i].IfSpeed = &ifSpeed + } + } + return interfaces +} + +// +// CPU component functions are defined here. +// + func (c *networkDeviceCommunicator) GetCPUComponent(ctx context.Context) (device.CPUComponent, error) { if !c.deviceClassCommunicator.hasAvailableComponent(cpuComponent) { return device.CPUComponent{}, tholaerr.NewComponentNotFoundError("no cpu component available for this device") @@ -248,25 +483,116 @@ func (c *networkDeviceCommunicator) GetCPUComponent(ctx context.Context) (device return cpu, nil } -func (c *networkDeviceCommunicator) GetUPSComponent(ctx context.Context) (device.UPSComponent, error) { - if !c.deviceClassCommunicator.hasAvailableComponent(upsComponent) { - return device.UPSComponent{}, tholaerr.NewComponentNotFoundError("no ups component available for this device") +func (c *networkDeviceCommunicator) GetCPUComponentCPULoad(ctx context.Context) ([]float64, error) { + if !c.deviceClassCommunicator.hasAvailableComponent(cpuComponent) { + return nil, tholaerr.NewComponentNotFoundError("no cpu component available for this device") + } + fClass := newCommunicatorAdapter(c.deviceClassCommunicator).getCPULoad + fCom := utility.IfThenElse(c.codeCommunicator != nil, adapterFunc(newCommunicatorAdapter(c.codeCommunicator).getCPULoad), emptyAdapterFunc).(adapterFunc) + fSub := utility.IfThenElse(c.sub != nil, adapterFunc(newCommunicatorAdapter(c.sub).getCPULoad), emptyAdapterFunc).(adapterFunc) + res, err := c.executeWithRecursion(fClass, fCom, fSub, ctx) + if err != nil { + return nil, err } + return res.([]float64), err +} + +func (c *networkDeviceCommunicator) GetCPUComponentCPUTemperature(ctx context.Context) ([]float64, error) { + if !c.deviceClassCommunicator.hasAvailableComponent(cpuComponent) { + return nil, tholaerr.NewComponentNotFoundError("no cpu component available for this device") + } + fClass := newCommunicatorAdapter(c.deviceClassCommunicator).getCPUTemperature + fCom := utility.IfThenElse(c.codeCommunicator != nil, adapterFunc(newCommunicatorAdapter(c.codeCommunicator).getCPUTemperature), emptyAdapterFunc).(adapterFunc) + fSub := utility.IfThenElse(c.sub != nil, adapterFunc(newCommunicatorAdapter(c.sub).getCPUTemperature), emptyAdapterFunc).(adapterFunc) + res, err := c.executeWithRecursion(fClass, fCom, fSub, ctx) + if err != nil { + return nil, err + } + return res.([]float64), err +} + +// +// Memory component functions are defined here. +// + +func (c *networkDeviceCommunicator) GetMemoryComponentMemoryUsage(ctx context.Context) (float64, error) { + if c.isHead() && !c.deviceClassCommunicator.hasAvailableComponent(memoryComponent) { + return 0, tholaerr.NewComponentNotFoundError("no memory component available for this device") + } + fClass := newCommunicatorAdapter(c.deviceClassCommunicator).getMemoryUsage + fCom := utility.IfThenElse(c.codeCommunicator != nil, adapterFunc(newCommunicatorAdapter(c.codeCommunicator).getMemoryUsage), emptyAdapterFunc).(adapterFunc) + fSub := utility.IfThenElse(c.sub != nil, adapterFunc(newCommunicatorAdapter(c.sub).getMemoryUsage), emptyAdapterFunc).(adapterFunc) + res, err := c.executeWithRecursion(fClass, fCom, fSub, ctx) + if err != nil { + return 0, err + } + return res.(float64), err +} + +// +// Disk component functions are defined here. +// + +func (c *networkDeviceCommunicator) GetDiskComponent(ctx context.Context) (device.DiskComponent, error) { + if !c.deviceClassCommunicator.hasAvailableComponent(diskComponent) { + return device.DiskComponent{}, tholaerr.NewComponentNotFoundError("no disk component available for this device") + } + + var disk device.DiskComponent - var ups device.UPSComponent empty := true - alarmLowVoltage, err := c.head.GetUPSComponentAlarmLowVoltageDisconnect(ctx) + storages, err := c.head.GetDiskComponentStorages(ctx) if err != nil { if !tholaerr.IsNotFoundError(err) && !tholaerr.IsNotImplementedError(err) { - return device.UPSComponent{}, errors.Wrap(err, "error occurred during get alarm") + return device.DiskComponent{}, errors.Wrap(err, "error occurred during get disk component storages") } } else { - ups.AlarmLowVoltageDisconnect = &alarmLowVoltage + disk.Storages = storages empty = false } - batteryAmperage, err := c.head.GetUPSComponentBatteryAmperage(ctx) + if empty { + return device.DiskComponent{}, tholaerr.NewNotFoundError("no disk data available") + } + + return disk, nil +} + +func (c *networkDeviceCommunicator) GetDiskComponentStorages(ctx context.Context) ([]device.DiskComponentStorage, error) { + fClass := newCommunicatorAdapter(c.deviceClassCommunicator).getDiskComponentStorages + fCom := utility.IfThenElse(c.codeCommunicator != nil, adapterFunc(newCommunicatorAdapter(c.codeCommunicator).getDiskComponentStorages), emptyAdapterFunc).(adapterFunc) + fSub := utility.IfThenElse(c.sub != nil, adapterFunc(newCommunicatorAdapter(c.sub).getDiskComponentStorages), emptyAdapterFunc).(adapterFunc) + res, err := c.executeWithRecursion(fClass, fCom, fSub, ctx) + if err != nil { + return nil, err + } + return res.([]device.DiskComponentStorage), err +} + +// +// UPS component functions are defined here. +// + +func (c *networkDeviceCommunicator) GetUPSComponent(ctx context.Context) (device.UPSComponent, error) { + if !c.deviceClassCommunicator.hasAvailableComponent(upsComponent) { + return device.UPSComponent{}, tholaerr.NewComponentNotFoundError("no ups component available for this device") + } + + var ups device.UPSComponent + empty := true + + alarmLowVoltage, err := c.head.GetUPSComponentAlarmLowVoltageDisconnect(ctx) + if err != nil { + if !tholaerr.IsNotFoundError(err) && !tholaerr.IsNotImplementedError(err) { + return device.UPSComponent{}, errors.Wrap(err, "error occurred during get alarm") + } + } else { + ups.AlarmLowVoltageDisconnect = &alarmLowVoltage + empty = false + } + + batteryAmperage, err := c.head.GetUPSComponentBatteryAmperage(ctx) if err != nil { if !tholaerr.IsNotFoundError(err) && !tholaerr.IsNotImplementedError(err) { return device.UPSComponent{}, errors.Wrap(err, "error occurred during get battery amperage") @@ -353,435 +679,23 @@ func (c *networkDeviceCommunicator) GetUPSComponent(ctx context.Context) (device } } else { ups.RectifierCurrent = &rectifierCurrent - empty = false - } - - systemVoltage, err := c.head.GetUPSComponentSystemVoltage(ctx) - if err != nil { - if !tholaerr.IsNotFoundError(err) && !tholaerr.IsNotImplementedError(err) { - return device.UPSComponent{}, errors.Wrap(err, "error occurred during get mains voltage applied") - } - } else { - ups.SystemVoltage = &systemVoltage - empty = false - } - - if empty { - return device.UPSComponent{}, tholaerr.NewNotFoundError("no ups data available") - } - return ups, nil -} - -func (c *networkDeviceCommunicator) GetSBCComponent(ctx context.Context) (device.SBCComponent, error) { - if !c.deviceClassCommunicator.hasAvailableComponent(sbcComponent) { - return device.SBCComponent{}, tholaerr.NewComponentNotFoundError("no sbc component available for this device") - } - - var sbc device.SBCComponent - - empty := true - - agents, err := c.head.GetSBCComponentAgents(ctx) - if err != nil { - if !tholaerr.IsNotFoundError(err) && !tholaerr.IsNotImplementedError(err) { - return device.SBCComponent{}, errors.Wrap(err, "error occurred during get sbc component agents") - } - } else { - sbc.Agents = agents - empty = false - } - - realms, err := c.head.GetSBCComponentRealms(ctx) - if err != nil { - if !tholaerr.IsNotFoundError(err) && !tholaerr.IsNotImplementedError(err) { - return device.SBCComponent{}, errors.Wrap(err, "error occurred during get sbc component realms") - } - } else { - sbc.Realms = realms - empty = false - } - - globalCPS, err := c.head.GetSBCComponentGlobalCallPerSecond(ctx) - if err != nil { - if !tholaerr.IsNotFoundError(err) && !tholaerr.IsNotImplementedError(err) { - return device.SBCComponent{}, errors.Wrap(err, "error occurred during get sbc component sbc global call per second") - } - } else { - sbc.GlobalCallPerSecond = &globalCPS - empty = false - } - - globalConcurrentSessions, err := c.head.GetSBCComponentGlobalConcurrentSessions(ctx) - if err != nil { - if !tholaerr.IsNotFoundError(err) && !tholaerr.IsNotImplementedError(err) { - return device.SBCComponent{}, errors.Wrap(err, "error occurred during get sbc global concurrent sessions") - } - } else { - sbc.GlobalConcurrentSessions = &globalConcurrentSessions - empty = false - } - - activeLocalContacts, err := c.head.GetSBCComponentActiveLocalContacts(ctx) - if err != nil { - if !tholaerr.IsNotFoundError(err) && !tholaerr.IsNotImplementedError(err) { - return device.SBCComponent{}, errors.Wrap(err, "error occurred during get active local contacts") - } - } else { - sbc.ActiveLocalContacts = &activeLocalContacts - empty = false - } - - transcodingCapacity, err := c.head.GetSBCComponentTranscodingCapacity(ctx) - if err != nil { - if !tholaerr.IsNotFoundError(err) && !tholaerr.IsNotImplementedError(err) { - return device.SBCComponent{}, errors.Wrap(err, "error occurred during get transcoding capacity") - } - } else { - sbc.TranscodingCapacity = &transcodingCapacity - empty = false - } - - licenseCapacity, err := c.head.GetSBCComponentLicenseCapacity(ctx) - if err != nil { - if !tholaerr.IsNotFoundError(err) && !tholaerr.IsNotImplementedError(err) { - return device.SBCComponent{}, errors.Wrap(err, "error occurred during get license capacity") - } - } else { - sbc.LicenseCapacity = &licenseCapacity - empty = false - } - - systemRedundancy, err := c.head.GetSBCComponentSystemRedundancy(ctx) - if err != nil { - if !tholaerr.IsNotFoundError(err) && !tholaerr.IsNotImplementedError(err) { - return device.SBCComponent{}, errors.Wrap(err, "error occurred during get system redundancy") - } - } else { - sbc.SystemRedundancy = &systemRedundancy - empty = false - } - - systemHealthScore, err := c.head.GetSBCComponentSystemHealthScore(ctx) - if err != nil { - if !tholaerr.IsNotFoundError(err) && !tholaerr.IsNotImplementedError(err) { - return device.SBCComponent{}, errors.Wrap(err, "error occurred during get system health score") - } - } else { - sbc.SystemHealthScore = &systemHealthScore - empty = false - } - - if empty { - return device.SBCComponent{}, tholaerr.NewNotFoundError("no sbc data available") - } - - return sbc, nil -} - -func (c *networkDeviceCommunicator) GetServerComponent(ctx context.Context) (device.ServerComponent, error) { - if !c.deviceClassCommunicator.hasAvailableComponent(serverComponent) { - return device.ServerComponent{}, tholaerr.NewComponentNotFoundError("no server component available for this device") - } - - var server device.ServerComponent - - empty := true - - procs, err := c.head.GetServerComponentProcs(ctx) - if err != nil { - if !tholaerr.IsNotFoundError(err) && !tholaerr.IsNotImplementedError(err) { - return device.ServerComponent{}, errors.Wrap(err, "error occurred during get server component procs") - } - } else { - server.Procs = &procs - empty = false - } - - users, err := c.head.GetServerComponentUsers(ctx) - if err != nil { - if !tholaerr.IsNotFoundError(err) && !tholaerr.IsNotImplementedError(err) { - return device.ServerComponent{}, errors.Wrap(err, "error occurred during get server component users") - } - } else { - server.Users = &users - empty = false - } - - if empty { - return device.ServerComponent{}, tholaerr.NewNotFoundError("no server data available") - } - - return server, nil -} - -func (c *networkDeviceCommunicator) GetDiskComponent(ctx context.Context) (device.DiskComponent, error) { - if !c.deviceClassCommunicator.hasAvailableComponent(diskComponent) { - return device.DiskComponent{}, tholaerr.NewComponentNotFoundError("no disk component available for this device") - } - - var disk device.DiskComponent - - empty := true - - storages, err := c.head.GetDiskComponentStorages(ctx) - if err != nil { - if !tholaerr.IsNotFoundError(err) && !tholaerr.IsNotImplementedError(err) { - return device.DiskComponent{}, errors.Wrap(err, "error occurred during get disk component storages") - } - } else { - disk.Storages = storages - empty = false - } - - if empty { - return device.DiskComponent{}, tholaerr.NewNotFoundError("no disk data available") - } - - return disk, nil -} - -func (c *networkDeviceCommunicator) GetHardwareHealthComponent(ctx context.Context) (device.HardwareHealthComponent, error) { - if !c.deviceClassCommunicator.hasAvailableComponent(hardwareHealthComponent) { - return device.HardwareHealthComponent{}, tholaerr.NewComponentNotFoundError("no hardware health component available for this device") - } - - var hardwareHealth device.HardwareHealthComponent - - empty := true - - state, err := c.head.GetHardwareHealthComponentEnvironmentMonitorState(ctx) - if err != nil { - if !tholaerr.IsNotFoundError(err) && !tholaerr.IsNotImplementedError(err) { - return device.HardwareHealthComponent{}, errors.Wrap(err, "error occurred during get environment monitor states") - } - } else { - hardwareHealth.EnvironmentMonitorState = &state - empty = false - } - - fans, err := c.head.GetHardwareHealthComponentFans(ctx) - if err != nil { - if !tholaerr.IsNotFoundError(err) && !tholaerr.IsNotImplementedError(err) { - return device.HardwareHealthComponent{}, errors.Wrap(err, "error occurred during get fans") - } - } else { - hardwareHealth.Fans = fans - empty = false - } - - powerSupply, err := c.head.GetHardwareHealthComponentPowerSupply(ctx) - if err != nil { - if !tholaerr.IsNotFoundError(err) && !tholaerr.IsNotImplementedError(err) { - return device.HardwareHealthComponent{}, errors.Wrap(err, "error occurred during get sbc component sbc global call per second") - } - } else { - hardwareHealth.PowerSupply = powerSupply - empty = false - } - - if empty { - return device.HardwareHealthComponent{}, tholaerr.NewNotFoundError("no sbc data available") - } - - return hardwareHealth, nil -} - -func (c *networkDeviceCommunicator) GetVendor(ctx context.Context) (string, error) { - fClass := newCommunicatorAdapter(c.deviceClassCommunicator).getVendor - fCom := utility.IfThenElse(c.codeCommunicator != nil, adapterFunc(newCommunicatorAdapter(c.codeCommunicator).getVendor), emptyAdapterFunc).(adapterFunc) - fSub := utility.IfThenElse(c.sub != nil, adapterFunc(newCommunicatorAdapter(c.sub).getVendor), emptyAdapterFunc).(adapterFunc) - res, err := c.executeWithRecursion(fClass, fCom, fSub, ctx) - if err != nil { - return "", err - } - s := res.(string) - if s == "" { - return "", tholaerr.NewNotFoundError("empty string returned") - } - return s, err -} - -func (c *networkDeviceCommunicator) GetModel(ctx context.Context) (string, error) { - fClass := newCommunicatorAdapter(c.deviceClassCommunicator).getModel - fCom := utility.IfThenElse(c.codeCommunicator != nil, adapterFunc(newCommunicatorAdapter(c.codeCommunicator).getModel), emptyAdapterFunc).(adapterFunc) - fSub := utility.IfThenElse(c.sub != nil, adapterFunc(newCommunicatorAdapter(c.sub).getModel), emptyAdapterFunc).(adapterFunc) - res, err := c.executeWithRecursion(fClass, fCom, fSub, ctx) - if err != nil { - return "", err - } - s := res.(string) - if s == "" { - return "", tholaerr.NewNotFoundError("empty string returned") - } - return s, err -} - -func (c *networkDeviceCommunicator) GetModelSeries(ctx context.Context) (string, error) { - fClass := newCommunicatorAdapter(c.deviceClassCommunicator).getModelSeries - fCom := utility.IfThenElse(c.codeCommunicator != nil, adapterFunc(newCommunicatorAdapter(c.codeCommunicator).getModelSeries), emptyAdapterFunc).(adapterFunc) - fSub := utility.IfThenElse(c.sub != nil, adapterFunc(newCommunicatorAdapter(c.sub).getModelSeries), emptyAdapterFunc).(adapterFunc) - res, err := c.executeWithRecursion(fClass, fCom, fSub, ctx) - if err != nil { - return "", err - } - s := res.(string) - if s == "" { - return "", tholaerr.NewNotFoundError("empty string returned") - } - return s, err -} - -func (c *networkDeviceCommunicator) GetSerialNumber(ctx context.Context) (string, error) { - fClass := newCommunicatorAdapter(c.deviceClassCommunicator).getSerialNumber - fCom := utility.IfThenElse(c.codeCommunicator != nil, adapterFunc(newCommunicatorAdapter(c.codeCommunicator).getSerialNumber), emptyAdapterFunc).(adapterFunc) - fSub := utility.IfThenElse(c.sub != nil, adapterFunc(newCommunicatorAdapter(c.sub).getSerialNumber), emptyAdapterFunc).(adapterFunc) - res, err := c.executeWithRecursion(fClass, fCom, fSub, ctx) - if err != nil { - return "", err - } - s := res.(string) - if s == "" { - return "", tholaerr.NewNotFoundError("empty string returned") - } - return s, err -} - -func (c *networkDeviceCommunicator) GetOSVersion(ctx context.Context) (string, error) { - fClass := newCommunicatorAdapter(c.deviceClassCommunicator).getOSVersion - fCom := utility.IfThenElse(c.codeCommunicator != nil, adapterFunc(newCommunicatorAdapter(c.codeCommunicator).getOSVersion), emptyAdapterFunc).(adapterFunc) - fSub := utility.IfThenElse(c.sub != nil, adapterFunc(newCommunicatorAdapter(c.sub).getOSVersion), emptyAdapterFunc).(adapterFunc) - res, err := c.executeWithRecursion(fClass, fCom, fSub, ctx) - if err != nil { - return "", err - } - s := res.(string) - if s == "" { - return "", tholaerr.NewNotFoundError("empty string returned") - } - return s, err -} - -func (c *networkDeviceCommunicator) GetInterfaces(ctx context.Context) ([]device.Interface, error) { - if c.isHead() && !c.deviceClassCommunicator.hasAvailableComponent(interfacesComponent) { - return []device.Interface{}, tholaerr.NewComponentNotFoundError("no interfaces component available for this device") - } - fClass := newCommunicatorAdapter(c.deviceClassCommunicator).getInterfaces - fCom := utility.IfThenElse(c.codeCommunicator != nil, adapterFunc(newCommunicatorAdapter(c.codeCommunicator).getInterfaces), emptyAdapterFunc).(adapterFunc) - fSub := utility.IfThenElse(c.sub != nil, adapterFunc(newCommunicatorAdapter(c.sub).getInterfaces), emptyAdapterFunc).(adapterFunc) - res, err := c.executeWithRecursion(fClass, fCom, fSub, ctx) - if err != nil { - return []device.Interface{}, err - } - if c.isHead() { - res = normalizeInterfaces(res.([]device.Interface)) - } - return res.([]device.Interface), err -} - -func (c *networkDeviceCommunicator) GetIfTable(ctx context.Context) ([]device.Interface, error) { - if c.isHead() && !c.deviceClassCommunicator.hasAvailableComponent(interfacesComponent) { - return []device.Interface{}, tholaerr.NewComponentNotFoundError("no interfaces component available for this device") - } - fClass := newCommunicatorAdapter(c.deviceClassCommunicator).getIfTable - fCom := utility.IfThenElse(c.codeCommunicator != nil, adapterFunc(newCommunicatorAdapter(c.codeCommunicator).getIfTable), emptyAdapterFunc).(adapterFunc) - fSub := utility.IfThenElse(c.sub != nil, adapterFunc(newCommunicatorAdapter(c.sub).getIfTable), emptyAdapterFunc).(adapterFunc) - res, err := c.executeWithRecursion(fClass, fCom, fSub, ctx) - if err != nil { - return []device.Interface{}, err - } - return res.([]device.Interface), err -} - -func (c *networkDeviceCommunicator) GetCountInterfaces(ctx context.Context) (int, error) { - fClass := newCommunicatorAdapter(c.deviceClassCommunicator).getCountInterfaces - fCom := utility.IfThenElse(c.codeCommunicator != nil, adapterFunc(newCommunicatorAdapter(c.codeCommunicator).getCountInterfaces), emptyAdapterFunc).(adapterFunc) - fSub := utility.IfThenElse(c.sub != nil, adapterFunc(newCommunicatorAdapter(c.sub).getCountInterfaces), emptyAdapterFunc).(adapterFunc) - res, err := c.executeWithRecursion(fClass, fCom, fSub, ctx) - if err != nil { - return 0, err - } - return res.(int), err -} - -func (c *networkDeviceCommunicator) GetCPUComponentCPULoad(ctx context.Context) ([]float64, error) { - if !c.deviceClassCommunicator.hasAvailableComponent(cpuComponent) { - return nil, tholaerr.NewComponentNotFoundError("no cpu component available for this device") - } - fClass := newCommunicatorAdapter(c.deviceClassCommunicator).getCPULoad - fCom := utility.IfThenElse(c.codeCommunicator != nil, adapterFunc(newCommunicatorAdapter(c.codeCommunicator).getCPULoad), emptyAdapterFunc).(adapterFunc) - fSub := utility.IfThenElse(c.sub != nil, adapterFunc(newCommunicatorAdapter(c.sub).getCPULoad), emptyAdapterFunc).(adapterFunc) - res, err := c.executeWithRecursion(fClass, fCom, fSub, ctx) - if err != nil { - return nil, err - } - return res.([]float64), err -} - -func (c *networkDeviceCommunicator) GetCPUComponentCPUTemperature(ctx context.Context) ([]float64, error) { - if !c.deviceClassCommunicator.hasAvailableComponent(cpuComponent) { - return nil, tholaerr.NewComponentNotFoundError("no cpu component available for this device") - } - fClass := newCommunicatorAdapter(c.deviceClassCommunicator).getCPUTemperature - fCom := utility.IfThenElse(c.codeCommunicator != nil, adapterFunc(newCommunicatorAdapter(c.codeCommunicator).getCPUTemperature), emptyAdapterFunc).(adapterFunc) - fSub := utility.IfThenElse(c.sub != nil, adapterFunc(newCommunicatorAdapter(c.sub).getCPUTemperature), emptyAdapterFunc).(adapterFunc) - res, err := c.executeWithRecursion(fClass, fCom, fSub, ctx) - if err != nil { - return nil, err - } - return res.([]float64), err -} - -func (c *networkDeviceCommunicator) GetMemoryComponentMemoryUsage(ctx context.Context) (float64, error) { - if c.isHead() && !c.deviceClassCommunicator.hasAvailableComponent(memoryComponent) { - return 0, tholaerr.NewComponentNotFoundError("no memory component available for this device") - } - fClass := newCommunicatorAdapter(c.deviceClassCommunicator).getMemoryUsage - fCom := utility.IfThenElse(c.codeCommunicator != nil, adapterFunc(newCommunicatorAdapter(c.codeCommunicator).getMemoryUsage), emptyAdapterFunc).(adapterFunc) - fSub := utility.IfThenElse(c.sub != nil, adapterFunc(newCommunicatorAdapter(c.sub).getMemoryUsage), emptyAdapterFunc).(adapterFunc) - res, err := c.executeWithRecursion(fClass, fCom, fSub, ctx) - if err != nil { - return 0, err - } - return res.(float64), err -} - -func (c *networkDeviceCommunicator) GetServerComponentProcs(ctx context.Context) (int, error) { - if !c.deviceClassCommunicator.hasAvailableComponent(serverComponent) { - return 0, tholaerr.NewComponentNotFoundError("no server component available for this device") - } - fClass := newCommunicatorAdapter(c.deviceClassCommunicator).getServerProcs - fCom := utility.IfThenElse(c.codeCommunicator != nil, adapterFunc(newCommunicatorAdapter(c.codeCommunicator).getServerProcs), emptyAdapterFunc).(adapterFunc) - fSub := utility.IfThenElse(c.sub != nil, adapterFunc(newCommunicatorAdapter(c.sub).getServerProcs), emptyAdapterFunc).(adapterFunc) - res, err := c.executeWithRecursion(fClass, fCom, fSub, ctx) - if err != nil { - return 0, err - } - return res.(int), err -} - -func (c *networkDeviceCommunicator) GetServerComponentUsers(ctx context.Context) (int, error) { - if !c.deviceClassCommunicator.hasAvailableComponent(serverComponent) { - return 0, tholaerr.NewComponentNotFoundError("no server component available for this device") + empty = false } - fClass := newCommunicatorAdapter(c.deviceClassCommunicator).getServerUsers - fCom := utility.IfThenElse(c.codeCommunicator != nil, adapterFunc(newCommunicatorAdapter(c.codeCommunicator).getServerUsers), emptyAdapterFunc).(adapterFunc) - fSub := utility.IfThenElse(c.sub != nil, adapterFunc(newCommunicatorAdapter(c.sub).getServerUsers), emptyAdapterFunc).(adapterFunc) - res, err := c.executeWithRecursion(fClass, fCom, fSub, ctx) + + systemVoltage, err := c.head.GetUPSComponentSystemVoltage(ctx) if err != nil { - return 0, err + if !tholaerr.IsNotFoundError(err) && !tholaerr.IsNotImplementedError(err) { + return device.UPSComponent{}, errors.Wrap(err, "error occurred during get mains voltage applied") + } + } else { + ups.SystemVoltage = &systemVoltage + empty = false } - return res.(int), err -} -func (c *networkDeviceCommunicator) GetDiskComponentStorages(ctx context.Context) ([]device.DiskComponentStorage, error) { - fClass := newCommunicatorAdapter(c.deviceClassCommunicator).getDiskComponentStorages - fCom := utility.IfThenElse(c.codeCommunicator != nil, adapterFunc(newCommunicatorAdapter(c.codeCommunicator).getDiskComponentStorages), emptyAdapterFunc).(adapterFunc) - fSub := utility.IfThenElse(c.sub != nil, adapterFunc(newCommunicatorAdapter(c.sub).getDiskComponentStorages), emptyAdapterFunc).(adapterFunc) - res, err := c.executeWithRecursion(fClass, fCom, fSub, ctx) - if err != nil { - return nil, err + if empty { + return device.UPSComponent{}, tholaerr.NewNotFoundError("no ups data available") } - return res.([]device.DiskComponentStorage), err + return ups, nil } func (c *networkDeviceCommunicator) GetUPSComponentAlarmLowVoltageDisconnect(ctx context.Context) (int, error) { @@ -905,6 +819,184 @@ func (c *networkDeviceCommunicator) GetUPSComponentSystemVoltage(ctx context.Con return res.(float64), err } +// +// Server component functions are defined here. +// + +func (c *networkDeviceCommunicator) GetServerComponent(ctx context.Context) (device.ServerComponent, error) { + if !c.deviceClassCommunicator.hasAvailableComponent(serverComponent) { + return device.ServerComponent{}, tholaerr.NewComponentNotFoundError("no server component available for this device") + } + + var server device.ServerComponent + + empty := true + + procs, err := c.head.GetServerComponentProcs(ctx) + if err != nil { + if !tholaerr.IsNotFoundError(err) && !tholaerr.IsNotImplementedError(err) { + return device.ServerComponent{}, errors.Wrap(err, "error occurred during get server component procs") + } + } else { + server.Procs = &procs + empty = false + } + + users, err := c.head.GetServerComponentUsers(ctx) + if err != nil { + if !tholaerr.IsNotFoundError(err) && !tholaerr.IsNotImplementedError(err) { + return device.ServerComponent{}, errors.Wrap(err, "error occurred during get server component users") + } + } else { + server.Users = &users + empty = false + } + + if empty { + return device.ServerComponent{}, tholaerr.NewNotFoundError("no server data available") + } + + return server, nil +} + +func (c *networkDeviceCommunicator) GetServerComponentProcs(ctx context.Context) (int, error) { + if !c.deviceClassCommunicator.hasAvailableComponent(serverComponent) { + return 0, tholaerr.NewComponentNotFoundError("no server component available for this device") + } + fClass := newCommunicatorAdapter(c.deviceClassCommunicator).getServerProcs + fCom := utility.IfThenElse(c.codeCommunicator != nil, adapterFunc(newCommunicatorAdapter(c.codeCommunicator).getServerProcs), emptyAdapterFunc).(adapterFunc) + fSub := utility.IfThenElse(c.sub != nil, adapterFunc(newCommunicatorAdapter(c.sub).getServerProcs), emptyAdapterFunc).(adapterFunc) + res, err := c.executeWithRecursion(fClass, fCom, fSub, ctx) + if err != nil { + return 0, err + } + return res.(int), err +} + +func (c *networkDeviceCommunicator) GetServerComponentUsers(ctx context.Context) (int, error) { + if !c.deviceClassCommunicator.hasAvailableComponent(serverComponent) { + return 0, tholaerr.NewComponentNotFoundError("no server component available for this device") + } + fClass := newCommunicatorAdapter(c.deviceClassCommunicator).getServerUsers + fCom := utility.IfThenElse(c.codeCommunicator != nil, adapterFunc(newCommunicatorAdapter(c.codeCommunicator).getServerUsers), emptyAdapterFunc).(adapterFunc) + fSub := utility.IfThenElse(c.sub != nil, adapterFunc(newCommunicatorAdapter(c.sub).getServerUsers), emptyAdapterFunc).(adapterFunc) + res, err := c.executeWithRecursion(fClass, fCom, fSub, ctx) + if err != nil { + return 0, err + } + return res.(int), err +} + +// +// SBC component functions are defined here. +// + +func (c *networkDeviceCommunicator) GetSBCComponent(ctx context.Context) (device.SBCComponent, error) { + if !c.deviceClassCommunicator.hasAvailableComponent(sbcComponent) { + return device.SBCComponent{}, tholaerr.NewComponentNotFoundError("no sbc component available for this device") + } + + var sbc device.SBCComponent + + empty := true + + agents, err := c.head.GetSBCComponentAgents(ctx) + if err != nil { + if !tholaerr.IsNotFoundError(err) && !tholaerr.IsNotImplementedError(err) { + return device.SBCComponent{}, errors.Wrap(err, "error occurred during get sbc component agents") + } + } else { + sbc.Agents = agents + empty = false + } + + realms, err := c.head.GetSBCComponentRealms(ctx) + if err != nil { + if !tholaerr.IsNotFoundError(err) && !tholaerr.IsNotImplementedError(err) { + return device.SBCComponent{}, errors.Wrap(err, "error occurred during get sbc component realms") + } + } else { + sbc.Realms = realms + empty = false + } + + globalCPS, err := c.head.GetSBCComponentGlobalCallPerSecond(ctx) + if err != nil { + if !tholaerr.IsNotFoundError(err) && !tholaerr.IsNotImplementedError(err) { + return device.SBCComponent{}, errors.Wrap(err, "error occurred during get sbc component sbc global call per second") + } + } else { + sbc.GlobalCallPerSecond = &globalCPS + empty = false + } + + globalConcurrentSessions, err := c.head.GetSBCComponentGlobalConcurrentSessions(ctx) + if err != nil { + if !tholaerr.IsNotFoundError(err) && !tholaerr.IsNotImplementedError(err) { + return device.SBCComponent{}, errors.Wrap(err, "error occurred during get sbc global concurrent sessions") + } + } else { + sbc.GlobalConcurrentSessions = &globalConcurrentSessions + empty = false + } + + activeLocalContacts, err := c.head.GetSBCComponentActiveLocalContacts(ctx) + if err != nil { + if !tholaerr.IsNotFoundError(err) && !tholaerr.IsNotImplementedError(err) { + return device.SBCComponent{}, errors.Wrap(err, "error occurred during get active local contacts") + } + } else { + sbc.ActiveLocalContacts = &activeLocalContacts + empty = false + } + + transcodingCapacity, err := c.head.GetSBCComponentTranscodingCapacity(ctx) + if err != nil { + if !tholaerr.IsNotFoundError(err) && !tholaerr.IsNotImplementedError(err) { + return device.SBCComponent{}, errors.Wrap(err, "error occurred during get transcoding capacity") + } + } else { + sbc.TranscodingCapacity = &transcodingCapacity + empty = false + } + + licenseCapacity, err := c.head.GetSBCComponentLicenseCapacity(ctx) + if err != nil { + if !tholaerr.IsNotFoundError(err) && !tholaerr.IsNotImplementedError(err) { + return device.SBCComponent{}, errors.Wrap(err, "error occurred during get license capacity") + } + } else { + sbc.LicenseCapacity = &licenseCapacity + empty = false + } + + systemRedundancy, err := c.head.GetSBCComponentSystemRedundancy(ctx) + if err != nil { + if !tholaerr.IsNotFoundError(err) && !tholaerr.IsNotImplementedError(err) { + return device.SBCComponent{}, errors.Wrap(err, "error occurred during get system redundancy") + } + } else { + sbc.SystemRedundancy = &systemRedundancy + empty = false + } + + systemHealthScore, err := c.head.GetSBCComponentSystemHealthScore(ctx) + if err != nil { + if !tholaerr.IsNotFoundError(err) && !tholaerr.IsNotImplementedError(err) { + return device.SBCComponent{}, errors.Wrap(err, "error occurred during get system health score") + } + } else { + sbc.SystemHealthScore = &systemHealthScore + empty = false + } + + if empty { + return device.SBCComponent{}, tholaerr.NewNotFoundError("no sbc data available") + } + + return sbc, nil +} + func (c *networkDeviceCommunicator) GetSBCComponentAgents(ctx context.Context) ([]device.SBCComponentAgent, error) { fClass := newCommunicatorAdapter(c.deviceClassCommunicator).getSBCComponentAgents fCom := utility.IfThenElse(c.codeCommunicator != nil, adapterFunc(newCommunicatorAdapter(c.codeCommunicator).getSBCComponentAgents), emptyAdapterFunc).(adapterFunc) @@ -1004,6 +1096,56 @@ func (c *networkDeviceCommunicator) GetSBCComponentSystemHealthScore(ctx context return res.(int), err } +// +// Hardware health component functions are defined here. +// + +func (c *networkDeviceCommunicator) GetHardwareHealthComponent(ctx context.Context) (device.HardwareHealthComponent, error) { + if !c.deviceClassCommunicator.hasAvailableComponent(hardwareHealthComponent) { + return device.HardwareHealthComponent{}, tholaerr.NewComponentNotFoundError("no hardware health component available for this device") + } + + var hardwareHealth device.HardwareHealthComponent + + empty := true + + state, err := c.head.GetHardwareHealthComponentEnvironmentMonitorState(ctx) + if err != nil { + if !tholaerr.IsNotFoundError(err) && !tholaerr.IsNotImplementedError(err) { + return device.HardwareHealthComponent{}, errors.Wrap(err, "error occurred during get environment monitor states") + } + } else { + hardwareHealth.EnvironmentMonitorState = &state + empty = false + } + + fans, err := c.head.GetHardwareHealthComponentFans(ctx) + if err != nil { + if !tholaerr.IsNotFoundError(err) && !tholaerr.IsNotImplementedError(err) { + return device.HardwareHealthComponent{}, errors.Wrap(err, "error occurred during get fans") + } + } else { + hardwareHealth.Fans = fans + empty = false + } + + powerSupply, err := c.head.GetHardwareHealthComponentPowerSupply(ctx) + if err != nil { + if !tholaerr.IsNotFoundError(err) && !tholaerr.IsNotImplementedError(err) { + return device.HardwareHealthComponent{}, errors.Wrap(err, "error occurred during get sbc component sbc global call per second") + } + } else { + hardwareHealth.PowerSupply = powerSupply + empty = false + } + + if empty { + return device.HardwareHealthComponent{}, tholaerr.NewNotFoundError("no sbc data available") + } + + return hardwareHealth, nil +} + func (c *networkDeviceCommunicator) GetHardwareHealthComponentEnvironmentMonitorState(ctx context.Context) (int, error) { fClass := newCommunicatorAdapter(c.deviceClassCommunicator).getHardwareHealthComponentEnvironmentMonitorState fCom := utility.IfThenElse(c.codeCommunicator != nil, adapterFunc(newCommunicatorAdapter(c.codeCommunicator).getHardwareHealthComponentEnvironmentMonitorState), emptyAdapterFunc).(adapterFunc) @@ -1040,13 +1182,3 @@ func (c *networkDeviceCommunicator) GetHardwareHealthComponentPowerSupply(ctx co func (c *networkDeviceCommunicator) isHead() bool { return c.head.GetDeviceClass() == c.GetDeviceClass() } - -func normalizeInterfaces(interfaces []device.Interface) []device.Interface { - for i, interf := range interfaces { - if interf.IfSpeed != nil && interf.IfHighSpeed != nil && *interf.IfSpeed == math.MaxUint32 { - ifSpeed := *interf.IfHighSpeed * 1000000 - interfaces[i].IfSpeed = &ifSpeed - } - } - return interfaces -} diff --git a/core/communicator/powerone.go b/core/communicator/powerone.go index c2bef66..5d3eda6 100644 --- a/core/communicator/powerone.go +++ b/core/communicator/powerone.go @@ -15,10 +15,12 @@ type poweronePCCCommunicator struct { baseCommunicator } +// GetUPSComponentMainsVoltageApplied returns the ups state of powerone/acc devices. func (c *poweroneACCCommunicator) GetUPSComponentMainsVoltageApplied(ctx context.Context) (bool, error) { return getPoweroneMainsVoltageApplied(ctx, ".1.3.6.1.4.1.5961.4.3.2.0") } +// GetUPSComponentMainsVoltageApplied returns the ups state of powerone/pcc devices. func (c *poweronePCCCommunicator) GetUPSComponentMainsVoltageApplied(ctx context.Context) (bool, error) { return getPoweroneMainsVoltageApplied(ctx, ".1.3.6.1.4.1.5961.3.3.2.0") } From 135038b6e9d86bb88759f8cab829093dc08e519a Mon Sep 17 00:00:00 2001 From: mikameyer Date: Wed, 17 Mar 2021 08:32:51 +0100 Subject: [PATCH 11/12] version bump --- doc/doc.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/doc/doc.go b/doc/doc.go index 0e90d5e..9bebe9b 100644 --- a/doc/doc.go +++ b/doc/doc.go @@ -27,4 +27,4 @@ // swagger:meta package doc -const Version = "v0.2.2" +const Version = "v0.2.3" From 2f25225ec92db2a7b1e7969f3db3f51362e3f717 Mon Sep 17 00:00:00 2001 From: mikameyer Date: Wed, 17 Mar 2021 08:49:57 +0100 Subject: [PATCH 12/12] bump echo version --- go.mod | 2 +- go.sum | 2 ++ 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/go.mod b/go.mod index bccc9db..b0a1a54 100644 --- a/go.mod +++ b/go.mod @@ -12,7 +12,7 @@ require ( github.com/huandu/go-sqlbuilder v1.8.0 github.com/inexio/go-monitoringplugin v1.0.4 github.com/jmoiron/sqlx v1.2.0 - github.com/labstack/echo/v4 v4.2.0 + github.com/labstack/echo/v4 v4.2.1 github.com/mitchellh/colorstring v0.0.0-20190213212951-d06e56a500db github.com/mitchellh/mapstructure v1.3.3 github.com/pkg/errors v0.9.1 diff --git a/go.sum b/go.sum index 92bd235..526b8ee 100644 --- a/go.sum +++ b/go.sum @@ -180,6 +180,8 @@ github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE= github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= github.com/labstack/echo/v4 v4.2.0 h1:jkCSsjXmBmapVXF6U4BrSz/cgofWM0CU3Q74wQvXkIc= github.com/labstack/echo/v4 v4.2.0/go.mod h1:AA49e0DZ8kk5jTOOCKNuPR6oTnBS0dYiM4FW1e6jwpg= +github.com/labstack/echo/v4 v4.2.1 h1:LF5Iq7t/jrtUuSutNuiEWtB5eiHfZ5gSe2pcu5exjQw= +github.com/labstack/echo/v4 v4.2.1/go.mod h1:AA49e0DZ8kk5jTOOCKNuPR6oTnBS0dYiM4FW1e6jwpg= github.com/labstack/gommon v0.3.0 h1:JEeO0bvc78PKdyHxloTKiF8BD5iGrH8T6MSeGvSgob0= github.com/labstack/gommon v0.3.0/go.mod h1:MULnywXg0yavhxWKc+lOruYdAhDwPK9wf0OL7NoOu+k= github.com/leodido/go-urn v1.2.0/go.mod h1:+8+nEpDfqqsY+g338gtMEUOtuK+4dEMhiQEgxpxOKII=