From: Abukar Mohamed Date: Fri, 22 Oct 2021 11:32:25 +0000 (+0000) Subject: Merge "Special version for alarm manager" into alarm_wa X-Git-Tag: v0.9.2-1 X-Git-Url: https://gerrit.o-ran-sc.org/r/gitweb?a=commitdiff_plain;h=2a05b784df856f77c8c4c0a64ddc4200f14adf13;hp=b1ed7be0b303c9c6ec3744b82caf7d1c720ee19a;p=ric-plt%2Fxapp-frame.git Merge "Special version for alarm manager" into alarm_wa --- diff --git a/api/xapp_rest_api.yaml b/api/xapp_rest_api.yaml index 8f08dd9..c2e1be0 100644 --- a/api/xapp_rest_api.yaml +++ b/api/xapp_rest_api.yaml @@ -1,7 +1,7 @@ swagger: '2.0' info: description: This is the initial REST API for RIC subscription - version: 0.0.3 + version: 0.0.4 title: RIC subscription license: name: Apache 2.0 @@ -63,9 +63,13 @@ paths: schema: $ref: '#/definitions/SubscriptionResponse' '400': + description: Not Found + '404': description: Invalid input '500': description: Internal error + '503': + description: Service Unavailable '/subscriptions/{subscriptionId}': delete: tags: @@ -244,24 +248,22 @@ definitions: minimum: 0 maximum: 4095 E2SubscriptionDirectives: + description: Optional. If not set Submgr uses its default values type: object properties: E2TimeoutTimerValue: description: How long time response is waited from E2 node type: integer - default: 2 minimum: 1 maximum: 10 E2RetryCount: description: How many times E2 subscription request is retried type: integer - default: 2 minimum: 0 maximum: 10 RMRRoutingNeeded: description: Subscription needs RMR route from E2Term to xApp type: boolean - default: True SubscriptionDetails: $ref: '#/definitions/SubscriptionDetailsList' SubscriptionResponse: @@ -281,9 +283,6 @@ definitions: required: - XappEventInstanceId - E2EventInstanceId - - ErrorCause - - ErrorSource - - TimeoutType properties: XappEventInstanceId: type: integer @@ -293,32 +292,17 @@ definitions: type: integer minimum: 0 maximum: 65535 - RejectCause: - description: Reason for REST subscription rejection. - type: string - default: None - enum: - - None - - REST-subscription-ongoing # xApp should retry after delay - - REST-subscription-delete-ongoing # xApp should retry after delay - - Invalid-REST-request-message - - REST-subscription-with-given-id-does-not-exist - - E2-interface-down - - Other ErrorCause: description: Descriptive error cause. Empty string when no error. type: string - default: '' ErrorSource: description: Source of error cause. type: string - default: None - enum: [None, SUBMGR, RTMGR, DBAAS, ASN1, E2Node] + enum: [SUBMGR, RTMGR, DBAAS, ASN1, E2Node] TimeoutType: - description: Type timeout. xApp should retry if timeout occours. + description: Type timeout. xApp should retry if timeout occurs. type: string - default: None - enum: [None, E2-Timeout, RTMGR-Timeout, DBAAS-Timeout] + enum: [E2-Timeout, RTMGR-Timeout, DBAAS-Timeout] SubscriptionData: type: object properties: diff --git a/pkg/clientapi/common/subscribe_responses.go b/pkg/clientapi/common/subscribe_responses.go index db86016..a50361a 100644 --- a/pkg/clientapi/common/subscribe_responses.go +++ b/pkg/clientapi/common/subscribe_responses.go @@ -35,12 +35,24 @@ func (o *SubscribeReader) ReadResponse(response runtime.ClientResponse, consumer return nil, err } return nil, result + case 404: + result := NewSubscribeNotFound() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result case 500: result := NewSubscribeInternalServerError() if err := result.readResponse(response, consumer, o.formats); err != nil { return nil, err } return nil, result + case 503: + result := NewSubscribeServiceUnavailable() + if err := result.readResponse(response, consumer, o.formats); err != nil { + return nil, err + } + return nil, result default: return nil, runtime.NewAPIError("unknown error", response, response.Code()) @@ -87,7 +99,7 @@ func NewSubscribeBadRequest() *SubscribeBadRequest { /*SubscribeBadRequest handles this case with default header values. -Invalid input +Not Found */ type SubscribeBadRequest struct { } @@ -101,6 +113,27 @@ func (o *SubscribeBadRequest) readResponse(response runtime.ClientResponse, cons return nil } +// NewSubscribeNotFound creates a SubscribeNotFound with default headers values +func NewSubscribeNotFound() *SubscribeNotFound { + return &SubscribeNotFound{} +} + +/*SubscribeNotFound handles this case with default header values. + +Invalid input +*/ +type SubscribeNotFound struct { +} + +func (o *SubscribeNotFound) Error() string { + return fmt.Sprintf("[POST /subscriptions][%d] subscribeNotFound ", 404) +} + +func (o *SubscribeNotFound) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + return nil +} + // NewSubscribeInternalServerError creates a SubscribeInternalServerError with default headers values func NewSubscribeInternalServerError() *SubscribeInternalServerError { return &SubscribeInternalServerError{} @@ -121,3 +154,24 @@ func (o *SubscribeInternalServerError) readResponse(response runtime.ClientRespo return nil } + +// NewSubscribeServiceUnavailable creates a SubscribeServiceUnavailable with default headers values +func NewSubscribeServiceUnavailable() *SubscribeServiceUnavailable { + return &SubscribeServiceUnavailable{} +} + +/*SubscribeServiceUnavailable handles this case with default header values. + +Service Unavailable +*/ +type SubscribeServiceUnavailable struct { +} + +func (o *SubscribeServiceUnavailable) Error() string { + return fmt.Sprintf("[POST /subscriptions][%d] subscribeServiceUnavailable ", 503) +} + +func (o *SubscribeServiceUnavailable) readResponse(response runtime.ClientResponse, consumer runtime.Consumer, formats strfmt.Registry) error { + + return nil +} diff --git a/pkg/clientmodel/subscription_instance.go b/pkg/clientmodel/subscription_instance.go index 8c6ae48..9cdf5d9 100644 --- a/pkg/clientmodel/subscription_instance.go +++ b/pkg/clientmodel/subscription_instance.go @@ -26,22 +26,15 @@ type SubscriptionInstance struct { E2EventInstanceID *int64 `json:"E2EventInstanceId"` // Descriptive error cause. Empty string when no error. - // Required: true - ErrorCause *string `json:"ErrorCause"` + ErrorCause string `json:"ErrorCause,omitempty"` // Source of error cause. - // Required: true - // Enum: [None SUBMGR RTMGR DBAAS ASN1 E2Node] - ErrorSource *string `json:"ErrorSource"` + // Enum: [SUBMGR RTMGR DBAAS ASN1 E2Node] + ErrorSource string `json:"ErrorSource,omitempty"` - // Reason for REST subscription rejection. - // Enum: [None REST-subscription-ongoing REST-subscription-delete-ongoing Invalid-REST-request-message REST-subscription-with-given-id-does-not-exist E2-interface-down Other] - RejectCause *string `json:"RejectCause,omitempty"` - - // Type timeout. xApp should retry if timeout occours. - // Required: true - // Enum: [None E2-Timeout RTMGR-Timeout DBAAS-Timeout] - TimeoutType *string `json:"TimeoutType"` + // Type timeout. xApp should retry if timeout occurs. + // Enum: [E2-Timeout RTMGR-Timeout DBAAS-Timeout] + TimeoutType string `json:"TimeoutType,omitempty"` // xapp event instance Id // Required: true @@ -58,18 +51,10 @@ func (m *SubscriptionInstance) Validate(formats strfmt.Registry) error { res = append(res, err) } - if err := m.validateErrorCause(formats); err != nil { - res = append(res, err) - } - if err := m.validateErrorSource(formats); err != nil { res = append(res, err) } - if err := m.validateRejectCause(formats); err != nil { - res = append(res, err) - } - if err := m.validateTimeoutType(formats); err != nil { res = append(res, err) } @@ -101,20 +86,11 @@ func (m *SubscriptionInstance) validateE2EventInstanceID(formats strfmt.Registry return nil } -func (m *SubscriptionInstance) validateErrorCause(formats strfmt.Registry) error { - - if err := validate.Required("ErrorCause", "body", m.ErrorCause); err != nil { - return err - } - - return nil -} - var subscriptionInstanceTypeErrorSourcePropEnum []interface{} func init() { var res []string - if err := json.Unmarshal([]byte(`["None","SUBMGR","RTMGR","DBAAS","ASN1","E2Node"]`), &res); err != nil { + if err := json.Unmarshal([]byte(`["SUBMGR","RTMGR","DBAAS","ASN1","E2Node"]`), &res); err != nil { panic(err) } for _, v := range res { @@ -124,9 +100,6 @@ func init() { const ( - // SubscriptionInstanceErrorSourceNone captures enum value "None" - SubscriptionInstanceErrorSourceNone string = "None" - // SubscriptionInstanceErrorSourceSUBMGR captures enum value "SUBMGR" SubscriptionInstanceErrorSourceSUBMGR string = "SUBMGR" @@ -153,70 +126,12 @@ func (m *SubscriptionInstance) validateErrorSourceEnum(path, location string, va func (m *SubscriptionInstance) validateErrorSource(formats strfmt.Registry) error { - if err := validate.Required("ErrorSource", "body", m.ErrorSource); err != nil { - return err - } - - // value enum - if err := m.validateErrorSourceEnum("ErrorSource", "body", *m.ErrorSource); err != nil { - return err - } - - return nil -} - -var subscriptionInstanceTypeRejectCausePropEnum []interface{} - -func init() { - var res []string - if err := json.Unmarshal([]byte(`["None","REST-subscription-ongoing","REST-subscription-delete-ongoing","Invalid-REST-request-message","REST-subscription-with-given-id-does-not-exist","E2-interface-down","Other"]`), &res); err != nil { - panic(err) - } - for _, v := range res { - subscriptionInstanceTypeRejectCausePropEnum = append(subscriptionInstanceTypeRejectCausePropEnum, v) - } -} - -const ( - - // SubscriptionInstanceRejectCauseNone captures enum value "None" - SubscriptionInstanceRejectCauseNone string = "None" - - // SubscriptionInstanceRejectCauseRESTSubscriptionOngoing captures enum value "REST-subscription-ongoing" - SubscriptionInstanceRejectCauseRESTSubscriptionOngoing string = "REST-subscription-ongoing" - - // SubscriptionInstanceRejectCauseRESTSubscriptionDeleteOngoing captures enum value "REST-subscription-delete-ongoing" - SubscriptionInstanceRejectCauseRESTSubscriptionDeleteOngoing string = "REST-subscription-delete-ongoing" - - // SubscriptionInstanceRejectCauseInvalidRESTRequestMessage captures enum value "Invalid-REST-request-message" - SubscriptionInstanceRejectCauseInvalidRESTRequestMessage string = "Invalid-REST-request-message" - - // SubscriptionInstanceRejectCauseRESTSubscriptionWithGivenIDDoesNotExist captures enum value "REST-subscription-with-given-id-does-not-exist" - SubscriptionInstanceRejectCauseRESTSubscriptionWithGivenIDDoesNotExist string = "REST-subscription-with-given-id-does-not-exist" - - // SubscriptionInstanceRejectCauseE2InterfaceDown captures enum value "E2-interface-down" - SubscriptionInstanceRejectCauseE2InterfaceDown string = "E2-interface-down" - - // SubscriptionInstanceRejectCauseOther captures enum value "Other" - SubscriptionInstanceRejectCauseOther string = "Other" -) - -// prop value enum -func (m *SubscriptionInstance) validateRejectCauseEnum(path, location string, value string) error { - if err := validate.Enum(path, location, value, subscriptionInstanceTypeRejectCausePropEnum); err != nil { - return err - } - return nil -} - -func (m *SubscriptionInstance) validateRejectCause(formats strfmt.Registry) error { - - if swag.IsZero(m.RejectCause) { // not required + if swag.IsZero(m.ErrorSource) { // not required return nil } // value enum - if err := m.validateRejectCauseEnum("RejectCause", "body", *m.RejectCause); err != nil { + if err := m.validateErrorSourceEnum("ErrorSource", "body", m.ErrorSource); err != nil { return err } @@ -227,7 +142,7 @@ var subscriptionInstanceTypeTimeoutTypePropEnum []interface{} func init() { var res []string - if err := json.Unmarshal([]byte(`["None","E2-Timeout","RTMGR-Timeout","DBAAS-Timeout"]`), &res); err != nil { + if err := json.Unmarshal([]byte(`["E2-Timeout","RTMGR-Timeout","DBAAS-Timeout"]`), &res); err != nil { panic(err) } for _, v := range res { @@ -237,9 +152,6 @@ func init() { const ( - // SubscriptionInstanceTimeoutTypeNone captures enum value "None" - SubscriptionInstanceTimeoutTypeNone string = "None" - // SubscriptionInstanceTimeoutTypeE2Timeout captures enum value "E2-Timeout" SubscriptionInstanceTimeoutTypeE2Timeout string = "E2-Timeout" @@ -260,12 +172,12 @@ func (m *SubscriptionInstance) validateTimeoutTypeEnum(path, location string, va func (m *SubscriptionInstance) validateTimeoutType(formats strfmt.Registry) error { - if err := validate.Required("TimeoutType", "body", m.TimeoutType); err != nil { - return err + if swag.IsZero(m.TimeoutType) { // not required + return nil } // value enum - if err := m.validateTimeoutTypeEnum("TimeoutType", "body", *m.TimeoutType); err != nil { + if err := m.validateTimeoutTypeEnum("TimeoutType", "body", m.TimeoutType); err != nil { return err } diff --git a/pkg/clientmodel/subscription_params.go b/pkg/clientmodel/subscription_params.go index b116e50..8e22633 100644 --- a/pkg/clientmodel/subscription_params.go +++ b/pkg/clientmodel/subscription_params.go @@ -257,7 +257,7 @@ func (m *SubscriptionParamsClientEndpoint) UnmarshalBinary(b []byte) error { return nil } -// SubscriptionParamsE2SubscriptionDirectives subscription params e2 subscription directives +// SubscriptionParamsE2SubscriptionDirectives Optional. If not set Submgr uses its default values // // swagger:model SubscriptionParamsE2SubscriptionDirectives type SubscriptionParamsE2SubscriptionDirectives struct { @@ -273,7 +273,7 @@ type SubscriptionParamsE2SubscriptionDirectives struct { E2TimeoutTimerValue int64 `json:"E2TimeoutTimerValue,omitempty"` // Subscription needs RMR route from E2Term to xApp - RMRRoutingNeeded *bool `json:"RMRRoutingNeeded,omitempty"` + RMRRoutingNeeded bool `json:"RMRRoutingNeeded,omitempty"` } // Validate validates this subscription params e2 subscription directives diff --git a/pkg/models/subscription_instance.go b/pkg/models/subscription_instance.go index e028de9..970ae26 100644 --- a/pkg/models/subscription_instance.go +++ b/pkg/models/subscription_instance.go @@ -26,22 +26,15 @@ type SubscriptionInstance struct { E2EventInstanceID *int64 `json:"E2EventInstanceId"` // Descriptive error cause. Empty string when no error. - // Required: true - ErrorCause *string `json:"ErrorCause"` + ErrorCause string `json:"ErrorCause,omitempty"` // Source of error cause. - // Required: true - // Enum: [None SUBMGR RTMGR DBAAS ASN1 E2Node] - ErrorSource *string `json:"ErrorSource"` + // Enum: [SUBMGR RTMGR DBAAS ASN1 E2Node] + ErrorSource string `json:"ErrorSource,omitempty"` - // Reason for REST subscription rejection. - // Enum: [None REST-subscription-ongoing REST-subscription-delete-ongoing Invalid-REST-request-message REST-subscription-with-given-id-does-not-exist E2-interface-down Other] - RejectCause *string `json:"RejectCause,omitempty"` - - // Type timeout. xApp should retry if timeout occours. - // Required: true - // Enum: [None E2-Timeout RTMGR-Timeout DBAAS-Timeout] - TimeoutType *string `json:"TimeoutType"` + // Type timeout. xApp should retry if timeout occurs. + // Enum: [E2-Timeout RTMGR-Timeout DBAAS-Timeout] + TimeoutType string `json:"TimeoutType,omitempty"` // xapp event instance Id // Required: true @@ -58,18 +51,10 @@ func (m *SubscriptionInstance) Validate(formats strfmt.Registry) error { res = append(res, err) } - if err := m.validateErrorCause(formats); err != nil { - res = append(res, err) - } - if err := m.validateErrorSource(formats); err != nil { res = append(res, err) } - if err := m.validateRejectCause(formats); err != nil { - res = append(res, err) - } - if err := m.validateTimeoutType(formats); err != nil { res = append(res, err) } @@ -101,20 +86,11 @@ func (m *SubscriptionInstance) validateE2EventInstanceID(formats strfmt.Registry return nil } -func (m *SubscriptionInstance) validateErrorCause(formats strfmt.Registry) error { - - if err := validate.Required("ErrorCause", "body", m.ErrorCause); err != nil { - return err - } - - return nil -} - var subscriptionInstanceTypeErrorSourcePropEnum []interface{} func init() { var res []string - if err := json.Unmarshal([]byte(`["None","SUBMGR","RTMGR","DBAAS","ASN1","E2Node"]`), &res); err != nil { + if err := json.Unmarshal([]byte(`["SUBMGR","RTMGR","DBAAS","ASN1","E2Node"]`), &res); err != nil { panic(err) } for _, v := range res { @@ -124,9 +100,6 @@ func init() { const ( - // SubscriptionInstanceErrorSourceNone captures enum value "None" - SubscriptionInstanceErrorSourceNone string = "None" - // SubscriptionInstanceErrorSourceSUBMGR captures enum value "SUBMGR" SubscriptionInstanceErrorSourceSUBMGR string = "SUBMGR" @@ -153,70 +126,12 @@ func (m *SubscriptionInstance) validateErrorSourceEnum(path, location string, va func (m *SubscriptionInstance) validateErrorSource(formats strfmt.Registry) error { - if err := validate.Required("ErrorSource", "body", m.ErrorSource); err != nil { - return err - } - - // value enum - if err := m.validateErrorSourceEnum("ErrorSource", "body", *m.ErrorSource); err != nil { - return err - } - - return nil -} - -var subscriptionInstanceTypeRejectCausePropEnum []interface{} - -func init() { - var res []string - if err := json.Unmarshal([]byte(`["None","REST-subscription-ongoing","REST-subscription-delete-ongoing","Invalid-REST-request-message","REST-subscription-with-given-id-does-not-exist","E2-interface-down","Other"]`), &res); err != nil { - panic(err) - } - for _, v := range res { - subscriptionInstanceTypeRejectCausePropEnum = append(subscriptionInstanceTypeRejectCausePropEnum, v) - } -} - -const ( - - // SubscriptionInstanceRejectCauseNone captures enum value "None" - SubscriptionInstanceRejectCauseNone string = "None" - - // SubscriptionInstanceRejectCauseRESTSubscriptionOngoing captures enum value "REST-subscription-ongoing" - SubscriptionInstanceRejectCauseRESTSubscriptionOngoing string = "REST-subscription-ongoing" - - // SubscriptionInstanceRejectCauseRESTSubscriptionDeleteOngoing captures enum value "REST-subscription-delete-ongoing" - SubscriptionInstanceRejectCauseRESTSubscriptionDeleteOngoing string = "REST-subscription-delete-ongoing" - - // SubscriptionInstanceRejectCauseInvalidRESTRequestMessage captures enum value "Invalid-REST-request-message" - SubscriptionInstanceRejectCauseInvalidRESTRequestMessage string = "Invalid-REST-request-message" - - // SubscriptionInstanceRejectCauseRESTSubscriptionWithGivenIDDoesNotExist captures enum value "REST-subscription-with-given-id-does-not-exist" - SubscriptionInstanceRejectCauseRESTSubscriptionWithGivenIDDoesNotExist string = "REST-subscription-with-given-id-does-not-exist" - - // SubscriptionInstanceRejectCauseE2InterfaceDown captures enum value "E2-interface-down" - SubscriptionInstanceRejectCauseE2InterfaceDown string = "E2-interface-down" - - // SubscriptionInstanceRejectCauseOther captures enum value "Other" - SubscriptionInstanceRejectCauseOther string = "Other" -) - -// prop value enum -func (m *SubscriptionInstance) validateRejectCauseEnum(path, location string, value string) error { - if err := validate.Enum(path, location, value, subscriptionInstanceTypeRejectCausePropEnum); err != nil { - return err - } - return nil -} - -func (m *SubscriptionInstance) validateRejectCause(formats strfmt.Registry) error { - - if swag.IsZero(m.RejectCause) { // not required + if swag.IsZero(m.ErrorSource) { // not required return nil } // value enum - if err := m.validateRejectCauseEnum("RejectCause", "body", *m.RejectCause); err != nil { + if err := m.validateErrorSourceEnum("ErrorSource", "body", m.ErrorSource); err != nil { return err } @@ -227,7 +142,7 @@ var subscriptionInstanceTypeTimeoutTypePropEnum []interface{} func init() { var res []string - if err := json.Unmarshal([]byte(`["None","E2-Timeout","RTMGR-Timeout","DBAAS-Timeout"]`), &res); err != nil { + if err := json.Unmarshal([]byte(`["E2-Timeout","RTMGR-Timeout","DBAAS-Timeout"]`), &res); err != nil { panic(err) } for _, v := range res { @@ -237,9 +152,6 @@ func init() { const ( - // SubscriptionInstanceTimeoutTypeNone captures enum value "None" - SubscriptionInstanceTimeoutTypeNone string = "None" - // SubscriptionInstanceTimeoutTypeE2Timeout captures enum value "E2-Timeout" SubscriptionInstanceTimeoutTypeE2Timeout string = "E2-Timeout" @@ -260,12 +172,12 @@ func (m *SubscriptionInstance) validateTimeoutTypeEnum(path, location string, va func (m *SubscriptionInstance) validateTimeoutType(formats strfmt.Registry) error { - if err := validate.Required("TimeoutType", "body", m.TimeoutType); err != nil { - return err + if swag.IsZero(m.TimeoutType) { // not required + return nil } // value enum - if err := m.validateTimeoutTypeEnum("TimeoutType", "body", *m.TimeoutType); err != nil { + if err := m.validateTimeoutTypeEnum("TimeoutType", "body", m.TimeoutType); err != nil { return err } diff --git a/pkg/models/subscription_params.go b/pkg/models/subscription_params.go index a7151d5..5eda090 100644 --- a/pkg/models/subscription_params.go +++ b/pkg/models/subscription_params.go @@ -257,7 +257,7 @@ func (m *SubscriptionParamsClientEndpoint) UnmarshalBinary(b []byte) error { return nil } -// SubscriptionParamsE2SubscriptionDirectives subscription params e2 subscription directives +// SubscriptionParamsE2SubscriptionDirectives Optional. If not set Submgr uses its default values // // swagger:model SubscriptionParamsE2SubscriptionDirectives type SubscriptionParamsE2SubscriptionDirectives struct { @@ -273,7 +273,7 @@ type SubscriptionParamsE2SubscriptionDirectives struct { E2TimeoutTimerValue int64 `json:"E2TimeoutTimerValue,omitempty"` // Subscription needs RMR route from E2Term to xApp - RMRRoutingNeeded *bool `json:"RMRRoutingNeeded,omitempty"` + RMRRoutingNeeded bool `json:"RMRRoutingNeeded,omitempty"` } // Validate validates this subscription params e2 subscription directives diff --git a/pkg/restapi/operations/common/subscribe_responses.go b/pkg/restapi/operations/common/subscribe_responses.go index 4af5582..34c5d19 100644 --- a/pkg/restapi/operations/common/subscribe_responses.go +++ b/pkg/restapi/operations/common/subscribe_responses.go @@ -60,7 +60,7 @@ func (o *SubscribeCreated) WriteResponse(rw http.ResponseWriter, producer runtim // SubscribeBadRequestCode is the HTTP code returned for type SubscribeBadRequest const SubscribeBadRequestCode int = 400 -/*SubscribeBadRequest Invalid input +/*SubscribeBadRequest Not Found swagger:response subscribeBadRequest */ @@ -81,6 +81,30 @@ func (o *SubscribeBadRequest) WriteResponse(rw http.ResponseWriter, producer run rw.WriteHeader(400) } +// SubscribeNotFoundCode is the HTTP code returned for type SubscribeNotFound +const SubscribeNotFoundCode int = 404 + +/*SubscribeNotFound Invalid input + +swagger:response subscribeNotFound +*/ +type SubscribeNotFound struct { +} + +// NewSubscribeNotFound creates SubscribeNotFound with default headers values +func NewSubscribeNotFound() *SubscribeNotFound { + + return &SubscribeNotFound{} +} + +// WriteResponse to the client +func (o *SubscribeNotFound) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.Header().Del(runtime.HeaderContentType) //Remove Content-Type on empty responses + + rw.WriteHeader(404) +} + // SubscribeInternalServerErrorCode is the HTTP code returned for type SubscribeInternalServerError const SubscribeInternalServerErrorCode int = 500 @@ -104,3 +128,27 @@ func (o *SubscribeInternalServerError) WriteResponse(rw http.ResponseWriter, pro rw.WriteHeader(500) } + +// SubscribeServiceUnavailableCode is the HTTP code returned for type SubscribeServiceUnavailable +const SubscribeServiceUnavailableCode int = 503 + +/*SubscribeServiceUnavailable Service Unavailable + +swagger:response subscribeServiceUnavailable +*/ +type SubscribeServiceUnavailable struct { +} + +// NewSubscribeServiceUnavailable creates SubscribeServiceUnavailable with default headers values +func NewSubscribeServiceUnavailable() *SubscribeServiceUnavailable { + + return &SubscribeServiceUnavailable{} +} + +// WriteResponse to the client +func (o *SubscribeServiceUnavailable) WriteResponse(rw http.ResponseWriter, producer runtime.Producer) { + + rw.Header().Del(runtime.HeaderContentType) //Remove Content-Type on empty responses + + rw.WriteHeader(503) +} diff --git a/pkg/xapp/metrics.go b/pkg/xapp/metrics.go index 40adbcd..a90aaed 100644 --- a/pkg/xapp/metrics.go +++ b/pkg/xapp/metrics.go @@ -35,6 +35,30 @@ type CounterOpts prometheus.Opts type Counter prometheus.Counter type Gauge prometheus.Gauge +type CounterVec struct { + Vec *prometheus.CounterVec + Opts CounterOpts + Labels []string +} + +type GaugeVec struct { + Vec *prometheus.GaugeVec + Opts CounterOpts + Labels []string +} + +func strSliceCompare(a, b []string) bool { + if len(a) != len(b) { + return false + } + for i, v := range a { + if v != b[i] { + return false + } + } + return true +} + //----------------------------------------------------------------------------- // //----------------------------------------------------------------------------- @@ -107,6 +131,16 @@ func (met *MetricGroupsCache) GDec(metric string) { met.gauges[metric].Dec() } +func (met *MetricGroupsCache) CombineCounterGroupsWithPrefix(prefix string, srcs ...map[string]Counter) { + met.Lock() + defer met.Unlock() + for _, src := range srcs { + for k, v := range src { + met.counters[prefix+k] = v + } + } +} + func (met *MetricGroupsCache) CombineCounterGroups(srcs ...map[string]Counter) { met.Lock() defer met.Unlock() @@ -117,6 +151,16 @@ func (met *MetricGroupsCache) CombineCounterGroups(srcs ...map[string]Counter) { } } +func (met *MetricGroupsCache) CombineGaugeGroupsWithPrefix(prefix string, srcs ...map[string]Gauge) { + met.Lock() + defer met.Unlock() + for _, src := range srcs { + for k, v := range src { + met.gauges[prefix+k] = v + } + } +} + func (met *MetricGroupsCache) CombineGaugeGroups(srcs ...map[string]Gauge) { met.Lock() defer met.Unlock() @@ -141,10 +185,14 @@ func NewMetricGroupsCache() *MetricGroupsCache { var globalLock sync.Mutex var cache_allcounters map[string]Counter var cache_allgauges map[string]Gauge +var cache_allcountervects map[string]CounterVec +var cache_allgaugevects map[string]GaugeVec func init() { cache_allcounters = make(map[string]Counter) cache_allgauges = make(map[string]Gauge) + cache_allcountervects = make(map[string]CounterVec) + cache_allgaugevects = make(map[string]GaugeVec) } //----------------------------------------------------------------------------- @@ -185,65 +233,158 @@ func (m *Metrics) getFullName(opts prometheus.Opts, labels []string) string { return fmt.Sprintf("%s_%s_%s_%s", opts.Namespace, opts.Subsystem, opts.Name, labelname) } -/* - * Handling counters - */ -func (m *Metrics) registerCounter(opts CounterOpts) Counter { - Logger.Info("Register new counter with opts: %v", opts) - return promauto.NewCounter(prometheus.CounterOpts(opts)) +// +// +// +func (m *Metrics) RegisterCounter(opts CounterOpts, subsytem string) Counter { + globalLock.Lock() + defer globalLock.Unlock() + opts.Namespace = m.Namespace + opts.Subsystem = subsytem + id := m.getFullName(prometheus.Opts(opts), []string{}) + if _, ok := cache_allcounters[id]; !ok { + Logger.Info("Register new counter with opts: %v", opts) + cache_allcounters[id] = promauto.NewCounter(prometheus.CounterOpts(opts)) + } + return cache_allcounters[id] +} + +// +// +// +func (m *Metrics) RegisterCounterGroup(optsgroup []CounterOpts, subsytem string) map[string]Counter { + c := make(map[string]Counter) + for _, opts := range optsgroup { + c[opts.Name] = m.RegisterCounter(opts, subsytem) + } + return c } -func (m *Metrics) RegisterCounterGroup(opts []CounterOpts, subsytem string) (c map[string]Counter) { +// +// +// +func (m *Metrics) RegisterLabeledCounter(opts CounterOpts, labelNames []string, labelValues []string, subsytem string) Counter { globalLock.Lock() defer globalLock.Unlock() - c = make(map[string]Counter) - for _, opt := range opts { - opt.Namespace = m.Namespace - opt.Subsystem = subsytem - - id := m.getFullName(prometheus.Opts(opt), []string{}) - if _, ok := cache_allcounters[id]; !ok { - cache_allcounters[id] = m.registerCounter(opt) - } + opts.Namespace = m.Namespace + opts.Subsystem = subsytem + vecid := m.getFullName(prometheus.Opts(opts), []string{}) + if _, ok := cache_allcountervects[vecid]; !ok { + Logger.Info("Register new counter vector with opts: %v labelNames: %v", opts, labelNames) + entry := CounterVec{} + entry.Opts = opts + entry.Labels = labelNames + entry.Vec = promauto.NewCounterVec(prometheus.CounterOpts(entry.Opts), entry.Labels) + cache_allcountervects[vecid] = entry + } + entry := cache_allcountervects[vecid] + if strSliceCompare(entry.Labels, labelNames) == false { + Logger.Warn("id:%s cached counter vec labels dont match %v != %v", vecid, entry.Labels, labelNames) + } - c[opt.Name] = cache_allcounters[id] + valid := m.getFullName(prometheus.Opts(entry.Opts), labelValues) + if _, ok := cache_allcounters[valid]; !ok { + Logger.Info("Register new counter from vector with opts: %v labelValues: %v", entry.Opts, labelValues) + cache_allcounters[valid] = entry.Vec.WithLabelValues(labelValues...) } + return cache_allcounters[valid] - return } -/* - * Handling gauges - */ -func (m *Metrics) registerGauge(opts CounterOpts) Gauge { - Logger.Info("Register new gauge with opts: %v", opts) - return promauto.NewGauge(prometheus.GaugeOpts(opts)) +// +// +// +func (m *Metrics) RegisterLabeledCounterGroup(optsgroup []CounterOpts, labelNames []string, labelValues []string, subsytem string) map[string]Counter { + c := make(map[string]Counter) + for _, opts := range optsgroup { + c[opts.Name] = m.RegisterLabeledCounter(opts, labelNames, labelValues, subsytem) + } + return c } -func (m *Metrics) RegisterGaugeGroup(opts []CounterOpts, subsytem string) (c map[string]Gauge) { +// +// +// +func (m *Metrics) RegisterGauge(opts CounterOpts, subsytem string) Gauge { globalLock.Lock() defer globalLock.Unlock() - c = make(map[string]Gauge) - for _, opt := range opts { - opt.Namespace = m.Namespace - opt.Subsystem = subsytem + opts.Namespace = m.Namespace + opts.Subsystem = subsytem + id := m.getFullName(prometheus.Opts(opts), []string{}) + if _, ok := cache_allgauges[id]; !ok { + Logger.Info("Register new gauge with opts: %v", opts) + cache_allgauges[id] = promauto.NewGauge(prometheus.GaugeOpts(opts)) + } + return cache_allgauges[id] +} - id := m.getFullName(prometheus.Opts(opt), []string{}) - if _, ok := cache_allgauges[id]; !ok { - cache_allgauges[id] = m.registerGauge(opt) - } +// +// +// +func (m *Metrics) RegisterGaugeGroup(optsgroup []CounterOpts, subsytem string) map[string]Gauge { + c := make(map[string]Gauge) + for _, opts := range optsgroup { + c[opts.Name] = m.RegisterGauge(opts, subsytem) + } + return c +} - c[opt.Name] = cache_allgauges[id] +// +// +// +func (m *Metrics) RegisterLabeledGauge(opt CounterOpts, labelNames []string, labelValues []string, subsytem string) Gauge { + globalLock.Lock() + defer globalLock.Unlock() + opt.Namespace = m.Namespace + opt.Subsystem = subsytem + vecid := m.getFullName(prometheus.Opts(opt), []string{}) + if _, ok := cache_allgaugevects[vecid]; !ok { + Logger.Info("Register new gauge vector with opt: %v labelNames: %v", opt, labelNames) + entry := GaugeVec{} + entry.Opts = opt + entry.Labels = labelNames + entry.Vec = promauto.NewGaugeVec(prometheus.GaugeOpts(entry.Opts), entry.Labels) + cache_allgaugevects[vecid] = entry + } + entry := cache_allgaugevects[vecid] + if strSliceCompare(entry.Labels, labelNames) == false { + Logger.Warn("id:%s cached gauge vec labels dont match %v != %v", vecid, entry.Labels, labelNames) } + valid := m.getFullName(prometheus.Opts(entry.Opts), labelValues) + if _, ok := cache_allgauges[valid]; !ok { + Logger.Info("Register new gauge from vector with opts: %v labelValues: %v", entry.Opts, labelValues) + cache_allgauges[valid] = entry.Vec.WithLabelValues(labelValues...) + } + return cache_allgauges[valid] + +} - return +// +// +// +func (m *Metrics) RegisterLabeledGaugeGroup(opts []CounterOpts, labelNames []string, labelValues []string, subsytem string) map[string]Gauge { + c := make(map[string]Gauge) + for _, opt := range opts { + c[opt.Name] = m.RegisterLabeledGauge(opt, labelNames, labelValues, subsytem) + } + return c } /* * Handling counter vectors * - * Example: + * Examples: + + //--------- + vec := Metric.RegisterCounterVec( + CounterOpts{Name: "counter0", Help: "counter0"}, + []string{"host"}, + "SUBSYSTEM") + + stat:=Metric.GetCounterFromVect([]string{"localhost:8888"},vec) + stat.Inc() + //--------- vec := Metric.RegisterCounterVecGroup( []CounterOpts{ {Name: "counter1", Help: "counter1"}, @@ -252,60 +393,91 @@ func (m *Metrics) RegisterGaugeGroup(opts []CounterOpts, subsytem string) (c map []string{"host"}, "SUBSYSTEM") - stat:=Metric.GetCounterGroupFromVects([]string{"localhost:8888"}, vec) - + stats:=Metric.GetCounterGroupFromVects([]string{"localhost:8888"}, vec) + stats["counter1"].Inc() */ -type CounterVec struct { - Vec *prometheus.CounterVec - Opts CounterOpts -} -func (m *Metrics) registerCounterVec(opts CounterOpts, labelNames []string) *prometheus.CounterVec { - Logger.Info("Register new counter vector with opts: %v labelNames: %v", opts, labelNames) - return promauto.NewCounterVec(prometheus.CounterOpts(opts), labelNames) +// Deprecated: Use RegisterLabeledCounter +func (m *Metrics) RegisterCounterVec(opts CounterOpts, labelNames []string, subsytem string) CounterVec { + globalLock.Lock() + defer globalLock.Unlock() + opts.Namespace = m.Namespace + opts.Subsystem = subsytem + id := m.getFullName(prometheus.Opts(opts), []string{}) + if _, ok := cache_allcountervects[id]; !ok { + Logger.Info("Register new counter vector with opts: %v labelNames: %v", opts, labelNames) + entry := CounterVec{} + entry.Opts = opts + entry.Labels = labelNames + entry.Vec = promauto.NewCounterVec(prometheus.CounterOpts(entry.Opts), entry.Labels) + cache_allcountervects[id] = entry + } + entry := cache_allcountervects[id] + if strSliceCompare(entry.Labels, labelNames) == false { + Logger.Warn("id:%s cached counter vec labels dont match %v != %v", id, entry.Labels, labelNames) + } + return entry } -func (m *Metrics) RegisterCounterVecGroup(opts []CounterOpts, labelNames []string, subsytem string) (c map[string]CounterVec) { - c = make(map[string]CounterVec) - for _, opt := range opts { - entry := CounterVec{} - entry.Opts = opt - entry.Opts.Namespace = m.Namespace - entry.Opts.Subsystem = subsytem - entry.Vec = m.registerCounterVec(entry.Opts, labelNames) - c[opt.Name] = entry +// Deprecated: Use RegisterLabeledCounterGroup +func (m *Metrics) RegisterCounterVecGroup(optsgroup []CounterOpts, labelNames []string, subsytem string) map[string]CounterVec { + c := make(map[string]CounterVec) + for _, opts := range optsgroup { + c[opts.Name] = m.RegisterCounterVec(opts, labelNames, subsytem) } - return + return c } -func (m *Metrics) GetCounterGroupFromVectsWithPrefix(prefix string, labels []string, vects ...map[string]CounterVec) (c map[string]Counter) { +// Deprecated: Use RegisterLabeledCounter +func (m *Metrics) GetCounterFromVect(labelValues []string, vec CounterVec) (c Counter) { globalLock.Lock() defer globalLock.Unlock() - c = make(map[string]Counter) - for _, vec := range vects { - for name, opt := range vec { - - id := m.getFullName(prometheus.Opts(opt.Opts), labels) - if _, ok := cache_allcounters[id]; !ok { - Logger.Info("Register new counter from vector with opts: %v labels: %v prefix: %s", opt.Opts, labels, prefix) - cache_allcounters[id] = opt.Vec.WithLabelValues(labels...) - } - c[prefix+name] = cache_allcounters[id] + id := m.getFullName(prometheus.Opts(vec.Opts), labelValues) + if _, ok := cache_allcounters[id]; !ok { + Logger.Info("Register new counter from vector with opts: %v labelValues: %v", vec.Opts, labelValues) + cache_allcounters[id] = vec.Vec.WithLabelValues(labelValues...) + } + return cache_allcounters[id] +} + +// Deprecated: Use RegisterLabeledCounterGroup +func (m *Metrics) GetCounterGroupFromVects(labelValues []string, vects ...map[string]CounterVec) map[string]Counter { + c := make(map[string]Counter) + for _, vect := range vects { + for name, vec := range vect { + c[name] = m.GetCounterFromVect(labelValues, vec) } } - return + return c } -func (m *Metrics) GetCounterGroupFromVects(labels []string, vects ...map[string]CounterVec) (c map[string]Counter) { - return m.GetCounterGroupFromVectsWithPrefix("", labels, vects...) +// Deprecated: Use RegisterLabeledCounterGroup +func (m *Metrics) GetCounterGroupFromVectsWithPrefix(prefix string, labelValues []string, vects ...map[string]CounterVec) map[string]Counter { + c := make(map[string]Counter) + for _, vect := range vects { + for name, vec := range vect { + c[prefix+name] = m.GetCounterFromVect(labelValues, vec) + } + } + return c } /* * Handling gauge vectors * - * Example: + * Examples: + + //--------- + vec := Metric.RegisterGaugeVec( + CounterOpts{Name: "gauge0", Help: "gauge0"}, + []string{"host"}, + "SUBSYSTEM") - vec := Metric.RegisterGaugeVecGroup( + stat:=Metric.GetGaugeFromVect([]string{"localhost:8888"},vec) + stat.Inc() + + //--------- + vecgrp := Metric.RegisterGaugeVecGroup( []CounterOpts{ {Name: "gauge1", Help: "gauge1"}, {Name: "gauge2", Help: "gauge2"}, @@ -313,51 +485,71 @@ func (m *Metrics) GetCounterGroupFromVects(labels []string, vects ...map[string] []string{"host"}, "SUBSYSTEM") - stat:=Metric.GetGaugeGroupFromVects([]string{"localhost:8888"},vec) - + stats:=Metric.GetGaugeGroupFromVects([]string{"localhost:8888"},vecgrp) + stats["gauge1"].Inc() */ -type GaugeVec struct { - Vec *prometheus.GaugeVec - Opts CounterOpts -} -func (m *Metrics) registerGaugeVec(opts CounterOpts, labelNames []string) *prometheus.GaugeVec { - Logger.Info("Register new gauge vector with opts: %v labelNames: %v", opts, labelNames) - return promauto.NewGaugeVec(prometheus.GaugeOpts(opts), labelNames) -} - -func (m *Metrics) RegisterGaugeVecGroup(opts []CounterOpts, labelNames []string, subsytem string) (c map[string]GaugeVec) { - c = make(map[string]GaugeVec) - for _, opt := range opts { +// Deprecated: Use RegisterLabeledGauge +func (m *Metrics) RegisterGaugeVec(opt CounterOpts, labelNames []string, subsytem string) GaugeVec { + globalLock.Lock() + defer globalLock.Unlock() + opt.Namespace = m.Namespace + opt.Subsystem = subsytem + id := m.getFullName(prometheus.Opts(opt), []string{}) + if _, ok := cache_allgaugevects[id]; !ok { + Logger.Info("Register new gauge vector with opt: %v labelNames: %v", opt, labelNames) entry := GaugeVec{} entry.Opts = opt - entry.Opts.Namespace = m.Namespace - entry.Opts.Subsystem = subsytem - entry.Vec = m.registerGaugeVec(entry.Opts, labelNames) - c[opt.Name] = entry + entry.Labels = labelNames + entry.Vec = promauto.NewGaugeVec(prometheus.GaugeOpts(entry.Opts), entry.Labels) + cache_allgaugevects[id] = entry + } + entry := cache_allgaugevects[id] + if strSliceCompare(entry.Labels, labelNames) == false { + Logger.Warn("id:%s cached gauge vec labels dont match %v != %v", id, entry.Labels, labelNames) + } + return entry +} +// Deprecated: Use RegisterLabeledGaugeGroup +func (m *Metrics) RegisterGaugeVecGroup(opts []CounterOpts, labelNames []string, subsytem string) map[string]GaugeVec { + c := make(map[string]GaugeVec) + for _, opt := range opts { + c[opt.Name] = m.RegisterGaugeVec(opt, labelNames, subsytem) } - return + return c } -func (m *Metrics) GetGaugeGroupFromVectsWithPrefix(prefix string, labels []string, vects ...map[string]GaugeVec) (c map[string]Gauge) { +// Deprecated: Use RegisterLabeledGauge +func (m *Metrics) GetGaugeFromVect(labelValues []string, vec GaugeVec) Gauge { globalLock.Lock() defer globalLock.Unlock() - c = make(map[string]Gauge) - for _, vec := range vects { - for name, opt := range vec { - - id := m.getFullName(prometheus.Opts(opt.Opts), labels) - if _, ok := cache_allgauges[id]; !ok { - Logger.Info("Register new gauge from vector with opts: %v labels: %v prefix: %s", opt.Opts, labels, prefix) - cache_allgauges[id] = opt.Vec.WithLabelValues(labels...) - } - c[prefix+name] = cache_allgauges[id] + id := m.getFullName(prometheus.Opts(vec.Opts), labelValues) + if _, ok := cache_allgauges[id]; !ok { + Logger.Info("Register new gauge from vector with opts: %v labelValues: %v", vec.Opts, labelValues) + cache_allgauges[id] = vec.Vec.WithLabelValues(labelValues...) + } + return cache_allgauges[id] +} + +// Deprecated: Use RegisterLabeledGaugeGroup +func (m *Metrics) GetGaugeGroupFromVects(labelValues []string, vects ...map[string]GaugeVec) map[string]Gauge { + c := make(map[string]Gauge) + for _, vect := range vects { + for name, vec := range vect { + c[name] = m.GetGaugeFromVect(labelValues, vec) } } - return + return c } -func (m *Metrics) GetGaugeGroupFromVects(labels []string, vects ...map[string]GaugeVec) (c map[string]Gauge) { - return m.GetGaugeGroupFromVectsWithPrefix("", labels, vects...) +// Deprecated: Use RegisterLabeledGaugeGroup +func (m *Metrics) GetGaugeGroupFromVectsWithPrefix(prefix string, labelValues []string, vects ...map[string]GaugeVec) map[string]Gauge { + c := make(map[string]Gauge) + for _, vect := range vects { + for name, vec := range vect { + c[prefix+name] = m.GetGaugeFromVect(labelValues, vec) + } + } + return c } diff --git a/pkg/xapp/metrics_test.go b/pkg/xapp/metrics_test.go index bd7c737..aad90b1 100755 --- a/pkg/xapp/metrics_test.go +++ b/pkg/xapp/metrics_test.go @@ -23,61 +23,446 @@ import ( "testing" ) -var mCVect map[string]CounterVec -var mGVect map[string]GaugeVec -var mGGroup map[string]Gauge +func TestMetricCounter(t *testing.T) { + TestCounterOpt := CounterOpts{Name: "CounterBlaah1", Help: "CounterBlaah1"} + ret1 := Metric.RegisterCounter(TestCounterOpt, "TestMetricCounter") + ret1.Inc() + ret2 := Metric.RegisterCounter(TestCounterOpt, "TestMetricCounter") + ret2.Inc() + if ret1 != ret2 { + t.Errorf("ret1 not same than ret2. cache not working?") + } +} -func TestMetricSetup(t *testing.T) { - mCVect = Metric.RegisterCounterVecGroup( - []CounterOpts{ - {Name: "counter1", Help: "counter1"}, - }, +func TestMetricCounterGroup(t *testing.T) { + var TestCounterOpts = []CounterOpts{ + {Name: "CounterBlaah1", Help: "CounterBlaah1"}, + {Name: "CounterBlaah2", Help: "CounterBlaah2"}, + {Name: "CounterBlaah3", Help: "CounterBlaah3"}, + {Name: "CounterBlaah4", Help: "CounterBlaah4"}, + } + + ret1 := Metric.RegisterCounterGroup(TestCounterOpts, "TestMetricCounterGroup") + + if len(ret1) == 0 { + t.Errorf("ret1 counter group is empty") + } + + ret1["CounterBlaah1"].Inc() + ret1["CounterBlaah2"].Inc() + ret1["CounterBlaah3"].Inc() + ret1["CounterBlaah4"].Inc() + + ret2 := Metric.RegisterCounterGroup(TestCounterOpts, "TestMetricCounterGroup") + + if len(ret2) == 0 { + t.Errorf("ret2 counter group is empty") + } + + ret2["CounterBlaah1"].Inc() + ret2["CounterBlaah2"].Inc() + ret2["CounterBlaah3"].Inc() + ret2["CounterBlaah4"].Inc() + + if len(ret1) != len(ret2) { + t.Errorf("ret1 len %d differs from ret2 len %d", len(ret1), len(ret2)) + } +} + +func TestMetricLabeledCounter(t *testing.T) { + // + // + c_1_1 := Metric.RegisterLabeledCounter( + CounterOpts{Name: "counter1", Help: "counter1"}, []string{"name", "event"}, - "SUBSYSTEM") + []string{"name1", "event1"}, + "SUBSYSTEML0") - mGVect = Metric.RegisterGaugeVecGroup( - []CounterOpts{ - {Name: "counter2", Help: "counter2"}, - }, + c_1_2 := Metric.RegisterLabeledCounter( + CounterOpts{Name: "counter1", Help: "counter1"}, []string{"name", "event"}, - "SUBSYSTEM") + []string{"name1", "event1"}, + "SUBSYSTEML0") + + c_1_1.Inc() + c_1_2.Inc() + if c_1_1 != c_1_2 { + t.Errorf("c_1_1 not same than c_1_2. cache not working?") + } + + // + // + c_2_1 := Metric.RegisterLabeledCounter( + CounterOpts{Name: "counter1", Help: "counter1"}, + []string{"name", "event"}, + []string{"name1", "event2"}, + "SUBSYSTEML0") + + c_2_2 := Metric.RegisterLabeledCounter( + CounterOpts{Name: "counter1", Help: "counter1"}, + []string{"name", "event"}, + []string{"name1", "event2"}, + "SUBSYSTEML0") + + c_2_1.Inc() + c_2_2.Inc() + if c_2_1 != c_2_2 { + t.Errorf("c_2_1 not same than c_2_2. cache not working?") + } + + if c_1_1 == c_2_1 { + t.Errorf("c_1_1 same than c_2_1. what?") + } + if c_1_2 == c_2_2 { + t.Errorf("c_1_2 same than c_2_2. what?") + } - mGGroup = Metric.RegisterGaugeGroup( - []CounterOpts{ - {Name: "counter3", Help: "counter3"}, - }, - "SUBSYSTEM2") } -func TestMetricCounter(t *testing.T) { - var TestCounterOpts = []CounterOpts{ - {Name: "Blaah1", Help: "Blaah1"}, - {Name: "Blaah2", Help: "Blaah2"}, - {Name: "Blaah3", Help: "Blaah3"}, - {Name: "Blaah4", Help: "Blaah4"}, +func TestMetricLabeledCounterMismatch(t *testing.T) { + Metric.RegisterLabeledCounter( + CounterOpts{Name: "counter1", Help: "counter1"}, + []string{"name", "event"}, + []string{"name1", "event1"}, + "SUBSYSTEMLERR") + + Metric.RegisterLabeledCounter( + CounterOpts{Name: "counter1", Help: "counter1"}, + []string{"name", "eventmismatch"}, + []string{"name1", "event1"}, + "SUBSYSTEMLERR") +} + +func TestMetricLabeledCounterGroup(t *testing.T) { + // + // + c_grp1 := Metric.RegisterLabeledCounterGroup( + []CounterOpts{{Name: "counter1", Help: "counter1"}}, + []string{"name", "event"}, + []string{"name1", "event1"}, + "SUBSYSTEML1") + + if _, ok := c_grp1["counter1"]; ok == false { + t.Errorf("c_grp1 counter1 not exists") + } + c_grp1["counter1"].Inc() + + // + // + c_grp2 := Metric.RegisterLabeledCounterGroup( + []CounterOpts{{Name: "counter1", Help: "counter1"}}, + []string{"name", "event"}, + []string{"name1", "event2"}, + "SUBSYSTEML1") + + if _, ok := c_grp2["counter1"]; ok == false { + t.Errorf("c_grp2 counter1 not exists") + } + c_grp2["counter1"].Inc() +} + +func TestMetricGauge(t *testing.T) { + TestGaugeOpts := CounterOpts{Name: "GaugeBlaah1", Help: "GaugeBlaah1"} + ret1 := Metric.RegisterGauge(TestGaugeOpts, "TestMetricGauge") + ret1.Inc() + ret2 := Metric.RegisterGauge(TestGaugeOpts, "TestMetricGauge") + ret2.Inc() + if ret1 != ret2 { + t.Errorf("ret1 not same than ret2. cache not working?") + } +} + +func TestMetricGaugeGroup(t *testing.T) { + var TestGaugeOpts = []CounterOpts{ + {Name: "GaugeBlaah1", Help: "GaugeBlaah1"}, + {Name: "GaugeBlaah2", Help: "GaugeBlaah2"}, + {Name: "GaugeBlaah3", Help: "GaugeBlaah3"}, + {Name: "GaugeBlaah4", Help: "GaugeBlaah4"}, } - ret1 := Metric.RegisterCounterGroup(TestCounterOpts, "TestMetricCounter") + ret1 := Metric.RegisterGaugeGroup(TestGaugeOpts, "TestMetricGaugeGroup") if len(ret1) == 0 { - t.Errorf("ret1 counter group is empty") + t.Errorf("ret1 gauge group is empty") } - ret2 := Metric.RegisterCounterGroup(TestCounterOpts, "TestMetricCounter") + ret1["GaugeBlaah1"].Inc() + ret1["GaugeBlaah2"].Inc() + ret1["GaugeBlaah3"].Inc() + ret1["GaugeBlaah4"].Inc() + + ret2 := Metric.RegisterGaugeGroup(TestGaugeOpts, "TestMetricGaugeGroup") if len(ret2) == 0 { - t.Errorf("ret2 counter group is empty") + t.Errorf("ret2 gauge group is empty") } + ret2["GaugeBlaah1"].Inc() + ret2["GaugeBlaah2"].Inc() + ret2["GaugeBlaah3"].Inc() + ret2["GaugeBlaah4"].Inc() + if len(ret1) != len(ret2) { t.Errorf("ret1 len %d differs from ret2 len %d", len(ret1), len(ret2)) } } +func TestMetricLabeledGauge(t *testing.T) { + // + // + c_1_1 := Metric.RegisterLabeledGauge( + CounterOpts{Name: "gauge1", Help: "gauge1"}, + []string{"name", "event"}, + []string{"name1", "event1"}, + "SUBSYSTEML0") + + c_1_2 := Metric.RegisterLabeledGauge( + CounterOpts{Name: "gauge1", Help: "gauge1"}, + []string{"name", "event"}, + []string{"name1", "event1"}, + "SUBSYSTEML0") + + c_1_1.Inc() + c_1_2.Inc() + if c_1_1 != c_1_2 { + t.Errorf("c_1_1 not same than c_1_2. cache not working?") + } + + // + // + c_2_1 := Metric.RegisterLabeledGauge( + CounterOpts{Name: "gauge1", Help: "gauge1"}, + []string{"name", "event"}, + []string{"name1", "event2"}, + "SUBSYSTEML0") + + c_2_2 := Metric.RegisterLabeledGauge( + CounterOpts{Name: "gauge1", Help: "gauge1"}, + []string{"name", "event"}, + []string{"name1", "event2"}, + "SUBSYSTEML0") + + c_2_1.Inc() + c_2_2.Inc() + if c_2_1 != c_2_2 { + t.Errorf("c_2_1 not same than c_2_2. cache not working?") + } + + if c_1_1 == c_2_1 { + t.Errorf("c_1_1 same than c_2_1. what?") + } + if c_1_2 == c_2_2 { + t.Errorf("c_1_2 same than c_2_2. what?") + } + +} + +func TestMetricLabeledGaugeMismatch(t *testing.T) { + Metric.RegisterLabeledGauge( + CounterOpts{Name: "gauge1", Help: "gauge1"}, + []string{"name", "event"}, + []string{"name1", "event1"}, + "SUBSYSTEMLERR") + + Metric.RegisterLabeledGauge( + CounterOpts{Name: "gauge1", Help: "gauge1"}, + []string{"name", "eventmismatch"}, + []string{"name1", "event1"}, + "SUBSYSTEMLERR") +} + +func TestMetricLabeledGaugeGroup(t *testing.T) { + // + // + g_grp1 := Metric.RegisterLabeledGaugeGroup( + []CounterOpts{{Name: "gauge1", Help: "gauge1"}}, + []string{"name", "event"}, + []string{"name1", "event1"}, + "SUBSYSTEML1") + + if _, ok := g_grp1["gauge1"]; ok == false { + t.Errorf("g_grp1 gauge1 not exists") + } + g_grp1["gauge1"].Inc() + + // + // + g_grp2 := Metric.RegisterLabeledGaugeGroup( + []CounterOpts{{Name: "gauge1", Help: "gauge1"}}, + []string{"name", "event"}, + []string{"name1", "event2"}, + "SUBSYSTEML1") + + if _, ok := g_grp2["gauge1"]; ok == false { + t.Errorf("g_grp2 gauge1 not exists") + } + g_grp2["gauge1"].Inc() +} + +func TestMetricGroupCache(t *testing.T) { + // + // + c_grp1 := Metric.RegisterLabeledCounterGroup( + []CounterOpts{{Name: "counter1", Help: "counter1"}}, + []string{"name", "event"}, + []string{"name1", "event1"}, + "SUBSYSTEML1") + if _, ok := c_grp1["counter1"]; ok == false { + t.Errorf("c_grp1 counter1 not exists") + } + c_grp1["counter1"].Inc() + + // + // + c_grp2 := Metric.RegisterLabeledCounterGroup( + []CounterOpts{{Name: "counter1", Help: "counter1"}}, + []string{"name", "event"}, + []string{"name1", "event2"}, + "SUBSYSTEML1") + if _, ok := c_grp2["counter1"]; ok == false { + t.Errorf("c_grp2 counter1 not exists") + } + c_grp2["counter1"].Inc() + + // + // + g_grp1 := Metric.RegisterLabeledGaugeGroup( + []CounterOpts{{Name: "gauge1", Help: "gauge1"}}, + []string{"name", "event"}, + []string{"name1", "event1"}, + "SUBSYSTEML1") + if _, ok := g_grp1["gauge1"]; ok == false { + t.Errorf("g_grp1 gauge1 not exists") + } + g_grp1["gauge1"].Inc() + + // + // + g_grp2 := Metric.RegisterLabeledGaugeGroup( + []CounterOpts{{Name: "gauge1", Help: "gauge1"}}, + []string{"name", "event"}, + []string{"name1", "event2"}, + "SUBSYSTEML1") + if _, ok := g_grp2["gauge1"]; ok == false { + t.Errorf("g_grp2 gauge1 not exists") + } + g_grp2["gauge1"].Inc() + + // + // + m_grp := NewMetricGroupsCache() + m_grp.CombineCounterGroupsWithPrefix("event1_", c_grp1) + m_grp.CombineCounterGroupsWithPrefix("event2_", c_grp2) + m_grp.CombineGaugeGroupsWithPrefix("event1_", g_grp1) + m_grp.CombineGaugeGroupsWithPrefix("event2_", g_grp2) + + if m_grp == nil { + t.Errorf("Cache failed") + } + + if m_grp.CIs("event1_counter1") == false { + t.Errorf("m_grp.Counters event1_counter1 not exists") + } + m_grp.CInc("event1_counter1") + + if m_grp.CIs("event2_counter1") == false { + t.Errorf("m_grp.Counters event2_counter1 not exists") + } + m_grp.CInc("event2_counter1") + + if m_grp.GIs("event1_gauge1") == false { + t.Errorf("m_grp.Gauges event1_gauge1 not exists") + } + m_grp.GInc("event1_gauge1") + + if m_grp.GIs("event2_gauge1") == false { + t.Errorf("m_grp.Gauges event2_gauge1 not exists") + } + m_grp.GInc("event2_gauge1") + + m_grp.CAdd("event2_counter1", 1) + m_grp.CGet("event2_counter1") + m_grp.GGet("event2_gauge1") + m_grp.GDec("event2_gauge1") + m_grp.GSet("event2_gauge1", 1) +} + +// ---- +// VECTORS ARE OLD WAY +// *Labeled* will do all work under the hood +// ---- + +var mCVect CounterVec +var mGVect GaugeVec + +var mCGroupVect map[string]CounterVec +var mGGroupVect map[string]GaugeVec + +func TestMetricSetup(t *testing.T) { + mCVect = Metric.RegisterCounterVec(CounterOpts{Name: "counter1", Help: "counter1"}, []string{"name", "event"}, "SUBSYSTEM0") + + mCGroupVect = Metric.RegisterCounterVecGroup( + []CounterOpts{ + {Name: "counter1", Help: "counter1"}, + }, + []string{"name", "event"}, + "SUBSYSTEM1") + + mGVect = Metric.RegisterGaugeVec(CounterOpts{Name: "gauge1", Help: "gauge1"}, []string{"name", "event"}, "SUBSYSTEM0") + + mGGroupVect = Metric.RegisterGaugeVecGroup( + []CounterOpts{ + {Name: "gauge1", Help: "gauge1"}, + }, + []string{"name", "event"}, + "SUBSYSTEM1") + + tmpCVect := Metric.RegisterCounterVec(CounterOpts{Name: "counter1", Help: "counter1"}, []string{"name", "event"}, "SUBSYSTEM0") + + if tmpCVect.Vec != mCVect.Vec { + t.Errorf("tmpCVect not same than mCVect. cache not working?") + } + + tmpGVect := Metric.RegisterGaugeVec(CounterOpts{Name: "gauge1", Help: "gauge1"}, []string{"name", "event"}, "SUBSYSTEM0") + + if tmpGVect.Vec != mGVect.Vec { + t.Errorf("tmpGVect not same than mGVect. cache not working?") + } + + Metric.RegisterCounterVec(CounterOpts{Name: "counter1", Help: "counter1"}, []string{"name", "eventMismatch"}, "SUBSYSTEM0") + Metric.RegisterGaugeVec(CounterOpts{Name: "gauge1", Help: "gauge1"}, []string{"name", "eventMismatch"}, "SUBSYSTEM0") + +} + func TestMetricCounterVector(t *testing.T) { // // - c_grp1 := Metric.GetCounterGroupFromVects([]string{"name1", "event1"}, mCVect) + c_1_1 := Metric.GetCounterFromVect([]string{"name1", "event1"}, mCVect) + c_1_1.Inc() + c_1_2 := Metric.GetCounterFromVect([]string{"name1", "event1"}, mCVect) + c_1_2.Inc() + if c_1_1 != c_1_2 { + t.Errorf("c_1_1 not same than c_1_2. cache not working?") + } + // + // + c_2_1 := Metric.GetCounterFromVect([]string{"name1", "event2"}, mCVect) + c_2_1.Inc() + c_2_2 := Metric.GetCounterFromVect([]string{"name1", "event2"}, mCVect) + c_2_2.Inc() + if c_2_1 != c_2_2 { + t.Errorf("c_2_1 not same than c_2_2. cache not working?") + } + if c_1_1 == c_2_1 { + t.Errorf("c_1_1 same than c_2_1. what?") + } + +} + +func TestMetricCounterGroupVector(t *testing.T) { + // + // + c_grp1 := Metric.GetCounterGroupFromVects([]string{"name1", "event1"}, mCGroupVect) if _, ok := c_grp1["counter1"]; ok == false { t.Errorf("c_grp1 counter1 not exists") } @@ -85,7 +470,7 @@ func TestMetricCounterVector(t *testing.T) { // // - c_grp2 := Metric.GetCounterGroupFromVects([]string{"name1", "event2"}, mCVect) + c_grp2 := Metric.GetCounterGroupFromVects([]string{"name1", "event2"}, mCGroupVect) if _, ok := c_grp2["counter1"]; ok == false { t.Errorf("c_grp2 counter1 not exists") } @@ -95,25 +480,49 @@ func TestMetricCounterVector(t *testing.T) { func TestMetricGaugeVector(t *testing.T) { // // - g_grp1 := Metric.GetGaugeGroupFromVects([]string{"name1", "event1"}, mGVect) - if _, ok := g_grp1["counter2"]; ok == false { - t.Errorf("g_grp1 counter2 not exists") + c_1_1 := Metric.GetGaugeFromVect([]string{"name1", "event1"}, mGVect) + c_1_1.Inc() + c_1_2 := Metric.GetGaugeFromVect([]string{"name1", "event1"}, mGVect) + c_1_2.Inc() + if c_1_1 != c_1_2 { + t.Errorf("c_1_1 not same than c_1_2. cache not working?") + } + // + // + c_2_1 := Metric.GetGaugeFromVect([]string{"name1", "event2"}, mGVect) + c_2_1.Inc() + c_2_2 := Metric.GetGaugeFromVect([]string{"name1", "event2"}, mGVect) + c_2_2.Inc() + if c_2_1 != c_2_2 { + t.Errorf("c_2_1 not same than c_2_2. cache not working?") + } + if c_1_1 == c_2_1 { + t.Errorf("c_1_1 same than c_2_1. what?") + } +} + +func TestMetricGaugeGroupVector(t *testing.T) { + // + // + g_grp1 := Metric.GetGaugeGroupFromVects([]string{"name1", "event1"}, mGGroupVect) + if _, ok := g_grp1["gauge1"]; ok == false { + t.Errorf("g_grp1 gauge1 not exists") } - g_grp1["counter2"].Inc() + g_grp1["gauge1"].Inc() // // - g_grp2 := Metric.GetGaugeGroupFromVects([]string{"name1", "event2"}, mGVect) - if _, ok := g_grp2["counter2"]; ok == false { - t.Errorf("g_grp2 counter2 not exists") + g_grp2 := Metric.GetGaugeGroupFromVects([]string{"name1", "event2"}, mGGroupVect) + if _, ok := g_grp2["gauge1"]; ok == false { + t.Errorf("g_grp2 gauge1 not exists") } - g_grp2["counter2"].Inc() + g_grp2["gauge1"].Inc() } -func TestMetricCounterVectorPrefix(t *testing.T) { +func TestMetricCounterGroupVectorPrefix(t *testing.T) { // // - c_grp1 := Metric.GetCounterGroupFromVectsWithPrefix("event1_", []string{"name1", "event1"}, mCVect) + c_grp1 := Metric.GetCounterGroupFromVectsWithPrefix("event1_", []string{"name1", "event1"}, mCGroupVect) if _, ok := c_grp1["event1_counter1"]; ok == false { t.Errorf("c_grp1 event1_counter1 not exists") } @@ -121,7 +530,7 @@ func TestMetricCounterVectorPrefix(t *testing.T) { // // - c_grp2 := Metric.GetCounterGroupFromVectsWithPrefix("event2_", []string{"name1", "event2"}, mCVect) + c_grp2 := Metric.GetCounterGroupFromVectsWithPrefix("event2_", []string{"name1", "event2"}, mCGroupVect) if _, ok := c_grp2["event2_counter1"]; ok == false { t.Errorf("c_grp2 event2_counter1 not exists") } @@ -149,85 +558,85 @@ func TestMetricCounterVectorPrefix(t *testing.T) { m_grp.CGet("event2_counter1") } -func TestMetricGaugeVectorPrefix(t *testing.T) { +func TestMetricGaugeGroupVectorPrefix(t *testing.T) { // // - g_grp1 := Metric.GetGaugeGroupFromVectsWithPrefix("event1_", []string{"name1", "event1"}, mGVect) - if _, ok := g_grp1["event1_counter2"]; ok == false { - t.Errorf("g_grp1 event1_counter2 not exists") + g_grp1 := Metric.GetGaugeGroupFromVectsWithPrefix("event1_", []string{"name1", "event1"}, mGGroupVect) + if _, ok := g_grp1["event1_gauge1"]; ok == false { + t.Errorf("g_grp1 event1_gauge1 not exists") } - g_grp1["event1_counter2"].Inc() + g_grp1["event1_gauge1"].Inc() // // - g_grp2 := Metric.GetGaugeGroupFromVectsWithPrefix("event2_", []string{"name1", "event2"}, mGVect) - if _, ok := g_grp2["event2_counter2"]; ok == false { - t.Errorf("g_grp2 event2_counter2 not exists") + g_grp2 := Metric.GetGaugeGroupFromVectsWithPrefix("event2_", []string{"name1", "event2"}, mGGroupVect) + if _, ok := g_grp2["event2_gauge1"]; ok == false { + t.Errorf("g_grp2 event2_gauge1 not exists") } - g_grp2["event2_counter2"].Inc() + g_grp2["event2_gauge1"].Inc() m_grp := NewMetricGroupsCache() m_grp.CombineGaugeGroups(g_grp1, g_grp2) // // - if m_grp.GIs("event1_counter2") == false { - t.Errorf("m_grp event1_counter2 not exists") + if m_grp.GIs("event1_gauge1") == false { + t.Errorf("m_grp event1_gauge1 not exists") } - m_grp.GInc("event1_counter2") + m_grp.GInc("event1_gauge1") // // - if m_grp.GIs("event2_counter2") == false { - t.Errorf("m_grp event2_counter2 not exists") + if m_grp.GIs("event2_gauge1") == false { + t.Errorf("m_grp event2_gauge1 not exists") } - m_grp.GInc("event2_counter2") + m_grp.GInc("event2_gauge1") - m_grp.GGet("event2_counter2") - m_grp.GDec("event2_counter2") - m_grp.GSet("event2_counter2", 1) + m_grp.GGet("event2_gauge1") + m_grp.GDec("event2_gauge1") + m_grp.GSet("event2_gauge1", 1) } -func TestMetricGroupCache(t *testing.T) { +func TestMetricGroupCacheWithVect(t *testing.T) { // // - c_grp1 := Metric.GetCounterGroupFromVectsWithPrefix("event1_", []string{"name1", "event1"}, mCVect) - if _, ok := c_grp1["event1_counter1"]; ok == false { - t.Errorf("c_grp1 event1_counter1 not exists") + c_grp1 := Metric.GetCounterGroupFromVects([]string{"name1", "event1"}, mCGroupVect) + if _, ok := c_grp1["counter1"]; ok == false { + t.Errorf("c_grp1 counter1 not exists") } - c_grp1["event1_counter1"].Inc() + c_grp1["counter1"].Inc() // // - c_grp2 := Metric.GetCounterGroupFromVectsWithPrefix("event2_", []string{"name1", "event2"}, mCVect) - if _, ok := c_grp2["event2_counter1"]; ok == false { - t.Errorf("c_grp2 event2_counter1 not exists") + c_grp2 := Metric.GetCounterGroupFromVects([]string{"name1", "event2"}, mCGroupVect) + if _, ok := c_grp2["counter1"]; ok == false { + t.Errorf("c_grp2 counter1 not exists") } - c_grp2["event2_counter1"].Inc() + c_grp2["counter1"].Inc() // // - g_grp1 := Metric.GetGaugeGroupFromVectsWithPrefix("event1_", []string{"name1", "event1"}, mGVect) - if _, ok := g_grp1["event1_counter2"]; ok == false { - t.Errorf("g_grp1 event1_counter2 not exists") + g_grp1 := Metric.GetGaugeGroupFromVects([]string{"name1", "event1"}, mGGroupVect) + if _, ok := g_grp1["gauge1"]; ok == false { + t.Errorf("g_grp1 gauge1 not exists") } - g_grp1["event1_counter2"].Inc() + g_grp1["gauge1"].Inc() // // - g_grp2 := Metric.GetGaugeGroupFromVectsWithPrefix("event2_", []string{"name1", "event2"}, mGVect) - if _, ok := g_grp2["event2_counter2"]; ok == false { - t.Errorf("g_grp2 event2_counter2 not exists") + g_grp2 := Metric.GetGaugeGroupFromVects([]string{"name1", "event2"}, mGGroupVect) + if _, ok := g_grp2["gauge1"]; ok == false { + t.Errorf("g_grp2 gauge1 not exists") } - g_grp2["event2_counter2"].Inc() + g_grp2["gauge1"].Inc() // // m_grp := NewMetricGroupsCache() - m_grp.CombineCounterGroups(c_grp1) - m_grp.CombineCounterGroups(c_grp2) - m_grp.CombineGaugeGroups(g_grp1) - m_grp.CombineGaugeGroups(g_grp2) + m_grp.CombineCounterGroupsWithPrefix("event1_", c_grp1) + m_grp.CombineCounterGroupsWithPrefix("event2_", c_grp2) + m_grp.CombineGaugeGroupsWithPrefix("event1_", g_grp1) + m_grp.CombineGaugeGroupsWithPrefix("event2_", g_grp2) if m_grp == nil { t.Errorf("Cache failed") @@ -243,19 +652,19 @@ func TestMetricGroupCache(t *testing.T) { } m_grp.CInc("event2_counter1") - if m_grp.GIs("event1_counter2") == false { - t.Errorf("m_grp.Gauges event1_counter2 not exists") + if m_grp.GIs("event1_gauge1") == false { + t.Errorf("m_grp.Gauges event1_gauge1 not exists") } - m_grp.GInc("event1_counter2") + m_grp.GInc("event1_gauge1") - if m_grp.GIs("event2_counter2") == false { - t.Errorf("m_grp.Gauges event2_counter2 not exists") + if m_grp.GIs("event2_gauge1") == false { + t.Errorf("m_grp.Gauges event2_gauge1 not exists") } - m_grp.GInc("event2_counter2") + m_grp.GInc("event2_gauge1") m_grp.CAdd("event2_counter1", 1) m_grp.CGet("event2_counter1") - m_grp.GGet("event2_counter2") - m_grp.GDec("event2_counter2") - m_grp.GSet("event2_counter2", 1) + m_grp.GGet("event2_gauge1") + m_grp.GDec("event2_gauge1") + m_grp.GSet("event2_gauge1", 1) } diff --git a/pkg/xapp/subscription.go b/pkg/xapp/subscription.go index 01e351f..8f49e99 100755 --- a/pkg/xapp/subscription.go +++ b/pkg/xapp/subscription.go @@ -120,11 +120,14 @@ func (r *Subscriber) Listen(createSubscription SubscriptionHandler, getSubscript // Subscription: Subscribe api.CommonSubscribeHandler = common.SubscribeHandlerFunc( func(params common.SubscribeParams) middleware.Responder { - Logger.Error("Subscribe: Params=%+v", params.SubscriptionParams) resp, retCode := createSubscription(params.SubscriptionParams) if retCode != common.SubscribeCreatedCode { if retCode == common.SubscribeBadRequestCode { return common.NewSubscribeBadRequest() + } else if retCode == common.SubscribeNotFoundCode { + return common.NewSubscribeNotFound() + } else if retCode == common.SubscribeServiceUnavailableCode { + return common.NewSubscribeServiceUnavailable() } else { return common.NewSubscribeInternalServerError() } @@ -135,7 +138,6 @@ func (r *Subscriber) Listen(createSubscription SubscriptionHandler, getSubscript // Subscription: Unsubscribe api.CommonUnsubscribeHandler = common.UnsubscribeHandlerFunc( func(p common.UnsubscribeParams) middleware.Responder { - Logger.Error("Unsubscribe: SubscriptionID=%+v", p.SubscriptionID) retCode := delSubscription(p.SubscriptionID) if retCode != common.UnsubscribeNoContentCode { if retCode == common.UnsubscribeBadRequestCode { @@ -209,7 +211,6 @@ func (r *Subscriber) Subscribe(p *apimodel.SubscriptionParams) (*apimodel.Subscr if err != nil { return &apimodel.SubscriptionResponse{}, err } - return result.Payload, err } diff --git a/pkg/xapp/subscription_test.go b/pkg/xapp/subscription_test.go index d41649f..ffdea34 100755 --- a/pkg/xapp/subscription_test.go +++ b/pkg/xapp/subscription_test.go @@ -35,7 +35,7 @@ var ( procedureCode = int64(27) typeOfMessage = int64(1) subscriptionId = "" - hPort = int64(8080) + hPort = int64(8086) // See log: "Xapp started, listening on: :8086" rPort = int64(4560) clientEndpoint = clientmodel.SubscriptionParamsClientEndpoint{Host: "localhost", HTTPPort: &hPort, RMRPort: &rPort} ) @@ -56,12 +56,14 @@ func TestSubscriptionQueryHandling(t *testing.T) { assert.Equal(t, resp[0].SubscriptionID, int64(11)) assert.Equal(t, resp[0].Meid, "Test-Gnb") assert.Equal(t, resp[0].ClientEndpoint, []string{"127.0.0.1:4056"}) + <-time.After(1 * time.Second) } func TestSubscriptionHandling(t *testing.T) { subscriptionParams := GetSubscriptionparams() Subscription.SetResponseCB(func(resp *clientmodel.SubscriptionResponse) { + fmt.Println("TestSubscriptionHandling: notification received") assert.Equal(t, len(resp.SubscriptionInstances), 1) assert.Equal(t, *resp.SubscriptionInstances[0].XappEventInstanceID, int64(11)) assert.Equal(t, *resp.SubscriptionInstances[0].E2EventInstanceID, int64(22)) @@ -69,13 +71,15 @@ func TestSubscriptionHandling(t *testing.T) { _, err := Subscription.Subscribe(subscriptionParams) assert.Equal(t, err, nil) + <-time.After(1 * time.Second) } func TestSubscriptionWithClientProvidedIdHandling(t *testing.T) { subscriptionParams := GetSubscriptionparams() subscriptionParams.SubscriptionID = "myxapp" - + Subscription.SetResponseCB(func(resp *clientmodel.SubscriptionResponse) { + fmt.Println("TestSubscriptionWithClientProvidedIdHandling: notification received") assert.Equal(t, len(resp.SubscriptionInstances), 1) assert.Equal(t, *resp.SubscriptionInstances[0].XappEventInstanceID, int64(11)) assert.Equal(t, *resp.SubscriptionInstances[0].E2EventInstanceID, int64(22)) @@ -83,36 +87,69 @@ func TestSubscriptionWithClientProvidedIdHandling(t *testing.T) { _, err := Subscription.Subscribe(subscriptionParams) assert.Equal(t, err, nil) + <-time.After(1 * time.Second) } -func TestBadRequestSubscriptionHandling(t *testing.T) { +func TestFailureNotificationHandling(t *testing.T) { subscriptionParams := GetSubscriptionparams() - subscriptionParams.SubscriptionID = "123_send_bad_request_response" + subscriptionParams.SubscriptionID = "send_failure_notification" Subscription.SetResponseCB(func(resp *clientmodel.SubscriptionResponse) { assert.Equal(t, len(resp.SubscriptionInstances), 1) assert.Equal(t, *resp.SubscriptionInstances[0].XappEventInstanceID, int64(11)) - assert.Equal(t, *resp.SubscriptionInstances[0].E2EventInstanceID, int64(22)) + assert.Equal(t, *resp.SubscriptionInstances[0].E2EventInstanceID, int64(0)) + assert.Equal(t, resp.SubscriptionInstances[0].ErrorCause, "Some error") + assert.Equal(t, resp.SubscriptionInstances[0].ErrorSource, "SUBMGR") + assert.Equal(t, resp.SubscriptionInstances[0].TimeoutType, "E2-Timeout") }) + _, err := Subscription.Subscribe(subscriptionParams) + assert.Equal(t, err, nil) + <-time.After(1 * time.Second) +} + +func TestBadRequestSubscriptionHandling(t *testing.T) { + subscriptionParams := GetSubscriptionparams() + subscriptionParams.SubscriptionID = "send_400_bad_request_response" + + // Notification is not coming + _, err := Subscription.Subscribe(subscriptionParams) assert.Equal(t, err.Error(), "[POST /subscriptions][400] subscribeBadRequest ") - fmt.Println("Error:",err) + fmt.Println("Error:", err) +} + +func TestNotFoundRequestSubscriptionHandling(t *testing.T) { + subscriptionParams := GetSubscriptionparams() + subscriptionParams.SubscriptionID = "send_404_not_found_response" + + // Notification is not coming + + _, err := Subscription.Subscribe(subscriptionParams) + assert.Equal(t, err.Error(), "[POST /subscriptions][404] subscribeNotFound ") + fmt.Println("Error:", err) } func TestInternalServerErrorSubscriptionHandling(t *testing.T) { subscriptionParams := GetSubscriptionparams() - subscriptionParams.SubscriptionID = "123_send_internal_server_error_response" + subscriptionParams.SubscriptionID = "send_500_internal_server_error_response" - Subscription.SetResponseCB(func(resp *clientmodel.SubscriptionResponse) { - assert.Equal(t, len(resp.SubscriptionInstances), 1) - assert.Equal(t, *resp.SubscriptionInstances[0].XappEventInstanceID, int64(11)) - assert.Equal(t, *resp.SubscriptionInstances[0].E2EventInstanceID, int64(22)) - }) + // Notification is not coming _, err := Subscription.Subscribe(subscriptionParams) assert.Equal(t, err.Error(), "[POST /subscriptions][500] subscribeInternalServerError ") - fmt.Println("Error:",err) + fmt.Println("Error:", err) +} + +func TestServiceUnavailableSubscriptionHandling(t *testing.T) { + subscriptionParams := GetSubscriptionparams() + subscriptionParams.SubscriptionID = "send_503_Service_Unavailable_response" + + // Notification is not coming + + _, err := Subscription.Subscribe(subscriptionParams) + assert.Equal(t, err.Error(), "[POST /subscriptions][503] subscribeServiceUnavailable ") + fmt.Println("Error:", err) } func GetSubscriptionparams() *clientmodel.SubscriptionParams { @@ -142,25 +179,25 @@ func GetSubscriptionparams() *clientmodel.SubscriptionParams { } func TestSuccessfulSubscriptionDeleteHandling(t *testing.T) { - subscriptionId = "123_send_successful_response" + subscriptionId = "send_201_successful_response" err := Subscription.Unsubscribe(subscriptionId) assert.Equal(t, err, nil) - fmt.Println("Error:",err) + fmt.Println("Error:", err) } func TestBadRequestSubscriptionDeleteHandling(t *testing.T) { - subscriptionId = "123_send_bad_request_response" + subscriptionId = "send_400_bad_request_response" err := Subscription.Unsubscribe(subscriptionId) assert.NotEqual(t, err, nil) - fmt.Println("Error:",err.Error()) + fmt.Println("Error:", err.Error()) assert.Equal(t, err.Error(), "[DELETE /subscriptions/{subscriptionId}][400] unsubscribeBadRequest ") } func TestInternalServerErrorSubscriptionDeleteHandling(t *testing.T) { - subscriptionId = "123_send_internal_server_error_response" + subscriptionId = "send_500_internal_server_error_response" err := Subscription.Unsubscribe(subscriptionId) assert.NotEqual(t, err, nil) - fmt.Println("Error:",err.Error()) + fmt.Println("Error:", err.Error()) assert.Equal(t, err.Error(), "[DELETE /subscriptions/{subscriptionId}][500] unsubscribeInternalServerError ") } @@ -188,22 +225,51 @@ func SubscriptionRespHandler(resp *clientmodel.SubscriptionResponse) { } func processSubscriptions(subscriptionId string) { - // Generate requestorId, instanceId + + // Generate xappInstanceId xappInstanceId := int64(11) - e2InstanceId := int64(22) - resp := &models.SubscriptionResponse{ - SubscriptionID: &subscriptionId, - SubscriptionInstances: []*models.SubscriptionInstance{ - { - XappEventInstanceID: &xappInstanceId, - E2EventInstanceID: &e2InstanceId, + if subscriptionId == "send_failure_notification" { + fmt.Println("Sending error notification") + + // Generate e2InstanceId + e2InstanceId := int64(0) + resp := &models.SubscriptionResponse{ + SubscriptionID: &subscriptionId, + SubscriptionInstances: []*models.SubscriptionInstance{ + { + XappEventInstanceID: &xappInstanceId, + E2EventInstanceID: &e2InstanceId, + ErrorCause: "Some error", + ErrorSource: "SUBMGR", + TimeoutType: "E2-Timeout", + }, }, - }, - } + } - // Notify the client: don't worry about errors ... Notify() will handle retries, etc. - Subscription.Notify(resp, models.SubscriptionParamsClientEndpoint{Host: "localhost", HTTPPort: &hPort, RMRPort: &rPort}) + Subscription.Notify(resp, models.SubscriptionParamsClientEndpoint{Host: "localhost", HTTPPort: &hPort, RMRPort: &rPort}) + return + } else { + + fmt.Println("Sending successful notification") + + // Generate e2InstanceId + e2InstanceId := int64(22) + + resp := &models.SubscriptionResponse{ + SubscriptionID: &subscriptionId, + SubscriptionInstances: []*models.SubscriptionInstance{ + { + XappEventInstanceID: &xappInstanceId, + E2EventInstanceID: &e2InstanceId, + }, + }, + } + + // Notify the client: don't worry about errors ... Notify() will handle retries, etc. + Subscription.Notify(resp, models.SubscriptionParamsClientEndpoint{Host: "localhost", HTTPPort: &hPort, RMRPort: &rPort}) + return + } } func subscriptionHandler(params interface{}) (*models.SubscriptionResponse, int) { @@ -225,21 +291,29 @@ func subscriptionHandler(params interface{}) (*models.SubscriptionResponse, int) assert.Equal(suite, timeToWait, *p.SubscriptionDetails[0].ActionToBeSetupList[0].SubsequentAction.TimeToWait) assert.ElementsMatch(suite, []int64{5, 6, 7, 8}, p.SubscriptionDetails[0].ActionToBeSetupList[0].ActionDefinition) - // Generate a unique subscriptionId - subscriptionId = fmt.Sprintf("%s-%s", meid, clientEndpoint.Host) - - if p.SubscriptionID == "123_send_bad_request_response" { - // Simulate bad request case - return &models.SubscriptionResponse{ - }, common.UnsubscribeBadRequestCode - + if p.SubscriptionID != "send_failure_notification" { + // Generate a unique subscriptionId + subscriptionId = fmt.Sprintf("%s-%s", meid, clientEndpoint.Host) + } else { + subscriptionId = "send_failure_notification" } - - if p.SubscriptionID == "123_send_internal_server_error_response" { - // Simulate bad internal server error case - return &models.SubscriptionResponse{ - }, common.UnsubscribeInternalServerErrorCode + if p.SubscriptionID == "send_400_bad_request_response" { + fmt.Println("send_400_bad_request_response") + return &models.SubscriptionResponse{}, common.SubscribeBadRequestCode } + if p.SubscriptionID == "send_404_not_found_response" { + fmt.Println("send_404_not_found_response") + return &models.SubscriptionResponse{}, common.SubscribeNotFoundCode + } + if p.SubscriptionID == "send_500_internal_server_error_response" { + fmt.Println("send_500_internal_server_error_response") + return &models.SubscriptionResponse{}, common.SubscribeInternalServerErrorCode + } + if p.SubscriptionID == "send_503_Service_Unavailable_response" { + fmt.Println("send_503_Service_Unavailable_response") + return &models.SubscriptionResponse{}, common.SubscribeServiceUnavailableCode + } + // Process subscriptions on the background go processSubscriptions(subscriptionId) @@ -262,11 +336,14 @@ func queryHandler() (models.SubscriptionList, error) { func deleteHandler(ep string) int { assert.Equal(suite, subscriptionId, ep) - if subscriptionId == "123_send_successful_response" { + if subscriptionId == "send_201_successful_response" { return common.UnsubscribeNoContentCode - } else if subscriptionId == "123_send_bad_request_response" { + } else if subscriptionId == "send_400_bad_request_response" { return common.UnsubscribeBadRequestCode - } else { + } else if subscriptionId == "send_500_internal_server_error_response" { return common.UnsubscribeInternalServerErrorCode + } else { + fmt.Println("Unknown subscriptionId:", subscriptionId) + return 0 } } diff --git a/pkg/xapp/xapp.go b/pkg/xapp/xapp.go index 151b14b..a38efbc 100755 --- a/pkg/xapp/xapp.go +++ b/pkg/xapp/xapp.go @@ -37,6 +37,7 @@ import ( ) // For testing purpose go version 1.13 -> + var _ = func() bool { testing.Init() return true