From a7b869f553c9d10bb03778e4dbabc16b7654bb47 Mon Sep 17 00:00:00 2001 From: tasmiyafathima14 Date: Mon, 29 May 2023 10:50:42 +0530 Subject: [PATCH 01/19] updating latest redis support --- build/Redis/Dockerfile.redis | 2 +- install/Docker/dockerfiles/Dockerfile.redis | 2 +- .../helmcharts/redis-ha/Chart.yaml | 4 ++-- odim-controller/helmcharts/redis/Chart.yaml | 4 ++-- .../helmcharts/redis/templates/_helpers.tpl | 20 +++++++++---------- .../odimra/group_vars/all/all.yaml | 10 +++++----- 6 files changed, 21 insertions(+), 21 deletions(-) diff --git a/build/Redis/Dockerfile.redis b/build/Redis/Dockerfile.redis index c2552ed4b..b376e18bf 100755 --- a/build/Redis/Dockerfile.redis +++ b/build/Redis/Dockerfile.redis @@ -11,7 +11,7 @@ #WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the #License for the specific language governing permissions and limitations # under the License. -FROM redis:7.0.8 +FROM redis:7.0.11 COPY Redis/start2db.sh /usr/local/bin/ COPY Redis/createschema.sh /usr/local/bin/ diff --git a/install/Docker/dockerfiles/Dockerfile.redis b/install/Docker/dockerfiles/Dockerfile.redis index f931c7bf2..3c12d143c 100644 --- a/install/Docker/dockerfiles/Dockerfile.redis +++ b/install/Docker/dockerfiles/Dockerfile.redis @@ -12,7 +12,7 @@ #License for the specific language governing permissions and limitations # under the License. -FROM redis:7.0.8 +FROM redis:7.0.11 ARG ODIMRA_USER_ID ARG ODIMRA_GROUP_ID diff --git a/odim-controller/helmcharts/redis-ha/Chart.yaml b/odim-controller/helmcharts/redis-ha/Chart.yaml index 0846aeaf2..8eab5d7c8 100644 --- a/odim-controller/helmcharts/redis-ha/Chart.yaml +++ b/odim-controller/helmcharts/redis-ha/Chart.yaml @@ -1,5 +1,5 @@ apiVersion: v2 -name: redis-ha-7.0.8 +name: redis-ha-7.0.11 description: A Helm chart for redis # A chart can be either an 'application' or a 'library' chart. @@ -20,4 +20,4 @@ version: 4.0.0 # This is the version number of the application being deployed. This version number should be # incremented each time you make changes to the application. Versions are not expected to # follow Semantic Versioning. They should reflect the version the application is using. -appVersion: 7.0.8 +appVersion: 7.0.11 diff --git a/odim-controller/helmcharts/redis/Chart.yaml b/odim-controller/helmcharts/redis/Chart.yaml index d424b844a..d2457fa6d 100644 --- a/odim-controller/helmcharts/redis/Chart.yaml +++ b/odim-controller/helmcharts/redis/Chart.yaml @@ -1,5 +1,5 @@ apiVersion: v2 -name: redis-7.0.8 +name: redis-7.0.11 description: A Helm chart for redis # A chart can be either an 'application' or a 'library' chart. @@ -20,4 +20,4 @@ version: 4.0.0 # This is the version number of the application being deployed. This version number should be # incremented each time you make changes to the application. Versions are not expected to # follow Semantic Versioning. They should reflect the version the application is using. -appVersion: 7.0.8 +appVersion: 7.0.11 diff --git a/odim-controller/helmcharts/redis/templates/_helpers.tpl b/odim-controller/helmcharts/redis/templates/_helpers.tpl index ca49c11a4..ab935afe7 100644 --- a/odim-controller/helmcharts/redis/templates/_helpers.tpl +++ b/odim-controller/helmcharts/redis/templates/_helpers.tpl @@ -1,7 +1,7 @@ {{/* Expand the name of the chart. */}} -{{- define "redis-7.0.8.name" -}} +{{- define "redis-7.0.11.name" -}} {{- default .Chart.Name .Values.nameOverride | trunc 63 | trimSuffix "-" }} {{- end }} @@ -10,7 +10,7 @@ Create a default fully qualified app name. We truncate at 63 chars because some Kubernetes name fields are limited to this (by the DNS naming spec). If release name contains chart name it will be used as a full name. */}} -{{- define "redis-7.0.8.fullname" -}} +{{- define "redis-7.0.11.fullname" -}} {{- if .Values.fullnameOverride }} {{- .Values.fullnameOverride | trunc 63 | trimSuffix "-" }} {{- else }} @@ -26,16 +26,16 @@ If release name contains chart name it will be used as a full name. {{/* Create chart name and version as used by the chart label. */}} -{{- define "redis-7.0.8.chart" -}} +{{- define "redis-7.0.11.chart" -}} {{- printf "%s-%s" .Chart.Name .Chart.Version | replace "+" "_" | trunc 63 | trimSuffix "-" }} {{- end }} {{/* Common labels */}} -{{- define "redis-7.0.8.labels" -}} -helm.sh/chart: {{ include "redis-7.0.8.chart" . }} -{{ include "redis-7.0.8.selectorLabels" . }} +{{- define "redis-7.0.11.labels" -}} +helm.sh/chart: {{ include "redis-7.0.11.chart" . }} +{{ include "redis-7.0.11.selectorLabels" . }} {{- if .Chart.AppVersion }} app.kubernetes.io/version: {{ .Chart.AppVersion | quote }} {{- end }} @@ -45,17 +45,17 @@ app.kubernetes.io/managed-by: {{ .Release.Service }} {{/* Selector labels */}} -{{- define "redis-7.0.8.selectorLabels" -}} -app.kubernetes.io/name: {{ include "redis-7.0.8.name" . }} +{{- define "redis-7.0.11.selectorLabels" -}} +app.kubernetes.io/name: {{ include "redis-7.0.11.name" . }} app.kubernetes.io/instance: {{ .Release.Name }} {{- end }} {{/* Create the name of the service account to use */}} -{{- define "redis-7.0.8.serviceAccountName" -}} +{{- define "redis-7.0.11.serviceAccountName" -}} {{- if .Values.serviceAccount.create }} -{{- default (include "redis-7.0.8.fullname" .) .Values.serviceAccount.name }} +{{- default (include "redis-7.0.11.fullname" .) .Values.serviceAccount.name }} {{- else }} {{- default "default" .Values.serviceAccount.name }} {{- end }} diff --git a/odim-controller/odimra/group_vars/all/all.yaml b/odim-controller/odimra/group_vars/all/all.yaml index 7326e1b99..29aeb352f 100755 --- a/odim-controller/odimra/group_vars/all/all.yaml +++ b/odim-controller/odimra/group_vars/all/all.yaml @@ -22,23 +22,23 @@ odim_pv_pvc_secrets_helmcharts: odimra-k8s-access-config: odimra-k8s-access-config-1.0.0 odim_third_party_helmcharts: zookeeper: zookeeper-3.7.0-0.2.0 - redis: redis-7.0.8-4.0.0 + redis: redis-7.0.11-4.0.0 kafka: kafka-3.1.0-0.2.0 etcd: etcd-1.0.0 odim_Kafka_helmcharts: zookeeper: zookeeper-3.7.0-0.2.0 - redis: redis-7.0.8-4.0.0 + redis: redis-7.0.11-4.0.0 kafka: kafka-3.1.0-0.2.0 etcd: etcd-1.0.0 odim_Redis_helmcharts: - redis: redis-7.0.8-4.0.0 + redis: redis-7.0.11-4.0.0 etcd: etcd-1.0.0 odim_third_party_har_helmcharts: - redis: redis-ha-7.0.8-4.0.0 + redis: redis-ha-7.0.11-4.0.0 etcd: etcd-ha-1.0.0 odim_third_party_ha_helmcharts: zookeeper: zookeeper-ha-3.7.0-0.2.0 - redis: redis-ha-7.0.8-4.0.0 + redis: redis-ha-7.0.11-4.0.0 kafka: kafka-ha-3.1.0-0.2.0 etcd: etcd-ha-1.0.0 odim_svc_helmcharts: From 2df2fed216e52f1ab43bc3e8146d25d084aacdba Mon Sep 17 00:00:00 2001 From: tasmiyafathima14 Date: Tue, 30 May 2023 18:10:29 +0530 Subject: [PATCH 02/19] updating redis version --- build_images.sh | 2 +- odim-controller/helmcharts/redis-ha/Chart.yaml | 2 +- odim-controller/helmcharts/redis-ha/values.yaml | 2 +- odim-controller/helmcharts/redis/Chart.yaml | 2 +- odim-controller/helmcharts/redis/values.yaml | 2 +- 5 files changed, 5 insertions(+), 5 deletions(-) diff --git a/build_images.sh b/build_images.sh index bd7d248ac..1b4f9ac21 100755 --- a/build_images.sh +++ b/build_images.sh @@ -54,7 +54,7 @@ eval_cmd_exec "/usr/bin/docker build -f install/Docker/dockerfiles/Dockerfile.od # third party docker images eval_cmd_exec "/usr/bin/docker build -f install/Docker/dockerfiles/Dockerfile.etcd -t etcd:1.16 ." "etcd" -eval_cmd_exec "/usr/bin/docker build -f install/Docker/dockerfiles/Dockerfile.redis -t redis:4.0 ." "redis" +eval_cmd_exec "/usr/bin/docker build -f install/Docker/dockerfiles/Dockerfile.redis -t redis:5.0 ." "redis" eval_cmd_exec "/usr/bin/docker build -f install/Docker/dockerfiles/Dockerfile.kafka -t kafka:2.0 ." "kafka" eval_cmd_exec "/usr/bin/docker build -f install/Docker/dockerfiles/Dockerfile.zookeeper -t zookeeper:2.0 ." "zookeeper" diff --git a/odim-controller/helmcharts/redis-ha/Chart.yaml b/odim-controller/helmcharts/redis-ha/Chart.yaml index 8eab5d7c8..a1c493e8c 100644 --- a/odim-controller/helmcharts/redis-ha/Chart.yaml +++ b/odim-controller/helmcharts/redis-ha/Chart.yaml @@ -15,7 +15,7 @@ type: application # This is the chart version. This version number should be incremented each time you make changes # to the chart and its templates, including the app version. # Versions are expected to follow Semantic Versioning (https://semver.org/) -version: 4.0.0 +version: 5.0.0 # This is the version number of the application being deployed. This version number should be # incremented each time you make changes to the application. Versions are not expected to diff --git a/odim-controller/helmcharts/redis-ha/values.yaml b/odim-controller/helmcharts/redis-ha/values.yaml index 7886282c9..bb4a99b38 100644 --- a/odim-controller/helmcharts/redis-ha/values.yaml +++ b/odim-controller/helmcharts/redis-ha/values.yaml @@ -1,5 +1,5 @@ odimra: - redisImageTag: "4.0" + redisImageTag: "5.0" namespace: groupID: redisOndiskDataPath: diff --git a/odim-controller/helmcharts/redis/Chart.yaml b/odim-controller/helmcharts/redis/Chart.yaml index d2457fa6d..c8c1a9c3c 100644 --- a/odim-controller/helmcharts/redis/Chart.yaml +++ b/odim-controller/helmcharts/redis/Chart.yaml @@ -15,7 +15,7 @@ type: application # This is the chart version. This version number should be incremented each time you make changes # to the chart and its templates, including the app version. # Versions are expected to follow Semantic Versioning (https://semver.org/) -version: 4.0.0 +version: 5.0.0 # This is the version number of the application being deployed. This version number should be # incremented each time you make changes to the application. Versions are not expected to diff --git a/odim-controller/helmcharts/redis/values.yaml b/odim-controller/helmcharts/redis/values.yaml index 277d0f176..c9f37cb30 100644 --- a/odim-controller/helmcharts/redis/values.yaml +++ b/odim-controller/helmcharts/redis/values.yaml @@ -1,6 +1,6 @@ odimra: namespace: groupID: - redisImageTag: "4.0" + redisImageTag: "5.0" redisInMemoryPassword: redisOnDiskPassword: From f8ba53c80cb4be38b2300ed6da42ba815eca0743 Mon Sep 17 00:00:00 2001 From: tasmiyafathima14 Date: Sat, 3 Jun 2023 18:57:59 +0530 Subject: [PATCH 03/19] updating redis version --- odim-controller/odimra/group_vars/all/all.yaml | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/odim-controller/odimra/group_vars/all/all.yaml b/odim-controller/odimra/group_vars/all/all.yaml index 29aeb352f..f8100ddad 100755 --- a/odim-controller/odimra/group_vars/all/all.yaml +++ b/odim-controller/odimra/group_vars/all/all.yaml @@ -22,23 +22,23 @@ odim_pv_pvc_secrets_helmcharts: odimra-k8s-access-config: odimra-k8s-access-config-1.0.0 odim_third_party_helmcharts: zookeeper: zookeeper-3.7.0-0.2.0 - redis: redis-7.0.11-4.0.0 + redis: redis-7.0.11-5.0.0 kafka: kafka-3.1.0-0.2.0 etcd: etcd-1.0.0 odim_Kafka_helmcharts: zookeeper: zookeeper-3.7.0-0.2.0 - redis: redis-7.0.11-4.0.0 + redis: redis-7.0.11-5.0.0 kafka: kafka-3.1.0-0.2.0 etcd: etcd-1.0.0 odim_Redis_helmcharts: - redis: redis-7.0.11-4.0.0 + redis: redis-7.0.11-5.0.0 etcd: etcd-1.0.0 odim_third_party_har_helmcharts: - redis: redis-ha-7.0.11-4.0.0 + redis: redis-ha-7.0.11-5.0.0 etcd: etcd-ha-1.0.0 odim_third_party_ha_helmcharts: zookeeper: zookeeper-ha-3.7.0-0.2.0 - redis: redis-ha-7.0.11-4.0.0 + redis: redis-ha-7.0.11-5.0.0 kafka: kafka-ha-3.1.0-0.2.0 etcd: etcd-ha-1.0.0 odim_svc_helmcharts: From 72ae43e2fec22ce13a77eb97eca16ffe08a8a2d6 Mon Sep 17 00:00:00 2001 From: Banoshi Date: Thu, 15 Jun 2023 00:25:52 +0530 Subject: [PATCH 04/19] remove code duplicates from svc-api --- lib-utilities/common/crypto_test.go | 18 +- lib-utilities/common/dbconn_test.go | 18 +- lib-utilities/common/jobqueue_test.go | 18 +- lib-utilities/common/mockconfig_test.go | 18 +- lib-utilities/common/responses.go | 28 ++ lib-utilities/common/workerpool_test.go | 18 +- lib-utilities/config/mockconfig_test.go | 18 +- lib-utilities/errors/error.go | 6 +- lib-utilities/errors/error_test.go | 18 +- lib-utilities/response/errorresponse.go | 2 +- lib-utilities/response/errorresponse_test.go | 18 +- .../response/successresponse_test.go | 18 +- lib-utilities/services/pluginTask.go | 144 +++--- svc-api/handle/account.go | 144 ++---- svc-api/handle/aggregator.go | 472 +++++------------- svc-api/handle/aggregator_test.go | 210 ++++---- svc-api/handle/chassis.go | 12 +- svc-api/handle/compositionservice.go | 241 +++------ svc-api/handle/compositionservice_test.go | 16 +- svc-api/handle/events.go | 110 +--- svc-api/handle/fabrics.go | 359 ++++--------- svc-api/handle/handlers.go | 60 +-- svc-api/handle/licenses.go | 33 +- svc-api/handle/managers.go | 249 +++------ svc-api/handle/role.go | 81 +-- svc-api/handle/systems.go | 307 +++--------- svc-api/handle/task.go | 43 +- svc-api/handle/telemetry.go | 187 ++----- svc-api/handle/update.go | 158 ++---- svc-api/messages/sessions.go | 2 +- svc-api/models/metadata.go | 8 +- svc-api/models/odata.go | 6 +- svc-api/models/serviceroot.go | 16 +- svc-api/models/version.go | 4 +- svc-api/response/accounts.go | 22 +- svc-api/response/error.go | 2 +- svc-api/response/list.go | 2 +- svc-api/response/registries.go | 6 +- svc-api/response/session.go | 8 +- svc-api/rpc/composition_service.go | 2 +- 40 files changed, 1024 insertions(+), 2078 deletions(-) diff --git a/lib-utilities/common/crypto_test.go b/lib-utilities/common/crypto_test.go index b77fea02a..0b376ef78 100644 --- a/lib-utilities/common/crypto_test.go +++ b/lib-utilities/common/crypto_test.go @@ -1,15 +1,15 @@ -//(C) Copyright [2020] Hewlett Packard Enterprise Development LP +// (C) Copyright [2020] Hewlett Packard Enterprise Development LP // -//Licensed under the Apache License, Version 2.0 (the "License"); you may -//not use this file except in compliance with the License. You may obtain -//a copy of the License at +// Licensed under the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. You may obtain +// a copy of the License at // -// http://www.apache.org/licenses/LICENSE-2.0 +// http://www.apache.org/licenses/LICENSE-2.0 // -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -//WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -//License for the specific language governing permissions and limitations +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +// License for the specific language governing permissions and limitations // under the License. package common diff --git a/lib-utilities/common/dbconn_test.go b/lib-utilities/common/dbconn_test.go index 58c7ef353..eff58d4d3 100644 --- a/lib-utilities/common/dbconn_test.go +++ b/lib-utilities/common/dbconn_test.go @@ -1,15 +1,15 @@ -//(C) Copyright [2020] Hewlett Packard Enterprise Development LP +// (C) Copyright [2020] Hewlett Packard Enterprise Development LP // -//Licensed under the Apache License, Version 2.0 (the "License"); you may -//not use this file except in compliance with the License. You may obtain -//a copy of the License at +// Licensed under the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. You may obtain +// a copy of the License at // -// http://www.apache.org/licenses/LICENSE-2.0 +// http://www.apache.org/licenses/LICENSE-2.0 // -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -//WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -//License for the specific language governing permissions and limitations +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +// License for the specific language governing permissions and limitations // under the License. package common diff --git a/lib-utilities/common/jobqueue_test.go b/lib-utilities/common/jobqueue_test.go index 772e8e0a4..7bb116657 100644 --- a/lib-utilities/common/jobqueue_test.go +++ b/lib-utilities/common/jobqueue_test.go @@ -1,15 +1,15 @@ -//(C) Copyright [2020] Hewlett Packard Enterprise Development LP +// (C) Copyright [2020] Hewlett Packard Enterprise Development LP // -//Licensed under the Apache License, Version 2.0 (the "License"); you may -//not use this file except in compliance with the License. You may obtain -//a copy of the License at +// Licensed under the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. You may obtain +// a copy of the License at // -// http://www.apache.org/licenses/LICENSE-2.0 +// http://www.apache.org/licenses/LICENSE-2.0 // -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -//WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -//License for the specific language governing permissions and limitations +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +// License for the specific language governing permissions and limitations // under the License. package common diff --git a/lib-utilities/common/mockconfig_test.go b/lib-utilities/common/mockconfig_test.go index f8e68602e..50275aaba 100644 --- a/lib-utilities/common/mockconfig_test.go +++ b/lib-utilities/common/mockconfig_test.go @@ -1,15 +1,15 @@ -//(C) Copyright [2020] Hewlett Packard Enterprise Development LP +// (C) Copyright [2020] Hewlett Packard Enterprise Development LP // -//Licensed under the Apache License, Version 2.0 (the "License"); you may -//not use this file except in compliance with the License. You may obtain -//a copy of the License at +// Licensed under the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. You may obtain +// a copy of the License at // -// http://www.apache.org/licenses/LICENSE-2.0 +// http://www.apache.org/licenses/LICENSE-2.0 // -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -//WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -//License for the specific language governing permissions and limitations +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +// License for the specific language governing permissions and limitations // under the License. package common diff --git a/lib-utilities/common/responses.go b/lib-utilities/common/responses.go index 4714500bf..aabc3483b 100644 --- a/lib-utilities/common/responses.go +++ b/lib-utilities/common/responses.go @@ -19,6 +19,7 @@ import ( "context" "net/http" + "github.com/ODIM-Project/ODIM/lib-utilities/response" iris "github.com/kataras/iris/v12" "google.golang.org/grpc/metadata" ) @@ -118,3 +119,30 @@ func CreateContext(transactionID, actionID, actionName, threadID, threadName, pr ctx = context.WithValue(ctx, ProcessName, processName) return ctx } + +// SendInvalidSessionResponse writes the response to client when no valid session is found +func SendInvalidSessionResponse(ctx iris.Context, errorMessage string) { + response := GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) + SetResponseHeader(ctx, response.Header) + ctx.StatusCode(http.StatusUnauthorized) + ctx.JSON(&response.Body) + return +} + +// SendFailedRPCCallResponse writes the response to client when a RPC call fails +func SendFailedRPCCallResponse(ctx iris.Context, errorMessage string) { + response := GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) + SetResponseHeader(ctx, response.Header) + ctx.StatusCode(http.StatusInternalServerError) + ctx.JSON(&response.Body) + return +} + +// SendMalformedJSONRequestErrResponse writes the response to client when the request contains malformed JSON structure +func SendMalformedJSONRequestErrResponse(ctx iris.Context, errorMessage string) { + response := GeneralError(http.StatusBadRequest, response.MalformedJSON, errorMessage, nil, nil) + SetResponseHeader(ctx, response.Header) + ctx.StatusCode(http.StatusBadRequest) + ctx.JSON(&response.Body) + return +} diff --git a/lib-utilities/common/workerpool_test.go b/lib-utilities/common/workerpool_test.go index 6c78e0495..8f4855753 100644 --- a/lib-utilities/common/workerpool_test.go +++ b/lib-utilities/common/workerpool_test.go @@ -1,15 +1,15 @@ -//(C) Copyright [2020] Hewlett Packard Enterprise Development LP +// (C) Copyright [2020] Hewlett Packard Enterprise Development LP // -//Licensed under the Apache License, Version 2.0 (the "License"); you may -//not use this file except in compliance with the License. You may obtain -//a copy of the License at +// Licensed under the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. You may obtain +// a copy of the License at // -// http://www.apache.org/licenses/LICENSE-2.0 +// http://www.apache.org/licenses/LICENSE-2.0 // -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -//WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -//License for the specific language governing permissions and limitations +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +// License for the specific language governing permissions and limitations // under the License. package common diff --git a/lib-utilities/config/mockconfig_test.go b/lib-utilities/config/mockconfig_test.go index cdab657ab..d7b9e97ae 100644 --- a/lib-utilities/config/mockconfig_test.go +++ b/lib-utilities/config/mockconfig_test.go @@ -1,15 +1,15 @@ -//(C) Copyright [2020] Hewlett Packard Enterprise Development LP +// (C) Copyright [2020] Hewlett Packard Enterprise Development LP // -//Licensed under the Apache License, Version 2.0 (the "License"); you may -//not use this file except in compliance with the License. You may obtain -//a copy of the License at +// Licensed under the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. You may obtain +// a copy of the License at // -// http://www.apache.org/licenses/LICENSE-2.0 +// http://www.apache.org/licenses/LICENSE-2.0 // -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -//WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -//License for the specific language governing permissions and limitations +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +// License for the specific language governing permissions and limitations // under the License. // package ... package config diff --git a/lib-utilities/errors/error.go b/lib-utilities/errors/error.go index b426d6b87..97f2fe729 100644 --- a/lib-utilities/errors/error.go +++ b/lib-utilities/errors/error.go @@ -21,19 +21,19 @@ import ( "net/http" ) -//CommonError struct definition +// CommonError struct definition type CommonError struct { Error ErrorClass `json:"error"` } -//ErrorClass struct definition +// ErrorClass struct definition type ErrorClass struct { Code string `json:"code"` Message string `json:"message"` MessageExtendedInfo []MsgExtendedInfo `json:"@Message.ExtendedInfo,omitempty"` } -//MsgExtendedInfo struct definition +// MsgExtendedInfo struct definition type MsgExtendedInfo struct { OdataType string `json:"@odata.type,omitempty"` MessageID string `json:"MessageId,omitempty"` diff --git a/lib-utilities/errors/error_test.go b/lib-utilities/errors/error_test.go index 91ed232f6..2a54eb8bf 100644 --- a/lib-utilities/errors/error_test.go +++ b/lib-utilities/errors/error_test.go @@ -1,15 +1,15 @@ -//(C) Copyright [2020] Hewlett Packard Enterprise Development LP +// (C) Copyright [2020] Hewlett Packard Enterprise Development LP // -//Licensed under the Apache License, Version 2.0 (the "License"); you may -//not use this file except in compliance with the License. You may obtain -//a copy of the License at +// Licensed under the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. You may obtain +// a copy of the License at // -// http://www.apache.org/licenses/LICENSE-2.0 +// http://www.apache.org/licenses/LICENSE-2.0 // -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -//WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -//License for the specific language governing permissions and limitations +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +// License for the specific language governing permissions and limitations // under the License. package errors diff --git a/lib-utilities/response/errorresponse.go b/lib-utilities/response/errorresponse.go index cea33da7e..ce838cda1 100644 --- a/lib-utilities/response/errorresponse.go +++ b/lib-utilities/response/errorresponse.go @@ -353,7 +353,7 @@ func (a *Args) CreateGenericErrorResponse() CommonError { return e } -//CreateInternalErrorResponse is used to create internal server error response +// CreateInternalErrorResponse is used to create internal server error response func (resp *RPC) CreateInternalErrorResponse(errorMessage string) { resp.StatusCode = http.StatusInternalServerError resp.StatusMessage = InternalError diff --git a/lib-utilities/response/errorresponse_test.go b/lib-utilities/response/errorresponse_test.go index 63baf6c42..02df0d902 100644 --- a/lib-utilities/response/errorresponse_test.go +++ b/lib-utilities/response/errorresponse_test.go @@ -1,15 +1,15 @@ -//(C) Copyright [2020] Hewlett Packard Enterprise Development LP +// (C) Copyright [2020] Hewlett Packard Enterprise Development LP // -//Licensed under the Apache License, Version 2.0 (the "License"); you may -//not use this file except in compliance with the License. You may obtain -//a copy of the License at +// Licensed under the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. You may obtain +// a copy of the License at // -// http://www.apache.org/licenses/LICENSE-2.0 +// http://www.apache.org/licenses/LICENSE-2.0 // -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -//WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -//License for the specific language governing permissions and limitations +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +// License for the specific language governing permissions and limitations // under the License. package response diff --git a/lib-utilities/response/successresponse_test.go b/lib-utilities/response/successresponse_test.go index 98270444b..48533c999 100644 --- a/lib-utilities/response/successresponse_test.go +++ b/lib-utilities/response/successresponse_test.go @@ -1,15 +1,15 @@ -//(C) Copyright [2020] Hewlett Packard Enterprise Development LP +// (C) Copyright [2020] Hewlett Packard Enterprise Development LP // -//Licensed under the Apache License, Version 2.0 (the "License"); you may -//not use this file except in compliance with the License. You may obtain -//a copy of the License at +// Licensed under the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. You may obtain +// a copy of the License at // -// http://www.apache.org/licenses/LICENSE-2.0 +// http://www.apache.org/licenses/LICENSE-2.0 // -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -//WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -//License for the specific language governing permissions and limitations +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +// License for the specific language governing permissions and limitations // under the License. package response diff --git a/lib-utilities/services/pluginTask.go b/lib-utilities/services/pluginTask.go index d0a16029b..600edb59a 100644 --- a/lib-utilities/services/pluginTask.go +++ b/lib-utilities/services/pluginTask.go @@ -1,72 +1,72 @@ -//(C) Copyright [2023] Hewlett Packard Enterprise Development LP -// -//Licensed under the Apache License, Version 2.0 (the "License"); you may -//not use this file except in compliance with the License. You may obtain -//a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -//WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -//License for the specific language governing permissions and limitations -// under the License. - -// Package services ... -package services - -import ( - "context" - "fmt" - "strings" - - redis "github.com/ODIM-Project/ODIM/lib-persistence-manager/persistencemgr" - "github.com/ODIM-Project/ODIM/lib-utilities/common" - "github.com/ODIM-Project/ODIM/lib-utilities/errors" -) - -// SavePluginTaskInfo saves the ip of plugin instance that handle the task, -// task id of task which created in odim, and the taskmon URL returned -// from plugin in DB -func SavePluginTaskInfo(ctx context.Context, pluginIP, pluginServerName, - odimTaskID, pluginTaskMonURL string) error { - - pluginTaskID := strings.TrimPrefix(pluginTaskMonURL, "/taskmon/") - pluginTaskInfo := common.PluginTask{ - IP: pluginIP, - PluginServerName: pluginServerName, - OdimTaskID: odimTaskID, - PluginTaskMonURL: pluginTaskMonURL, - } - - err := createPluginTask(ctx, pluginTaskID, pluginTaskInfo) - if err != nil { - return fmt.Errorf("Error while saving plugin task info in DB: %s", - err.Error()) - } - return nil -} - -// createPluginTask will insert plugin task info in DB -func createPluginTask(ctx context.Context, key string, - value interface{}) *errors.Error { - - table := "PluginTask" - connPool, err := redis.GetDBConnection(redis.InMemory) - if err != nil { - return errors.PackError(err.ErrNo(), "error while trying to connecting"+ - " to DB: ", err.Error()) - } - - if err = connPool.Create(table, key, value); err != nil { - return errors.PackError(err.ErrNo(), "error while trying to insert"+ - " plugin task: ", err.Error()) - } - - if err = connPool.AddMemberToSet(common.PluginTaskIndex, key); err != nil { - return errors.PackError(err.ErrNo(), "error while trying to add "+ - " plugin task to set: ", err.Error()) - } - - return nil -} +//(C) Copyright [2023] Hewlett Packard Enterprise Development LP +// +//Licensed under the Apache License, Version 2.0 (the "License"); you may +//not use this file except in compliance with the License. You may obtain +//a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +//Unless required by applicable law or agreed to in writing, software +//distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +//WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +//License for the specific language governing permissions and limitations +// under the License. + +// Package services ... +package services + +import ( + "context" + "fmt" + "strings" + + redis "github.com/ODIM-Project/ODIM/lib-persistence-manager/persistencemgr" + "github.com/ODIM-Project/ODIM/lib-utilities/common" + "github.com/ODIM-Project/ODIM/lib-utilities/errors" +) + +// SavePluginTaskInfo saves the ip of plugin instance that handle the task, +// task id of task which created in odim, and the taskmon URL returned +// from plugin in DB +func SavePluginTaskInfo(ctx context.Context, pluginIP, pluginServerName, + odimTaskID, pluginTaskMonURL string) error { + + pluginTaskID := strings.TrimPrefix(pluginTaskMonURL, "/taskmon/") + pluginTaskInfo := common.PluginTask{ + IP: pluginIP, + PluginServerName: pluginServerName, + OdimTaskID: odimTaskID, + PluginTaskMonURL: pluginTaskMonURL, + } + + err := createPluginTask(ctx, pluginTaskID, pluginTaskInfo) + if err != nil { + return fmt.Errorf("Error while saving plugin task info in DB: %s", + err.Error()) + } + return nil +} + +// createPluginTask will insert plugin task info in DB +func createPluginTask(ctx context.Context, key string, + value interface{}) *errors.Error { + + table := "PluginTask" + connPool, err := redis.GetDBConnection(redis.InMemory) + if err != nil { + return errors.PackError(err.ErrNo(), "error while trying to connecting"+ + " to DB: ", err.Error()) + } + + if err = connPool.Create(table, key, value); err != nil { + return errors.PackError(err.ErrNo(), "error while trying to insert"+ + " plugin task: ", err.Error()) + } + + if err = connPool.AddMemberToSet(common.PluginTaskIndex, key); err != nil { + return errors.PackError(err.ErrNo(), "error while trying to add "+ + " plugin task to set: ", err.Error()) + } + + return nil +} diff --git a/svc-api/handle/account.go b/svc-api/handle/account.go index 0103685ba..a43a991ba 100644 --- a/svc-api/handle/account.go +++ b/svc-api/handle/account.go @@ -18,12 +18,10 @@ package handle import ( "context" "encoding/json" - "net/http" "github.com/ODIM-Project/ODIM/lib-utilities/common" l "github.com/ODIM-Project/ODIM/lib-utilities/logs" accountproto "github.com/ODIM-Project/ODIM/lib-utilities/proto/account" - "github.com/ODIM-Project/ODIM/lib-utilities/response" iris "github.com/kataras/iris/v12" ) @@ -45,34 +43,25 @@ func (a *AccountRPCs) GetAccountService(ctx iris.Context) { defer ctx.Next() ctxt := ctx.Request().Context() req := accountproto.AccountRequest{ - SessionToken: ctx.Request().Header.Get("X-Auth-Token"), + SessionToken: ctx.Request().Header.Get(AuthTokenHeader), } l.LogWithFields(ctx).Debug("Incoming request received for the Get Account service") if req.SessionToken == "" { - errorMessage := "no X-Auth-Token found in request header" + errorMessage := invalidAuthTokenErrMsg l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + common.SendInvalidSessionResponse(ctx, errorMessage) } resp, err := a.GetServiceRPC(ctxt, req) if err != nil && resp == nil { - errorMessage := "something went wrong with the RPC calls: " + err.Error() + errorMessage := rpcCallFailedErrMsg + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) + common.SendFailedRPCCallResponse(ctx, errorMessage) return } l.LogWithFields(ctx).Debugf("Outgoing response for Getting Account service is %s and response status %d", string(resp.Body), int(resp.StatusCode)) ctx.ResponseWriter().Header().Set("Allow", "GET") - common.SetResponseHeader(ctx, resp.Header) - ctx.StatusCode(int(resp.StatusCode)) - ctx.Write(resp.Body) + sendAccountResponse(ctx, resp) } @@ -89,23 +78,15 @@ func (a *AccountRPCs) CreateAccount(ctx iris.Context) { if err != nil { errorMessage := "error while trying to get JSON body from the account create request body: " + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusBadRequest, response.MalformedJSON, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusBadRequest) - ctx.JSON(&response.Body) - return + common.SendMalformedJSONRequestErrResponse(ctx, errorMessage) } l.LogWithFields(ctxt).Debug("Incoming request for create account received") - sessionToken := ctx.Request().Header.Get("X-Auth-Token") + sessionToken := ctx.Request().Header.Get(AuthTokenHeader) if sessionToken == "" { - errorMessage := "no X-Auth-Token found in request header" + errorMessage := invalidAuthTokenErrMsg l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + common.SendInvalidSessionResponse(ctx, errorMessage) } // Marshalling the req to make account request @@ -118,18 +99,13 @@ func (a *AccountRPCs) CreateAccount(ctx iris.Context) { resp, err := a.CreateRPC(ctxt, createRequest) if err != nil && resp == nil { - errorMessage := "something went wrong with the RPC calls: " + err.Error() + errorMessage := rpcCallFailedErrMsg + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) + common.SendFailedRPCCallResponse(ctx, errorMessage) return } - common.SetResponseHeader(ctx, resp.Header) - ctx.StatusCode(int(resp.StatusCode)) - ctx.Write(resp.Body) + sendAccountResponse(ctx, resp) l.LogWithFields(ctxt).Debugf("Outgoing response for create account is %s and response status %d", string(resp.Body), int(resp.StatusCode)) } @@ -142,34 +118,25 @@ func (a *AccountRPCs) GetAllAccounts(ctx iris.Context) { defer ctx.Next() ctxt := ctx.Request().Context() req := accountproto.AccountRequest{ - SessionToken: ctx.Request().Header.Get("X-Auth-Token"), + SessionToken: ctx.Request().Header.Get(AuthTokenHeader), } l.LogWithFields(ctxt).Debug("Incoming request for get all accounts received") if req.SessionToken == "" { - errorMessage := "no X-Auth-Token found in request header" + errorMessage := invalidAuthTokenErrMsg l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + common.SendInvalidSessionResponse(ctx, errorMessage) } resp, err := a.GetAllAccountsRPC(ctxt, req) if err != nil && resp == nil { - errorMessage := "something went wrong with the RPC calls: " + err.Error() + errorMessage := rpcCallFailedErrMsg + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) + common.SendFailedRPCCallResponse(ctx, errorMessage) return } ctx.ResponseWriter().Header().Set("Allow", "GET, POST") - common.SetResponseHeader(ctx, resp.Header) - ctx.StatusCode(int(resp.StatusCode)) - ctx.Write(resp.Body) + sendAccountResponse(ctx, resp) l.LogWithFields(ctxt).Debugf("outgoing response for get all accounts is %s and response status %d", string(resp.Body), int(resp.StatusCode)) } @@ -183,35 +150,26 @@ func (a *AccountRPCs) GetAccount(ctx iris.Context) { defer ctx.Next() ctxt := ctx.Request().Context() req := accountproto.GetAccountRequest{ - SessionToken: ctx.Request().Header.Get("X-Auth-Token"), + SessionToken: ctx.Request().Header.Get(AuthTokenHeader), AccountID: ctx.Params().Get("id"), } l.LogWithFields(ctxt).Debugf("Incoming request for get account info received for %s", req.AccountID) if req.SessionToken == "" { - errorMessage := "no X-Auth-Token found in request header" + errorMessage := invalidAuthTokenErrMsg l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + common.SendInvalidSessionResponse(ctx, errorMessage) } resp, err := a.GetAccountRPC(ctxt, req) if err != nil && resp == nil { - errorMessage := "something went wrong with the RPC calls: " + err.Error() + errorMessage := rpcCallFailedErrMsg + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) + common.SendFailedRPCCallResponse(ctx, errorMessage) return } ctx.ResponseWriter().Header().Set("Allow", "GET, PATCH, DELETE") - common.SetResponseHeader(ctx, resp.Header) - ctx.StatusCode(int(resp.StatusCode)) - ctx.Write(resp.Body) + sendAccountResponse(ctx, resp) l.LogWithFields(ctxt).Debugf("outgoing response for get account is %s and response status %d", string(resp.Body), int(resp.StatusCode)) } @@ -231,24 +189,16 @@ func (a *AccountRPCs) UpdateAccount(ctx iris.Context) { if err != nil { errorMessage := "error while trying to get JSON body from the account update request body: " + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusBadRequest, response.MalformedJSON, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusBadRequest) - ctx.JSON(&response.Body) - return + common.SendMalformedJSONRequestErrResponse(ctx, errorMessage) } - sessionToken := ctx.Request().Header.Get("X-Auth-Token") + sessionToken := ctx.Request().Header.Get(AuthTokenHeader) accountID := ctx.Params().Get("id") l.LogWithFields(ctxt).Debugf("Incoming request for updating account received for %s", accountID) if sessionToken == "" { - errorMessage := "no X-Auth-Token found in request header" + errorMessage := invalidAuthTokenErrMsg l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + common.SendInvalidSessionResponse(ctx, errorMessage) } // Marshalling the req to make account request @@ -262,18 +212,13 @@ func (a *AccountRPCs) UpdateAccount(ctx iris.Context) { resp, err := a.UpdateRPC(ctxt, updateRequest) if err != nil && resp == nil { - errorMessage := "something went wrong with the RPC calls: " + err.Error() + errorMessage := rpcCallFailedErrMsg + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) + common.SendFailedRPCCallResponse(ctx, errorMessage) return } - common.SetResponseHeader(ctx, resp.Header) - ctx.StatusCode(int(resp.StatusCode)) - ctx.Write(resp.Body) + sendAccountResponse(ctx, resp) l.LogWithFields(ctxt).Debugf("outgoing response for updating account is %s and response status %d", string(resp.Body), int(resp.StatusCode)) } @@ -287,34 +232,31 @@ func (a *AccountRPCs) DeleteAccount(ctx iris.Context) { defer ctx.Next() ctxt := ctx.Request().Context() req := accountproto.DeleteAccountRequest{ - SessionToken: ctx.Request().Header.Get("X-Auth-Token"), + SessionToken: ctx.Request().Header.Get(AuthTokenHeader), AccountID: ctx.Params().Get("id"), } l.LogWithFields(ctxt).Debugf("Incoming request for deleting account received with %s", req.AccountID) if req.SessionToken == "" { - errorMessage := "no X-Auth-Token found in request header" + errorMessage := invalidAuthTokenErrMsg l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + common.SendInvalidSessionResponse(ctx, errorMessage) } resp, err := a.DeleteRPC(ctxt, req) if err != nil && resp == nil { - errorMessage := "something went wrong with the RPC calls: " + err.Error() + errorMessage := rpcCallFailedErrMsg + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) + common.SendFailedRPCCallResponse(ctx, errorMessage) return } + sendAccountResponse(ctx, resp) + l.LogWithFields(ctxt).Debugf("outgoing response for deleting account with %s and response status %d", req.AccountID, int(resp.StatusCode)) +} + +// sendAccountResponse writes the account response to client +func sendAccountResponse(ctx iris.Context, resp *accountproto.AccountResponse) { common.SetResponseHeader(ctx, resp.Header) ctx.StatusCode(int(resp.StatusCode)) ctx.Write(resp.Body) - l.LogWithFields(ctxt).Debugf("outgoing response for deleting account with %s and response status %d", req.AccountID, int(resp.StatusCode)) - } diff --git a/svc-api/handle/aggregator.go b/svc-api/handle/aggregator.go index 00f6d43de..4064aab21 100644 --- a/svc-api/handle/aggregator.go +++ b/svc-api/handle/aggregator.go @@ -51,37 +51,34 @@ type AggregatorRPCs struct { GetSetDefaultBootOrderActionInfoRPC func(context.Context, aggregatorproto.AggregatorRequest) (*aggregatorproto.AggregatorResponse, error) } +const ( + // AuthTokenHeader holds the key of X-Auth-Token header + AuthTokenHeader = "X-Auth-Token" + rpcCallFailedErrMsg = "something went wrong with the RPC calls: " + invalidAuthTokenErrMsg = "no X-Auth-Token found in request header" +) + // GetAggregationService is the handler for getting AggregationService details func (a *AggregatorRPCs) GetAggregationService(ctx iris.Context) { defer ctx.Next() ctxt := ctx.Request().Context() l.LogWithFields(ctxt).Debugf("Incoming request received for get aggregation service") req := aggregatorproto.AggregatorRequest{ - SessionToken: ctx.Request().Header.Get("X-Auth-Token"), + SessionToken: ctx.Request().Header.Get(AuthTokenHeader), } if req.SessionToken == "" { - errorMessage := "no X-Auth-Token found in request header" - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + errorMessage := invalidAuthTokenErrMsg + common.SendInvalidSessionResponse(ctx, errorMessage) } resp, err := a.GetAggregationServiceRPC(ctxt, req) if err != nil { - errorMessage := "something went wrong with the RPC calls: " + err.Error() + errorMessage := rpcCallFailedErrMsg + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) - return + common.SendFailedRPCCallResponse(ctx, errorMessage) } ctx.ResponseWriter().Header().Set("Allow", "GET") - common.SetResponseHeader(ctx, resp.Header) - ctx.StatusCode(int(resp.StatusCode)) - ctx.Write(resp.Body) + sendAggregatorResponse(ctx, resp) l.LogWithFields(ctxt).Debugf("outgoing response for get aggregation service is %s with response code %d", string(resp.Body), int(resp.StatusCode)) } @@ -96,23 +93,15 @@ func (a *AggregatorRPCs) Reset(ctx iris.Context) { var req interface{} err := ctx.ReadJSON(&req) if err != nil { - errorMessage := "error while trying to get JSON body from the request body: " + err.Error() + errorMessage := "error while trying to get JSON body from the request body: " + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusBadRequest, response.MalformedJSON, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusBadRequest) - ctx.JSON(&response.Body) - return + common.SendMalformedJSONRequestErrResponse(ctx, errorMessage) } - sessionToken := ctx.Request().Header.Get("X-Auth-Token") + sessionToken := ctx.Request().Header.Get(AuthTokenHeader) if sessionToken == "" { - errorMessage := "no X-Auth-Token found in request header" - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + errorMessage := invalidAuthTokenErrMsg + common.SendInvalidSessionResponse(ctx, errorMessage) } // marshalling the req to make aggregator delete request @@ -121,10 +110,7 @@ func (a *AggregatorRPCs) Reset(ctx iris.Context) { if err != nil { errorMessage := "error while trying to create JSON request body: " + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) + common.SendFailedRPCCallResponse(ctx, errorMessage) return } @@ -136,16 +122,11 @@ func (a *AggregatorRPCs) Reset(ctx iris.Context) { if err != nil { errorMessage := "RPC error: " + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) + common.SendFailedRPCCallResponse(ctx, errorMessage) return } - common.SetResponseHeader(ctx, resp.Header) - ctx.StatusCode(int(resp.StatusCode)) - ctx.Write(resp.Body) + sendAggregatorResponse(ctx, resp) l.LogWithFields(ctxt).Debugf("outgoing response for resetting compute system is %s and response code %d", string(resp.Body), int(resp.StatusCode)) } @@ -159,23 +140,15 @@ func (a *AggregatorRPCs) SetDefaultBootOrder(ctx iris.Context) { var req interface{} err := ctx.ReadJSON(&req) if err != nil { - errorMessage := "error while trying to get JSON body from the request body: " + err.Error() + errorMessage := "error while trying to get JSON body from the request body: " + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusBadRequest, response.MalformedJSON, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusBadRequest) - ctx.JSON(&response.Body) - return + common.SendMalformedJSONRequestErrResponse(ctx, errorMessage) } - sessionToken := ctx.Request().Header.Get("X-Auth-Token") + sessionToken := ctx.Request().Header.Get(AuthTokenHeader) if sessionToken == "" { - errorMessage := "no X-Auth-Token found in request header" - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + errorMessage := invalidAuthTokenErrMsg + common.SendInvalidSessionResponse(ctx, errorMessage) } // marshalling the req to make aggregator SetDefaultBootOrder request @@ -184,10 +157,7 @@ func (a *AggregatorRPCs) SetDefaultBootOrder(ctx iris.Context) { if err != nil { errorMessage := "error while trying to create JSON request body: " + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) + common.SendFailedRPCCallResponse(ctx, errorMessage) return } @@ -199,16 +169,11 @@ func (a *AggregatorRPCs) SetDefaultBootOrder(ctx iris.Context) { if err != nil { errorMessage := "RPC error: " + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) + common.SendFailedRPCCallResponse(ctx, errorMessage) return } - common.SetResponseHeader(ctx, resp.Header) - ctx.StatusCode(int(resp.StatusCode)) - ctx.Write(resp.Body) + sendAggregatorResponse(ctx, resp) } // AddAggregationSource is the handler for adding AggregationSource details @@ -221,22 +186,14 @@ func (a *AggregatorRPCs) AddAggregationSource(ctx iris.Context) { if err != nil { errorMessage := "error while trying to get JSON body from the aggregator request body: " + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusBadRequest, response.MalformedJSON, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusBadRequest) - ctx.JSON(&response.Body) - return + common.SendMalformedJSONRequestErrResponse(ctx, errorMessage) } - sessionToken := ctx.Request().Header.Get("X-Auth-Token") + sessionToken := ctx.Request().Header.Get(AuthTokenHeader) if sessionToken == "" { - errorMessage := "no X-Auth-Token found in request header" - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + errorMessage := invalidAuthTokenErrMsg + common.SendInvalidSessionResponse(ctx, errorMessage) } // marshalling the req to make aggregator add request @@ -251,16 +208,11 @@ func (a *AggregatorRPCs) AddAggregationSource(ctx iris.Context) { if err != nil { errorMessage := "RPC error: " + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) + common.SendFailedRPCCallResponse(ctx, errorMessage) return } - common.SetResponseHeader(ctx, resp.Header) - ctx.StatusCode(int(resp.StatusCode)) - ctx.Write(resp.Body) + sendAggregatorResponse(ctx, resp) } // GetAllAggregationSource is the handler for getting all AggregationSource details @@ -269,30 +221,21 @@ func (a *AggregatorRPCs) GetAllAggregationSource(ctx iris.Context) { ctxt := ctx.Request().Context() l.LogWithFields(ctxt).Debugf("Incoming request received for getting all aggregationsources") req := aggregatorproto.AggregatorRequest{ - SessionToken: ctx.Request().Header.Get("X-Auth-Token"), + SessionToken: ctx.Request().Header.Get(AuthTokenHeader), } if req.SessionToken == "" { - errorMessage := "no X-Auth-Token found in request header" - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + errorMessage := invalidAuthTokenErrMsg + common.SendInvalidSessionResponse(ctx, errorMessage) } resp, err := a.GetAllAggregationSourceRPC(ctxt, req) if err != nil { errorMessage := " RPC error:" + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) + common.SendFailedRPCCallResponse(ctx, errorMessage) return } ctx.ResponseWriter().Header().Set("Allow", "GET, POST") - common.SetResponseHeader(ctx, resp.Header) - ctx.StatusCode(int(resp.StatusCode)) - ctx.Write(resp.Body) + sendAggregatorResponse(ctx, resp) l.LogWithFields(ctxt).Debugf("Outgoing response for getting all aggregation sources is %s with response code %d", string(resp.Body), int(resp.StatusCode)) } @@ -301,32 +244,23 @@ func (a *AggregatorRPCs) GetAggregationSource(ctx iris.Context) { defer ctx.Next() ctxt := ctx.Request().Context() req := aggregatorproto.AggregatorRequest{ - SessionToken: ctx.Request().Header.Get("X-Auth-Token"), + SessionToken: ctx.Request().Header.Get(AuthTokenHeader), URL: ctx.Request().RequestURI, } l.LogWithFields(ctxt).Debugf("Incoming request received for getting aggregationsource with uri %s", req.URL) if req.SessionToken == "" { - errorMessage := "no X-Auth-Token found in request header" - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + errorMessage := invalidAuthTokenErrMsg + common.SendInvalidSessionResponse(ctx, errorMessage) } resp, err := a.GetAggregationSourceRPC(ctxt, req) if err != nil { errorMessage := " RPC error:" + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) + common.SendFailedRPCCallResponse(ctx, errorMessage) return } ctx.ResponseWriter().Header().Set("Allow", "GET, PATCH, DELETE") - common.SetResponseHeader(ctx, resp.Header) - ctx.StatusCode(int(resp.StatusCode)) - ctx.Write(resp.Body) + sendAggregatorResponse(ctx, resp) l.LogWithFields(ctxt).Debugf("Outgoing response for getting aggregation source is %s with response code %d", string(resp.Body), int(resp.StatusCode)) } @@ -339,22 +273,14 @@ func (a *AggregatorRPCs) UpdateAggregationSource(ctx iris.Context) { if err != nil { errorMessage := "error while trying to get JSON body from the aggregator request body: " + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusBadRequest, response.MalformedJSON, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusBadRequest) - ctx.JSON(&response.Body) - return + common.SendMalformedJSONRequestErrResponse(ctx, errorMessage) } - sessionToken := ctx.Request().Header.Get("X-Auth-Token") + sessionToken := ctx.Request().Header.Get(AuthTokenHeader) if sessionToken == "" { - errorMessage := "no X-Auth-Token found in request header" - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + errorMessage := invalidAuthTokenErrMsg + common.SendInvalidSessionResponse(ctx, errorMessage) } // marshalling the req to make aggregator add request @@ -371,16 +297,11 @@ func (a *AggregatorRPCs) UpdateAggregationSource(ctx iris.Context) { if err != nil { errorMessage := "RPC error: " + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) + common.SendFailedRPCCallResponse(ctx, errorMessage) return } - common.SetResponseHeader(ctx, resp.Header) - ctx.StatusCode(int(resp.StatusCode)) - ctx.Write(resp.Body) + sendAggregatorResponse(ctx, resp) l.LogWithFields(ctxt).Debugf("Outgoing response for updating aggregation source is %s with response code %d", string(resp.Body), int(resp.StatusCode)) } @@ -390,32 +311,23 @@ func (a *AggregatorRPCs) DeleteAggregationSource(ctx iris.Context) { defer ctx.Next() ctxt := ctx.Request().Context() req := aggregatorproto.AggregatorRequest{ - SessionToken: ctx.Request().Header.Get("X-Auth-Token"), + SessionToken: ctx.Request().Header.Get(AuthTokenHeader), URL: ctx.Request().RequestURI, } l.LogWithFields(ctxt).Debugf("Incoming request received for deleting aggregationsource with uri %s", req.URL) if req.SessionToken == "" { - errorMessage := "no X-Auth-Token found in request header" - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + errorMessage := invalidAuthTokenErrMsg + common.SendInvalidSessionResponse(ctx, errorMessage) } resp, err := a.DeleteAggregationSourceRPC(ctxt, req) if err != nil { errorMessage := " RPC error:" + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) + common.SendFailedRPCCallResponse(ctx, errorMessage) return } l.LogWithFields(ctxt).Debugf("Outgoing response for deleting aggregation source is %s with response code %d", string(resp.Body), int(resp.StatusCode)) - common.SetResponseHeader(ctx, resp.Header) - ctx.StatusCode(int(resp.StatusCode)) - ctx.Write(resp.Body) + sendAggregatorResponse(ctx, resp) } // CreateAggregate is the handler for creating an aggregate @@ -427,22 +339,14 @@ func (a *AggregatorRPCs) CreateAggregate(ctx iris.Context) { if err != nil { errorMessage := "error while trying to get JSON body from the aggregator request body: " + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusBadRequest, response.MalformedJSON, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusBadRequest) - ctx.JSON(&response.Body) - return + common.SendMalformedJSONRequestErrResponse(ctx, errorMessage) } - sessionToken := ctx.Request().Header.Get("X-Auth-Token") + sessionToken := ctx.Request().Header.Get(AuthTokenHeader) if sessionToken == "" { - errorMessage := "no X-Auth-Token found in request header" - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + errorMessage := invalidAuthTokenErrMsg + common.SendInvalidSessionResponse(ctx, errorMessage) } // marshalling the req to make aggregator create request @@ -456,16 +360,11 @@ func (a *AggregatorRPCs) CreateAggregate(ctx iris.Context) { if err != nil { errorMessage := "RPC error: " + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) + common.SendFailedRPCCallResponse(ctx, errorMessage) return } l.LogWithFields(ctxt).Debugf("Outgoing response for creating aggregate is %s with response code %d", string(resp.Body), int(resp.StatusCode)) - common.SetResponseHeader(ctx, resp.Header) - ctx.StatusCode(int(resp.StatusCode)) - ctx.Write(resp.Body) + sendAggregatorResponse(ctx, resp) } @@ -475,31 +374,21 @@ func (a *AggregatorRPCs) GetAggregateCollection(ctx iris.Context) { ctxt := ctx.Request().Context() l.LogWithFields(ctxt).Debug("Incoming request received for getting all aggregate collections") req := aggregatorproto.AggregatorRequest{ - SessionToken: ctx.Request().Header.Get("X-Auth-Token"), + SessionToken: ctx.Request().Header.Get(AuthTokenHeader), } if req.SessionToken == "" { - errorMessage := "no X-Auth-Token found in request header" - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + errorMessage := invalidAuthTokenErrMsg + common.SendInvalidSessionResponse(ctx, errorMessage) } resp, err := a.GetAggregateCollectionRPC(ctxt, req) if err != nil { - errorMessage := "something went wrong with the RPC calls: " + err.Error() + errorMessage := rpcCallFailedErrMsg + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) - return + common.SendFailedRPCCallResponse(ctx, errorMessage) } l.LogWithFields(ctxt).Debugf("Outgoing response for getting all aggregate collections is %s with response code %d", string(resp.Body), int(resp.StatusCode)) ctx.ResponseWriter().Header().Set("Allow", "GET, POST") - common.SetResponseHeader(ctx, resp.Header) - ctx.StatusCode(int(resp.StatusCode)) - ctx.Write(resp.Body) + sendAggregatorResponse(ctx, resp) } @@ -508,33 +397,23 @@ func (a *AggregatorRPCs) GetAggregate(ctx iris.Context) { defer ctx.Next() ctxt := ctx.Request().Context() req := aggregatorproto.AggregatorRequest{ - SessionToken: ctx.Request().Header.Get("X-Auth-Token"), + SessionToken: ctx.Request().Header.Get(AuthTokenHeader), URL: ctx.Request().RequestURI, } l.LogWithFields(ctxt).Debugf("Incoming request received for getting aggregate with request uri %s", req.URL) if req.SessionToken == "" { - errorMessage := "no X-Auth-Token found in request header" - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + errorMessage := invalidAuthTokenErrMsg + common.SendInvalidSessionResponse(ctx, errorMessage) } resp, err := a.GetAggregateRPC(ctxt, req) if err != nil { - errorMessage := "something went wrong with the RPC calls: " + err.Error() + errorMessage := rpcCallFailedErrMsg + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) - return + common.SendFailedRPCCallResponse(ctx, errorMessage) } l.LogWithFields(ctxt).Debugf("Outgoing response for getting aggregate is %s with response code %d", string(resp.Body), int(resp.StatusCode)) ctx.ResponseWriter().Header().Set("Allow", "GET, DELETE") - common.SetResponseHeader(ctx, resp.Header) - ctx.StatusCode(int(resp.StatusCode)) - ctx.Write(resp.Body) + sendAggregatorResponse(ctx, resp) } // DeleteAggregate is the handler for deleting an aggregate @@ -542,32 +421,22 @@ func (a *AggregatorRPCs) DeleteAggregate(ctx iris.Context) { defer ctx.Next() ctxt := ctx.Request().Context() req := aggregatorproto.AggregatorRequest{ - SessionToken: ctx.Request().Header.Get("X-Auth-Token"), + SessionToken: ctx.Request().Header.Get(AuthTokenHeader), URL: ctx.Request().RequestURI, } l.LogWithFields(ctxt).Debugf("Incoming request received for deleting aggregate with request uri %s", req.URL) if req.SessionToken == "" { - errorMessage := "no X-Auth-Token found in request header" - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + errorMessage := invalidAuthTokenErrMsg + common.SendInvalidSessionResponse(ctx, errorMessage) } resp, err := a.DeleteAggregateRPC(ctxt, req) if err != nil { - errorMessage := "something went wrong with the RPC calls: " + err.Error() + errorMessage := rpcCallFailedErrMsg + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) - return + common.SendFailedRPCCallResponse(ctx, errorMessage) } l.LogWithFields(ctxt).Debugf("Outgoing response for deleting aggregate is %s with response code %d", string(resp.Body), int(resp.StatusCode)) - common.SetResponseHeader(ctx, resp.Header) - ctx.StatusCode(int(resp.StatusCode)) - ctx.Write(resp.Body) + sendAggregatorResponse(ctx, resp) } // AddElementsToAggregate is the handler for adding elements to an aggregate @@ -579,22 +448,14 @@ func (a *AggregatorRPCs) AddElementsToAggregate(ctx iris.Context) { if err != nil { errorMessage := "error while trying to get JSON body from the aggregator request body: " + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusBadRequest, response.MalformedJSON, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusBadRequest) - ctx.JSON(&response.Body) - return + common.SendMalformedJSONRequestErrResponse(ctx, errorMessage) } - sessionToken := ctx.Request().Header.Get("X-Auth-Token") + sessionToken := ctx.Request().Header.Get(AuthTokenHeader) if sessionToken == "" { - errorMessage := "no X-Auth-Token found in request header" - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + errorMessage := invalidAuthTokenErrMsg + common.SendInvalidSessionResponse(ctx, errorMessage) } // marshalling the req to make aggregator add request @@ -609,18 +470,12 @@ func (a *AggregatorRPCs) AddElementsToAggregate(ctx iris.Context) { resp, err := a.AddElementsToAggregateRPC(ctxt, addRequest) if err != nil { - errorMessage := "something went wrong with the RPC calls: " + err.Error() + errorMessage := rpcCallFailedErrMsg + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) - return + common.SendFailedRPCCallResponse(ctx, errorMessage) } l.LogWithFields(ctxt).Debugf("Outgoing response for adding an element to an aggregate is %s with response code %d", string(resp.Body), int(resp.StatusCode)) - common.SetResponseHeader(ctx, resp.Header) - ctx.StatusCode(int(resp.StatusCode)) - ctx.Write(resp.Body) + sendAggregatorResponse(ctx, resp) } // RemoveElementsFromAggregate is the handler for removing elements from an aggregate @@ -632,22 +487,14 @@ func (a *AggregatorRPCs) RemoveElementsFromAggregate(ctx iris.Context) { if err != nil { errorMessage := "error while trying to get JSON body from the aggregator request body: " + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusBadRequest, response.MalformedJSON, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusBadRequest) - ctx.JSON(&response.Body) - return + common.SendMalformedJSONRequestErrResponse(ctx, errorMessage) } - sessionToken := ctx.Request().Header.Get("X-Auth-Token") + sessionToken := ctx.Request().Header.Get(AuthTokenHeader) if sessionToken == "" { - errorMessage := "no X-Auth-Token found in request header" - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + errorMessage := invalidAuthTokenErrMsg + common.SendInvalidSessionResponse(ctx, errorMessage) } // marshalling the req to make aggregator remove request @@ -661,18 +508,12 @@ func (a *AggregatorRPCs) RemoveElementsFromAggregate(ctx iris.Context) { l.LogWithFields(ctxt).Debugf("Incoming request received for deleting element with uri %s from the aggregation collections with request body %s", removeRequest.URL, string(removeRequest.RequestBody)) resp, err := a.RemoveElementsFromAggregateRPC(ctxt, removeRequest) if err != nil { - errorMessage := "something went wrong with the RPC calls: " + err.Error() + errorMessage := rpcCallFailedErrMsg + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) - return + common.SendFailedRPCCallResponse(ctx, errorMessage) } l.LogWithFields(ctxt).Debugf("Outgoing response for removing an element from an aggregate is %s with response code %d", string(resp.Body), int(resp.StatusCode)) - common.SetResponseHeader(ctx, resp.Header) - ctx.StatusCode(int(resp.StatusCode)) - ctx.Write(resp.Body) + sendAggregatorResponse(ctx, resp) } // ResetAggregateElements is the handler for resetting elements of an aggregate @@ -684,22 +525,14 @@ func (a *AggregatorRPCs) ResetAggregateElements(ctx iris.Context) { if err != nil { errorMessage := "error while trying to get JSON body from the aggregator request body: " + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusBadRequest, response.MalformedJSON, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusBadRequest) - ctx.JSON(&response.Body) - return + common.SendMalformedJSONRequestErrResponse(ctx, errorMessage) } - sessionToken := ctx.Request().Header.Get("X-Auth-Token") + sessionToken := ctx.Request().Header.Get(AuthTokenHeader) if sessionToken == "" { - errorMessage := "no X-Auth-Token found in request header" - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + errorMessage := invalidAuthTokenErrMsg + common.SendInvalidSessionResponse(ctx, errorMessage) } // marshalling the req to make aggregator reset elements request @@ -713,32 +546,22 @@ func (a *AggregatorRPCs) ResetAggregateElements(ctx iris.Context) { l.LogWithFields(ctxt).Debugf("Incoming request received for resetting aggregate elements with uri %s with request body %s", resetRequest.URL, string(resetRequest.RequestBody)) resp, err := a.ResetAggregateElementsRPC(ctxt, resetRequest) if err != nil { - errorMessage := "something went wrong with the RPC calls: " + err.Error() + errorMessage := rpcCallFailedErrMsg + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) - return + common.SendFailedRPCCallResponse(ctx, errorMessage) } l.LogWithFields(ctxt).Debugf("Outgoing response for resetting aggregate elements is %s with response code %d", string(resp.Body), int(resp.StatusCode)) - common.SetResponseHeader(ctx, resp.Header) - ctx.StatusCode(int(resp.StatusCode)) - ctx.Write(resp.Body) + sendAggregatorResponse(ctx, resp) } // SetDefaultBootOrderAggregateElements is the handler for SetDefaultBootOrder elements of an aggregate func (a *AggregatorRPCs) SetDefaultBootOrderAggregateElements(ctx iris.Context) { defer ctx.Next() ctxt := ctx.Request().Context() - sessionToken := ctx.Request().Header.Get("X-Auth-Token") + sessionToken := ctx.Request().Header.Get(AuthTokenHeader) if sessionToken == "" { - errorMessage := "no X-Auth-Token found in request header" - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + errorMessage := invalidAuthTokenErrMsg + common.SendInvalidSessionResponse(ctx, errorMessage) } bootOrderRequest := aggregatorproto.AggregatorRequest{ @@ -748,18 +571,12 @@ func (a *AggregatorRPCs) SetDefaultBootOrderAggregateElements(ctx iris.Context) l.LogWithFields(ctxt).Debugf("Incoming request received for setting default boot order for all the element of an aggregate with uri %s and request body %s", bootOrderRequest.URL, string(bootOrderRequest.RequestBody)) resp, err := a.SetDefaultBootOrderAggregateElementsRPC(ctxt, bootOrderRequest) if err != nil { - errorMessage := "something went wrong with the RPC calls: " + err.Error() + errorMessage := rpcCallFailedErrMsg + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) - return + common.SendFailedRPCCallResponse(ctx, errorMessage) } l.LogWithFields(ctxt).Debugf("Outgoing response for setting default boot order for all the elements of an aggregate is %s with response code %d", string(resp.Body), int(resp.StatusCode)) - common.SetResponseHeader(ctx, resp.Header) - ctx.StatusCode(int(resp.StatusCode)) - ctx.Write(resp.Body) + sendAggregatorResponse(ctx, resp) } // GetAllConnectionMethods is the handler for get all connection methods @@ -768,32 +585,22 @@ func (a *AggregatorRPCs) GetAllConnectionMethods(ctx iris.Context) { ctxt := ctx.Request().Context() l.LogWithFields(ctxt).Debugf("Incoming request received for getting all the connection methods") req := aggregatorproto.AggregatorRequest{ - SessionToken: ctx.Request().Header.Get("X-Auth-Token"), + SessionToken: ctx.Request().Header.Get(AuthTokenHeader), } if req.SessionToken == "" { - errorMessage := "no X-Auth-Token found in request header" - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + errorMessage := invalidAuthTokenErrMsg + common.SendInvalidSessionResponse(ctx, errorMessage) } resp, err := a.GetAllConnectionMethodsRPC(ctxt, req) if err != nil { - errorMessage := "something went wrong with the RPC calls: " + err.Error() + errorMessage := rpcCallFailedErrMsg + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) - return + common.SendFailedRPCCallResponse(ctx, errorMessage) } l.LogWithFields(ctxt).Debugf("Outgoing response for getting all the connection methods is %s with response code %d", string(resp.Body), int(resp.StatusCode)) ctx.ResponseWriter().Header().Set("Allow", "GET") - common.SetResponseHeader(ctx, resp.Header) - ctx.StatusCode(int(resp.StatusCode)) - ctx.Write(resp.Body) + sendAggregatorResponse(ctx, resp) } // GetConnectionMethod is the handler for get connection method @@ -801,33 +608,23 @@ func (a *AggregatorRPCs) GetConnectionMethod(ctx iris.Context) { defer ctx.Next() ctxt := ctx.Request().Context() req := aggregatorproto.AggregatorRequest{ - SessionToken: ctx.Request().Header.Get("X-Auth-Token"), + SessionToken: ctx.Request().Header.Get(AuthTokenHeader), URL: ctx.Request().RequestURI, } l.LogWithFields(ctxt).Debugf("Incoming request received for getting the connection methods with the request URL %s", req.URL) if req.SessionToken == "" { - errorMessage := "no X-Auth-Token found in request header" - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + errorMessage := invalidAuthTokenErrMsg + common.SendInvalidSessionResponse(ctx, errorMessage) } resp, err := a.GetConnectionMethodRPC(ctxt, req) if err != nil { - errorMessage := "something went wrong with the RPC calls: " + err.Error() + errorMessage := rpcCallFailedErrMsg + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) - return + common.SendFailedRPCCallResponse(ctx, errorMessage) } l.LogWithFields(ctxt).Debugf("Outgoing response for getting a collection method is %s with response code %d", string(resp.Body), int(resp.StatusCode)) ctx.ResponseWriter().Header().Set("Allow", "GET") - common.SetResponseHeader(ctx, resp.Header) - ctx.StatusCode(int(resp.StatusCode)) - ctx.Write(resp.Body) + sendAggregatorResponse(ctx, resp) } // GetResetActionInfoService is the handler for getting GetResetActionInfoService details @@ -836,15 +633,11 @@ func (a *AggregatorRPCs) GetResetActionInfoService(ctx iris.Context) { ctxt := ctx.Request().Context() l.LogWithFields(ctxt).Debugf("Incoming request received for getting reset action info") req := aggregatorproto.AggregatorRequest{ - SessionToken: ctx.Request().Header.Get("X-Auth-Token"), + SessionToken: ctx.Request().Header.Get(AuthTokenHeader), } if req.SessionToken == "" { - errorMessage := "no X-Auth-Token found in request header" - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + errorMessage := invalidAuthTokenErrMsg + common.SendInvalidSessionResponse(ctx, errorMessage) } resp, err := a.GetResetActionInfoServiceRPC(ctxt, req) if err != nil { @@ -858,9 +651,7 @@ func (a *AggregatorRPCs) GetResetActionInfoService(ctx iris.Context) { } l.LogWithFields(ctxt).Debugf("Outgoing response for getting a reset action information is %s with response code %d", string(resp.Body), int(resp.StatusCode)) ctx.ResponseWriter().Header().Set("Allow", "GET") - common.SetResponseHeader(ctx, resp.Header) - ctx.StatusCode(int(resp.StatusCode)) - ctx.Write(resp.Body) + sendAggregatorResponse(ctx, resp) } @@ -870,15 +661,11 @@ func (a *AggregatorRPCs) GetSetDefaultBootOrderActionInfo(ctx iris.Context) { ctxt := ctx.Request().Context() l.LogWithFields(ctxt).Debugf("Incoming request received for getting the action info for set default boot order") req := aggregatorproto.AggregatorRequest{ - SessionToken: ctx.Request().Header.Get("X-Auth-Token"), + SessionToken: ctx.Request().Header.Get(AuthTokenHeader), } if req.SessionToken == "" { - errorMessage := "no X-Auth-Token found in request header" - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + errorMessage := invalidAuthTokenErrMsg + common.SendInvalidSessionResponse(ctx, errorMessage) } resp, err := a.GetSetDefaultBootOrderActionInfoRPC(ctxt, req) if err != nil { @@ -892,8 +679,13 @@ func (a *AggregatorRPCs) GetSetDefaultBootOrderActionInfo(ctx iris.Context) { } l.LogWithFields(ctxt).Debugf("Outgoing response for getting a set default boot order action information is %s with response code %d", string(resp.Body), int(resp.StatusCode)) ctx.ResponseWriter().Header().Set("Allow", "GET") + sendAggregatorResponse(ctx, resp) + +} + +// sendSystemsResponse writes the aggregator response to client +func sendAggregatorResponse(ctx iris.Context, resp *aggregatorproto.AggregatorResponse) { common.SetResponseHeader(ctx, resp.Header) ctx.StatusCode(int(resp.StatusCode)) ctx.Write(resp.Body) - } diff --git a/svc-api/handle/aggregator_test.go b/svc-api/handle/aggregator_test.go index 0c97de643..74441c82c 100644 --- a/svc-api/handle/aggregator_test.go +++ b/svc-api/handle/aggregator_test.go @@ -41,117 +41,33 @@ func testDeleteComputeRPCWIthRPCError(ctx context.Context, req aggregatorproto.A return &aggregatorproto.AggregatorResponse{}, errors.New("Unable to RPC Call") } func testGetAggregationService(ctx context.Context, req aggregatorproto.AggregatorRequest) (*aggregatorproto.AggregatorResponse, error) { - var response = &aggregatorproto.AggregatorResponse{} - if req.SessionToken == "ValidToken" { - response = &aggregatorproto.AggregatorResponse{ - StatusCode: 200, - StatusMessage: "Success", - Body: []byte(`{"Response":"Success"}`), - } - } else if req.SessionToken == "InvalidToken" { - response = &aggregatorproto.AggregatorResponse{ - StatusCode: 401, - StatusMessage: "Unauthorized", Body: []byte(`{"Response":"Unauthorized"}`), - } - } else if req.SessionToken == "token" { - return &aggregatorproto.AggregatorResponse{}, errors.New("Unable to RPC Call") - } - return response, nil + response, err := getMockAggregatorResponse(ctx, req, 200, 401) + return response, err } func testAddAggregationSourceRPCCall(ctx context.Context, req aggregatorproto.AggregatorRequest) (*aggregatorproto.AggregatorResponse, error) { - var response = &aggregatorproto.AggregatorResponse{} - if req.SessionToken == "ValidToken" { - response = &aggregatorproto.AggregatorResponse{ - StatusCode: http.StatusAccepted, - StatusMessage: "Success", - Body: []byte(`{"Response":"Success"}`), - } - } else if req.SessionToken == "InvalidToken" { - response = &aggregatorproto.AggregatorResponse{ - StatusCode: http.StatusUnauthorized, - StatusMessage: "Unauthorized", Body: []byte(`{"Response":"Unauthorized"}`), - } - } else if req.SessionToken == "token" { - return &aggregatorproto.AggregatorResponse{}, errors.New("Unable to RPC Call") - } - return response, nil + response, err := getMockAggregatorResponse(ctx, req, http.StatusAccepted, http.StatusUnauthorized) + return response, err } func testGetAllAggregationSourceRPC(ctx context.Context, req aggregatorproto.AggregatorRequest) (*aggregatorproto.AggregatorResponse, error) { - var response = &aggregatorproto.AggregatorResponse{} - if req.SessionToken == "ValidToken" { - response = &aggregatorproto.AggregatorResponse{ - StatusCode: http.StatusOK, - StatusMessage: "Success", - Body: []byte(`{"Response":"Success"}`), - } - } else if req.SessionToken == "InvalidToken" { - response = &aggregatorproto.AggregatorResponse{ - StatusCode: http.StatusUnauthorized, - StatusMessage: "Unauthorized", Body: []byte(`{"Response":"Unauthorized"}`), - } - } else if req.SessionToken == "token" { - return &aggregatorproto.AggregatorResponse{}, errors.New("Unable to RPC Call") - } - return response, nil + response, err := getMockAggregatorResponse(ctx, req, http.StatusOK, http.StatusUnauthorized) + return response, err } func testUpdateAggregationSourceRPCCall(ctx context.Context, req aggregatorproto.AggregatorRequest) (*aggregatorproto.AggregatorResponse, error) { - var response = &aggregatorproto.AggregatorResponse{} - if req.SessionToken == "ValidToken" { - response = &aggregatorproto.AggregatorResponse{ - StatusCode: http.StatusOK, - StatusMessage: "Success", - Body: []byte(`{"Response":"Success"}`), - } - } else if req.SessionToken == "InvalidToken" { - response = &aggregatorproto.AggregatorResponse{ - StatusCode: http.StatusUnauthorized, - StatusMessage: "Unauthorized", Body: []byte(`{"Response":"Unauthorized"}`), - } - } else if req.SessionToken == "token" { - return &aggregatorproto.AggregatorResponse{}, errors.New("Unable to RPC Call") - } - return response, nil + response, err := getMockAggregatorResponse(ctx, req, http.StatusOK, http.StatusUnauthorized) + return response, err } func testGetAggregationSourceRPC(ctx context.Context, req aggregatorproto.AggregatorRequest) (*aggregatorproto.AggregatorResponse, error) { - var response = &aggregatorproto.AggregatorResponse{} - if req.SessionToken == "ValidToken" { - response = &aggregatorproto.AggregatorResponse{ - StatusCode: http.StatusOK, - StatusMessage: "Success", - Body: []byte(`{"Response":"Success"}`), - } - } else if req.SessionToken == "InvalidToken" { - response = &aggregatorproto.AggregatorResponse{ - StatusCode: http.StatusUnauthorized, - StatusMessage: "Unauthorized", Body: []byte(`{"Response":"Unauthorized"}`), - } - } else if req.SessionToken == "token" { - return &aggregatorproto.AggregatorResponse{}, errors.New("Unable to RPC Call") - } - return response, nil + response, err := getMockAggregatorResponse(ctx, req, http.StatusOK, http.StatusUnauthorized) + return response, err } func testDeleteAggregationSourceRPCCall(ctx context.Context, req aggregatorproto.AggregatorRequest) (*aggregatorproto.AggregatorResponse, error) { - var response = &aggregatorproto.AggregatorResponse{} - if req.SessionToken == "ValidToken" { - response = &aggregatorproto.AggregatorResponse{ - StatusCode: http.StatusAccepted, - StatusMessage: "Success", - Body: []byte(`{"Response":"Success"}`), - } - } else if req.SessionToken == "InvalidToken" { - response = &aggregatorproto.AggregatorResponse{ - StatusCode: http.StatusUnauthorized, - StatusMessage: "Unauthorized", Body: []byte(`{"Response":"Unauthorized"}`), - } - } else if req.SessionToken == "token" { - return &aggregatorproto.AggregatorResponse{}, errors.New("Unable to RPC Call") - } - return response, nil + response, err := getMockAggregatorResponse(ctx, req, http.StatusAccepted, http.StatusUnauthorized) + return response, err } func testAggregateRPCCall(ctx context.Context, req aggregatorproto.AggregatorRequest) (*aggregatorproto.AggregatorResponse, error) { @@ -346,9 +262,33 @@ func TestAddAggregationSource(t *testing.T) { redfishRoutes := testApp.Party("/redfish/v1/AggregationService/AggregationSources") redfishRoutes.Post("/", a.AddAggregationSource) test := httptest.New(t, testApp) - test.POST("/redfish/v1/AggregationService/AggregationSources").WithHeader("X-Auth-Token", "ValidToken").WithJSON(addAggregationSourceRequest).Expect().Status(http.StatusAccepted) - test.POST("/redfish/v1/AggregationService/AggregationSources").WithHeader("X-Auth-Token", "InvalidToken").WithJSON(addAggregationSourceRequest).Expect().Status(http.StatusUnauthorized) - test.POST("/redfish/v1/AggregationService/AggregationSources").WithHeader("X-Auth-Token", "token").WithJSON(addAggregationSourceRequest).Expect().Status(http.StatusInternalServerError) + tests := []struct { + name string + authToken string + expectedStatus int + }{ + { + name: "Success", + authToken: "ValidToken", + expectedStatus: http.StatusAccepted, + }, + { + name: "Unauthorized error", + authToken: "InvalidToken", + expectedStatus: http.StatusUnauthorized, + }, + { + name: "Internal server error", + authToken: "token", + expectedStatus: http.StatusInternalServerError, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + test.POST("/redfish/v1/AggregationService/AggregationSources").WithHeader("X-Auth-Token", tt.authToken).WithJSON(addAggregationSourceRequest).Expect().Status(tt.expectedStatus) + }) + } } func TestGetAllAggregationSource(t *testing.T) { @@ -425,31 +365,45 @@ func TestCreateAggregate(t *testing.T) { redfishRoutes := testApp.Party("/redfish/v1/AggregationService/Aggregates") redfishRoutes.Post("/", a.CreateAggregate) test := httptest.New(t, testApp) - // update status code after the code is added - // test with valid token - test.POST( - "/redfish/v1/AggregationService/Aggregates", - ).WithHeader("X-Auth-Token", "ValidToken").WithJSON(aggregateRequest).Expect().Status(http.StatusCreated) - - // test with Invalid token - test.POST( - "/redfish/v1/AggregationService/Aggregates", - ).WithHeader("X-Auth-Token", "InvalidToken").WithJSON(aggregateRequest).Expect().Status(http.StatusUnauthorized) - - // test without token - test.POST( - "/redfish/v1/AggregationService/Aggregates", - ).WithHeader("X-Auth-Token", "").WithJSON(aggregateRequest).Expect().Status(http.StatusUnauthorized) + tests := []struct { + name string + authToken string + expectedStatus int + }{ + { + name: "valid token", + authToken: "ValidToken", + expectedStatus: http.StatusCreated, + }, + { + name: "Invalid token", + authToken: "InvalidToken", + expectedStatus: http.StatusUnauthorized, + }, + { + name: "without token", + authToken: "", + expectedStatus: http.StatusUnauthorized, + }, + { + name: "RPC Error", + authToken: "token", + expectedStatus: http.StatusInternalServerError, + }, + } // test without RequestBody test.POST( "/redfish/v1/AggregationService/Aggregates", ).WithHeader("X-Auth-Token", "ValidToken").Expect().Status(http.StatusBadRequest) - // test for RPC Error - test.POST( - "/redfish/v1/AggregationService/Aggregates", - ).WithHeader("X-Auth-Token", "token").WithJSON(aggregateRequest).Expect().Status(http.StatusInternalServerError) + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + test.POST( + "/redfish/v1/AggregationService/Aggregates", + ).WithHeader("X-Auth-Token", tt.authToken).WithJSON(aggregateRequest).Expect().Status(tt.expectedStatus) + }) + } } func TestGetAggregateCollection(t *testing.T) { @@ -731,3 +685,23 @@ func TestGetConnectionMethod(t *testing.T) { "/redfish/v1/AggregationService/ConnectionMethods/74116e00-0a4a-53e6-a959-e6a7465d6358", ).WithHeader("X-Auth-Token", "token").Expect().Status(http.StatusInternalServerError) //TODO : replace with http.StatusInternalServerError } + +// getMockAggregatorResponse will return a mock aggregator response based on the token in request +func getMockAggregatorResponse(ctx context.Context, req aggregatorproto.AggregatorRequest, validTokenStatusCode, invalidTokenStatusCode int32) (*aggregatorproto.AggregatorResponse, error) { + var response = &aggregatorproto.AggregatorResponse{} + if req.SessionToken == "ValidToken" { + response = &aggregatorproto.AggregatorResponse{ + StatusCode: validTokenStatusCode, + StatusMessage: "Success", + Body: []byte(`{"Response":"Success"}`), + } + } else if req.SessionToken == "InvalidToken" { + response = &aggregatorproto.AggregatorResponse{ + StatusCode: invalidTokenStatusCode, + StatusMessage: "Unauthorized", Body: []byte(`{"Response":"Unauthorized"}`), + } + } else if req.SessionToken == "token" { + return &aggregatorproto.AggregatorResponse{}, errors.New("Unable to RPC Call") + } + return response, nil +} diff --git a/svc-api/handle/chassis.go b/svc-api/handle/chassis.go index 56136cd40..8de2d4b68 100644 --- a/svc-api/handle/chassis.go +++ b/svc-api/handle/chassis.go @@ -58,7 +58,7 @@ func (chassis *ChassisRPCs) CreateChassis(ctx iris.Context) { ctxt, chassisproto.CreateChassisRequest{ RequestBody: *requestBody, - SessionToken: ctx.Request().Header.Get("X-Auth-Token"), + SessionToken: ctx.Request().Header.Get(AuthTokenHeader), }, ) @@ -88,7 +88,7 @@ func (chassis *ChassisRPCs) GetChassisCollection(ctx iris.Context) { defer ctx.Next() ctxt := ctx.Request().Context() req := chassisproto.GetChassisRequest{ - SessionToken: ctx.Request().Header.Get("X-Auth-Token"), + SessionToken: ctx.Request().Header.Get(AuthTokenHeader), URL: ctx.Request().RequestURI} l.LogWithFields(ctxt).Debugf("Incoming request received for getting chassis collection with request uri %s", string(req.URL)) if req.SessionToken == "" { @@ -124,7 +124,7 @@ func (chassis *ChassisRPCs) GetChassisResource(ctx iris.Context) { defer ctx.Next() ctxt := ctx.Request().Context() req := chassisproto.GetChassisRequest{ - SessionToken: ctx.Request().Header.Get("X-Auth-Token"), + SessionToken: ctx.Request().Header.Get(AuthTokenHeader), RequestParam: ctx.Params().Get("id"), ResourceID: ctx.Params().Get("rid"), URL: ctx.Request().RequestURI} @@ -163,7 +163,7 @@ func (chassis *ChassisRPCs) GetChassis(ctx iris.Context) { defer ctx.Next() ctxt := ctx.Request().Context() req := chassisproto.GetChassisRequest{ - SessionToken: ctx.Request().Header.Get("X-Auth-Token"), + SessionToken: ctx.Request().Header.Get(AuthTokenHeader), RequestParam: ctx.Params().Get("id"), URL: ctx.Request().RequestURI} l.LogWithFields(ctxt).Debugf("Incoming request received for getting chassis with request uri %s and request params %s", req.URL, req.RequestParam) @@ -210,7 +210,7 @@ func (chassis *ChassisRPCs) UpdateChassis(ctx iris.Context) { } l.LogWithFields(ctxt).Debugf("Incoming request received for updating chassis with request body %s", string(*requestBody)) rr, rerr := chassis.UpdateChassisRPC(ctxt, chassisproto.UpdateChassisRequest{ - SessionToken: ctx.Request().Header.Get("X-Auth-Token"), + SessionToken: ctx.Request().Header.Get(AuthTokenHeader), URL: ctx.Request().RequestURI, RequestBody: *requestBody, }) @@ -232,7 +232,7 @@ func (chassis *ChassisRPCs) DeleteChassis(ctx iris.Context) { ctxt := ctx.Request().Context() l.LogWithFields(ctxt).Debugf("Incoming request received for deleting chassis with request uri %s", ctx.Request().RequestURI) rpcResp, rpcErr := chassis.DeleteChassisRPC(ctxt, chassisproto.DeleteChassisRequest{ - SessionToken: ctx.Request().Header.Get("X-Auth-Token"), + SessionToken: ctx.Request().Header.Get(AuthTokenHeader), URL: ctx.Request().RequestURI, }) diff --git a/svc-api/handle/compositionservice.go b/svc-api/handle/compositionservice.go index 1a7117d9a..626c04d26 100755 --- a/svc-api/handle/compositionservice.go +++ b/svc-api/handle/compositionservice.go @@ -12,7 +12,7 @@ //License for the specific language governing permissions and limitations // under the License. -//Package handle ... +// Package handle ... package handle import ( @@ -45,28 +45,21 @@ type CompositionServiceRPCs struct { GetCompositionReservationsRPC func(req compositionserviceproto.GetCompositionResourceRequest) (*compositionserviceproto.CompositionServiceResponse, error) } -//GetCompositionService fetches all composition service +// GetCompositionService fetches all composition service func (cs *CompositionServiceRPCs) GetCompositionService(ctx iris.Context) { defer ctx.Next() req := compositionserviceproto.GetCompositionServiceRequest{ - SessionToken: ctx.Request().Header.Get("X-Auth-Token"), + SessionToken: ctx.Request().Header.Get(AuthTokenHeader), URL: ctx.Request().RequestURI, } if req.SessionToken == "" { - errorMessage := "error: no X-Auth-Token found in request header" - l.Log.Error(errorMessage) - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + errorMessage := invalidAuthTokenErrorMsg + writeErrorResponse(ctx, http.StatusUnauthorized, response.NoValidSession, errorMessage) } resp, err := cs.GetCompositionServiceRPC(req) if err != nil { errorMessage := "error: RPC error:" + err.Error() - l.Log.Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) + writeErrorResponse(ctx, http.StatusInternalServerError, response.InternalError, errorMessage) return } @@ -79,24 +72,17 @@ func (cs *CompositionServiceRPCs) GetCompositionService(ctx iris.Context) { func (cs *CompositionServiceRPCs) GetResourceBlockCollection(ctx iris.Context) { defer ctx.Next() req := compositionserviceproto.GetCompositionResourceRequest{ - SessionToken: ctx.Request().Header.Get("X-Auth-Token"), + SessionToken: ctx.Request().Header.Get(AuthTokenHeader), URL: ctx.Request().RequestURI, } if req.SessionToken == "" { - errorMessage := "error: no X-Auth-Token found in request header" - l.Log.Error(errorMessage) - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + errorMessage := invalidAuthTokenErrorMsg + writeErrorResponse(ctx, http.StatusUnauthorized, response.NoValidSession, errorMessage) } resp, err := cs.GetResourceBlockCollectionRPC(req) if err != nil { errorMessage := "error: RPC error:" + err.Error() - l.Log.Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) + writeErrorResponse(ctx, http.StatusInternalServerError, response.InternalError, errorMessage) return } @@ -109,25 +95,18 @@ func (cs *CompositionServiceRPCs) GetResourceBlockCollection(ctx iris.Context) { func (cs *CompositionServiceRPCs) GetResourceBlock(ctx iris.Context) { defer ctx.Next() req := compositionserviceproto.GetCompositionResourceRequest{ - SessionToken: ctx.Request().Header.Get("X-Auth-Token"), + SessionToken: ctx.Request().Header.Get(AuthTokenHeader), URL: ctx.Request().RequestURI, ResourceID: ctx.Params().Get("id"), } if req.SessionToken == "" { - errorMessage := "error: no X-Auth-Token found in request header" - l.Log.Error(errorMessage) - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + errorMessage := invalidAuthTokenErrorMsg + writeErrorResponse(ctx, http.StatusUnauthorized, response.NoValidSession, errorMessage) } resp, err := cs.GetResourceBlockRPC(req) if err != nil { errorMessage := "error: RPC error:" + err.Error() - l.Log.Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) + writeErrorResponse(ctx, http.StatusInternalServerError, response.InternalError, errorMessage) return } @@ -143,30 +122,19 @@ func (cs *CompositionServiceRPCs) CreateResourceBlock(ctx iris.Context) { err := ctx.ReadJSON(&req) if err != nil { errorMessage := "error while trying to get JSON body from the create Resource Block request body: " + err.Error() - l.Log.Error(errorMessage) - response := common.GeneralError(http.StatusBadRequest, response.MalformedJSON, errorMessage, nil, nil) - ctx.StatusCode(http.StatusBadRequest) - ctx.JSON(&response.Body) - return + writeErrorResponse(ctx, http.StatusBadRequest, response.MalformedJSON, errorMessage) } request, err := json.Marshal(req) if err != nil { errorMessage := "error while trying to create JSON request body: " + err.Error() - l.Log.Error(errorMessage) - response := common.GeneralError(http.StatusBadRequest, response.MalformedJSON, errorMessage, nil, nil) - ctx.StatusCode(http.StatusBadRequest) - ctx.JSON(&response.Body) + writeErrorResponse(ctx, http.StatusBadRequest, response.MalformedJSON, errorMessage) return } - sessionToken := ctx.Request().Header.Get("X-Auth-Token") + sessionToken := ctx.Request().Header.Get(AuthTokenHeader) if sessionToken == "" { - errorMessage := "error: no X-Auth-Token found in request header" - l.Log.Error(errorMessage) - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + errorMessage := invalidAuthTokenErrorMsg + writeErrorResponse(ctx, http.StatusUnauthorized, response.NoValidSession, errorMessage) } blockReq := compositionserviceproto.CreateCompositionResourceRequest{ @@ -178,10 +146,7 @@ func (cs *CompositionServiceRPCs) CreateResourceBlock(ctx iris.Context) { resp, err := cs.CreateResourceBlockRPC(blockReq) if err != nil { errorMessage := "RPC error:" + err.Error() - l.Log.Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) + writeErrorResponse(ctx, http.StatusInternalServerError, response.InternalError, errorMessage) return } @@ -193,14 +158,10 @@ func (cs *CompositionServiceRPCs) CreateResourceBlock(ctx iris.Context) { // DeleteResourceBlock Remove Resource Block Instance func (cs *CompositionServiceRPCs) DeleteResourceBlock(ctx iris.Context) { defer ctx.Next() - sessionToken := ctx.Request().Header.Get("X-Auth-Token") + sessionToken := ctx.Request().Header.Get(AuthTokenHeader) if sessionToken == "" { - errorMessage := "error: no X-Auth-Token found in request header" - l.Log.Error(errorMessage) - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + errorMessage := invalidAuthTokenErrorMsg + writeErrorResponse(ctx, http.StatusUnauthorized, response.NoValidSession, errorMessage) } req := compositionserviceproto.DeleteCompositionResourceRequest{ @@ -211,10 +172,7 @@ func (cs *CompositionServiceRPCs) DeleteResourceBlock(ctx iris.Context) { resp, err := cs.DeleteResourceBlockRPC(req) if err != nil { errorMessage := "RPC error:" + err.Error() - l.Log.Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) + writeErrorResponse(ctx, http.StatusInternalServerError, response.InternalError, errorMessage) return } @@ -227,24 +185,17 @@ func (cs *CompositionServiceRPCs) DeleteResourceBlock(ctx iris.Context) { func (cs *CompositionServiceRPCs) GetResourceZoneCollection(ctx iris.Context) { defer ctx.Next() req := compositionserviceproto.GetCompositionResourceRequest{ - SessionToken: ctx.Request().Header.Get("X-Auth-Token"), + SessionToken: ctx.Request().Header.Get(AuthTokenHeader), URL: ctx.Request().RequestURI, } if req.SessionToken == "" { - errorMessage := "error: no X-Auth-Token found in request header" - l.Log.Error(errorMessage) - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + errorMessage := invalidAuthTokenErrorMsg + writeErrorResponse(ctx, http.StatusUnauthorized, response.NoValidSession, errorMessage) } resp, err := cs.GetResourceZoneCollectionRPC(req) if err != nil { errorMessage := "error: RPC error:" + err.Error() - l.Log.Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) + writeErrorResponse(ctx, http.StatusInternalServerError, response.InternalError, errorMessage) return } @@ -257,25 +208,18 @@ func (cs *CompositionServiceRPCs) GetResourceZoneCollection(ctx iris.Context) { func (cs *CompositionServiceRPCs) GetResourceZone(ctx iris.Context) { defer ctx.Next() req := compositionserviceproto.GetCompositionResourceRequest{ - SessionToken: ctx.Request().Header.Get("X-Auth-Token"), + SessionToken: ctx.Request().Header.Get(AuthTokenHeader), URL: ctx.Request().RequestURI, ResourceID: ctx.Params().Get("id"), } if req.SessionToken == "" { - errorMessage := "error: no X-Auth-Token found in request header" - l.Log.Error(errorMessage) - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + errorMessage := invalidAuthTokenErrorMsg + writeErrorResponse(ctx, http.StatusUnauthorized, response.NoValidSession, errorMessage) } resp, err := cs.GetResourceZoneRPC(req) if err != nil { errorMessage := "error: RPC error:" + err.Error() - l.Log.Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) + writeErrorResponse(ctx, http.StatusInternalServerError, response.InternalError, errorMessage) return } @@ -291,30 +235,19 @@ func (cs *CompositionServiceRPCs) CreateResourceZone(ctx iris.Context) { err := ctx.ReadJSON(&req) if err != nil { errorMessage := "error while trying to get JSON body from the create Resource zone request body: " + err.Error() - l.Log.Error(errorMessage) - response := common.GeneralError(http.StatusBadRequest, response.MalformedJSON, errorMessage, nil, nil) - ctx.StatusCode(http.StatusBadRequest) - ctx.JSON(&response.Body) - return + writeErrorResponse(ctx, http.StatusBadRequest, response.MalformedJSON, errorMessage) } request, err := json.Marshal(req) if err != nil { errorMessage := "error while trying to create JSON request body: " + err.Error() - l.Log.Error(errorMessage) - response := common.GeneralError(http.StatusBadRequest, response.MalformedJSON, errorMessage, nil, nil) - ctx.StatusCode(http.StatusBadRequest) - ctx.JSON(&response.Body) + writeErrorResponse(ctx, http.StatusBadRequest, response.MalformedJSON, errorMessage) return } - sessionToken := ctx.Request().Header.Get("X-Auth-Token") + sessionToken := ctx.Request().Header.Get(AuthTokenHeader) if sessionToken == "" { - errorMessage := "error: no X-Auth-Token found in request header" - l.Log.Error(errorMessage) - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + errorMessage := invalidAuthTokenErrorMsg + writeErrorResponse(ctx, http.StatusUnauthorized, response.NoValidSession, errorMessage) } zoneReq := compositionserviceproto.CreateCompositionResourceRequest{ @@ -326,10 +259,7 @@ func (cs *CompositionServiceRPCs) CreateResourceZone(ctx iris.Context) { resp, err := cs.CreateResourceZoneRPC(zoneReq) if err != nil { errorMessage := "RPC error:" + err.Error() - l.Log.Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) + writeErrorResponse(ctx, http.StatusInternalServerError, response.InternalError, errorMessage) return } @@ -341,14 +271,10 @@ func (cs *CompositionServiceRPCs) CreateResourceZone(ctx iris.Context) { // DeleteResourceZone remove Resource zone Instance func (cs *CompositionServiceRPCs) DeleteResourceZone(ctx iris.Context) { defer ctx.Next() - sessionToken := ctx.Request().Header.Get("X-Auth-Token") + sessionToken := ctx.Request().Header.Get(AuthTokenHeader) if sessionToken == "" { - errorMessage := "error: no X-Auth-Token found in request header" - l.Log.Error(errorMessage) - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + errorMessage := invalidAuthTokenErrorMsg + writeErrorResponse(ctx, http.StatusUnauthorized, response.NoValidSession, errorMessage) } req := compositionserviceproto.DeleteCompositionResourceRequest{ @@ -359,10 +285,7 @@ func (cs *CompositionServiceRPCs) DeleteResourceZone(ctx iris.Context) { resp, err := cs.DeleteResourceZoneRPC(req) if err != nil { errorMessage := "RPC error:" + err.Error() - l.Log.Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) + writeErrorResponse(ctx, http.StatusInternalServerError, response.InternalError, errorMessage) return } @@ -378,31 +301,20 @@ func (cs *CompositionServiceRPCs) Compose(ctx iris.Context) { err := ctx.ReadJSON(&req) if err != nil { errorMessage := "error while trying to get JSON body from the compose request body: " + err.Error() - l.Log.Error(errorMessage) - response := common.GeneralError(http.StatusBadRequest, response.MalformedJSON, errorMessage, nil, nil) - ctx.StatusCode(http.StatusBadRequest) - ctx.JSON(&response.Body) - return + writeErrorResponse(ctx, http.StatusBadRequest, response.MalformedJSON, errorMessage) } request, err := json.Marshal(req) if err != nil { errorMessage := "error while trying to create JSON request body: " + err.Error() - l.Log.Error(errorMessage) - response := common.GeneralError(http.StatusBadRequest, response.MalformedJSON, errorMessage, nil, nil) - ctx.StatusCode(http.StatusBadRequest) - ctx.JSON(&response.Body) + writeErrorResponse(ctx, http.StatusBadRequest, response.MalformedJSON, errorMessage) return } - sessionToken := ctx.Request().Header.Get("X-Auth-Token") + sessionToken := ctx.Request().Header.Get(AuthTokenHeader) if sessionToken == "" { - errorMessage := "error: no X-Auth-Token found in request header" - l.Log.Error(errorMessage) - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + errorMessage := invalidAuthTokenErrorMsg + writeErrorResponse(ctx, http.StatusUnauthorized, response.NoValidSession, errorMessage) } composeReq := compositionserviceproto.ComposeRequest{ @@ -414,10 +326,7 @@ func (cs *CompositionServiceRPCs) Compose(ctx iris.Context) { resp, err := cs.ComposeRPC(composeReq) if err != nil { errorMessage := "RPC error:" + err.Error() - l.Log.Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) + writeErrorResponse(ctx, http.StatusInternalServerError, response.InternalError, errorMessage) return } @@ -430,25 +339,18 @@ func (cs *CompositionServiceRPCs) Compose(ctx iris.Context) { func (cs *CompositionServiceRPCs) GetActivePool(ctx iris.Context) { defer ctx.Next() req := compositionserviceproto.GetCompositionResourceRequest{ - SessionToken: ctx.Request().Header.Get("X-Auth-Token"), + SessionToken: ctx.Request().Header.Get(AuthTokenHeader), URL: ctx.Request().RequestURI, } if req.SessionToken == "" { - errorMessage := "error: no X-Auth-Token found in request header" - l.Log.Error(errorMessage) - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + errorMessage := invalidAuthTokenErrorMsg + writeErrorResponse(ctx, http.StatusUnauthorized, response.NoValidSession, errorMessage) } resp, err := cs.GetActivePoolRPC(req) if err != nil { errorMessage := "RPC error:" + err.Error() - l.Log.Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) + writeErrorResponse(ctx, http.StatusInternalServerError, response.InternalError, errorMessage) return } @@ -461,25 +363,18 @@ func (cs *CompositionServiceRPCs) GetActivePool(ctx iris.Context) { func (cs *CompositionServiceRPCs) GetFreePool(ctx iris.Context) { defer ctx.Next() req := compositionserviceproto.GetCompositionResourceRequest{ - SessionToken: ctx.Request().Header.Get("X-Auth-Token"), + SessionToken: ctx.Request().Header.Get(AuthTokenHeader), URL: ctx.Request().RequestURI, } if req.SessionToken == "" { - errorMessage := "error: no X-Auth-Token found in request header" - l.Log.Error(errorMessage) - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + errorMessage := invalidAuthTokenErrorMsg + writeErrorResponse(ctx, http.StatusUnauthorized, response.NoValidSession, errorMessage) } resp, err := cs.GetFreePoolRPC(req) if err != nil { errorMessage := "RPC error:" + err.Error() - l.Log.Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) + writeErrorResponse(ctx, http.StatusInternalServerError, response.InternalError, errorMessage) return } @@ -492,25 +387,18 @@ func (cs *CompositionServiceRPCs) GetFreePool(ctx iris.Context) { func (cs *CompositionServiceRPCs) GetCompositionReservations(ctx iris.Context) { defer ctx.Next() req := compositionserviceproto.GetCompositionResourceRequest{ - SessionToken: ctx.Request().Header.Get("X-Auth-Token"), + SessionToken: ctx.Request().Header.Get(AuthTokenHeader), URL: ctx.Request().RequestURI, } if req.SessionToken == "" { - errorMessage := "error: no X-Auth-Token found in request header" - l.Log.Error(errorMessage) - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + errorMessage := invalidAuthTokenErrorMsg + writeErrorResponse(ctx, http.StatusUnauthorized, response.NoValidSession, errorMessage) } resp, err := cs.GetCompositionReservationsRPC(req) if err != nil { errorMessage := "RPC error:" + err.Error() - l.Log.Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) + writeErrorResponse(ctx, http.StatusInternalServerError, response.InternalError, errorMessage) return } @@ -518,3 +406,12 @@ func (cs *CompositionServiceRPCs) GetCompositionReservations(ctx iris.Context) { ctx.StatusCode(int(resp.StatusCode)) ctx.Write(resp.Body) } + +// writeErrorResponse writes error response to client +func writeErrorResponse(ctx iris.Context, statusCode int32, statusMsg, errorMessage string) { + l.Log.Error(errorMessage) + response := common.GeneralError(statusCode, statusMsg, errorMessage, nil, nil) + ctx.StatusCode(int(statusCode)) + ctx.JSON(&response.Body) + return +} diff --git a/svc-api/handle/compositionservice_test.go b/svc-api/handle/compositionservice_test.go index f75426910..f4da70661 100644 --- a/svc-api/handle/compositionservice_test.go +++ b/svc-api/handle/compositionservice_test.go @@ -1,15 +1,15 @@ -//(C) Copyright [2020] Hewlett Packard Enterprise Development LP +// (C) Copyright [2020] Hewlett Packard Enterprise Development LP // -//Licensed under the Apache License, Version 2.0 (the "License"); you may -//not use this file except in compliance with the License. You may obtain -//a copy of the License at +// Licensed under the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. You may obtain +// a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -//WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -//License for the specific language governing permissions and limitations +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +// License for the specific language governing permissions and limitations // under the License. package handle diff --git a/svc-api/handle/events.go b/svc-api/handle/events.go index 4f3086b52..7f9afb7f8 100644 --- a/svc-api/handle/events.go +++ b/svc-api/handle/events.go @@ -18,12 +18,10 @@ package handle import ( "context" "encoding/json" - "net/http" "github.com/ODIM-Project/ODIM/lib-utilities/common" l "github.com/ODIM-Project/ODIM/lib-utilities/logs" eventsproto "github.com/ODIM-Project/ODIM/lib-utilities/proto/events" - "github.com/ODIM-Project/ODIM/lib-utilities/response" iris "github.com/kataras/iris/v12" ) @@ -43,24 +41,16 @@ func (e *EventsRPCs) GetEventService(ctx iris.Context) { ctxt := ctx.Request().Context() l.LogWithFields(ctxt).Debug("Incoming request received for the Get Event service") req := eventsproto.EventSubRequest{ - SessionToken: ctx.Request().Header.Get("X-Auth-Token"), + SessionToken: ctx.Request().Header.Get(AuthTokenHeader), } if req.SessionToken == "" { - errorMessage := "no X-Auth-Token found in request header" - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + errorMessage := invalidAuthTokenErrMsg + common.SendInvalidSessionResponse(ctx, errorMessage) } resp, err := e.GetEventServiceRPC(ctxt, req) if err != nil { l.LogWithFields(ctxt).Error(err.Error()) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, err.Error(), nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) - return + common.SendFailedRPCCallResponse(ctx, err.Error()) } l.LogWithFields(ctxt).Debugf("Outgoing response for Getting Event service is %s and response status %d", string(resp.Body), int(resp.StatusCode)) ctx.ResponseWriter().Header().Set("Allow", "GET") @@ -80,32 +70,20 @@ func (e *EventsRPCs) CreateEventSubscription(ctx iris.Context) { if err != nil { errorMessage := "error while trying to get JSON body from the event subscription request body: " + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusBadRequest, response.MalformedJSON, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusBadRequest) - ctx.JSON(&response.Body) - return + common.SendMalformedJSONRequestErrResponse(ctx, errorMessage) } - req.SessionToken = ctx.Request().Header.Get("X-Auth-Token") + req.SessionToken = ctx.Request().Header.Get(AuthTokenHeader) if req.SessionToken == "" { - errorMessage := "no X-Auth-Token found in request header" - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + errorMessage := invalidAuthTokenErrMsg + common.SendInvalidSessionResponse(ctx, errorMessage) } req.PostBody, _ = json.Marshal(&SubscriptionReq) l.LogWithFields(ctxt).Debugf("Incoming request received for creating event subscription with request body %s", string(req.PostBody)) resp, err := e.CreateEventSubscriptionRPC(ctxt, req) if err != nil { l.LogWithFields(ctxt).Error(err.Error()) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, err.Error(), nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) - return + common.SendFailedRPCCallResponse(ctx, err.Error()) } l.LogWithFields(ctxt).Debugf("Outgoing response for creating event subscription is %s with response code %d", string(resp.Body), int(resp.StatusCode)) common.SetResponseHeader(ctx, resp.Header) @@ -124,33 +102,21 @@ func (e *EventsRPCs) SubmitTestEvent(ctx iris.Context) { if err != nil { errorMessage := "error while trying to get JSON body from the SubmitTestEvent request body: " + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusBadRequest, response.MalformedJSON, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusBadRequest) - ctx.JSON(&response.Body) - return + common.SendMalformedJSONRequestErrResponse(ctx, errorMessage) } - req.SessionToken = ctx.Request().Header.Get("X-Auth-Token") + req.SessionToken = ctx.Request().Header.Get(AuthTokenHeader) if req.SessionToken == "" { - errorMessage := "no X-Auth-Token found in request header" - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + errorMessage := invalidAuthTokenErrMsg + common.SendInvalidSessionResponse(ctx, errorMessage) } req.PostBody, _ = json.Marshal(&SubmitTestEventReq) l.LogWithFields(ctxt).Debugf("Incoming request received for submit test event with request body %s", string(req.PostBody)) resp, err := e.SubmitTestEventRPC(ctxt, req) if err != nil { l.LogWithFields(ctxt).Error(err.Error()) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, err.Error(), nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) - return + common.SendFailedRPCCallResponse(ctx, err.Error()) } l.LogWithFields(ctxt).Debugf("Outgoing response for submit test event is %s with response code %d", string(resp.Body), int(resp.StatusCode)) common.SetResponseHeader(ctx, resp.Header) @@ -164,25 +130,17 @@ func (e *EventsRPCs) GetEventSubscription(ctx iris.Context) { ctxt := ctx.Request().Context() var req eventsproto.EventRequest req.EventSubscriptionID = ctx.Params().Get("id") - req.SessionToken = ctx.Request().Header.Get("X-Auth-Token") + req.SessionToken = ctx.Request().Header.Get(AuthTokenHeader) l.LogWithFields(ctxt).Debugf("Incoming request received for getting event subscription with id %s", req.EventSubscriptionID) if req.SessionToken == "" { - errorMessage := "no X-Auth-Token found in request header" - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + errorMessage := invalidAuthTokenErrMsg + common.SendInvalidSessionResponse(ctx, errorMessage) } resp, err := e.GetEventSubscriptionRPC(ctxt, req) if err != nil { l.LogWithFields(ctxt).Error(err.Error()) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, err.Error(), nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response) - return + common.SendFailedRPCCallResponse(ctx, err.Error()) } l.LogWithFields(ctxt).Debugf("Outgoing response for getting event subscription is %s with response code %d", string(resp.Body), int(resp.StatusCode)) ctx.ResponseWriter().Header().Set("Allow", "GET, DELETE") @@ -197,25 +155,17 @@ func (e *EventsRPCs) DeleteEventSubscription(ctx iris.Context) { ctxt := ctx.Request().Context() var req eventsproto.EventRequest req.EventSubscriptionID = ctx.Params().Get("id") - req.SessionToken = ctx.Request().Header.Get("X-Auth-Token") + req.SessionToken = ctx.Request().Header.Get(AuthTokenHeader) l.LogWithFields(ctxt).Debugf("Incoming request received for deleting event subscription with id %s", req.EventSubscriptionID) if req.SessionToken == "" { - errorMessage := "no X-Auth-Token found in request header" - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + errorMessage := invalidAuthTokenErrMsg + common.SendInvalidSessionResponse(ctx, errorMessage) } resp, err := e.DeleteEventSubscriptionRPC(ctxt, req) if err != nil { l.LogWithFields(ctxt).Error(err.Error()) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, err.Error(), nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) - return + common.SendFailedRPCCallResponse(ctx, err.Error()) } l.LogWithFields(ctxt).Debugf("Outgoing response for deleting event subscription is %s with response code %d", string(resp.Body), int(resp.StatusCode)) common.SetResponseHeader(ctx, resp.Header) @@ -228,25 +178,17 @@ func (e *EventsRPCs) GetEventSubscriptionsCollection(ctx iris.Context) { defer ctx.Next() ctxt := ctx.Request().Context() var req eventsproto.EventRequest - req.SessionToken = ctx.Request().Header.Get("X-Auth-Token") + req.SessionToken = ctx.Request().Header.Get(AuthTokenHeader) l.LogWithFields(ctxt).Debugf("Incoming request received for getting all the event subscription collections") if req.SessionToken == "" { - errorMessage := "no X-Auth-Token found in request header" - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + errorMessage := invalidAuthTokenErrMsg + common.SendInvalidSessionResponse(ctx, errorMessage) } resp, err := e.GetEventSubscriptionsCollectionRPC(ctxt, req) if err != nil { l.LogWithFields(ctxt).Error(err.Error()) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, err.Error(), nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) - return + common.SendFailedRPCCallResponse(ctx, err.Error()) } l.LogWithFields(ctxt).Debugf("Outgoing response for getting event subscription collections is %s with response code %d", string(resp.Body), int(resp.StatusCode)) ctx.ResponseWriter().Header().Set("Allow", "GET, POST") diff --git a/svc-api/handle/fabrics.go b/svc-api/handle/fabrics.go index dabbef14d..5c8d21140 100644 --- a/svc-api/handle/fabrics.go +++ b/svc-api/handle/fabrics.go @@ -18,12 +18,10 @@ package handle import ( "context" "encoding/json" - "net/http" "github.com/ODIM-Project/ODIM/lib-utilities/common" l "github.com/ODIM-Project/ODIM/lib-utilities/logs" fabricsproto "github.com/ODIM-Project/ODIM/lib-utilities/proto/fabrics" - "github.com/ODIM-Project/ODIM/lib-utilities/response" iris "github.com/kataras/iris/v12" ) @@ -34,42 +32,34 @@ type FabricRPCs struct { DeleteFabricResourceRPC func(context.Context, fabricsproto.FabricRequest) (*fabricsproto.FabricResponse, error) } +const ( + rpcFailedErrMsg = "RPC error: " +) + // GetFabricCollection defines the GetFabricCollection iris handler. // The method extracts given Fabric Resource func (f *FabricRPCs) GetFabricCollection(ctx iris.Context) { defer ctx.Next() ctxt := ctx.Request().Context() - req := fabricsproto.FabricRequest{ - SessionToken: ctx.Request().Header.Get("X-Auth-Token"), - URL: ctx.Request().RequestURI, - } + req := getFabricRequest(ctx) l.LogWithFields(ctxt).Debugf("Incoming request received for getting fabric collection with request url %s", req.URL) if req.SessionToken == "" { - errorMessage := "error: no X-Auth-Token found in request header" - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + errorMessage := invalidAuthTokenErrorMsg + common.SendInvalidSessionResponse(ctx, errorMessage) } resp, err := f.GetFabricResourceRPC(ctxt, req) if err != nil && resp == nil { - errorMessage := "RPC error: " + err.Error() + errorMessage := rpcFailedErrMsg + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) + common.SendFailedRPCCallResponse(ctx, errorMessage) return } resp.Header = map[string]string{ "Allow": `"GET"`, } l.LogWithFields(ctxt).Debugf("Outgoing response for getting all fabric collection is %s with status code %d", string(resp.Body), int(resp.StatusCode)) - common.SetResponseHeader(ctx, resp.Header) - ctx.StatusCode(int(resp.StatusCode)) - ctx.Write(resp.Body) + sendFabricResponse(ctx, resp) } // GetFabric defines the GetFabric iris handler. @@ -77,37 +67,25 @@ func (f *FabricRPCs) GetFabricCollection(ctx iris.Context) { func (f *FabricRPCs) GetFabric(ctx iris.Context) { defer ctx.Next() ctxt := ctx.Request().Context() - req := fabricsproto.FabricRequest{ - SessionToken: ctx.Request().Header.Get("X-Auth-Token"), - URL: ctx.Request().RequestURI, - } + req := getFabricRequest(ctx) l.LogWithFields(ctxt).Debugf("Incoming request received for creating fabric with request url %s", req.URL) if req.SessionToken == "" { - errorMessage := "error: no X-Auth-Token found in request header" - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + errorMessage := invalidAuthTokenErrorMsg + common.SendInvalidSessionResponse(ctx, errorMessage) } resp, err := f.GetFabricResourceRPC(ctxt, req) if err != nil && resp == nil { - errorMessage := "RPC error: " + err.Error() + errorMessage := rpcFailedErrMsg + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) + common.SendFailedRPCCallResponse(ctx, errorMessage) return } resp.Header = map[string]string{ "Allow": `"GET"`, } l.LogWithFields(ctxt).Debugf("Outgoing response for creating fabric is %s with status code %d", string(resp.Body), int(resp.StatusCode)) - common.SetResponseHeader(ctx, resp.Header) - ctx.StatusCode(int(resp.StatusCode)) - ctx.Write(resp.Body) + sendFabricResponse(ctx, resp) } // GetFabricSwitchCollection defines the GetFabricSwitchCollection iris handler. @@ -115,37 +93,25 @@ func (f *FabricRPCs) GetFabric(ctx iris.Context) { func (f *FabricRPCs) GetFabricSwitchCollection(ctx iris.Context) { defer ctx.Next() ctxt := ctx.Request().Context() - req := fabricsproto.FabricRequest{ - SessionToken: ctx.Request().Header.Get("X-Auth-Token"), - URL: ctx.Request().RequestURI, - } + req := getFabricRequest(ctx) l.LogWithFields(ctxt).Debugf("Incoming request received for getting fabric switch collection with request url %s", req.URL) if req.SessionToken == "" { - errorMessage := "error: no X-Auth-Token found in request header" - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + errorMessage := invalidAuthTokenErrorMsg + common.SendInvalidSessionResponse(ctx, errorMessage) } resp, err := f.GetFabricResourceRPC(ctxt, req) if err != nil && resp == nil { - errorMessage := "RPC error: " + err.Error() + errorMessage := rpcFailedErrMsg + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) + common.SendFailedRPCCallResponse(ctx, errorMessage) return } resp.Header = map[string]string{ "Allow": `"GET"`, } l.LogWithFields(ctxt).Debugf("Outgoing response for getting all fabric switch collection is %s with status code %d", string(resp.Body), int(resp.StatusCode)) - common.SetResponseHeader(ctx, resp.Header) - ctx.StatusCode(int(resp.StatusCode)) - ctx.Write(resp.Body) + sendFabricResponse(ctx, resp) } // GetFabricSwitch defines the GetFabricSwitch iris handler. @@ -153,37 +119,25 @@ func (f *FabricRPCs) GetFabricSwitchCollection(ctx iris.Context) { func (f *FabricRPCs) GetFabricSwitch(ctx iris.Context) { defer ctx.Next() ctxt := ctx.Request().Context() - req := fabricsproto.FabricRequest{ - SessionToken: ctx.Request().Header.Get("X-Auth-Token"), - URL: ctx.Request().RequestURI, - } + req := getFabricRequest(ctx) l.LogWithFields(ctxt).Debugf("Incoming request received for creating fabric switch with request url %s", req.URL) if req.SessionToken == "" { - errorMessage := "error: no X-Auth-Token found in request header" - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + errorMessage := invalidAuthTokenErrorMsg + common.SendInvalidSessionResponse(ctx, errorMessage) } resp, err := f.GetFabricResourceRPC(ctxt, req) if err != nil && resp == nil { - errorMessage := "RPC error: " + err.Error() + errorMessage := rpcFailedErrMsg + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) + common.SendFailedRPCCallResponse(ctx, errorMessage) return } resp.Header = map[string]string{ "Allow": `"GET"`, } l.LogWithFields(ctxt).Debugf("Outgoing response for creating fabric switch is %s with status code %d", string(resp.Body), int(resp.StatusCode)) - common.SetResponseHeader(ctx, resp.Header) - ctx.StatusCode(int(resp.StatusCode)) - ctx.Write(resp.Body) + sendFabricResponse(ctx, resp) } // GetSwitchPortCollection defines the GetSwitchPortCollection iris handler. @@ -191,37 +145,25 @@ func (f *FabricRPCs) GetFabricSwitch(ctx iris.Context) { func (f *FabricRPCs) GetSwitchPortCollection(ctx iris.Context) { defer ctx.Next() ctxt := ctx.Request().Context() - req := fabricsproto.FabricRequest{ - SessionToken: ctx.Request().Header.Get("X-Auth-Token"), - URL: ctx.Request().RequestURI, - } + req := getFabricRequest(ctx) l.LogWithFields(ctxt).Debugf("Incoming request received for getting switch port collection with request url %s", req.URL) if req.SessionToken == "" { - errorMessage := "error: no X-Auth-Token found in request header" - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + errorMessage := invalidAuthTokenErrorMsg + common.SendInvalidSessionResponse(ctx, errorMessage) } resp, err := f.GetFabricResourceRPC(ctxt, req) if err != nil && resp == nil { - errorMessage := "RPC error: " + err.Error() + errorMessage := rpcFailedErrMsg + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) + common.SendFailedRPCCallResponse(ctx, errorMessage) return } resp.Header = map[string]string{ "Allow": `"GET"`, } l.LogWithFields(ctxt).Debugf("Outgoing response for getting switch port collection is %s with status code %d", string(resp.Body), int(resp.StatusCode)) - common.SetResponseHeader(ctx, resp.Header) - ctx.StatusCode(int(resp.StatusCode)) - ctx.Write(resp.Body) + sendFabricResponse(ctx, resp) } // GetSwitchPort defines the GetSwitchPort iris handler. @@ -229,37 +171,25 @@ func (f *FabricRPCs) GetSwitchPortCollection(ctx iris.Context) { func (f *FabricRPCs) GetSwitchPort(ctx iris.Context) { defer ctx.Next() ctxt := ctx.Request().Context() - req := fabricsproto.FabricRequest{ - SessionToken: ctx.Request().Header.Get("X-Auth-Token"), - URL: ctx.Request().RequestURI, - } + req := getFabricRequest(ctx) l.LogWithFields(ctxt).Debugf("Incoming request received for getting switch port with request url %s", req.URL) if req.SessionToken == "" { - errorMessage := "error: no X-Auth-Token found in request header" - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + errorMessage := invalidAuthTokenErrorMsg + common.SendInvalidSessionResponse(ctx, errorMessage) } resp, err := f.GetFabricResourceRPC(ctxt, req) if err != nil && resp == nil { - errorMessage := "RPC error: " + err.Error() + errorMessage := rpcFailedErrMsg + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) + common.SendFailedRPCCallResponse(ctx, errorMessage) return } resp.Header = map[string]string{ "Allow": `"GET", "PATCH"`, } l.LogWithFields(ctxt).Debugf("Outgoing response for getting switch port is %s with status code %d", string(resp.Body), int(resp.StatusCode)) - common.SetResponseHeader(ctx, resp.Header) - ctx.StatusCode(int(resp.StatusCode)) - ctx.Write(resp.Body) + sendFabricResponse(ctx, resp) } // GetFabricZoneCollection defines the GetFabricZoneCollection iris handler. @@ -267,37 +197,25 @@ func (f *FabricRPCs) GetSwitchPort(ctx iris.Context) { func (f *FabricRPCs) GetFabricZoneCollection(ctx iris.Context) { defer ctx.Next() ctxt := ctx.Request().Context() - req := fabricsproto.FabricRequest{ - SessionToken: ctx.Request().Header.Get("X-Auth-Token"), - URL: ctx.Request().RequestURI, - } + req := getFabricRequest(ctx) l.LogWithFields(ctxt).Debugf("Incoming request received for getting fabric zone collection with request url %s", req.URL) if req.SessionToken == "" { - errorMessage := "error: no X-Auth-Token found in request header" - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + errorMessage := invalidAuthTokenErrorMsg + common.SendInvalidSessionResponse(ctx, errorMessage) } resp, err := f.GetFabricResourceRPC(ctxt, req) if err != nil && resp == nil { - errorMessage := "RPC error: " + err.Error() + errorMessage := rpcFailedErrMsg + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) + common.SendFailedRPCCallResponse(ctx, errorMessage) return } resp.Header = map[string]string{ "Allow": `"GET", "POST"`, } l.LogWithFields(ctxt).Debugf("Outgoing response for getting fabric zone collection is %s with status code %d", string(resp.Body), int(resp.StatusCode)) - common.SetResponseHeader(ctx, resp.Header) - ctx.StatusCode(int(resp.StatusCode)) - ctx.Write(resp.Body) + sendFabricResponse(ctx, resp) } // GetFabricZone defines the GetFabricZone iris handler. @@ -305,37 +223,25 @@ func (f *FabricRPCs) GetFabricZoneCollection(ctx iris.Context) { func (f *FabricRPCs) GetFabricZone(ctx iris.Context) { defer ctx.Next() ctxt := ctx.Request().Context() - req := fabricsproto.FabricRequest{ - SessionToken: ctx.Request().Header.Get("X-Auth-Token"), - URL: ctx.Request().RequestURI, - } + req := getFabricRequest(ctx) l.LogWithFields(ctxt).Debugf("Incoming request received for getting fabric zone with request url %s", req.URL) if req.SessionToken == "" { - errorMessage := "error: no X-Auth-Token found in request header" - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + errorMessage := invalidAuthTokenErrorMsg + common.SendInvalidSessionResponse(ctx, errorMessage) } resp, err := f.GetFabricResourceRPC(ctxt, req) if err != nil && resp == nil { - errorMessage := "RPC error: " + err.Error() + errorMessage := rpcFailedErrMsg + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) + common.SendFailedRPCCallResponse(ctx, errorMessage) return } resp.Header = map[string]string{ "Allow": `"GET", "PUT", "PATCH", "DELETE"`, } l.LogWithFields(ctxt).Debugf("Outgoing response for getting fabric zone is %s with status code %d", string(resp.Body), int(resp.StatusCode)) - common.SetResponseHeader(ctx, resp.Header) - ctx.StatusCode(int(resp.StatusCode)) - ctx.Write(resp.Body) + sendFabricResponse(ctx, resp) } // GetFabricEndPointCollection defines the GetFabricEndPointCollection iris handler. @@ -343,37 +249,25 @@ func (f *FabricRPCs) GetFabricZone(ctx iris.Context) { func (f *FabricRPCs) GetFabricEndPointCollection(ctx iris.Context) { defer ctx.Next() ctxt := ctx.Request().Context() - req := fabricsproto.FabricRequest{ - SessionToken: ctx.Request().Header.Get("X-Auth-Token"), - URL: ctx.Request().RequestURI, - } + req := getFabricRequest(ctx) l.LogWithFields(ctxt).Debugf("Incoming request received for getting fabric endpoint collection with request url %s", req.URL) if req.SessionToken == "" { - errorMessage := "error: no X-Auth-Token found in request header" - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + errorMessage := invalidAuthTokenErrorMsg + common.SendInvalidSessionResponse(ctx, errorMessage) } resp, err := f.GetFabricResourceRPC(ctxt, req) if err != nil && resp == nil { - errorMessage := "RPC error: " + err.Error() + errorMessage := rpcFailedErrMsg + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) + common.SendFailedRPCCallResponse(ctx, errorMessage) return } resp.Header = map[string]string{ "Allow": `"GET", "POST"`, } l.LogWithFields(ctxt).Debugf("Outgoing response for getting fabric endpoint collection is %s with status code %d", string(resp.Body), int(resp.StatusCode)) - common.SetResponseHeader(ctx, resp.Header) - ctx.StatusCode(int(resp.StatusCode)) - ctx.Write(resp.Body) + sendFabricResponse(ctx, resp) } // GetFabricEndPoints defines the GetFabricEndPoints iris handler. @@ -381,37 +275,25 @@ func (f *FabricRPCs) GetFabricEndPointCollection(ctx iris.Context) { func (f *FabricRPCs) GetFabricEndPoints(ctx iris.Context) { defer ctx.Next() ctxt := ctx.Request().Context() - req := fabricsproto.FabricRequest{ - SessionToken: ctx.Request().Header.Get("X-Auth-Token"), - URL: ctx.Request().RequestURI, - } + req := getFabricRequest(ctx) l.LogWithFields(ctxt).Debugf("Incoming request received for getting fabric endpoint with request url %s", req.URL) if req.SessionToken == "" { - errorMessage := "error: no X-Auth-Token found in request header" - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + errorMessage := invalidAuthTokenErrorMsg + common.SendInvalidSessionResponse(ctx, errorMessage) } resp, err := f.GetFabricResourceRPC(ctxt, req) if err != nil && resp == nil { - errorMessage := "RPC error: " + err.Error() + errorMessage := rpcFailedErrMsg + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) + common.SendFailedRPCCallResponse(ctx, errorMessage) return } resp.Header = map[string]string{ "Allow": `"GET", "PUT", "PATCH", "DELETE"`, } l.LogWithFields(ctxt).Debugf("Outgoing response for getting fabric endpoint is %s with status code %d", string(resp.Body), int(resp.StatusCode)) - common.SetResponseHeader(ctx, resp.Header) - ctx.StatusCode(int(resp.StatusCode)) - ctx.Write(resp.Body) + sendFabricResponse(ctx, resp) } // GetFabricAddressPoolCollection defines the GetFabricAddressPoolCollection iris handler. @@ -419,37 +301,25 @@ func (f *FabricRPCs) GetFabricEndPoints(ctx iris.Context) { func (f *FabricRPCs) GetFabricAddressPoolCollection(ctx iris.Context) { defer ctx.Next() ctxt := ctx.Request().Context() - req := fabricsproto.FabricRequest{ - SessionToken: ctx.Request().Header.Get("X-Auth-Token"), - URL: ctx.Request().RequestURI, - } + req := getFabricRequest(ctx) l.LogWithFields(ctxt).Debugf("Incoming request received for getting fabric address pool collection with request url %s", req.URL) if req.SessionToken == "" { - errorMessage := "error: no X-Auth-Token found in request header" - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + errorMessage := invalidAuthTokenErrorMsg + common.SendInvalidSessionResponse(ctx, errorMessage) } resp, err := f.GetFabricResourceRPC(ctxt, req) if err != nil && resp == nil { - errorMessage := "RPC error: " + err.Error() + errorMessage := rpcFailedErrMsg + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) + common.SendFailedRPCCallResponse(ctx, errorMessage) return } resp.Header = map[string]string{ "Allow": `"GET", "POST"`, } l.LogWithFields(ctxt).Debugf("Outgoing response for getting fabric address pool collection is %s with status code %d", string(resp.Body), int(resp.StatusCode)) - common.SetResponseHeader(ctx, resp.Header) - ctx.StatusCode(int(resp.StatusCode)) - ctx.Write(resp.Body) + sendFabricResponse(ctx, resp) } // GetFabricAddressPool defines the GetFabricAddressPool iris handler. @@ -457,37 +327,25 @@ func (f *FabricRPCs) GetFabricAddressPoolCollection(ctx iris.Context) { func (f *FabricRPCs) GetFabricAddressPool(ctx iris.Context) { defer ctx.Next() ctxt := ctx.Request().Context() - req := fabricsproto.FabricRequest{ - SessionToken: ctx.Request().Header.Get("X-Auth-Token"), - URL: ctx.Request().RequestURI, - } + req := getFabricRequest(ctx) l.LogWithFields(ctxt).Debugf("Incoming request received for getting fabric address pool with request url %s", req.URL) if req.SessionToken == "" { - errorMessage := "error: no X-Auth-Token found in request header" - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + errorMessage := invalidAuthTokenErrorMsg + common.SendInvalidSessionResponse(ctx, errorMessage) } resp, err := f.GetFabricResourceRPC(ctxt, req) if err != nil && resp == nil { - errorMessage := "RPC error: " + err.Error() + errorMessage := rpcFailedErrMsg + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) + common.SendFailedRPCCallResponse(ctx, errorMessage) return } resp.Header = map[string]string{ "Allow": `"GET", "PUT", "PATCH", "DELETE"`, } l.LogWithFields(ctxt).Debugf("Outgoing response for getting fabric address pool is %s with status code %d", string(resp.Body), int(resp.StatusCode)) - common.SetResponseHeader(ctx, resp.Header) - ctx.StatusCode(int(resp.StatusCode)) - ctx.Write(resp.Body) + sendFabricResponse(ctx, resp) } // UpdateFabricResource defines the UpdateFabricResource iris handler. @@ -496,29 +354,21 @@ func (f *FabricRPCs) UpdateFabricResource(ctx iris.Context) { defer ctx.Next() ctxt := ctx.Request().Context() req := fabricsproto.FabricRequest{ - SessionToken: ctx.Request().Header.Get("X-Auth-Token"), + SessionToken: ctx.Request().Header.Get(AuthTokenHeader), URL: ctx.Request().RequestURI, Method: ctx.Request().Method, } if req.SessionToken == "" { - errorMessage := "error: no X-Auth-Token found in request header" - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + errorMessage := invalidAuthTokenErrorMsg + common.SendInvalidSessionResponse(ctx, errorMessage) } var createReq interface{} err := ctx.ReadJSON(&createReq) if err != nil { errorMessage := "error while trying to get JSON body from the request body: " + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusBadRequest, response.MalformedJSON, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusBadRequest) - ctx.JSON(&response.Body) - return + common.SendMalformedJSONRequestErrResponse(ctx, errorMessage) } // marshalling the req to make fabric UpdateFabricResource request @@ -527,28 +377,20 @@ func (f *FabricRPCs) UpdateFabricResource(ctx iris.Context) { if err != nil { errorMessage := "error while trying to create JSON request body: " + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) + common.SendFailedRPCCallResponse(ctx, errorMessage) return } l.LogWithFields(ctxt).Debugf("Incoming request received for updating fabric resources with request url %s and request body %s", req.URL, string(request)) req.RequestBody = request resp, err := f.UpdateFabricResourceRPC(ctxt, req) if err != nil && resp == nil { - errorMessage := "RPC error: " + err.Error() + errorMessage := rpcFailedErrMsg + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) + common.SendFailedRPCCallResponse(ctx, errorMessage) return } l.LogWithFields(ctxt).Debugf("Outgoing response for updating fabric resource is %s with status code %d", string(resp.Body), int(resp.StatusCode)) - common.SetResponseHeader(ctx, resp.Header) - ctx.StatusCode(int(resp.StatusCode)) - ctx.Write(resp.Body) + sendFabricResponse(ctx, resp) } // DeleteFabricResource defines the DeleteFabricResource iris handler. @@ -556,32 +398,35 @@ func (f *FabricRPCs) UpdateFabricResource(ctx iris.Context) { func (f *FabricRPCs) DeleteFabricResource(ctx iris.Context) { defer ctx.Next() ctxt := ctx.Request().Context() - req := fabricsproto.FabricRequest{ - SessionToken: ctx.Request().Header.Get("X-Auth-Token"), - URL: ctx.Request().RequestURI, - } + req := getFabricRequest(ctx) l.LogWithFields(ctxt).Debugf("Incoming request received for deleting fabric resources with request url %s", req.URL) if req.SessionToken == "" { - errorMessage := "error: no X-Auth-Token found in request header" - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + errorMessage := invalidAuthTokenErrorMsg + common.SendInvalidSessionResponse(ctx, errorMessage) } resp, err := f.DeleteFabricResourceRPC(ctxt, req) if err != nil && resp == nil { - errorMessage := "RPC error: " + err.Error() + errorMessage := rpcFailedErrMsg + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) + common.SendFailedRPCCallResponse(ctx, errorMessage) return } l.LogWithFields(ctxt).Debugf("Outgoing response for deleting fabric resource is %s with status code %d", string(resp.Body), int(resp.StatusCode)) + sendFabricResponse(ctx, resp) +} + +// sendFabricResponse writes the fabric response to client +func sendFabricResponse(ctx iris.Context, resp *fabricsproto.FabricResponse) { common.SetResponseHeader(ctx, resp.Header) ctx.StatusCode(int(resp.StatusCode)) ctx.Write(resp.Body) } + +// getFabricRequest will extract the request from the context and return +func getFabricRequest(ctx iris.Context) fabricsproto.FabricRequest { + return fabricsproto.FabricRequest{ + SessionToken: ctx.Request().Header.Get(AuthTokenHeader), + URL: ctx.Request().RequestURI, + } +} diff --git a/svc-api/handle/handlers.go b/svc-api/handle/handlers.go index 503c78211..33f0366b6 100755 --- a/svc-api/handle/handlers.go +++ b/svc-api/handle/handlers.go @@ -819,13 +819,10 @@ func (r *Registry) GetRegistryFileCollection(ctx iris.Context) { defer ctx.Next() ctxt := ctx.Request().Context() // Authorize the request here - sessionToken := ctx.Request().Header.Get("X-Auth-Token") + sessionToken := ctx.Request().Header.Get(AuthTokenHeader) if sessionToken == "" { - errorMessage := "error: no X-Auth-Token found in request header" - response := common.GeneralError(http.StatusUnauthorized, errResponse.NoValidSession, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) + errorMessage := invalidAuthTokenErrorMsg + common.SendInvalidSessionResponse(ctx, errorMessage) return } authResp, err := r.Auth(ctxt, sessionToken, []string{common.PrivilegeLogin}, []string{}) @@ -834,11 +831,7 @@ func (r *Registry) GetRegistryFileCollection(ctx iris.Context) { if err != nil { errMsg = errMsg + ": " + err.Error() } - l.LogWithFields(ctxt).Error(errMsg) - ctx.StatusCode(int(authResp.StatusCode)) - common.SetResponseHeader(ctx, authResp.Header) - ctx.JSON(authResp.Body) - return + sendAuthErrorResponse(ctxt, ctx, errMsg, authResp) } //Get the Registrystore location @@ -894,7 +887,7 @@ func (r *Registry) GetRegistryFileCollection(ctx iris.Context) { func (r *Registry) GetMessageRegistryFileID(ctx iris.Context) { defer ctx.Next() ctxt := ctx.Request().Context() - sessionToken := ctx.Request().Header.Get("X-Auth-Token") + sessionToken := ctx.Request().Header.Get(AuthTokenHeader) regFileID := ctx.Params().Get("id") if strings.Contains(regFileID, ".json") { r.GetMessageRegistryFile(ctx) @@ -912,11 +905,8 @@ func (r *Registry) GetMessageRegistryFileID(ctx iris.Context) { } regFileID = strings.Replace(regFileID, "#", "%23", -1) if sessionToken == "" { - errorMessage := "error: no X-Auth-Token found in request header" - response := common.GeneralError(http.StatusUnauthorized, errResponse.NoValidSession, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) + errorMessage := invalidAuthTokenErrorMsg + common.SendInvalidSessionResponse(ctx, errorMessage) return } authResp, err := r.Auth(ctxt, sessionToken, []string{common.PrivilegeLogin}, []string{}) @@ -925,11 +915,7 @@ func (r *Registry) GetMessageRegistryFileID(ctx iris.Context) { if err != nil { errMsg = errMsg + ": " + err.Error() } - l.LogWithFields(ctxt).Error(errMsg) - ctx.StatusCode(int(authResp.StatusCode)) - common.SetResponseHeader(ctx, authResp.Header) - ctx.JSON(authResp.Body) - return + sendAuthErrorResponse(ctxt, ctx, errMsg, authResp) } var headers = map[string]string{ "Allow": "GET", @@ -997,7 +983,7 @@ func (r *Registry) GetMessageRegistryFileID(ctx iris.Context) { func (r *Registry) GetMessageRegistryFile(ctx iris.Context) { defer ctx.Next() ctxt := ctx.Request().Context() - sessionToken := ctx.Request().Header.Get("X-Auth-Token") + sessionToken := ctx.Request().Header.Get(AuthTokenHeader) regFileID := ctx.Params().Get("id") if strings.HasPrefix(regFileID, "#") { reqURI := ctx.Request().RequestURI @@ -1012,11 +998,8 @@ func (r *Registry) GetMessageRegistryFile(ctx iris.Context) { regFileID = strings.Replace(regFileID, "#", "%23", -1) l.LogWithFields(ctxt).Debugf("Retriveing message registry file with file id %s", regFileID) if sessionToken == "" { - errorMessage := "error: no X-Auth-Token found in request header" - response := common.GeneralError(http.StatusUnauthorized, errResponse.NoValidSession, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) + errorMessage := invalidAuthTokenErrorMsg + common.SendInvalidSessionResponse(ctx, errorMessage) return } authResp, err := r.Auth(ctxt, sessionToken, []string{common.PrivilegeLogin}, []string{}) @@ -1025,11 +1008,7 @@ func (r *Registry) GetMessageRegistryFile(ctx iris.Context) { if err != nil { errMsg = errMsg + ": " + err.Error() } - l.LogWithFields(ctxt).Error(errMsg) - ctx.StatusCode(int(authResp.StatusCode)) - common.SetResponseHeader(ctx, authResp.Header) - ctx.JSON(authResp.Body) - return + sendAuthErrorResponse(ctxt, ctx, errMsg, authResp) } var headers = map[string]string{ "Allow": "GET", @@ -1063,11 +1042,7 @@ func (r *Registry) GetMessageRegistryFile(ctx iris.Context) { l.LogWithFields(ctxt).Error(err.Error()) errorMessage := "error: Resource not found" l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, errResponse.InternalError, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) - return + common.SendFailedRPCCallResponse(ctx, errorMessage) } common.SetResponseHeader(ctx, headers) ctx.JSON(data) @@ -1401,3 +1376,12 @@ func RoleMethodNotAllowed(ctx iris.Context) { fillMethodNotAllowedErrorResponse(ctx) return } + +// sendAuthErrorResponse writes the response for an RPC call when authentication of session fails +func sendAuthErrorResponse(ctxt context.Context, ctx iris.Context, errorMessage string, authResp errResponse.RPC) { + l.LogWithFields(ctxt).Error(errorMessage) + ctx.StatusCode(int(authResp.StatusCode)) + common.SetResponseHeader(ctx, authResp.Header) + ctx.JSON(authResp.Body) + return +} diff --git a/svc-api/handle/licenses.go b/svc-api/handle/licenses.go index de6fadadf..344497f0e 100644 --- a/svc-api/handle/licenses.go +++ b/svc-api/handle/licenses.go @@ -40,12 +40,12 @@ func (lcns *LicenseRPCs) GetLicenseService(ctx iris.Context) { defer ctx.Next() ctxt := ctx.Request().Context() req := licenseproto.GetLicenseServiceRequest{ - SessionToken: ctx.Request().Header.Get("X-Auth-Token"), + SessionToken: ctx.Request().Header.Get(AuthTokenHeader), URL: ctx.Request().RequestURI, } l.LogWithFields(ctxt).Debug("Incoming request received for the Get License service") if req.SessionToken == "" { - errorMessage := "error: no X-Auth-Token found in request header" + errorMessage := invalidAuthTokenErrorMsg l.LogWithFields(ctxt).Error(errorMessage) response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) ctx.StatusCode(http.StatusUnauthorized) @@ -63,9 +63,7 @@ func (lcns *LicenseRPCs) GetLicenseService(ctx iris.Context) { } l.LogWithFields(ctx).Debugf("Outgoing response for Getting License service is %s and response status %d", string(resp.Body), int(resp.StatusCode)) ctx.ResponseWriter().Header().Set("Allow", "GET") - common.SetResponseHeader(ctx, resp.Header) - ctx.StatusCode(int(resp.StatusCode)) - ctx.Write(resp.Body) + sendGetLicenseResponse(ctx, resp) } // GetLicenseCollection fetches all licenses @@ -73,12 +71,12 @@ func (lcns *LicenseRPCs) GetLicenseCollection(ctx iris.Context) { defer ctx.Next() ctxt := ctx.Request().Context() req := licenseproto.GetLicenseRequest{ - SessionToken: ctx.Request().Header.Get("X-Auth-Token"), + SessionToken: ctx.Request().Header.Get(AuthTokenHeader), URL: ctx.Request().RequestURI, } l.LogWithFields(ctxt).Debugf("Incoming request received for getting license collection with request url %s", req.URL) if req.SessionToken == "" { - errorMessage := "error: no X-Auth-Token found in request header" + errorMessage := invalidAuthTokenErrorMsg l.LogWithFields(ctxt).Error(errorMessage) response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) ctx.StatusCode(http.StatusUnauthorized) @@ -96,9 +94,7 @@ func (lcns *LicenseRPCs) GetLicenseCollection(ctx iris.Context) { } l.LogWithFields(ctxt).Debugf("Outgoing response for getting license collection is %s with status code %d", string(resp.Body), int(resp.StatusCode)) ctx.ResponseWriter().Header().Set("Allow", "GET, POST") - common.SetResponseHeader(ctx, resp.Header) - ctx.StatusCode(int(resp.StatusCode)) - ctx.Write(resp.Body) + sendGetLicenseResponse(ctx, resp) } // GetLicenseResource fetches license resource @@ -106,12 +102,12 @@ func (lcns *LicenseRPCs) GetLicenseResource(ctx iris.Context) { defer ctx.Next() ctxt := ctx.Request().Context() req := licenseproto.GetLicenseResourceRequest{ - SessionToken: ctx.Request().Header.Get("X-Auth-Token"), + SessionToken: ctx.Request().Header.Get(AuthTokenHeader), URL: ctx.Request().RequestURI, } l.LogWithFields(ctxt).Debugf("Incoming request received for getting license resource with request url %s", req.URL) if req.SessionToken == "" { - errorMessage := "error: no X-Auth-Token found in request header" + errorMessage := invalidAuthTokenErrorMsg l.LogWithFields(ctxt).Error(errorMessage) response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) ctx.StatusCode(http.StatusUnauthorized) @@ -129,9 +125,7 @@ func (lcns *LicenseRPCs) GetLicenseResource(ctx iris.Context) { } l.LogWithFields(ctxt).Debugf("Outgoing response for getting license resource is %s with status code %d", string(resp.Body), int(resp.StatusCode)) ctx.ResponseWriter().Header().Set("Allow", "GET") - common.SetResponseHeader(ctx, resp.Header) - ctx.StatusCode(int(resp.StatusCode)) - ctx.Write(resp.Body) + sendGetLicenseResponse(ctx, resp) } // InstallLicenseService installs license @@ -161,12 +155,12 @@ func (lcns *LicenseRPCs) InstallLicenseService(ctx iris.Context) { } l.LogWithFields(ctxt).Debugf("Incoming request received for installing license service with request body %s", string(request)) req := licenseproto.InstallLicenseRequest{ - SessionToken: ctx.Request().Header.Get("X-Auth-Token"), + SessionToken: ctx.Request().Header.Get(AuthTokenHeader), URL: ctx.Request().RequestURI, RequestBody: request, } if req.SessionToken == "" { - errorMessage := "error: no X-Auth-Token found in request header" + errorMessage := invalidAuthTokenErrorMsg l.LogWithFields(ctxt).Error(errorMessage) response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) ctx.StatusCode(http.StatusUnauthorized) @@ -183,6 +177,11 @@ func (lcns *LicenseRPCs) InstallLicenseService(ctx iris.Context) { return } l.LogWithFields(ctxt).Debugf("Outgoing response for installing license service is %s with status code %d", string(resp.Body), int(resp.StatusCode)) + sendGetLicenseResponse(ctx, resp) +} + +// sendGetLicenseResponse writes the license response to client +func sendGetLicenseResponse(ctx iris.Context, resp *licenseproto.GetLicenseResponse) { common.SetResponseHeader(ctx, resp.Header) ctx.StatusCode(int(resp.StatusCode)) ctx.Write(resp.Body) diff --git a/svc-api/handle/managers.go b/svc-api/handle/managers.go index acd0fa34d..82c51c544 100644 --- a/svc-api/handle/managers.go +++ b/svc-api/handle/managers.go @@ -18,12 +18,10 @@ package handle import ( "context" "encoding/json" - "net/http" "github.com/ODIM-Project/ODIM/lib-utilities/common" l "github.com/ODIM-Project/ODIM/lib-utilities/logs" managersproto "github.com/ODIM-Project/ODIM/lib-utilities/proto/managers" - "github.com/ODIM-Project/ODIM/lib-utilities/response" iris "github.com/kataras/iris/v12" ) @@ -45,32 +43,22 @@ func (mgr *ManagersRPCs) GetManagersCollection(ctx iris.Context) { defer ctx.Next() ctxt := ctx.Request().Context() req := managersproto.ManagerRequest{ - SessionToken: ctx.Request().Header.Get("X-Auth-Token"), + SessionToken: ctx.Request().Header.Get(AuthTokenHeader), } l.LogWithFields(ctxt).Debug("Incoming request received for the getting all Managers collection") if req.SessionToken == "" { - errorMessage := "error: no X-Auth-Token found in request header" - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + errorMessage := invalidAuthTokenErrorMsg + common.SendInvalidSessionResponse(ctx, errorMessage) } resp, err := mgr.GetManagersCollectionRPC(ctxt, req) if err != nil { errorMessage := "error: RPC error:" + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) - return + common.SendFailedRPCCallResponse(ctx, errorMessage) } l.LogWithFields(ctx).Debugf("Outgoing response for Getting Managers collection is %s and response status %d", string(resp.Body), int(resp.StatusCode)) ctx.ResponseWriter().Header().Set("Allow", "GET") - common.SetResponseHeader(ctx, resp.Header) - ctx.StatusCode(int(resp.StatusCode)) - ctx.Write(resp.Body) + sendManagersResponse(ctx, resp) } // GetManager fetches computer managers details @@ -78,34 +66,24 @@ func (mgr *ManagersRPCs) GetManager(ctx iris.Context) { defer ctx.Next() ctxt := ctx.Request().Context() req := managersproto.ManagerRequest{ - SessionToken: ctx.Request().Header.Get("X-Auth-Token"), + SessionToken: ctx.Request().Header.Get(AuthTokenHeader), ManagerID: ctx.Params().Get("id"), URL: ctx.Request().RequestURI, } l.LogWithFields(ctxt).Debugf("Incoming request received for the getting a Managers with id %s", req.ManagerID) if req.SessionToken == "" { - errorMessage := "error: no X-Auth-Token found in request header" - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + errorMessage := invalidAuthTokenErrorMsg + common.SendInvalidSessionResponse(ctx, errorMessage) } resp, err := mgr.GetManagersRPC(ctxt, req) if err != nil { errorMessage := "RPC error:" + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) - return + common.SendFailedRPCCallResponse(ctx, errorMessage) } l.LogWithFields(ctx).Debugf("Outgoing response for getting Manager is %s and response status %d", string(resp.Body), int(resp.StatusCode)) ctx.ResponseWriter().Header().Set("Allow", "GET") - common.SetResponseHeader(ctx, resp.Header) - ctx.StatusCode(int(resp.StatusCode)) - ctx.Write(resp.Body) + sendManagersResponse(ctx, resp) } // GetManagersResource defines the GetManagersResource iris handler. @@ -115,36 +93,21 @@ func (mgr *ManagersRPCs) GetManager(ctx iris.Context) { func (mgr *ManagersRPCs) GetManagersResource(ctx iris.Context) { defer ctx.Next() ctxt := ctx.Request().Context() - req := managersproto.ManagerRequest{ - SessionToken: ctx.Request().Header.Get("X-Auth-Token"), - ManagerID: ctx.Params().Get("id"), - ResourceID: ctx.Params().Get("rid"), - URL: ctx.Request().RequestURI, - } + req := getManagerRequest(ctx) l.LogWithFields(ctxt).Debugf("Incoming request received for the getting a Managers resources with id %s and resource id %s", req.ManagerID, req.ResourceID) if req.SessionToken == "" { - errorMessage := "error: no X-Auth-Token found in request header" - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + errorMessage := invalidAuthTokenErrorMsg + common.SendInvalidSessionResponse(ctx, errorMessage) } resp, err := mgr.GetManagersResourceRPC(ctxt, req) if err != nil { errorMessage := "error: RPC error:" + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) - return + common.SendFailedRPCCallResponse(ctx, errorMessage) } l.LogWithFields(ctx).Debugf("Outgoing response for getting Manager resource is %s and response status %d", string(resp.Body), int(resp.StatusCode)) ctx.ResponseWriter().Header().Set("Allow", "GET") - common.SetResponseHeader(ctx, resp.Header) - ctx.StatusCode(int(resp.StatusCode)) - ctx.Write(resp.Body) + sendManagersResponse(ctx, resp) } // VirtualMediaInsert defines the Insert virtual media iris handler @@ -159,25 +122,17 @@ func (mgr *ManagersRPCs) VirtualMediaInsert(ctx iris.Context) { if err != nil { errorMessage := "while trying to get JSON body from the virtual media actions request body: " + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusBadRequest, response.MalformedJSON, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusBadRequest) - ctx.JSON(&response.Body) - return + common.SendMalformedJSONRequestErrResponse(ctx, errorMessage) } request, err := json.Marshal(reqIn) if err != nil { errorMessage := "while trying to create JSON request body: " + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) - return + common.SendFailedRPCCallResponse(ctx, errorMessage) } req := managersproto.ManagerRequest{ - SessionToken: ctx.Request().Header.Get("X-Auth-Token"), + SessionToken: ctx.Request().Header.Get(AuthTokenHeader), ManagerID: ctx.Params().Get("id"), ResourceID: ctx.Params().Get("rid"), URL: ctx.Request().RequestURI, @@ -185,27 +140,17 @@ func (mgr *ManagersRPCs) VirtualMediaInsert(ctx iris.Context) { } l.LogWithFields(ctxt).Debugf("Incoming request received for the virtual media insert with id %s and request body %s", req.ManagerID, string(request)) if req.SessionToken == "" { - errorMessage := "no X-Auth-Token found in request header" - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + errorMessage := invalidAuthTokenErrMsg + common.SendInvalidSessionResponse(ctx, errorMessage) } resp, err := mgr.VirtualMediaInsertRPC(ctxt, req) if err != nil { errorMessage := "RPC error:" + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) - return + common.SendFailedRPCCallResponse(ctx, errorMessage) } l.LogWithFields(ctx).Debugf("Outgoing response for virtual media insert is %s and response status %d", string(resp.Body), int(resp.StatusCode)) - common.SetResponseHeader(ctx, resp.Header) - ctx.StatusCode(int(resp.StatusCode)) - ctx.Write(resp.Body) + sendManagersResponse(ctx, resp) } // VirtualMediaEject defines the eject virtual media iris handler @@ -215,35 +160,20 @@ func (mgr *ManagersRPCs) VirtualMediaInsert(ctx iris.Context) { func (mgr *ManagersRPCs) VirtualMediaEject(ctx iris.Context) { defer ctx.Next() ctxt := ctx.Request().Context() - req := managersproto.ManagerRequest{ - SessionToken: ctx.Request().Header.Get("X-Auth-Token"), - ManagerID: ctx.Params().Get("id"), - ResourceID: ctx.Params().Get("rid"), - URL: ctx.Request().RequestURI, - } + req := getManagerRequest(ctx) l.LogWithFields(ctxt).Debugf("Incoming request received for the virtual media eject with id %s", req.ManagerID) if req.SessionToken == "" { - errorMessage := "no X-Auth-Token found in request header" - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + errorMessage := invalidAuthTokenErrMsg + common.SendInvalidSessionResponse(ctx, errorMessage) } resp, err := mgr.VirtualMediaEjectRPC(ctxt, req) if err != nil { errorMessage := "RPC error:" + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) - return + common.SendFailedRPCCallResponse(ctx, errorMessage) } l.LogWithFields(ctx).Debugf("Outgoing response for virtual media eject is %s and response status %d", string(resp.Body), int(resp.StatusCode)) - common.SetResponseHeader(ctx, resp.Header) - ctx.StatusCode(int(resp.StatusCode)) - ctx.Write(resp.Body) + sendManagersResponse(ctx, resp) } // GetRemoteAccountService defines the GetRemoteAccountService iris handler. @@ -253,30 +183,17 @@ func (mgr *ManagersRPCs) VirtualMediaEject(ctx iris.Context) { func (mgr *ManagersRPCs) GetRemoteAccountService(ctx iris.Context) { defer ctx.Next() ctxt := ctx.Request().Context() - req := managersproto.ManagerRequest{ - SessionToken: ctx.Request().Header.Get("X-Auth-Token"), - ManagerID: ctx.Params().Get("id"), - ResourceID: ctx.Params().Get("rid"), - URL: ctx.Request().RequestURI, - } + req := getManagerRequest(ctx) l.LogWithFields(ctxt).Debugf("Incoming request received for the getting remote account service with id %s", req.ManagerID) if req.SessionToken == "" { - errorMessage := "error: no X-Auth-Token found in request header" - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + errorMessage := invalidAuthTokenErrorMsg + common.SendInvalidSessionResponse(ctx, errorMessage) } resp, err := mgr.GetRemoteAccountServiceRPC(ctxt, req) if err != nil { errorMessage := "error: RPC error:" + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) - return + common.SendFailedRPCCallResponse(ctx, errorMessage) } switch req.URL { @@ -288,9 +205,7 @@ func (mgr *ManagersRPCs) GetRemoteAccountService(ctx iris.Context) { ctx.ResponseWriter().Header().Set("Allow", "GET") } l.LogWithFields(ctx).Debugf("Outgoing response for getting remote account service is %s and response status %d", string(resp.Body), int(resp.StatusCode)) - common.SetResponseHeader(ctx, resp.Header) - ctx.StatusCode(int(resp.StatusCode)) - ctx.Write(resp.Body) + sendManagersResponse(ctx, resp) } // CreateRemoteAccountService defines the CreateRemoteAccountService iris handler. @@ -305,25 +220,17 @@ func (mgr *ManagersRPCs) CreateRemoteAccountService(ctx iris.Context) { if err != nil { errorMessage := "while trying to get JSON body from the create remote account request body: " + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusBadRequest, response.MalformedJSON, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusBadRequest) - ctx.JSON(&response.Body) - return + common.SendMalformedJSONRequestErrResponse(ctx, errorMessage) } request, err := json.Marshal(reqIn) if err != nil { errorMessage := "while trying to create JSON request body in create remote account: " + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) - return + common.SendFailedRPCCallResponse(ctx, errorMessage) } req := managersproto.ManagerRequest{ - SessionToken: ctx.Request().Header.Get("X-Auth-Token"), + SessionToken: ctx.Request().Header.Get(AuthTokenHeader), ManagerID: ctx.Params().Get("id"), ResourceID: ctx.Params().Get("rid"), URL: ctx.Request().RequestURI, @@ -331,27 +238,17 @@ func (mgr *ManagersRPCs) CreateRemoteAccountService(ctx iris.Context) { } l.LogWithFields(ctxt).Debugf("Incoming request received for the creating remote account with id %s and request body %s", req.ManagerID, string(request)) if req.SessionToken == "" { - errorMessage := "error: no X-Auth-Token found in request header" - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + errorMessage := invalidAuthTokenErrorMsg + common.SendInvalidSessionResponse(ctx, errorMessage) } resp, err := mgr.CreateRemoteAccountServiceRPC(ctxt, req) if err != nil { errorMessage := "error: RPC error:" + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) - return + common.SendFailedRPCCallResponse(ctx, errorMessage) } l.LogWithFields(ctx).Debugf("Outgoing response for getting remote account service is %s and response status %d", string(resp.Body), int(resp.StatusCode)) - common.SetResponseHeader(ctx, resp.Header) - ctx.StatusCode(int(resp.StatusCode)) - ctx.Write(resp.Body) + sendManagersResponse(ctx, resp) } // UpdateRemoteAccountService defines the UpdateRemoteAccountService iris handler. @@ -366,25 +263,17 @@ func (mgr *ManagersRPCs) UpdateRemoteAccountService(ctx iris.Context) { if err != nil { errorMessage := "while trying to get JSON body from the update remote account request body: " + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusBadRequest, response.MalformedJSON, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusBadRequest) - ctx.JSON(&response.Body) - return + common.SendMalformedJSONRequestErrResponse(ctx, errorMessage) } request, err := json.Marshal(reqIn) if err != nil { errorMessage := "while trying to update JSON request body in update remote account: " + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) - return + common.SendFailedRPCCallResponse(ctx, errorMessage) } req := managersproto.ManagerRequest{ - SessionToken: ctx.Request().Header.Get("X-Auth-Token"), + SessionToken: ctx.Request().Header.Get(AuthTokenHeader), ManagerID: ctx.Params().Get("id"), ResourceID: ctx.Params().Get("rid"), URL: ctx.Request().RequestURI, @@ -392,27 +281,17 @@ func (mgr *ManagersRPCs) UpdateRemoteAccountService(ctx iris.Context) { } l.LogWithFields(ctxt).Debugf("Incoming request received for the updating remote account service with id %s and request body %s", req.ManagerID, string(request)) if req.SessionToken == "" { - errorMessage := "error: no X-Auth-Token found in request header" - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + errorMessage := invalidAuthTokenErrorMsg + common.SendInvalidSessionResponse(ctx, errorMessage) } resp, err := mgr.UpdateRemoteAccountServiceRPC(ctxt, req) if err != nil { errorMessage := "error: RPC error:" + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) - return + common.SendFailedRPCCallResponse(ctx, errorMessage) } l.LogWithFields(ctx).Debugf("Outgoing response for updating remote account service is %s and response status %d", string(resp.Body), int(resp.StatusCode)) - common.SetResponseHeader(ctx, resp.Header) - ctx.StatusCode(int(resp.StatusCode)) - ctx.Write(resp.Body) + sendManagersResponse(ctx, resp) } // DeleteRemoteAccountService defines the DeleteRemoteAccountService iris handler. @@ -422,33 +301,35 @@ func (mgr *ManagersRPCs) UpdateRemoteAccountService(ctx iris.Context) { func (mgr *ManagersRPCs) DeleteRemoteAccountService(ctx iris.Context) { defer ctx.Next() ctxt := ctx.Request().Context() - req := managersproto.ManagerRequest{ - SessionToken: ctx.Request().Header.Get("X-Auth-Token"), - ManagerID: ctx.Params().Get("id"), - ResourceID: ctx.Params().Get("rid"), - URL: ctx.Request().RequestURI, - } + req := getManagerRequest(ctx) l.LogWithFields(ctxt).Debugf("Incoming request received for the deleting remote account service with id %s", req.ManagerID) if req.SessionToken == "" { - errorMessage := "error: no X-Auth-Token found in request header" - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + errorMessage := invalidAuthTokenErrorMsg + common.SendInvalidSessionResponse(ctx, errorMessage) } resp, err := mgr.DeleteRemoteAccountServiceRPC(ctxt, req) if err != nil { errorMessage := "error: RPC error:" + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) - return + common.SendFailedRPCCallResponse(ctx, errorMessage) } l.LogWithFields(ctx).Debugf("Outgoing response for deleting remote account service is %s and response status %d", string(resp.Body), int(resp.StatusCode)) + sendManagersResponse(ctx, resp) +} + +// sendManagersResponse writes the managers response to client +func sendManagersResponse(ctx iris.Context, resp *managersproto.ManagerResponse) { common.SetResponseHeader(ctx, resp.Header) ctx.StatusCode(int(resp.StatusCode)) ctx.Write(resp.Body) } + +// getManagerRequest will extract the request from the context and return +func getManagerRequest(ctx iris.Context) managersproto.ManagerRequest { + return managersproto.ManagerRequest{ + SessionToken: ctx.Request().Header.Get(AuthTokenHeader), + ManagerID: ctx.Params().Get("id"), + ResourceID: ctx.Params().Get("rid"), + URL: ctx.Request().RequestURI, + } +} diff --git a/svc-api/handle/role.go b/svc-api/handle/role.go index b393ea707..1222efb09 100644 --- a/svc-api/handle/role.go +++ b/svc-api/handle/role.go @@ -18,12 +18,10 @@ package handle import ( "context" "encoding/json" - "net/http" "github.com/ODIM-Project/ODIM/lib-utilities/common" l "github.com/ODIM-Project/ODIM/lib-utilities/logs" roleproto "github.com/ODIM-Project/ODIM/lib-utilities/proto/role" - "github.com/ODIM-Project/ODIM/lib-utilities/response" iris "github.com/kataras/iris/v12" ) @@ -45,29 +43,19 @@ func (r *RoleRPCs) GetAllRoles(ctx iris.Context) { l.LogWithFields(ctxt).Debug("Incoming request received for the getting all roles") req := roleproto.GetRoleRequest{SessionToken: ctx.Request().Header.Get("X-Auth-Token")} if req.SessionToken == "" { - errorMessage := "error: no X-Auth-Token found in request header" - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + errorMessage := invalidAuthTokenErrorMsg + common.SendInvalidSessionResponse(ctx, errorMessage) } resp, err := r.GetAllRolesRPC(ctxt, req) if err != nil { errorMessage := "RPC error: " + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) - return + common.SendFailedRPCCallResponse(ctx, errorMessage) } l.LogWithFields(ctx).Debugf("Outgoing response for Getting all roles is %s and response status %d", string(resp.Body), int(resp.StatusCode)) ctx.ResponseWriter().Header().Set("Allow", "GET") - common.SetResponseHeader(ctx, resp.Header) - ctx.StatusCode(int(resp.StatusCode)) - ctx.Write(resp.Body) + sendRoleResponse(ctx, resp) } // GetRole defines the GetRole iris handler. @@ -80,12 +68,8 @@ func (r *RoleRPCs) GetRole(ctx iris.Context) { ctxt := ctx.Request().Context() req := roleproto.GetRoleRequest{SessionToken: ctx.Request().Header.Get("X-Auth-Token")} if req.SessionToken == "" { - errorMessage := "error: no X-Auth-Token found in request header" - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + errorMessage := invalidAuthTokenErrorMsg + common.SendInvalidSessionResponse(ctx, errorMessage) } req.Id = ctx.Params().Get("id") l.LogWithFields(ctxt).Debugf("Incoming request received for the getting a role with id %s", req.Id) @@ -93,11 +77,7 @@ func (r *RoleRPCs) GetRole(ctx iris.Context) { if err != nil { errorMessage := "RPC error:" + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) - return + common.SendFailedRPCCallResponse(ctx, errorMessage) } if req.Id == common.RoleAdmin || req.Id == common.RoleClient || req.Id == common.RoleMonitor { ctx.ResponseWriter().Header().Set("Allow", "GET, PATCH") @@ -105,9 +85,7 @@ func (r *RoleRPCs) GetRole(ctx iris.Context) { ctx.ResponseWriter().Header().Set("Allow", "GET, PATCH, DELETE") } l.LogWithFields(ctx).Debugf("Outgoing response for Getting a role is %s and response status %d", string(resp.Body), int(resp.StatusCode)) - common.SetResponseHeader(ctx, resp.Header) - ctx.StatusCode(int(resp.StatusCode)) - ctx.Write(resp.Body) + sendRoleResponse(ctx, resp) } // UpdateRole defines the UpdateRole iris handler. @@ -126,21 +104,13 @@ func (r *RoleRPCs) UpdateRole(ctx iris.Context) { if err != nil { l.LogWithFields(ctxt).Error("Error while trying to collect data from request: " + err.Error()) errorMessage := "error while trying to get JSON body from the role update request body: " + err.Error() - response := common.GeneralError(http.StatusBadRequest, response.MalformedJSON, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusBadRequest) - ctx.JSON(response.Body) - return + common.SendMalformedJSONRequestErrResponse(ctx, errorMessage) } req.SessionToken = ctx.Request().Header.Get("X-Auth-Token") if req.SessionToken == "" { - errorMessage := "error: no X-Auth-Token found in request header" - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + errorMessage := invalidAuthTokenErrorMsg + common.SendInvalidSessionResponse(ctx, errorMessage) } req.Id = ctx.Params().Get("id") l.LogWithFields(ctxt).Debugf("Incoming request received for the updating a role with id %s", req.Id) @@ -149,16 +119,10 @@ func (r *RoleRPCs) UpdateRole(ctx iris.Context) { if err != nil { errorMessage := "RPC error:" + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) - return + common.SendFailedRPCCallResponse(ctx, errorMessage) } l.LogWithFields(ctx).Debugf("Outgoing response for updating a role is %s and response status %d", string(resp.Body), int(resp.StatusCode)) - common.SetResponseHeader(ctx, resp.Header) - ctx.StatusCode(int(resp.StatusCode)) - ctx.Write(resp.Body) + sendRoleResponse(ctx, resp) } // DeleteRole ... @@ -169,12 +133,8 @@ func (r *RoleRPCs) DeleteRole(ctx iris.Context) { req.SessionToken = ctx.Request().Header.Get("X-Auth-Token") if req.SessionToken == "" { - errorMessage := "error: no X-Auth-Token found in request header" - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + errorMessage := invalidAuthTokenErrorMsg + common.SendInvalidSessionResponse(ctx, errorMessage) } req.ID = ctx.Params().Get("id") l.LogWithFields(ctxt).Debugf("Incoming request received for the deleting a role with id %s", req.ID) @@ -182,13 +142,14 @@ func (r *RoleRPCs) DeleteRole(ctx iris.Context) { if err != nil { errorMessage := "error: something went wrong with the RPC calls: " + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) - return + common.SendFailedRPCCallResponse(ctx, errorMessage) } l.LogWithFields(ctx).Debugf("Outgoing response for deleting a role is %s and response status %d", string(resp.Body), int(resp.StatusCode)) + sendRoleResponse(ctx, resp) +} + +// sendRoleResponse writes the role response to client +func sendRoleResponse(ctx iris.Context, resp *roleproto.RoleResponse) { common.SetResponseHeader(ctx, resp.Header) ctx.StatusCode(int(resp.StatusCode)) ctx.Write(resp.Body) diff --git a/svc-api/handle/systems.go b/svc-api/handle/systems.go index 569545dc6..abbc7e98d 100644 --- a/svc-api/handle/systems.go +++ b/svc-api/handle/systems.go @@ -18,12 +18,10 @@ package handle import ( "context" "encoding/json" - "net/http" "github.com/ODIM-Project/ODIM/lib-utilities/common" l "github.com/ODIM-Project/ODIM/lib-utilities/logs" systemsproto "github.com/ODIM-Project/ODIM/lib-utilities/proto/systems" - "github.com/ODIM-Project/ODIM/lib-utilities/response" iris "github.com/kataras/iris/v12" ) @@ -47,33 +45,23 @@ func (sys *SystemRPCs) GetSystemsCollection(ctx iris.Context) { ctxt := ctx.Request().Context() defer ctx.Next() req := systemsproto.GetSystemsRequest{ - SessionToken: ctx.Request().Header.Get("X-Auth-Token"), + SessionToken: ctx.Request().Header.Get(AuthTokenHeader), URL: ctx.Request().RequestURI, } l.LogWithFields(ctxt).Debugf("Incoming request received for getting systems collection %s", req.URL) if req.SessionToken == "" { - errorMessage := "error: no X-Auth-Token found in request header" - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + errorMessage := invalidAuthTokenErrorMsg + common.SendInvalidSessionResponse(ctx, errorMessage) } resp, err := sys.GetSystemsCollectionRPC(ctxt, req) if err != nil { errorMessage := "error: RPC error:" + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) - return + common.SendFailedRPCCallResponse(ctx, errorMessage) } l.LogWithFields(ctxt).Debugf("Outgoing response for getting systems collection is %s with status code %d", string(resp.Body), int(resp.StatusCode)) ctx.ResponseWriter().Header().Set("Allow", "GET") - common.SetResponseHeader(ctx, resp.Header) - ctx.StatusCode(int(resp.StatusCode)) - ctx.Write(resp.Body) + sendSystemsResponse(ctx, resp) } // GetSystem fetches computer system details @@ -81,35 +69,25 @@ func (sys *SystemRPCs) GetSystem(ctx iris.Context) { ctxt := ctx.Request().Context() defer ctx.Next() req := systemsproto.GetSystemsRequest{ - SessionToken: ctx.Request().Header.Get("X-Auth-Token"), + SessionToken: ctx.Request().Header.Get(AuthTokenHeader), RequestParam: ctx.Params().Get("id"), ResourceID: ctx.Params().Get("rid"), URL: ctx.Request().RequestURI, } l.LogWithFields(ctxt).Debugf("Incoming request received for getting system with URL %s", req.URL) if req.SessionToken == "" { - errorMessage := "error: no X-Auth-Token found in request header" - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + errorMessage := invalidAuthTokenErrorMsg + common.SendInvalidSessionResponse(ctx, errorMessage) } resp, err := sys.GetSystemRPC(ctxt, req) if err != nil { - errorMessage := "RPC error:" + err.Error() + errorMessage := rpcFailedErrMsg + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) - return + common.SendFailedRPCCallResponse(ctx, errorMessage) } l.LogWithFields(ctxt).Debugf("Outgoing response for getting system details is %s with status code %d", string(resp.Body), int(resp.StatusCode)) ctx.ResponseWriter().Header().Set("Allow", "GET, PATCH") - common.SetResponseHeader(ctx, resp.Header) - ctx.StatusCode(int(resp.StatusCode)) - ctx.Write(resp.Body) + sendSystemsResponse(ctx, resp) } // GetSystemResource defines the GetSystemResource iris handler. @@ -120,29 +98,21 @@ func (sys *SystemRPCs) GetSystemResource(ctx iris.Context) { ctxt := ctx.Request().Context() defer ctx.Next() req := systemsproto.GetSystemsRequest{ - SessionToken: ctx.Request().Header.Get("X-Auth-Token"), + SessionToken: ctx.Request().Header.Get(AuthTokenHeader), RequestParam: ctx.Params().Get("id"), ResourceID: ctx.Params().Get("rid"), URL: ctx.Request().RequestURI, } l.LogWithFields(ctxt).Debugf("Incoming request received for getting system resources with URL %s", req.URL) if req.SessionToken == "" { - errorMessage := "error: no X-Auth-Token found in request header" - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + errorMessage := invalidAuthTokenErrorMsg + common.SendInvalidSessionResponse(ctx, errorMessage) } resp, err := sys.GetSystemResourceRPC(ctxt, req) if err != nil { errorMessage := "error: RPC error:" + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) - return + common.SendFailedRPCCallResponse(ctx, errorMessage) } storageID := ctx.Params().Get("id2") @@ -159,9 +129,7 @@ func (sys *SystemRPCs) GetSystemResource(ctx iris.Context) { ctx.ResponseWriter().Header().Set("Allow", "GET") } l.LogWithFields(ctxt).Debugf("Outgoing response for getting systems resources is %s with status code %d", string(resp.Body), int(resp.StatusCode)) - common.SetResponseHeader(ctx, resp.Header) - ctx.StatusCode(int(resp.StatusCode)) - ctx.Write(resp.Body) + sendSystemsResponse(ctx, resp) } // ComputerSystemReset resets the indivitual computer systems @@ -173,21 +141,13 @@ func (sys *SystemRPCs) ComputerSystemReset(ctx iris.Context) { if err != nil { errorMessage := "error while trying to get JSON body from the system reset request body: " + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusBadRequest, response.MalformedJSON, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusBadRequest) - ctx.JSON(&response.Body) - return + common.SendMalformedJSONRequestErrResponse(ctx, errorMessage) } systemID := ctx.Params().Get("id") - sessionToken := ctx.Request().Header.Get("X-Auth-Token") + sessionToken := ctx.Request().Header.Get(AuthTokenHeader) if sessionToken == "" { - errorMessage := "error: no X-Auth-Token found in request header" - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + errorMessage := invalidAuthTokenErrorMsg + common.SendInvalidSessionResponse(ctx, errorMessage) } // Marshalling the req to make reset request @@ -200,18 +160,12 @@ func (sys *SystemRPCs) ComputerSystemReset(ctx iris.Context) { l.LogWithFields(ctxt).Debugf("Incoming request received for computer system reset with request body %s", string(request)) resp, err := sys.SystemResetRPC(ctxt, resetRequest) if err != nil { - errorMessage := "RPC error:" + err.Error() + errorMessage := rpcFailedErrMsg + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) - return + common.SendFailedRPCCallResponse(ctx, errorMessage) } l.LogWithFields(ctxt).Debugf("Outgoing response for computer system reset is %s with status code %d", string(resp.Body), int(resp.StatusCode)) - common.SetResponseHeader(ctx, resp.Header) - ctx.StatusCode(int(resp.StatusCode)) - ctx.Write(resp.Body) + sendSystemsResponse(ctx, resp) } // SetDefaultBootOrder is the handler to set default boot order @@ -222,30 +176,20 @@ func (sys *SystemRPCs) SetDefaultBootOrder(ctx iris.Context) { ctxt := ctx.Request().Context() var req systemsproto.DefaultBootOrderRequest req.SystemID = ctx.Params().Get("id") - req.SessionToken = ctx.Request().Header.Get("X-Auth-Token") + req.SessionToken = ctx.Request().Header.Get(AuthTokenHeader) if req.SessionToken == "" { - errorMessage := "error: no X-Auth-Token found in request header" - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + errorMessage := invalidAuthTokenErrorMsg + common.SendInvalidSessionResponse(ctx, errorMessage) } l.LogWithFields(ctxt).Debugf("Incoming request received for setting default boot order with request id %s", req.SystemID) resp, err := sys.SetDefaultBootOrderRPC(ctxt, req) if err != nil { - errorMessage := "RPC error:" + err.Error() + errorMessage := rpcFailedErrMsg + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) - return + common.SendFailedRPCCallResponse(ctx, errorMessage) } l.LogWithFields(ctxt).Debugf("Outgoing response for setting default boot order is %s with status code %d", string(resp.Body), int(resp.StatusCode)) - common.SetResponseHeader(ctx, resp.Header) - ctx.StatusCode(int(resp.StatusCode)) - ctx.Write(resp.Body) + sendSystemsResponse(ctx, resp) } // ChangeBiosSettings is the handler to set change bios settings @@ -259,31 +203,20 @@ func (sys *SystemRPCs) ChangeBiosSettings(ctx iris.Context) { if err != nil { errorMessage := "error while trying to get JSON body from bios setting request body: " + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusBadRequest, response.MalformedJSON, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusBadRequest) - ctx.JSON(&response.Body) - return + common.SendMalformedJSONRequestErrResponse(ctx, errorMessage) } request, err := json.Marshal(req) if err != nil { errorMessage := "error while trying to create JSON request body: " + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) + common.SendFailedRPCCallResponse(ctx, errorMessage) return } l.LogWithFields(ctxt).Debugf("Incoming request received for changing bios setting with request body %s", string(request)) - sessionToken := ctx.Request().Header.Get("X-Auth-Token") + sessionToken := ctx.Request().Header.Get(AuthTokenHeader) if sessionToken == "" { - errorMessage := "error: no X-Auth-Token found in request header" - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + errorMessage := invalidAuthTokenErrorMsg + common.SendInvalidSessionResponse(ctx, errorMessage) } biosRequest := systemsproto.BiosSettingsRequest{ SessionToken: sessionToken, @@ -292,18 +225,12 @@ func (sys *SystemRPCs) ChangeBiosSettings(ctx iris.Context) { } resp, err := sys.ChangeBiosSettingsRPC(ctxt, biosRequest) if err != nil { - errorMessage := "RPC error:" + err.Error() + errorMessage := rpcFailedErrMsg + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) - return + common.SendFailedRPCCallResponse(ctx, errorMessage) } l.LogWithFields(ctxt).Debugf("Outgoing response for changing bios setting is %s with status code %d", string(resp.Body), int(resp.StatusCode)) - common.SetResponseHeader(ctx, resp.Header) - ctx.StatusCode(int(resp.StatusCode)) - ctx.Write(resp.Body) + sendSystemsResponse(ctx, resp) } // ChangeBootOrderSettings is the handler to set change boot order settings @@ -317,31 +244,20 @@ func (sys *SystemRPCs) ChangeBootOrderSettings(ctx iris.Context) { if err != nil { errorMessage := "error while trying to get JSON body from change boot order setting request body: " + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusBadRequest, response.MalformedJSON, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusBadRequest) - ctx.JSON(&response.Body) - return + common.SendMalformedJSONRequestErrResponse(ctx, errorMessage) } request, err := json.Marshal(req) if err != nil { errorMessage := "error while trying to create JSON request body: " + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) + common.SendFailedRPCCallResponse(ctx, errorMessage) return } l.LogWithFields(ctxt).Debugf("Incoming request received for changing boot order setting with request body %s", string(request)) - sessionToken := ctx.Request().Header.Get("X-Auth-Token") + sessionToken := ctx.Request().Header.Get(AuthTokenHeader) if sessionToken == "" { - errorMessage := "error: no X-Auth-Token found in request header" - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + errorMessage := invalidAuthTokenErrorMsg + common.SendInvalidSessionResponse(ctx, errorMessage) } bootOrderRequest := systemsproto.BootOrderSettingsRequest{ SessionToken: sessionToken, @@ -350,18 +266,12 @@ func (sys *SystemRPCs) ChangeBootOrderSettings(ctx iris.Context) { } resp, err := sys.ChangeBootOrderSettingsRPC(ctxt, bootOrderRequest) if err != nil { - errorMessage := "RPC error:" + err.Error() + errorMessage := rpcFailedErrMsg + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) - return + common.SendFailedRPCCallResponse(ctx, errorMessage) } l.LogWithFields(ctxt).Debugf("Outgoing response for getting changing boot order setting is %s with status code %d", string(resp.Body), int(resp.StatusCode)) - common.SetResponseHeader(ctx, resp.Header) - ctx.StatusCode(int(resp.StatusCode)) - ctx.Write(resp.Body) + sendSystemsResponse(ctx, resp) } // UpdateSecureBoot is the handler to set change boot order settings @@ -375,31 +285,20 @@ func (sys *SystemRPCs) UpdateSecureBoot(ctx iris.Context) { if err != nil { errorMessage := "error while trying to get JSON body from update SecureBoot request body: " + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusBadRequest, response.MalformedJSON, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusBadRequest) - ctx.JSON(&response.Body) - return + common.SendMalformedJSONRequestErrResponse(ctx, errorMessage) } request, err := json.Marshal(req) if err != nil { errorMessage := "error while trying to create JSON request body: " + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) + common.SendFailedRPCCallResponse(ctx, errorMessage) return } l.LogWithFields(ctxt).Debugf("Incoming request received for updating SecureBoot with request body %s", string(request)) - sessionToken := ctx.Request().Header.Get("X-Auth-Token") + sessionToken := ctx.Request().Header.Get(AuthTokenHeader) if sessionToken == "" { - errorMessage := "error: no X-Auth-Token found in request header" - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + errorMessage := invalidAuthTokenErrorMsg + common.SendInvalidSessionResponse(ctx, errorMessage) } secureBootRequest := systemsproto.SecureBootRequest{ SessionToken: sessionToken, @@ -408,18 +307,12 @@ func (sys *SystemRPCs) UpdateSecureBoot(ctx iris.Context) { } resp, err := sys.UpdateSecureBootRPC(ctxt, secureBootRequest) if err != nil { - errorMessage := "RPC error:" + err.Error() + errorMessage := rpcFailedErrMsg + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) - return + common.SendFailedRPCCallResponse(ctx, errorMessage) } l.LogWithFields(ctxt).Debugf("Outgoing response for updating SecureBoot is %s with status code %d", string(resp.Body), int(resp.StatusCode)) - common.SetResponseHeader(ctx, resp.Header) - ctx.StatusCode(int(resp.StatusCode)) - ctx.Write(resp.Body) + sendSystemsResponse(ctx, resp) } // ResetSecureBoot shall reset the UEFI Secure Boot key databases. @@ -434,31 +327,20 @@ func (sys *SystemRPCs) ResetSecureBoot(ctx iris.Context) { if err != nil { errorMessage := "error while trying to get JSON body from reset SecureBoot key databases request body: " + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusBadRequest, response.MalformedJSON, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusBadRequest) - ctx.JSON(&response.Body) - return + common.SendMalformedJSONRequestErrResponse(ctx, errorMessage) } request, err := json.Marshal(req) if err != nil { errorMessage := "error while trying to create JSON request body: " + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) + common.SendFailedRPCCallResponse(ctx, errorMessage) return } l.LogWithFields(ctxt).Debugf("Incoming request received for resetting SecureBoot with request body %s", string(request)) - sessionToken := ctx.Request().Header.Get("X-Auth-Token") + sessionToken := ctx.Request().Header.Get(AuthTokenHeader) if sessionToken == "" { - errorMessage := "error: no X-Auth-Token found in request header" - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + errorMessage := invalidAuthTokenErrorMsg + common.SendInvalidSessionResponse(ctx, errorMessage) } secureBootRequest := systemsproto.SecureBootRequest{ SessionToken: sessionToken, @@ -467,18 +349,12 @@ func (sys *SystemRPCs) ResetSecureBoot(ctx iris.Context) { } resp, err := sys.ResetSecureBootRPC(ctxt, secureBootRequest) if err != nil { - errorMessage := "RPC error:" + err.Error() + errorMessage := rpcFailedErrMsg + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) - return + common.SendFailedRPCCallResponse(ctx, errorMessage) } l.LogWithFields(ctxt).Debugf("Outgoing response for updating SecureBoot is %s with status code %d", string(resp.Body), int(resp.StatusCode)) - common.SetResponseHeader(ctx, resp.Header) - ctx.StatusCode(int(resp.StatusCode)) - ctx.Write(resp.Body) + sendSystemsResponse(ctx, resp) } // CreateVolume is the handler to create a volume under storage @@ -492,31 +368,20 @@ func (sys *SystemRPCs) CreateVolume(ctx iris.Context) { if err != nil { errorMessage := "error while trying to get JSON body from the create volume request body: " + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusBadRequest, response.MalformedJSON, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusBadRequest) - ctx.JSON(&response.Body) - return + common.SendMalformedJSONRequestErrResponse(ctx, errorMessage) } request, err := json.Marshal(req) if err != nil { errorMessage := "error while trying to create JSON request body: " + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) + common.SendFailedRPCCallResponse(ctx, errorMessage) return } l.LogWithFields(ctxt).Debugf("Incoming request received for creating volume with request body %s", string(request)) - sessionToken := ctx.Request().Header.Get("X-Auth-Token") + sessionToken := ctx.Request().Header.Get(AuthTokenHeader) if sessionToken == "" { - errorMessage := "error: no X-Auth-Token found in request header" - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + errorMessage := invalidAuthTokenErrorMsg + common.SendInvalidSessionResponse(ctx, errorMessage) } volRequest := systemsproto.VolumeRequest{ SessionToken: sessionToken, @@ -526,18 +391,12 @@ func (sys *SystemRPCs) CreateVolume(ctx iris.Context) { } resp, err := sys.CreateVolumeRPC(ctxt, volRequest) if err != nil { - errorMessage := "RPC error:" + err.Error() + errorMessage := rpcFailedErrMsg + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) - return + common.SendFailedRPCCallResponse(ctx, errorMessage) } l.LogWithFields(ctxt).Debugf("Outgoing response for creating a volume is %s with status code %d", string(resp.Body), int(resp.StatusCode)) - common.SetResponseHeader(ctx, resp.Header) - ctx.StatusCode(int(resp.StatusCode)) - ctx.Write(resp.Body) + sendSystemsResponse(ctx, resp) } // DeleteVolume is the handler to delete a volume under storage @@ -552,21 +411,14 @@ func (sys *SystemRPCs) DeleteVolume(ctx iris.Context) { if err != nil { errorMessage := "error while trying to create JSON request body: " + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) + common.SendFailedRPCCallResponse(ctx, errorMessage) return } l.LogWithFields(ctxt).Debugf("Incoming request received for deleting volume with request body %s", string(request)) - sessionToken := ctx.Request().Header.Get("X-Auth-Token") + sessionToken := ctx.Request().Header.Get(AuthTokenHeader) if sessionToken == "" { - errorMessage := "error: no X-Auth-Token found in request header" - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + errorMessage := invalidAuthTokenErrorMsg + common.SendInvalidSessionResponse(ctx, errorMessage) } volRequest := systemsproto.VolumeRequest{ SessionToken: sessionToken, @@ -577,15 +429,16 @@ func (sys *SystemRPCs) DeleteVolume(ctx iris.Context) { } resp, err := sys.DeleteVolumeRPC(ctxt, volRequest) if err != nil { - errorMessage := "RPC error:" + err.Error() + errorMessage := rpcFailedErrMsg + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) - return + common.SendFailedRPCCallResponse(ctx, errorMessage) } l.LogWithFields(ctxt).Debugf("Outgoing response for deleting a volume is %s with status code %d", string(resp.Body), int(resp.StatusCode)) + sendSystemsResponse(ctx, resp) +} + +// sendSystemsResponse writes the systems response to client +func sendSystemsResponse(ctx iris.Context, resp *systemsproto.SystemsResponse) { common.SetResponseHeader(ctx, resp.Header) ctx.StatusCode(int(resp.StatusCode)) ctx.Write(resp.Body) diff --git a/svc-api/handle/task.go b/svc-api/handle/task.go index 7762675d3..10f8123f4 100644 --- a/svc-api/handle/task.go +++ b/svc-api/handle/task.go @@ -45,7 +45,7 @@ func (task *TaskRPCs) DeleteTask(ctx iris.Context) { ctxt := ctx.Request().Context() req := &taskproto.GetTaskRequest{ TaskID: ctx.Params().Get("TaskID"), - SessionToken: ctx.Request().Header.Get("X-Auth-Token"), + SessionToken: ctx.Request().Header.Get(AuthTokenHeader), } l.LogWithFields(ctxt).Debugf("Incoming request received for deleting task with taskid %s", req.TaskID) response, err := task.DeleteTaskRPC(ctxt, req) @@ -60,9 +60,7 @@ func (task *TaskRPCs) DeleteTask(ctx iris.Context) { return } l.LogWithFields(ctxt).Debugf("Outgoing response for deleting task is %s with status code %d", string(response.Body), int(response.StatusCode)) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(int(response.StatusCode)) - ctx.Write(response.Body) + sendTaskResponse(ctx, response) } // GetTaskStatus fetches task status @@ -73,7 +71,7 @@ func (task *TaskRPCs) GetTaskStatus(ctx iris.Context) { ctxt := ctx.Request().Context() req := &taskproto.GetTaskRequest{ TaskID: ctx.Params().Get("TaskID"), - SessionToken: ctx.Request().Header.Get("X-Auth-Token"), + SessionToken: ctx.Request().Header.Get(AuthTokenHeader), } l.LogWithFields(ctxt).Debugf("Incoming request received for getting task status with taskid %s", req.TaskID) response, err := task.GetTaskRPC(ctxt, req) @@ -89,9 +87,7 @@ func (task *TaskRPCs) GetTaskStatus(ctx iris.Context) { } l.LogWithFields(ctxt).Debugf("Outgoing response for getting task is %s with status code %d", string(response.Body), int(response.StatusCode)) ctx.ResponseWriter().Header().Set("Allow", "GET, DELETE") - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(int(response.StatusCode)) - ctx.Write(response.Body) + sendTaskResponse(ctx, response) } // GetSubTasks fetches sub task collection under given umbralla tasks @@ -102,7 +98,7 @@ func (task *TaskRPCs) GetSubTasks(ctx iris.Context) { ctxt := ctx.Request().Context() req := &taskproto.GetTaskRequest{ TaskID: ctx.Params().Get("TaskID"), - SessionToken: ctx.Request().Header.Get("X-Auth-Token"), + SessionToken: ctx.Request().Header.Get(AuthTokenHeader), } response, err := task.GetSubTasksRPC(ctxt, req) common.SetResponseHeader(ctx, response.Header) @@ -117,9 +113,7 @@ func (task *TaskRPCs) GetSubTasks(ctx iris.Context) { } l.LogWithFields(ctxt).Debugf("Outgoing response for getting sub tasks is %s with status code %d", string(response.Body), int(response.StatusCode)) ctx.ResponseWriter().Header().Set("Allow", "GET") - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(int(response.StatusCode)) - ctx.Write(response.Body) + sendTaskResponse(ctx, response) } // GetSubTask fetches sub task details @@ -131,7 +125,7 @@ func (task *TaskRPCs) GetSubTask(ctx iris.Context) { req := &taskproto.GetTaskRequest{ TaskID: ctx.Params().Get("TaskID"), SubTaskID: ctx.Params().Get("subTaskID"), - SessionToken: ctx.Request().Header.Get("X-Auth-Token"), + SessionToken: ctx.Request().Header.Get(AuthTokenHeader), } l.LogWithFields(ctxt).Debugf("Incoming request received for getting sub task information with taskid %s and subtaskid %s", req.TaskID, req.SubTaskID) response, err := task.GetSubTaskRPC(ctxt, req) @@ -147,9 +141,7 @@ func (task *TaskRPCs) GetSubTask(ctx iris.Context) { } l.LogWithFields(ctxt).Debugf("Outgoing response for getting sub task information is %s with status code %d", string(response.Body), int(response.StatusCode)) ctx.ResponseWriter().Header().Set("Allow", "GET") - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(int(response.StatusCode)) - ctx.Write(response.Body) + sendTaskResponse(ctx, response) } // GetTaskMonitor fetches task monitor @@ -160,7 +152,7 @@ func (task *TaskRPCs) GetTaskMonitor(ctx iris.Context) { ctxt := ctx.Request().Context() req := &taskproto.GetTaskRequest{ TaskID: ctx.Params().Get("TaskID"), - SessionToken: ctx.Request().Header.Get("X-Auth-Token"), + SessionToken: ctx.Request().Header.Get(AuthTokenHeader), } l.LogWithFields(ctxt).Debugf("Incoming request received for getting task mon for taskid %s", req.TaskID) response, err := task.GetTaskMonitorRPC(ctxt, req) @@ -176,9 +168,7 @@ func (task *TaskRPCs) GetTaskMonitor(ctx iris.Context) { } l.LogWithFields(ctxt).Debugf("Outgoing response for getting task monitoring information is %s with status code %d", string(response.Body), int(response.StatusCode)) ctx.ResponseWriter().Header().Set("Allow", "GET") - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(int(response.StatusCode)) - ctx.Write(response.Body) + sendTaskResponse(ctx, response) } // TaskCollection fetches all tasks available in DB @@ -188,7 +178,7 @@ func (task *TaskRPCs) TaskCollection(ctx iris.Context) { defer ctx.Next() ctxt := ctx.Request().Context() req := &taskproto.GetTaskRequest{ - SessionToken: ctx.Request().Header.Get("X-Auth-Token"), + SessionToken: ctx.Request().Header.Get(AuthTokenHeader), } l.LogWithFields(ctxt).Debugf("Incoming request received for getting task all the available tasks collection") if req.SessionToken == "" { @@ -212,9 +202,7 @@ func (task *TaskRPCs) TaskCollection(ctx iris.Context) { } l.LogWithFields(ctxt).Debugf("Outgoing response for getting task collections is %s with status code %d", string(response.Body), int(response.StatusCode)) ctx.ResponseWriter().Header().Set("Allow", "GET") - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(int(response.StatusCode)) - ctx.Write(response.Body) + sendTaskResponse(ctx, response) } @@ -225,7 +213,7 @@ func (task *TaskRPCs) GetTaskService(ctx iris.Context) { defer ctx.Next() ctxt := ctx.Request().Context() req := &taskproto.GetTaskRequest{ - SessionToken: ctx.Request().Header.Get("X-Auth-Token"), + SessionToken: ctx.Request().Header.Get(AuthTokenHeader), } response, err := task.GetTaskServiceRPC(ctxt, req) common.SetResponseHeader(ctx, response.Header) @@ -240,6 +228,11 @@ func (task *TaskRPCs) GetTaskService(ctx iris.Context) { } l.LogWithFields(ctxt).Debugf("Outgoing response for getting task service is %s with status code %d", string(response.Body), int(response.StatusCode)) ctx.ResponseWriter().Header().Set("Allow", "GET") + sendTaskResponse(ctx, response) +} + +// sendTaskResponse writes the task response to client +func sendTaskResponse(ctx iris.Context, response *taskproto.TaskResponse) { common.SetResponseHeader(ctx, response.Header) ctx.StatusCode(int(response.StatusCode)) ctx.Write(response.Body) diff --git a/svc-api/handle/telemetry.go b/svc-api/handle/telemetry.go index 72ba2f188..2f6ce03e5 100644 --- a/svc-api/handle/telemetry.go +++ b/svc-api/handle/telemetry.go @@ -17,12 +17,10 @@ package handle import ( "context" - "net/http" "github.com/ODIM-Project/ODIM/lib-utilities/common" l "github.com/ODIM-Project/ODIM/lib-utilities/logs" telemetryproto "github.com/ODIM-Project/ODIM/lib-utilities/proto/telemetry" - "github.com/ODIM-Project/ODIM/lib-utilities/response" iris "github.com/kataras/iris/v12" ) @@ -40,31 +38,28 @@ type TelemetryRPCs struct { UpdateTriggerRPC func(context.Context, telemetryproto.TelemetryRequest) (*telemetryproto.TelemetryResponse, error) } +const ( + rpcCallFailedErrorMsg = "error: something went wrong with the RPC calls: " + invalidAuthTokenErrorMsg = "error: no X-Auth-Token found in request header" +) + // GetTelemetryService is the handler for getting TelemetryService details func (a *TelemetryRPCs) GetTelemetryService(ctx iris.Context) { defer ctx.Next() ctxt := ctx.Request().Context() req := telemetryproto.TelemetryRequest{ - SessionToken: ctx.Request().Header.Get("X-Auth-Token"), + SessionToken: ctx.Request().Header.Get(AuthTokenHeader), } l.LogWithFields(ctxt).Debug("Incoming request received for getting telemetry service details") if req.SessionToken == "" { - errorMessage := "error: no X-Auth-Token found in request header" - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + errorMessage := invalidAuthTokenErrorMsg + common.SendInvalidSessionResponse(ctx, errorMessage) } resp, err := a.GetTelemetryServiceRPC(ctxt, req) if err != nil { - errorMessage := "error: something went wrong with the RPC calls: " + err.Error() + errorMessage := rpcCallFailedErrorMsg + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) - return + common.SendFailedRPCCallResponse(ctx, errorMessage) } l.LogWithFields(ctxt).Debugf("Outgoing response for getting telemetry service is %s with status code %d", string(resp.Body), int(resp.StatusCode)) ctx.ResponseWriter().Header().Set("Allow", "GET") @@ -79,27 +74,19 @@ func (a *TelemetryRPCs) GetMetricDefinitionCollection(ctx iris.Context) { defer ctx.Next() ctxt := ctx.Request().Context() req := telemetryproto.TelemetryRequest{ - SessionToken: ctx.Request().Header.Get("X-Auth-Token"), + SessionToken: ctx.Request().Header.Get(AuthTokenHeader), URL: ctx.Request().RequestURI, } l.LogWithFields(ctxt).Debugf("Incoming request received for getting metric definition collection details with request URI %s", req.URL) if req.SessionToken == "" { - errorMessage := "error: no X-Auth-Token found in request header" - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + errorMessage := invalidAuthTokenErrorMsg + common.SendInvalidSessionResponse(ctx, errorMessage) } resp, err := a.GetMetricDefinitionCollectionRPC(ctxt, req) if err != nil { - errorMessage := "error: something went wrong with the RPC calls: " + err.Error() + errorMessage := rpcCallFailedErrorMsg + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) - return + common.SendFailedRPCCallResponse(ctx, errorMessage) } l.LogWithFields(ctxt).Debugf("Outgoing response for getting metric definition collection is %s with status code %d", string(resp.Body), int(resp.StatusCode)) ctx.ResponseWriter().Header().Set("Allow", "GET") @@ -114,27 +101,19 @@ func (a *TelemetryRPCs) GetMetricReportDefinitionCollection(ctx iris.Context) { defer ctx.Next() ctxt := ctx.Request().Context() req := telemetryproto.TelemetryRequest{ - SessionToken: ctx.Request().Header.Get("X-Auth-Token"), + SessionToken: ctx.Request().Header.Get(AuthTokenHeader), URL: ctx.Request().RequestURI, } l.LogWithFields(ctxt).Debugf("Incoming request received for getting metric report definition collection details with request URI %s", req.URL) if req.SessionToken == "" { - errorMessage := "error: no X-Auth-Token found in request header" - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + errorMessage := invalidAuthTokenErrorMsg + common.SendInvalidSessionResponse(ctx, errorMessage) } resp, err := a.GetMetricReportDefinitionCollectionRPC(ctxt, req) if err != nil { - errorMessage := "error: something went wrong with the RPC calls: " + err.Error() + errorMessage := rpcCallFailedErrorMsg + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) - return + common.SendFailedRPCCallResponse(ctx, errorMessage) } l.LogWithFields(ctxt).Debugf("Outgoing response for getting metric report definition collection is %s with status code %d", string(resp.Body), int(resp.StatusCode)) ctx.ResponseWriter().Header().Set("Allow", "GET") @@ -149,27 +128,19 @@ func (a *TelemetryRPCs) GetMetricReportCollection(ctx iris.Context) { defer ctx.Next() ctxt := ctx.Request().Context() req := telemetryproto.TelemetryRequest{ - SessionToken: ctx.Request().Header.Get("X-Auth-Token"), + SessionToken: ctx.Request().Header.Get(AuthTokenHeader), URL: ctx.Request().RequestURI, } l.LogWithFields(ctxt).Debugf("Incoming request received for getting metric report collection details with request URI %s", req.URL) if req.SessionToken == "" { - errorMessage := "error: no X-Auth-Token found in request header" - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + errorMessage := invalidAuthTokenErrorMsg + common.SendInvalidSessionResponse(ctx, errorMessage) } resp, err := a.GetMetricReportCollectionRPC(ctxt, req) if err != nil { - errorMessage := "error: something went wrong with the RPC calls: " + err.Error() + errorMessage := rpcCallFailedErrorMsg + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) - return + common.SendFailedRPCCallResponse(ctx, errorMessage) } l.LogWithFields(ctxt).Debugf("Outgoing response for getting metric report collection is %s with status code %d", string(resp.Body), int(resp.StatusCode)) ctx.ResponseWriter().Header().Set("Allow", "GET") @@ -184,27 +155,19 @@ func (a *TelemetryRPCs) GetTriggerCollection(ctx iris.Context) { defer ctx.Next() ctxt := ctx.Request().Context() req := telemetryproto.TelemetryRequest{ - SessionToken: ctx.Request().Header.Get("X-Auth-Token"), + SessionToken: ctx.Request().Header.Get(AuthTokenHeader), URL: ctx.Request().RequestURI, } l.LogWithFields(ctxt).Debugf("Incoming request received for getting trigger collection details with request URI %s", req.URL) if req.SessionToken == "" { - errorMessage := "error: no X-Auth-Token found in request header" - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + errorMessage := invalidAuthTokenErrorMsg + common.SendInvalidSessionResponse(ctx, errorMessage) } resp, err := a.GetTriggerCollectionRPC(ctxt, req) if err != nil { - errorMessage := "error: something went wrong with the RPC calls: " + err.Error() + errorMessage := rpcCallFailedErrorMsg + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) - return + common.SendFailedRPCCallResponse(ctx, errorMessage) } l.LogWithFields(ctxt).Debugf("Outgoing response for getting trigger collection is %s with status code %d", string(resp.Body), int(resp.StatusCode)) ctx.ResponseWriter().Header().Set("Allow", "GET") @@ -219,27 +182,19 @@ func (a *TelemetryRPCs) GetMetricDefinition(ctx iris.Context) { defer ctx.Next() ctxt := ctx.Request().Context() req := telemetryproto.TelemetryRequest{ - SessionToken: ctx.Request().Header.Get("X-Auth-Token"), + SessionToken: ctx.Request().Header.Get(AuthTokenHeader), URL: ctx.Request().RequestURI, } l.LogWithFields(ctxt).Debugf("Incoming request received for getting metric definition details with request URI %s", req.URL) if req.SessionToken == "" { - errorMessage := "error: no X-Auth-Token found in request header" - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + errorMessage := invalidAuthTokenErrorMsg + common.SendInvalidSessionResponse(ctx, errorMessage) } resp, err := a.GetMetricDefinitionRPC(ctxt, req) if err != nil { - errorMessage := "error: something went wrong with the RPC calls: " + err.Error() + errorMessage := rpcCallFailedErrorMsg + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) - return + common.SendFailedRPCCallResponse(ctx, errorMessage) } l.LogWithFields(ctxt).Debugf("Outgoing response for getting metric definition is %s with status code %d", string(resp.Body), int(resp.StatusCode)) ctx.ResponseWriter().Header().Set("Allow", "GET") @@ -254,27 +209,19 @@ func (a *TelemetryRPCs) GetMetricReportDefinition(ctx iris.Context) { defer ctx.Next() ctxt := ctx.Request().Context() req := telemetryproto.TelemetryRequest{ - SessionToken: ctx.Request().Header.Get("X-Auth-Token"), + SessionToken: ctx.Request().Header.Get(AuthTokenHeader), URL: ctx.Request().RequestURI, } l.LogWithFields(ctxt).Debugf("Incoming request received for getting metric report definition details with request URI %s", req.URL) if req.SessionToken == "" { - errorMessage := "error: no X-Auth-Token found in request header" - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + errorMessage := invalidAuthTokenErrorMsg + common.SendInvalidSessionResponse(ctx, errorMessage) } resp, err := a.GetMetricReportDefinitionRPC(ctxt, req) if err != nil { - errorMessage := "error: something went wrong with the RPC calls: " + err.Error() + errorMessage := rpcCallFailedErrorMsg + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) - return + common.SendFailedRPCCallResponse(ctx, errorMessage) } l.LogWithFields(ctxt).Debugf("Outgoing response for getting metric report definition is %s with status code %d", string(resp.Body), int(resp.StatusCode)) ctx.ResponseWriter().Header().Set("Allow", "GET") @@ -289,27 +236,19 @@ func (a *TelemetryRPCs) GetMetricReport(ctx iris.Context) { defer ctx.Next() ctxt := ctx.Request().Context() req := telemetryproto.TelemetryRequest{ - SessionToken: ctx.Request().Header.Get("X-Auth-Token"), + SessionToken: ctx.Request().Header.Get(AuthTokenHeader), URL: ctx.Request().RequestURI, } l.LogWithFields(ctxt).Debugf("Incoming request received for getting metric report details with request URI %s", req.URL) if req.SessionToken == "" { - errorMessage := "error: no X-Auth-Token found in request header" - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + errorMessage := invalidAuthTokenErrorMsg + common.SendInvalidSessionResponse(ctx, errorMessage) } resp, err := a.GetMetricReportRPC(ctxt, req) if err != nil { - errorMessage := "error: something went wrong with the RPC calls: " + err.Error() + errorMessage := rpcCallFailedErrorMsg + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) - return + common.SendFailedRPCCallResponse(ctx, errorMessage) } l.LogWithFields(ctxt).Debugf("Outgoing response for getting metric definition collection is %s with status code %d", string(resp.Body), int(resp.StatusCode)) ctx.ResponseWriter().Header().Set("Allow", "GET") @@ -324,27 +263,19 @@ func (a *TelemetryRPCs) GetTrigger(ctx iris.Context) { defer ctx.Next() ctxt := ctx.Request().Context() req := telemetryproto.TelemetryRequest{ - SessionToken: ctx.Request().Header.Get("X-Auth-Token"), + SessionToken: ctx.Request().Header.Get(AuthTokenHeader), URL: ctx.Request().RequestURI, } if req.SessionToken == "" { - errorMessage := "error: no X-Auth-Token found in request header" - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + errorMessage := invalidAuthTokenErrorMsg + common.SendInvalidSessionResponse(ctx, errorMessage) } l.LogWithFields(ctxt).Debugf("Incoming request received for getting trigger details with request URI %s", req.URL) resp, err := a.GetTriggerRPC(ctxt, req) if err != nil { - errorMessage := "error: something went wrong with the RPC calls: " + err.Error() + errorMessage := rpcCallFailedErrorMsg + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) - return + common.SendFailedRPCCallResponse(ctx, errorMessage) } l.LogWithFields(ctxt).Debugf("Outgoing response for getting trigger details is %s with status code %d", string(resp.Body), int(resp.StatusCode)) ctx.ResponseWriter().Header().Set("Allow", "GET, PATCH") @@ -359,26 +290,18 @@ func (a *TelemetryRPCs) UpdateTrigger(ctx iris.Context) { defer ctx.Next() ctxt := ctx.Request().Context() req := telemetryproto.TelemetryRequest{ - SessionToken: ctx.Request().Header.Get("X-Auth-Token"), + SessionToken: ctx.Request().Header.Get(AuthTokenHeader), } l.LogWithFields(ctxt).Debug("Incoming request received for updating trigger") if req.SessionToken == "" { - errorMessage := "error: no X-Auth-Token found in request header" - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + errorMessage := invalidAuthTokenErrorMsg + common.SendInvalidSessionResponse(ctx, errorMessage) } resp, err := a.UpdateTriggerRPC(ctxt, req) if err != nil { - errorMessage := "error: something went wrong with the RPC calls: " + err.Error() + errorMessage := rpcCallFailedErrorMsg + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) - return + common.SendFailedRPCCallResponse(ctx, errorMessage) } l.LogWithFields(ctxt).Debugf("Outgoing response for updating trigger is %s with status code %d", string(resp.Body), int(resp.StatusCode)) common.SetResponseHeader(ctx, resp.Header) diff --git a/svc-api/handle/update.go b/svc-api/handle/update.go index 137b5f844..dda85f05a 100644 --- a/svc-api/handle/update.go +++ b/svc-api/handle/update.go @@ -46,33 +46,22 @@ func (a *UpdateRPCs) GetUpdateService(ctx iris.Context) { defer ctx.Next() ctxt := ctx.Request().Context() req := updateproto.UpdateRequest{ - SessionToken: ctx.Request().Header.Get("X-Auth-Token"), + SessionToken: ctx.Request().Header.Get(AuthTokenHeader), } l.LogWithFields(ctxt).Debug("Incoming request received for getting update service details") if req.SessionToken == "" { - errorMessage := "error: no X-Auth-Token found in request header" - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + errorMessage := invalidAuthTokenErrorMsg + common.SendInvalidSessionResponse(ctx, errorMessage) } resp, err := a.GetUpdateServiceRPC(ctxt, req) if err != nil { - errorMessage := "error: something went wrong with the RPC calls: " + err.Error() + errorMessage := rpcCallFailedErrorMsg + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) - return + common.SendFailedRPCCallResponse(ctx, errorMessage) } l.LogWithFields(ctxt).Debugf("Outgoing response for getting update service is %s with status code %d", string(resp.Body), int(resp.StatusCode)) ctx.ResponseWriter().Header().Set("Allow", "GET") - common.SetResponseHeader(ctx, resp.Header) - ctx.StatusCode(int(resp.StatusCode)) - ctx.Write(resp.Body) - + sendUpdateResponse(ctx, resp) } // GetFirmwareInventoryCollection is a handler for firmware inventory collection @@ -80,32 +69,22 @@ func (a *UpdateRPCs) GetFirmwareInventoryCollection(ctx iris.Context) { defer ctx.Next() ctxt := ctx.Request().Context() req := updateproto.UpdateRequest{ - SessionToken: ctx.Request().Header.Get("X-Auth-Token"), + SessionToken: ctx.Request().Header.Get(AuthTokenHeader), } l.LogWithFields(ctxt).Debug("Incoming request received for getting firmware inventory collection") if req.SessionToken == "" { - errorMessage := "error: no X-Auth-Token found in request header" - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + errorMessage := invalidAuthTokenErrorMsg + common.SendInvalidSessionResponse(ctx, errorMessage) } resp, err := a.GetFirmwareInventoryCollectionRPC(ctxt, req) if err != nil { - errorMessage := "error: something went wrong with the RPC calls: " + err.Error() + errorMessage := rpcCallFailedErrorMsg + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) - return + common.SendFailedRPCCallResponse(ctx, errorMessage) } l.LogWithFields(ctxt).Debugf("Outgoing response for getting firmware inventory collection is %s with status code %d", string(resp.Body), int(resp.StatusCode)) ctx.ResponseWriter().Header().Set("Allow", "GET") - common.SetResponseHeader(ctx, resp.Header) - ctx.StatusCode(int(resp.StatusCode)) - ctx.Write(resp.Body) + sendUpdateResponse(ctx, resp) } @@ -114,32 +93,22 @@ func (a *UpdateRPCs) GetSoftwareInventoryCollection(ctx iris.Context) { defer ctx.Next() ctxt := ctx.Request().Context() req := updateproto.UpdateRequest{ - SessionToken: ctx.Request().Header.Get("X-Auth-Token"), + SessionToken: ctx.Request().Header.Get(AuthTokenHeader), } l.LogWithFields(ctxt).Debug("Incoming request received for software inventory collection") if req.SessionToken == "" { - errorMessage := "error: no X-Auth-Token found in request header" - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + errorMessage := invalidAuthTokenErrorMsg + common.SendInvalidSessionResponse(ctx, errorMessage) } resp, err := a.GetSoftwareInventoryCollectionRPC(ctxt, req) if err != nil { - errorMessage := "error: something went wrong with the RPC calls: " + err.Error() + errorMessage := rpcCallFailedErrorMsg + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) - return + common.SendFailedRPCCallResponse(ctx, errorMessage) } l.LogWithFields(ctxt).Debugf("Outgoing response for getting software inventory collection is %s with status code %d", string(resp.Body), int(resp.StatusCode)) ctx.ResponseWriter().Header().Set("Allow", "GET") - common.SetResponseHeader(ctx, resp.Header) - ctx.StatusCode(int(resp.StatusCode)) - ctx.Write(resp.Body) + sendUpdateResponse(ctx, resp) } @@ -148,34 +117,24 @@ func (a *UpdateRPCs) GetFirmwareInventory(ctx iris.Context) { defer ctx.Next() ctxt := ctx.Request().Context() req := updateproto.UpdateRequest{ - SessionToken: ctx.Request().Header.Get("X-Auth-Token"), + SessionToken: ctx.Request().Header.Get(AuthTokenHeader), ResourceID: ctx.Params().Get("firmwareInventory_id"), URL: ctx.Request().RequestURI, } l.LogWithFields(ctxt).Debugf("Incoming request received for getting firmware inventory with url %s", req.URL) if req.SessionToken == "" { - errorMessage := "error: no X-Auth-Token found in request header" - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + errorMessage := invalidAuthTokenErrorMsg + common.SendInvalidSessionResponse(ctx, errorMessage) } resp, err := a.GetFirmwareInventoryRPC(ctxt, req) if err != nil { - errorMessage := "error: something went wrong with the RPC calls: " + err.Error() + errorMessage := rpcCallFailedErrorMsg + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) - return + common.SendFailedRPCCallResponse(ctx, errorMessage) } l.LogWithFields(ctxt).Debugf("Outgoing response for getting firmware inventory details is %s with status code %d", string(resp.Body), int(resp.StatusCode)) ctx.ResponseWriter().Header().Set("Allow", "GET") - common.SetResponseHeader(ctx, resp.Header) - ctx.StatusCode(int(resp.StatusCode)) - ctx.Write(resp.Body) + sendUpdateResponse(ctx, resp) } @@ -184,34 +143,24 @@ func (a *UpdateRPCs) GetSoftwareInventory(ctx iris.Context) { defer ctx.Next() ctxt := ctx.Request().Context() req := updateproto.UpdateRequest{ - SessionToken: ctx.Request().Header.Get("X-Auth-Token"), + SessionToken: ctx.Request().Header.Get(AuthTokenHeader), ResourceID: ctx.Params().Get("softwareInventory_id"), URL: ctx.Request().RequestURI, } l.LogWithFields(ctxt).Debugf("Incoming request received for getting software inventory with url %s", req.URL) if req.SessionToken == "" { - errorMessage := "error: no X-Auth-Token found in request header" - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + errorMessage := invalidAuthTokenErrorMsg + common.SendInvalidSessionResponse(ctx, errorMessage) } resp, err := a.GetSoftwareInventoryRPC(ctxt, req) if err != nil { - errorMessage := "error: something went wrong with the RPC calls: " + err.Error() + errorMessage := rpcCallFailedErrorMsg + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) - return + common.SendFailedRPCCallResponse(ctx, errorMessage) } l.LogWithFields(ctxt).Debugf("Outgoing response for getting software inventory details is %s with status code %d", string(resp.Body), int(resp.StatusCode)) ctx.ResponseWriter().Header().Set("Allow", "GET") - common.SetResponseHeader(ctx, resp.Header) - ctx.StatusCode(int(resp.StatusCode)) - ctx.Write(resp.Body) + sendUpdateResponse(ctx, resp) } @@ -224,20 +173,12 @@ func (a *UpdateRPCs) SimpleUpdate(ctx iris.Context) { if err != nil { errorMessage := "error while trying to get JSON body from the simple update request body: " + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusBadRequest, response.MalformedJSON, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusBadRequest) - ctx.JSON(&response.Body) - return + common.SendMalformedJSONRequestErrResponse(ctx, errorMessage) } - sessionToken := ctx.Request().Header.Get("X-Auth-Token") + sessionToken := ctx.Request().Header.Get(AuthTokenHeader) if sessionToken == "" { - errorMessage := "error: no X-Auth-Token found in request header" - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + errorMessage := invalidAuthTokenErrorMsg + common.SendInvalidSessionResponse(ctx, errorMessage) } // Marshalling the req to make reset request request, err := json.Marshal(req) @@ -257,16 +198,10 @@ func (a *UpdateRPCs) SimpleUpdate(ctx iris.Context) { if err != nil { errorMessage := "RPC error:" + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) - return + common.SendFailedRPCCallResponse(ctx, errorMessage) } l.LogWithFields(ctxt).Debugf("Outgoing response for simple update action is %s with status code %d", string(resp.Body), int(resp.StatusCode)) - common.SetResponseHeader(ctx, resp.Header) - ctx.StatusCode(int(resp.StatusCode)) - ctx.Write(resp.Body) + sendUpdateResponse(ctx, resp) } func validateSimpleUpdateRequest(ctx context.Context, requestBody []byte) response.RPC { @@ -319,14 +254,10 @@ func (a *UpdateRPCs) StartUpdate(ctx iris.Context) { defer ctx.Next() ctxt := ctx.Request().Context() l.LogWithFields(ctxt).Debug("Incoming request received for start update action") - sessionToken := ctx.Request().Header.Get("X-Auth-Token") + sessionToken := ctx.Request().Header.Get(AuthTokenHeader) if sessionToken == "" { - errorMessage := "error: no X-Auth-Token found in request header" - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + errorMessage := invalidAuthTokenErrorMsg + common.SendInvalidSessionResponse(ctx, errorMessage) } updateRequest := updateproto.UpdateRequest{ SessionToken: sessionToken, @@ -335,13 +266,14 @@ func (a *UpdateRPCs) StartUpdate(ctx iris.Context) { if err != nil { errorMessage := "RPC error:" + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) - return + common.SendFailedRPCCallResponse(ctx, errorMessage) } l.LogWithFields(ctxt).Debugf("Outgoing response for start update action is %s with status code %d", string(resp.Body), int(resp.StatusCode)) + sendUpdateResponse(ctx, resp) +} + +// sendUpdateResponse writes the update response to client +func sendUpdateResponse(ctx iris.Context, resp *updateproto.UpdateResponse) { common.SetResponseHeader(ctx, resp.Header) ctx.StatusCode(int(resp.StatusCode)) ctx.Write(resp.Body) diff --git a/svc-api/messages/sessions.go b/svc-api/messages/sessions.go index 33672a53f..95004f2f6 100644 --- a/svc-api/messages/sessions.go +++ b/svc-api/messages/sessions.go @@ -12,7 +12,7 @@ //License for the specific language governing permissions and limitations // under the License. -//Package messages ... +// Package messages ... package messages // SessionCreateRequest ... diff --git a/svc-api/models/metadata.go b/svc-api/models/metadata.go index d78abea85..c07b87eba 100644 --- a/svc-api/models/metadata.go +++ b/svc-api/models/metadata.go @@ -12,12 +12,12 @@ //License for the specific language governing permissions and limitations // under the License. -//Package models ... +// Package models ... package models import "encoding/xml" -//Metadata struct definition +// Metadata struct definition type Metadata struct { XMLName xml.Name `xml:"edmx:Edmx"` Xmlnsedmx string `xml:"xmlns:edmx,attr"` @@ -25,14 +25,14 @@ type Metadata struct { TopReference []Reference } -//Reference strcut definition +// Reference strcut definition type Reference struct { XMLName xml.Name `xml:"edmx:Reference"` URI string `xml:"Uri,attr"` TopInclude []Include `xml:"edmx:Include"` } -//Include struct definition +// Include struct definition type Include struct { Namespace string `xml:"Namespace,attr"` Alias string `xml:"Alias,attr,omitempty"` diff --git a/svc-api/models/odata.go b/svc-api/models/odata.go index c09eb1fde..ed71ff6ad 100644 --- a/svc-api/models/odata.go +++ b/svc-api/models/odata.go @@ -12,17 +12,17 @@ //License for the specific language governing permissions and limitations // under the License. -//Package models ... +// Package models ... package models -//Odata struct definition +// Odata struct definition type Odata struct { RedfishCopyright string `json:"@Redfish.Copyright"` OdataContext string `json:"@odata.context"` Value []*Value `json:"value"` } -//Value struct definition +// Value struct definition type Value struct { Name string `json:"name"` Kind string `json:"kind"` diff --git a/svc-api/models/serviceroot.go b/svc-api/models/serviceroot.go index 255f1403d..bad3aef11 100644 --- a/svc-api/models/serviceroot.go +++ b/svc-api/models/serviceroot.go @@ -12,10 +12,10 @@ //License for the specific language governing permissions and limitations // under the License. -//Package models ... +// Package models ... package models -//ServiceRoot struct definition +// ServiceRoot struct definition type ServiceRoot struct { OdataContext string `json:"@odata.context"` Etag string `json:"@odata.etag,omitempty"` @@ -63,7 +63,7 @@ type ServiceRoot struct { LicenseService *Service `json:"LicenseService,omitempty"` } -//PFSupported struct definition +// PFSupported struct definition type PFSupported struct { ExcerptQuery bool `json:"ExcerptQuery"` ExpandQuery *ExpandQuery `json:"ExpandQuery:omitempty"` @@ -72,7 +72,7 @@ type PFSupported struct { SelectQuery bool `json:"SelectQuery"` } -//ExpandQuery struct definition +// ExpandQuery struct definition type ExpandQuery struct { ExpandAll bool `json:"ExpandAll"` Levels bool `json:"Levels"` @@ -81,21 +81,21 @@ type ExpandQuery struct { NoLinks bool `json:"NoLinks"` } -//Service struct definition +// Service struct definition type Service struct { OdataID string `json:"@odata.id"` } -//Links struct definition +// Links struct definition type Links struct { Sessions Sessions `json:"Sessions"` } -//Sessions struct definition +// Sessions struct definition type Sessions struct { OdataID string `json:"@odata.id"` } -//OEM struct definition +// OEM struct definition type OEM struct { } diff --git a/svc-api/models/version.go b/svc-api/models/version.go index cc2c16bf1..fe01d7826 100644 --- a/svc-api/models/version.go +++ b/svc-api/models/version.go @@ -12,10 +12,10 @@ //License for the specific language governing permissions and limitations // under the License. -//Package models ... +// Package models ... package models -//Version struct definition +// Version struct definition type Version struct { V1 string `json:"v1"` } diff --git a/svc-api/response/accounts.go b/svc-api/response/accounts.go index b0f83ff0c..9bec29dd3 100644 --- a/svc-api/response/accounts.go +++ b/svc-api/response/accounts.go @@ -12,14 +12,14 @@ //License for the specific language governing permissions and limitations // under the License. -//Package response ... +// Package response ... package response import ( dmtf "github.com/ODIM-Project/ODIM/lib-dmtf/model" ) -//User struct is used to ommit password for display purposes +// User struct is used to ommit password for display purposes type User struct { OdataContext string `json:"@odata.context"` Etag string `json:"@odata.etag,omitempty"` @@ -35,21 +35,21 @@ type User struct { OEM OEM `json:"Oem"` } -//OEM struct definition +// OEM struct definition type OEM struct { } -//Links struct definition +// Links struct definition type Links struct { Role Role `json:"Role"` } -//Role struct definition +// Role struct definition type Role struct { OdataID string `json:"@odata.id"` } -//AccountService struct definition +// AccountService struct definition type AccountService struct { OdataType string `json:"@odata.type"` ID string `json:"Id"` @@ -84,23 +84,23 @@ type AccountService struct { TACACSplus *TACACSplus `json:"TACACSplus,omitempty"` } -//Accounts struct definition +// Accounts struct definition type Accounts struct { OdataID string `json:"@odata.id"` } -//OAuth2 struct definition +// OAuth2 struct definition type OAuth2 struct { } -//ActiveDirectory struct definition +// ActiveDirectory struct definition type ActiveDirectory struct { } -//LDAP struct definition +// LDAP struct definition type LDAP struct { } -//TACACSplus struct definition +// TACACSplus struct definition type TACACSplus struct { } diff --git a/svc-api/response/error.go b/svc-api/response/error.go index afdb02e1b..0e26ac67b 100644 --- a/svc-api/response/error.go +++ b/svc-api/response/error.go @@ -12,7 +12,7 @@ //License for the specific language governing permissions and limitations // under the License. -//Package response ... +// Package response ... package response // CommonError struct definition diff --git a/svc-api/response/list.go b/svc-api/response/list.go index 6b9947f6d..c538f1b49 100644 --- a/svc-api/response/list.go +++ b/svc-api/response/list.go @@ -12,7 +12,7 @@ //License for the specific language governing permissions and limitations // under the License. -//Package response defines the response structs +// Package response defines the response structs package response // ListResponse define list for odimra diff --git a/svc-api/response/registries.go b/svc-api/response/registries.go index 90f615eba..25c5a290d 100644 --- a/svc-api/response/registries.go +++ b/svc-api/response/registries.go @@ -12,10 +12,10 @@ //License for the specific language governing permissions and limitations // under the License. -//Package response ... +// Package response ... package response -//MessageRegistryFileID defines the message registry file id +// MessageRegistryFileID defines the message registry file id type MessageRegistryFileID struct { ID string `json:"Id"` OdataContext string `json:"@odata.context"` @@ -29,7 +29,7 @@ type MessageRegistryFileID struct { Registry string `json:"Registry"` } -//Location defines the locations/Paths of the file to retrieve. +// Location defines the locations/Paths of the file to retrieve. type Location struct { ArchiveFile string `json:"ArchiveFile,omitempty"` ArchiveURI string `json:"ArchiveUri,omitempty"` diff --git a/svc-api/response/session.go b/svc-api/response/session.go index cfbd1a7b2..03f7f5c72 100644 --- a/svc-api/response/session.go +++ b/svc-api/response/session.go @@ -12,7 +12,7 @@ //License for the specific language governing permissions and limitations // under the License. -//Package response ... +// Package response ... package response // RedfishSessionResponse will have all the @@ -45,7 +45,7 @@ type Session struct { UserName string `json:"UserName"` } -//SessionService struct definition +// SessionService struct definition type SessionService struct { OdataType string `json:"@odata.type"` ID string `json:"Id"` @@ -60,12 +60,12 @@ type SessionService struct { Etag string `json:"@odata.etag,omitempty"` } -//Sessions struct definition +// Sessions struct definition type Sessions struct { OdataID string `json:"@odata.id"` } -//Status struct definition +// Status struct definition type Status struct { State string `json:"State"` Health string `json:"Health"` diff --git a/svc-api/rpc/composition_service.go b/svc-api/rpc/composition_service.go index 97e32ff5f..18fb4f692 100755 --- a/svc-api/rpc/composition_service.go +++ b/svc-api/rpc/composition_service.go @@ -12,7 +12,7 @@ //License for the specific language governing permissions and limitations // under the License. -//Package rpc ... +// Package rpc ... package rpc import ( From 9776f8122b3029e98d746e056f941b4a19e239d5 Mon Sep 17 00:00:00 2001 From: Banoshi Date: Thu, 15 Jun 2023 11:36:25 +0530 Subject: [PATCH 05/19] refactor rpc files --- svc-api/rpc/account.go | 40 ++++++++------- svc-api/rpc/aggregator.go | 101 +++++++++++++++----------------------- svc-api/rpc/chassis.go | 31 +++++------- svc-api/rpc/events.go | 31 +++++------- svc-api/rpc/fabrics.go | 16 +++--- svc-api/rpc/licenses.go | 21 +++----- svc-api/rpc/managers.go | 46 +++++++---------- svc-api/rpc/role.go | 21 +++----- svc-api/rpc/sessions.go | 20 +++----- svc-api/rpc/system.go | 56 +++++++++------------ svc-api/rpc/task.go | 49 ++++++++---------- svc-api/rpc/telemetry.go | 51 ++++++++----------- 12 files changed, 197 insertions(+), 286 deletions(-) diff --git a/svc-api/rpc/account.go b/svc-api/rpc/account.go index d33a62894..b6460b5ed 100644 --- a/svc-api/rpc/account.go +++ b/svc-api/rpc/account.go @@ -22,6 +22,7 @@ import ( "github.com/ODIM-Project/ODIM/lib-utilities/common" accountproto "github.com/ODIM-Project/ODIM/lib-utilities/proto/account" "github.com/ODIM-Project/ODIM/lib-utilities/services" + "google.golang.org/grpc" ) // helper functions @@ -33,10 +34,9 @@ var ( // DoGetAccountServiceRequest defines the RPC call function for // the GetAccountService from account-session micro service func DoGetAccountServiceRequest(ctx context.Context, req accountproto.AccountRequest) (*accountproto.AccountResponse, error) { - ctx = common.CreateMetadata(ctx) - conn, err := ClientFunc(services.AccountSession) + ctx, conn, err := getConnection(ctx, services.AccountSession) if err != nil { - return nil, fmt.Errorf("Failed to create client connection: %v", err) + return nil, err } account := NewAccountClientFunc(conn) @@ -51,10 +51,9 @@ func DoGetAccountServiceRequest(ctx context.Context, req accountproto.AccountReq // DoAccountCreationRequest defines the RPC call function for // the AccountCreation from account-session micro service func DoAccountCreationRequest(ctx context.Context, req accountproto.CreateAccountRequest) (*accountproto.AccountResponse, error) { - ctx = common.CreateMetadata(ctx) - conn, err := ClientFunc(services.AccountSession) + ctx, conn, err := getConnection(ctx, services.AccountSession) if err != nil { - return nil, fmt.Errorf("Failed to create client connection: %v", err) + return nil, err } account := NewAccountClientFunc(conn) @@ -69,10 +68,9 @@ func DoAccountCreationRequest(ctx context.Context, req accountproto.CreateAccoun // DoGetAllAccountRequest defines the RPC call function for // the GetAllAccount from account-session micro service func DoGetAllAccountRequest(ctx context.Context, req accountproto.AccountRequest) (*accountproto.AccountResponse, error) { - ctx = common.CreateMetadata(ctx) - conn, err := ClientFunc(services.AccountSession) + ctx, conn, err := getConnection(ctx, services.AccountSession) if err != nil { - return nil, fmt.Errorf("Failed to create client connection: %v", err) + return nil, err } account := NewAccountClientFunc(conn) @@ -87,10 +85,9 @@ func DoGetAllAccountRequest(ctx context.Context, req accountproto.AccountRequest // DoGetAccountRequest defines the RPC call function for // the GetAccount from account-session micro service func DoGetAccountRequest(ctx context.Context, req accountproto.GetAccountRequest) (*accountproto.AccountResponse, error) { - ctx = common.CreateMetadata(ctx) - conn, err := ClientFunc(services.AccountSession) + ctx, conn, err := getConnection(ctx, services.AccountSession) if err != nil { - return nil, fmt.Errorf("Failed to create client connection: %v", err) + return nil, err } account := NewAccountClientFunc(conn) @@ -106,10 +103,9 @@ func DoGetAccountRequest(ctx context.Context, req accountproto.GetAccountRequest // DoUpdateAccountRequest defines the RPC call function for // the UpdateAccount from account-session micro service func DoUpdateAccountRequest(ctx context.Context, req accountproto.UpdateAccountRequest) (*accountproto.AccountResponse, error) { - ctx = common.CreateMetadata(ctx) - conn, err := ClientFunc(services.AccountSession) + ctx, conn, err := getConnection(ctx, services.AccountSession) if err != nil { - return nil, fmt.Errorf("Failed to create client connection: %v", err) + return nil, err } account := NewAccountClientFunc(conn) @@ -124,10 +120,9 @@ func DoUpdateAccountRequest(ctx context.Context, req accountproto.UpdateAccountR // DoAccountDeleteRequest defines the RPC call function for // the AccountDelete from account-session micro service func DoAccountDeleteRequest(ctx context.Context, req accountproto.DeleteAccountRequest) (*accountproto.AccountResponse, error) { - ctx = common.CreateMetadata(ctx) - conn, err := ClientFunc(services.AccountSession) + ctx, conn, err := getConnection(ctx, services.AccountSession) if err != nil { - return nil, fmt.Errorf("Failed to create client connection: %v", err) + return nil, err } account := NewAccountClientFunc(conn) @@ -138,3 +133,12 @@ func DoAccountDeleteRequest(ctx context.Context, req accountproto.DeleteAccountR defer conn.Close() return resp, err } + +func getConnection(ctx context.Context, service string) (context.Context, *grpc.ClientConn, error) { + ctx = common.CreateMetadata(ctx) + conn, err := ClientFunc(service) + if err != nil { + return ctx, nil, fmt.Errorf("Failed to create client connection: %v", err) + } + return ctx, conn, nil +} diff --git a/svc-api/rpc/aggregator.go b/svc-api/rpc/aggregator.go index 4bd6f7cf4..1d1247b57 100644 --- a/svc-api/rpc/aggregator.go +++ b/svc-api/rpc/aggregator.go @@ -19,7 +19,6 @@ import ( "context" "fmt" - "github.com/ODIM-Project/ODIM/lib-utilities/common" aggregatorproto "github.com/ODIM-Project/ODIM/lib-utilities/proto/aggregator" "github.com/ODIM-Project/ODIM/lib-utilities/services" ) @@ -32,10 +31,9 @@ var ( // DoGetAggregationService defines the RPC call function for // the GetAggregationService from aggregator micro service func DoGetAggregationService(ctx context.Context, req aggregatorproto.AggregatorRequest) (*aggregatorproto.AggregatorResponse, error) { - ctx = common.CreateMetadata(ctx) - conn, err := ClientFunc(services.Aggregator) + ctx, conn, err := getConnection(ctx, services.Aggregator) if err != nil { - return nil, fmt.Errorf("Failed to create client connection: %v", err) + return nil, err } aggregator := NewAggregatorClientFunc(conn) @@ -51,10 +49,9 @@ func DoGetAggregationService(ctx context.Context, req aggregatorproto.Aggregator // DoResetRequest defines the RPC call function for // the Reset from aggregator micro service func DoResetRequest(ctx context.Context, req aggregatorproto.AggregatorRequest) (*aggregatorproto.AggregatorResponse, error) { - ctx = common.CreateMetadata(ctx) - conn, err := ClientFunc(services.Aggregator) + ctx, conn, err := getConnection(ctx, services.Aggregator) if err != nil { - return nil, fmt.Errorf("Failed to create client connection: %v", err) + return nil, err } aggregator := NewAggregatorClientFunc(conn) @@ -70,10 +67,9 @@ func DoResetRequest(ctx context.Context, req aggregatorproto.AggregatorRequest) // DoSetDefaultBootOrderRequest defines the RPC call function for // the SetDefaultBootOrder from aggregator micro service func DoSetDefaultBootOrderRequest(ctx context.Context, req aggregatorproto.AggregatorRequest) (*aggregatorproto.AggregatorResponse, error) { - ctx = common.CreateMetadata(ctx) - conn, err := ClientFunc(services.Aggregator) + ctx, conn, err := getConnection(ctx, services.Aggregator) if err != nil { - return nil, fmt.Errorf("Failed to create client connection: %v", err) + return nil, err } aggregator := NewAggregatorClientFunc(conn) @@ -89,10 +85,9 @@ func DoSetDefaultBootOrderRequest(ctx context.Context, req aggregatorproto.Aggre // DoAddAggregationSource defines the RPC call function for // the AddAggregationSource from aggregator micro service func DoAddAggregationSource(ctx context.Context, req aggregatorproto.AggregatorRequest) (*aggregatorproto.AggregatorResponse, error) { - ctx = common.CreateMetadata(ctx) - conn, err := ClientFunc(services.Aggregator) + ctx, conn, err := getConnection(ctx, services.Aggregator) if err != nil { - return nil, fmt.Errorf("Failed to create client connection: %v", err) + return nil, err } aggregator := NewAggregatorClientFunc(conn) @@ -108,10 +103,9 @@ func DoAddAggregationSource(ctx context.Context, req aggregatorproto.AggregatorR // DoGetAllAggregationSource defines the RPC call function for // the GetAllAggregationSource from aggregator micro service func DoGetAllAggregationSource(ctx context.Context, req aggregatorproto.AggregatorRequest) (*aggregatorproto.AggregatorResponse, error) { - ctx = common.CreateMetadata(ctx) - conn, err := ClientFunc(services.Aggregator) + ctx, conn, err := getConnection(ctx, services.Aggregator) if err != nil { - return nil, fmt.Errorf("Failed to create client connection: %v", err) + return nil, err } aggregator := NewAggregatorClientFunc(conn) @@ -127,10 +121,9 @@ func DoGetAllAggregationSource(ctx context.Context, req aggregatorproto.Aggregat // DoGetAggregationSource defines the RPC call function for // the GetAggregationSource from aggregator micro service func DoGetAggregationSource(ctx context.Context, req aggregatorproto.AggregatorRequest) (*aggregatorproto.AggregatorResponse, error) { - ctx = common.CreateMetadata(ctx) - conn, err := ClientFunc(services.Aggregator) + ctx, conn, err := getConnection(ctx, services.Aggregator) if err != nil { - return nil, fmt.Errorf("Failed to create client connection: %v", err) + return nil, err } aggregator := NewAggregatorClientFunc(conn) @@ -146,10 +139,9 @@ func DoGetAggregationSource(ctx context.Context, req aggregatorproto.AggregatorR // DoUpdateAggregationSource defines the RPC call function for // the UpdateAggregationSource from aggregator micro service func DoUpdateAggregationSource(ctx context.Context, req aggregatorproto.AggregatorRequest) (*aggregatorproto.AggregatorResponse, error) { - ctx = common.CreateMetadata(ctx) - conn, err := ClientFunc(services.Aggregator) + ctx, conn, err := getConnection(ctx, services.Aggregator) if err != nil { - return nil, fmt.Errorf("Failed to create client connection: %v", err) + return nil, err } aggregator := NewAggregatorClientFunc(conn) @@ -165,10 +157,9 @@ func DoUpdateAggregationSource(ctx context.Context, req aggregatorproto.Aggregat // DoDeleteAggregationSource defines the RPC call function for // the DeleteAggregationSource from aggregator micro service func DoDeleteAggregationSource(ctx context.Context, req aggregatorproto.AggregatorRequest) (*aggregatorproto.AggregatorResponse, error) { - ctx = common.CreateMetadata(ctx) - conn, err := ClientFunc(services.Aggregator) + ctx, conn, err := getConnection(ctx, services.Aggregator) if err != nil { - return nil, fmt.Errorf("Failed to create client connection: %v", err) + return nil, err } aggregator := NewAggregatorClientFunc(conn) @@ -184,10 +175,9 @@ func DoDeleteAggregationSource(ctx context.Context, req aggregatorproto.Aggregat // DoCreateAggregate defines the RPC call function for // the CreateAggregate from aggregator micro service func DoCreateAggregate(ctx context.Context, req aggregatorproto.AggregatorRequest) (*aggregatorproto.AggregatorResponse, error) { - ctx = common.CreateMetadata(ctx) - conn, err := ClientFunc(services.Aggregator) + ctx, conn, err := getConnection(ctx, services.Aggregator) if err != nil { - return nil, fmt.Errorf("Failed to create client connection: %v", err) + return nil, err } aggregator := NewAggregatorClientFunc(conn) @@ -203,10 +193,9 @@ func DoCreateAggregate(ctx context.Context, req aggregatorproto.AggregatorReques // DoGetAggregateCollection defines the RPC call function for // the get aggregate collections from aggregator micro service func DoGetAggregateCollection(ctx context.Context, req aggregatorproto.AggregatorRequest) (*aggregatorproto.AggregatorResponse, error) { - ctx = common.CreateMetadata(ctx) - conn, err := ClientFunc(services.Aggregator) + ctx, conn, err := getConnection(ctx, services.Aggregator) if err != nil { - return nil, fmt.Errorf("Failed to create client connection: %v", err) + return nil, err } aggregator := NewAggregatorClientFunc(conn) @@ -222,10 +211,9 @@ func DoGetAggregateCollection(ctx context.Context, req aggregatorproto.Aggregato // DoGeteAggregate defines the RPC call function for // the get aggregate from aggregator micro service func DoGeteAggregate(ctx context.Context, req aggregatorproto.AggregatorRequest) (*aggregatorproto.AggregatorResponse, error) { - ctx = common.CreateMetadata(ctx) - conn, err := ClientFunc(services.Aggregator) + ctx, conn, err := getConnection(ctx, services.Aggregator) if err != nil { - return nil, fmt.Errorf("Failed to create client connection: %v", err) + return nil, err } aggregator := NewAggregatorClientFunc(conn) @@ -241,10 +229,9 @@ func DoGeteAggregate(ctx context.Context, req aggregatorproto.AggregatorRequest) // DoDeleteAggregate defines the RPC call function for // the delete aggregate from aggregator micro service func DoDeleteAggregate(ctx context.Context, req aggregatorproto.AggregatorRequest) (*aggregatorproto.AggregatorResponse, error) { - ctx = common.CreateMetadata(ctx) - conn, err := ClientFunc(services.Aggregator) + ctx, conn, err := getConnection(ctx, services.Aggregator) if err != nil { - return nil, fmt.Errorf("Failed to create client connection: %v", err) + return nil, err } aggregator := NewAggregatorClientFunc(conn) @@ -260,10 +247,9 @@ func DoDeleteAggregate(ctx context.Context, req aggregatorproto.AggregatorReques // DoAddElementsToAggregate defines the RPC call function for // the add elements to an aggregate from aggregator micro service func DoAddElementsToAggregate(ctx context.Context, req aggregatorproto.AggregatorRequest) (*aggregatorproto.AggregatorResponse, error) { - ctx = common.CreateMetadata(ctx) - conn, err := ClientFunc(services.Aggregator) + ctx, conn, err := getConnection(ctx, services.Aggregator) if err != nil { - return nil, fmt.Errorf("Failed to create client connection: %v", err) + return nil, err } aggregator := NewAggregatorClientFunc(conn) @@ -279,10 +265,9 @@ func DoAddElementsToAggregate(ctx context.Context, req aggregatorproto.Aggregato // DoRemoveElementsFromAggregate defines the RPC call function for // the remove elements from an aggregate from aggregator micro service func DoRemoveElementsFromAggregate(ctx context.Context, req aggregatorproto.AggregatorRequest) (*aggregatorproto.AggregatorResponse, error) { - ctx = common.CreateMetadata(ctx) - conn, err := ClientFunc(services.Aggregator) + ctx, conn, err := getConnection(ctx, services.Aggregator) if err != nil { - return nil, fmt.Errorf("Failed to create client connection: %v", err) + return nil, err } aggregator := NewAggregatorClientFunc(conn) @@ -298,10 +283,9 @@ func DoRemoveElementsFromAggregate(ctx context.Context, req aggregatorproto.Aggr // DoResetAggregateElements defines the RPC call function for // the reset elements of an aggregate from aggregator micro service func DoResetAggregateElements(ctx context.Context, req aggregatorproto.AggregatorRequest) (*aggregatorproto.AggregatorResponse, error) { - ctx = common.CreateMetadata(ctx) - conn, err := ClientFunc(services.Aggregator) + ctx, conn, err := getConnection(ctx, services.Aggregator) if err != nil { - return nil, fmt.Errorf("Failed to create client connection: %v", err) + return nil, err } aggregator := NewAggregatorClientFunc(conn) @@ -317,10 +301,9 @@ func DoResetAggregateElements(ctx context.Context, req aggregatorproto.Aggregato // DoSetDefaultBootOrderAggregateElements defines the RPC call function for // the set default boot order elements of an aggregate from aggregator micro service func DoSetDefaultBootOrderAggregateElements(ctx context.Context, req aggregatorproto.AggregatorRequest) (*aggregatorproto.AggregatorResponse, error) { - ctx = common.CreateMetadata(ctx) - conn, err := ClientFunc(services.Aggregator) + ctx, conn, err := getConnection(ctx, services.Aggregator) if err != nil { - return nil, fmt.Errorf("Failed to create client connection: %v", err) + return nil, err } aggregator := NewAggregatorClientFunc(conn) @@ -336,10 +319,9 @@ func DoSetDefaultBootOrderAggregateElements(ctx context.Context, req aggregatorp // DoGetAllConnectionMethods defines the RPC call function for // the get connection method collection from aggregator micro service func DoGetAllConnectionMethods(ctx context.Context, req aggregatorproto.AggregatorRequest) (*aggregatorproto.AggregatorResponse, error) { - ctx = common.CreateMetadata(ctx) - conn, err := ClientFunc(services.Aggregator) + ctx, conn, err := getConnection(ctx, services.Aggregator) if err != nil { - return nil, fmt.Errorf("Failed to create client connection: %v", err) + return nil, err } aggregator := NewAggregatorClientFunc(conn) @@ -355,10 +337,9 @@ func DoGetAllConnectionMethods(ctx context.Context, req aggregatorproto.Aggregat // DoGetConnectionMethod defines the RPC call function for // the get on connection method from aggregator micro service func DoGetConnectionMethod(ctx context.Context, req aggregatorproto.AggregatorRequest) (*aggregatorproto.AggregatorResponse, error) { - ctx = common.CreateMetadata(ctx) - conn, err := ClientFunc(services.Aggregator) + ctx, conn, err := getConnection(ctx, services.Aggregator) if err != nil { - return nil, fmt.Errorf("Failed to create client connection: %v", err) + return nil, err } aggregator := NewAggregatorClientFunc(conn) @@ -374,10 +355,9 @@ func DoGetConnectionMethod(ctx context.Context, req aggregatorproto.AggregatorRe // DoGetResetActionInfoService defines the RPC call function for // the GetResetActionInfoService from aggregator micro service func DoGetResetActionInfoService(ctx context.Context, req aggregatorproto.AggregatorRequest) (*aggregatorproto.AggregatorResponse, error) { - ctx = common.CreateMetadata(ctx) - conn, err := ClientFunc(services.Aggregator) + ctx, conn, err := getConnection(ctx, services.Aggregator) if err != nil { - return nil, fmt.Errorf("Failed to create client connection: %v", err) + return nil, err } aggregator := NewAggregatorClientFunc(conn) @@ -393,10 +373,9 @@ func DoGetResetActionInfoService(ctx context.Context, req aggregatorproto.Aggreg // DoGetSetDefaultBootOrderActionInfo defines the RPC call function for // the GetSetDefaultBootOrderActionInfo from aggregator micro service func DoGetSetDefaultBootOrderActionInfo(ctx context.Context, req aggregatorproto.AggregatorRequest) (*aggregatorproto.AggregatorResponse, error) { - ctx = common.CreateMetadata(ctx) - conn, err := ClientFunc(services.Aggregator) + ctx, conn, err := getConnection(ctx, services.Aggregator) if err != nil { - return nil, fmt.Errorf("Failed to create client connection: %v", err) + return nil, err } aggregator := NewAggregatorClientFunc(conn) diff --git a/svc-api/rpc/chassis.go b/svc-api/rpc/chassis.go index c742b2c1f..cf4baa35c 100644 --- a/svc-api/rpc/chassis.go +++ b/svc-api/rpc/chassis.go @@ -20,7 +20,6 @@ import ( "context" "fmt" - "github.com/ODIM-Project/ODIM/lib-utilities/common" chassisproto "github.com/ODIM-Project/ODIM/lib-utilities/proto/chassis" "github.com/ODIM-Project/ODIM/lib-utilities/services" ) @@ -32,10 +31,9 @@ var ( // GetChassisCollection will do the rpc call to collect all chassis func GetChassisCollection(ctx context.Context, req chassisproto.GetChassisRequest) (*chassisproto.GetChassisResponse, error) { - ctx = common.CreateMetadata(ctx) - conn, err := ClientFunc(services.Systems) + ctx, conn, err := getConnection(ctx, services.Systems) if err != nil { - return nil, fmt.Errorf("Failed to create client connection: %v", err) + return nil, err } asService := NewChassisClientFunc(conn) @@ -49,10 +47,9 @@ func GetChassisCollection(ctx context.Context, req chassisproto.GetChassisReques // GetChassisResource will do the rpc call to collect Chassis Resource func GetChassisResource(ctx context.Context, req chassisproto.GetChassisRequest) (*chassisproto.GetChassisResponse, error) { - ctx = common.CreateMetadata(ctx) - conn, err := ClientFunc(services.Systems) + ctx, conn, err := getConnection(ctx, services.Systems) if err != nil { - return nil, fmt.Errorf("Failed to create client connection: %v", err) + return nil, err } asService := NewChassisClientFunc(conn) @@ -66,10 +63,9 @@ func GetChassisResource(ctx context.Context, req chassisproto.GetChassisRequest) // GetChassis will do the rpc call to System Resource func GetChassis(ctx context.Context, req chassisproto.GetChassisRequest) (*chassisproto.GetChassisResponse, error) { - ctx = common.CreateMetadata(ctx) - conn, err := ClientFunc(services.Systems) + ctx, conn, err := getConnection(ctx, services.Systems) if err != nil { - return nil, fmt.Errorf("Failed to create client connection: %v", err) + return nil, err } asService := NewChassisClientFunc(conn) @@ -83,10 +79,9 @@ func GetChassis(ctx context.Context, req chassisproto.GetChassisRequest) (*chass // CreateChassis will do the rpc call to create a Chassis func CreateChassis(ctx context.Context, req chassisproto.CreateChassisRequest) (*chassisproto.GetChassisResponse, error) { - ctx = common.CreateMetadata(ctx) - conn, err := ClientFunc(services.Systems) + ctx, conn, err := getConnection(ctx, services.Systems) if err != nil { - return nil, fmt.Errorf("Failed to create client connection: %v", err) + return nil, err } service := NewChassisClientFunc(conn) @@ -100,10 +95,9 @@ func CreateChassis(ctx context.Context, req chassisproto.CreateChassisRequest) ( // DeleteChassis will do the rpc call to delete a chassis func DeleteChassis(ctx context.Context, req chassisproto.DeleteChassisRequest) (*chassisproto.GetChassisResponse, error) { - ctx = common.CreateMetadata(ctx) - conn, err := ClientFunc(services.Systems) + ctx, conn, err := getConnection(ctx, services.Systems) if err != nil { - return nil, fmt.Errorf("Failed to create client connection: %v", err) + return nil, err } service := NewChassisClientFunc(conn) @@ -117,10 +111,9 @@ func DeleteChassis(ctx context.Context, req chassisproto.DeleteChassisRequest) ( // UpdateChassis will do the rpc call to update a chassis func UpdateChassis(ctx context.Context, req chassisproto.UpdateChassisRequest) (*chassisproto.GetChassisResponse, error) { - ctx = common.CreateMetadata(ctx) - conn, err := ClientFunc(services.Systems) + ctx, conn, err := getConnection(ctx, services.Systems) if err != nil { - return nil, fmt.Errorf("Failed to create client connection: %v", err) + return nil, err } service := NewChassisClientFunc(conn) diff --git a/svc-api/rpc/events.go b/svc-api/rpc/events.go index 38c651634..6e3b1d7b4 100644 --- a/svc-api/rpc/events.go +++ b/svc-api/rpc/events.go @@ -19,7 +19,6 @@ import ( "context" "fmt" - "github.com/ODIM-Project/ODIM/lib-utilities/common" eventsproto "github.com/ODIM-Project/ODIM/lib-utilities/proto/events" "github.com/ODIM-Project/ODIM/lib-utilities/services" ) @@ -32,10 +31,9 @@ var ( // DoGetEventService defines the RPC call function for // the GetEventService from events micro service func DoGetEventService(ctx context.Context, req eventsproto.EventSubRequest) (*eventsproto.EventSubResponse, error) { - ctx = common.CreateMetadata(ctx) - conn, err := ClientFunc(services.Events) + ctx, conn, err := getConnection(ctx, services.Events) if err != nil { - return nil, fmt.Errorf("Failed to create client connection: %v", err) + return nil, err } events := NewEventsClientFunc(conn) @@ -51,10 +49,9 @@ func DoGetEventService(ctx context.Context, req eventsproto.EventSubRequest) (*e // DoCreateEventSubscription defines the RPC call function for // the CreateEventSubscription from events micro service func DoCreateEventSubscription(ctx context.Context, req eventsproto.EventSubRequest) (*eventsproto.EventSubResponse, error) { - ctx = common.CreateMetadata(ctx) - conn, err := ClientFunc(services.Events) + ctx, conn, err := getConnection(ctx, services.Events) if err != nil { - return nil, fmt.Errorf("Failed to create client connection: %v", err) + return nil, err } events := NewEventsClientFunc(conn) @@ -70,10 +67,9 @@ func DoCreateEventSubscription(ctx context.Context, req eventsproto.EventSubRequ // DoSubmitTestEvent defines the RPC call function for // the SubmitTestEvent from events micro service func DoSubmitTestEvent(ctx context.Context, req eventsproto.EventSubRequest) (*eventsproto.EventSubResponse, error) { - ctx = common.CreateMetadata(ctx) - conn, err := ClientFunc(services.Events) + ctx, conn, err := getConnection(ctx, services.Events) if err != nil { - return nil, fmt.Errorf("Failed to create client connection: %v", err) + return nil, err } events := NewEventsClientFunc(conn) @@ -89,10 +85,9 @@ func DoSubmitTestEvent(ctx context.Context, req eventsproto.EventSubRequest) (*e // DoGetEventSubscription defines the RPC call function for // the DoGetEventSubscription from events micro service func DoGetEventSubscription(ctx context.Context, req eventsproto.EventRequest) (*eventsproto.EventSubResponse, error) { - ctx = common.CreateMetadata(ctx) - conn, err := ClientFunc(services.Events) + ctx, conn, err := getConnection(ctx, services.Events) if err != nil { - return nil, fmt.Errorf("Failed to create client connection: %v", err) + return nil, err } events := NewEventsClientFunc(conn) @@ -108,10 +103,9 @@ func DoGetEventSubscription(ctx context.Context, req eventsproto.EventRequest) ( // DoDeleteEventSubscription defines the RPC call function for // the DoDeleteEventSubscription from events micro service func DoDeleteEventSubscription(ctx context.Context, req eventsproto.EventRequest) (*eventsproto.EventSubResponse, error) { - ctx = common.CreateMetadata(ctx) - conn, err := ClientFunc(services.Events) + ctx, conn, err := getConnection(ctx, services.Events) if err != nil { - return nil, fmt.Errorf("Failed to create client connection: %v", err) + return nil, err } events := NewEventsClientFunc(conn) @@ -127,10 +121,9 @@ func DoDeleteEventSubscription(ctx context.Context, req eventsproto.EventRequest // DoGetEventSubscriptionsCollection defines the RPC call function for // the DoGetEventSubscription from events micro service func DoGetEventSubscriptionsCollection(ctx context.Context, req eventsproto.EventRequest) (*eventsproto.EventSubResponse, error) { - ctx = common.CreateMetadata(ctx) - conn, err := ClientFunc(services.Events) + ctx, conn, err := getConnection(ctx, services.Events) if err != nil { - return nil, fmt.Errorf("Failed to create client connection: %v", err) + return nil, err } events := NewEventsClientFunc(conn) diff --git a/svc-api/rpc/fabrics.go b/svc-api/rpc/fabrics.go index 9f899d589..0e54497cc 100644 --- a/svc-api/rpc/fabrics.go +++ b/svc-api/rpc/fabrics.go @@ -19,7 +19,6 @@ import ( "context" "fmt" - "github.com/ODIM-Project/ODIM/lib-utilities/common" fabricsproto "github.com/ODIM-Project/ODIM/lib-utilities/proto/fabrics" "github.com/ODIM-Project/ODIM/lib-utilities/services" ) @@ -32,10 +31,9 @@ var ( // GetFabricResource defines the RPC call function for // the GetFabricResource from fabrics micro service func GetFabricResource(ctx context.Context, req fabricsproto.FabricRequest) (*fabricsproto.FabricResponse, error) { - ctx = common.CreateMetadata(ctx) - conn, err := ClientFunc(services.Fabrics) + ctx, conn, err := getConnection(ctx, services.Fabrics) if err != nil { - return nil, fmt.Errorf("Failed to create client connection: %v", err) + return nil, err } fab := NewFabricsClientFunc(conn) @@ -50,10 +48,9 @@ func GetFabricResource(ctx context.Context, req fabricsproto.FabricRequest) (*fa // UpdateFabricResource defines the RPC call function for creating/updating // the Fabric Resource such as Endpoints, Zones from fabrics micro service func UpdateFabricResource(ctx context.Context, req fabricsproto.FabricRequest) (*fabricsproto.FabricResponse, error) { - ctx = common.CreateMetadata(ctx) - conn, err := ClientFunc(services.Fabrics) + ctx, conn, err := getConnection(ctx, services.Fabrics) if err != nil { - return nil, fmt.Errorf("Failed to create client connection: %v", err) + return nil, err } fab := NewFabricsClientFunc(conn) @@ -69,10 +66,9 @@ func UpdateFabricResource(ctx context.Context, req fabricsproto.FabricRequest) ( // DeleteFabricResource defines the RPC call function for // the DeleteFabricResource from fabrics micro service func DeleteFabricResource(ctx context.Context, req fabricsproto.FabricRequest) (*fabricsproto.FabricResponse, error) { - ctx = common.CreateMetadata(ctx) - conn, err := ClientFunc(services.Fabrics) + ctx, conn, err := getConnection(ctx, services.Fabrics) if err != nil { - return nil, fmt.Errorf("Failed to create client connection: %v", err) + return nil, err } fab := NewFabricsClientFunc(conn) diff --git a/svc-api/rpc/licenses.go b/svc-api/rpc/licenses.go index 1aa6f0455..d8682cb96 100644 --- a/svc-api/rpc/licenses.go +++ b/svc-api/rpc/licenses.go @@ -18,17 +18,15 @@ import ( "context" "fmt" - "github.com/ODIM-Project/ODIM/lib-utilities/common" licenseproto "github.com/ODIM-Project/ODIM/lib-utilities/proto/licenses" "github.com/ODIM-Project/ODIM/lib-utilities/services" ) // GetLicenseService will do the rpc call to get License Service Information func GetLicenseService(ctx context.Context, req licenseproto.GetLicenseServiceRequest) (*licenseproto.GetLicenseResponse, error) { - ctx = common.CreateMetadata(ctx) - conn, err := services.ODIMService.Client(services.Licenses) + ctx, conn, err := getConnection(ctx, services.Licenses) if err != nil { - return nil, fmt.Errorf("Failed to create client connection: %v", err) + return nil, err } defer conn.Close() licenseService := licenseproto.NewLicensesClient(conn) @@ -41,10 +39,9 @@ func GetLicenseService(ctx context.Context, req licenseproto.GetLicenseServiceRe // GetLicenseCollection will do the rpc call to get License Service Information func GetLicenseCollection(ctx context.Context, req licenseproto.GetLicenseRequest) (*licenseproto.GetLicenseResponse, error) { - ctx = common.CreateMetadata(ctx) - conn, err := services.ODIMService.Client(services.Licenses) + ctx, conn, err := getConnection(ctx, services.Licenses) if err != nil { - return nil, fmt.Errorf("Failed to create client connection: %v", err) + return nil, err } defer conn.Close() licenseService := licenseproto.NewLicensesClient(conn) @@ -57,10 +54,9 @@ func GetLicenseCollection(ctx context.Context, req licenseproto.GetLicenseReques // GetLicenseResource will do the rpc call to get License Service Information func GetLicenseResource(ctx context.Context, req licenseproto.GetLicenseResourceRequest) (*licenseproto.GetLicenseResponse, error) { - ctx = common.CreateMetadata(ctx) - conn, err := services.ODIMService.Client(services.Licenses) + ctx, conn, err := getConnection(ctx, services.Licenses) if err != nil { - return nil, fmt.Errorf("Failed to create client connection: %v", err) + return nil, err } defer conn.Close() licenseService := licenseproto.NewLicensesClient(conn) @@ -73,10 +69,9 @@ func GetLicenseResource(ctx context.Context, req licenseproto.GetLicenseResource // InstallLicenseService will do the rpc call to install License func InstallLicenseService(ctx context.Context, req licenseproto.InstallLicenseRequest) (*licenseproto.GetLicenseResponse, error) { - ctx = common.CreateMetadata(ctx) - conn, err := services.ODIMService.Client(services.Licenses) + ctx, conn, err := getConnection(ctx, services.Licenses) if err != nil { - return nil, fmt.Errorf("Failed to create client connection: %v", err) + return nil, err } defer conn.Close() licenseService := licenseproto.NewLicensesClient(conn) diff --git a/svc-api/rpc/managers.go b/svc-api/rpc/managers.go index a027773a2..9100d6806 100644 --- a/svc-api/rpc/managers.go +++ b/svc-api/rpc/managers.go @@ -19,7 +19,6 @@ import ( "context" "fmt" - "github.com/ODIM-Project/ODIM/lib-utilities/common" managersproto "github.com/ODIM-Project/ODIM/lib-utilities/proto/managers" "github.com/ODIM-Project/ODIM/lib-utilities/services" ) @@ -31,10 +30,9 @@ var ( // GetManagersCollection will do the rpc call to collect Managers func GetManagersCollection(ctx context.Context, req managersproto.ManagerRequest) (*managersproto.ManagerResponse, error) { - ctx = common.CreateMetadata(ctx) - conn, err := ClientFunc(services.Managers) + ctx, conn, err := getConnection(ctx, services.Managers) if err != nil { - return nil, fmt.Errorf("Failed to create client connection: %v", err) + return nil, err } asService := NewManagersClientFunc(conn) @@ -48,10 +46,9 @@ func GetManagersCollection(ctx context.Context, req managersproto.ManagerRequest // GetManagers will do the rpc calls for the svc-managers func GetManagers(ctx context.Context, req managersproto.ManagerRequest) (*managersproto.ManagerResponse, error) { - ctx = common.CreateMetadata(ctx) - conn, err := ClientFunc(services.Managers) + ctx, conn, err := getConnection(ctx, services.Managers) if err != nil { - return nil, fmt.Errorf("Failed to create client connection: %v", err) + return nil, err } asService := NewManagersClientFunc(conn) @@ -65,10 +62,9 @@ func GetManagers(ctx context.Context, req managersproto.ManagerRequest) (*manage // GetManagersResource will do the rpc calls for the svc-managers func GetManagersResource(ctx context.Context, req managersproto.ManagerRequest) (*managersproto.ManagerResponse, error) { - ctx = common.CreateMetadata(ctx) - conn, err := ClientFunc(services.Managers) + ctx, conn, err := getConnection(ctx, services.Managers) if err != nil { - return nil, fmt.Errorf("Failed to create client connection: %v", err) + return nil, err } asService := NewManagersClientFunc(conn) @@ -82,10 +78,9 @@ func GetManagersResource(ctx context.Context, req managersproto.ManagerRequest) // VirtualMediaInsert will do the rpc calls for the svc-managers func VirtualMediaInsert(ctx context.Context, req managersproto.ManagerRequest) (*managersproto.ManagerResponse, error) { - ctx = common.CreateMetadata(ctx) - conn, err := ClientFunc(services.Managers) + ctx, conn, err := getConnection(ctx, services.Managers) if err != nil { - return nil, fmt.Errorf("Failed to create client connection: %v", err) + return nil, err } asService := NewManagersClientFunc(conn) @@ -99,10 +94,9 @@ func VirtualMediaInsert(ctx context.Context, req managersproto.ManagerRequest) ( // VirtualMediaEject will do the rpc calls for the svc-managers func VirtualMediaEject(ctx context.Context, req managersproto.ManagerRequest) (*managersproto.ManagerResponse, error) { - ctx = common.CreateMetadata(ctx) - conn, err := ClientFunc(services.Managers) + ctx, conn, err := getConnection(ctx, services.Managers) if err != nil { - return nil, fmt.Errorf("Failed to create client connection: %v", err) + return nil, err } asService := NewManagersClientFunc(conn) @@ -116,10 +110,9 @@ func VirtualMediaEject(ctx context.Context, req managersproto.ManagerRequest) (* // GetRemoteAccountService will do the rpc call to collect BMC accounts func GetRemoteAccountService(ctx context.Context, req managersproto.ManagerRequest) (*managersproto.ManagerResponse, error) { - ctx = common.CreateMetadata(ctx) - conn, err := ClientFunc(services.Managers) + ctx, conn, err := getConnection(ctx, services.Managers) if err != nil { - return nil, fmt.Errorf("Failed to create client connection: %v", err) + return nil, err } mService := NewManagersClientFunc(conn) @@ -133,10 +126,9 @@ func GetRemoteAccountService(ctx context.Context, req managersproto.ManagerReque // CreateRemoteAccountService will do the rpc call to create a new BMC account func CreateRemoteAccountService(ctx context.Context, req managersproto.ManagerRequest) (*managersproto.ManagerResponse, error) { - ctx = common.CreateMetadata(ctx) - conn, err := ClientFunc(services.Managers) + ctx, conn, err := getConnection(ctx, services.Managers) if err != nil { - return nil, fmt.Errorf("Failed to create client connection: %v", err) + return nil, err } mService := NewManagersClientFunc(conn) @@ -150,10 +142,9 @@ func CreateRemoteAccountService(ctx context.Context, req managersproto.ManagerRe // UpdateRemoteAccountService will do rpc call to update BMC account func UpdateRemoteAccountService(ctx context.Context, req managersproto.ManagerRequest) (*managersproto.ManagerResponse, error) { - ctx = common.CreateMetadata(ctx) - conn, err := ClientFunc(services.Managers) + ctx, conn, err := getConnection(ctx, services.Managers) if err != nil { - return nil, fmt.Errorf("Failed to create client connection: %v", err) + return nil, err } mService := NewManagersClientFunc(conn) @@ -167,10 +158,9 @@ func UpdateRemoteAccountService(ctx context.Context, req managersproto.ManagerRe // DeleteRemoteAccountService will do the rpc call to delete an existing BMC account func DeleteRemoteAccountService(ctx context.Context, req managersproto.ManagerRequest) (*managersproto.ManagerResponse, error) { - ctx = common.CreateMetadata(ctx) - conn, err := ClientFunc(services.Managers) + ctx, conn, err := getConnection(ctx, services.Managers) if err != nil { - return nil, fmt.Errorf("Failed to create client connection: %v", err) + return nil, err } mService := NewManagersClientFunc(conn) diff --git a/svc-api/rpc/role.go b/svc-api/rpc/role.go index 955e25e54..a70c07be5 100644 --- a/svc-api/rpc/role.go +++ b/svc-api/rpc/role.go @@ -19,7 +19,6 @@ import ( "context" "fmt" - "github.com/ODIM-Project/ODIM/lib-utilities/common" roleproto "github.com/ODIM-Project/ODIM/lib-utilities/proto/role" "github.com/ODIM-Project/ODIM/lib-utilities/services" ) @@ -32,10 +31,9 @@ var ( // GetRole defines the RPC call function for // the GetRole from account-session micro service func GetRole(ctx context.Context, req roleproto.GetRoleRequest) (*roleproto.RoleResponse, error) { - ctx = common.CreateMetadata(ctx) - conn, err := ClientFunc(services.AccountSession) + ctx, conn, err := getConnection(ctx, services.AccountSession) if err != nil { - return nil, fmt.Errorf("Failed to create client connection: %v", err) + return nil, err } asService := NewRolesClientFunc(conn) @@ -50,10 +48,9 @@ func GetRole(ctx context.Context, req roleproto.GetRoleRequest) (*roleproto.Role // GetAllRoles defines the RPC call function for // the GetAllRoles from account-session micro service func GetAllRoles(ctx context.Context, req roleproto.GetRoleRequest) (*roleproto.RoleResponse, error) { - ctx = common.CreateMetadata(ctx) - conn, err := ClientFunc(services.AccountSession) + ctx, conn, err := getConnection(ctx, services.AccountSession) if err != nil { - return nil, fmt.Errorf("Failed to create client connection: %v", err) + return nil, err } asService := NewRolesClientFunc(conn) @@ -68,10 +65,9 @@ func GetAllRoles(ctx context.Context, req roleproto.GetRoleRequest) (*roleproto. // UpdateRole defines the RPC call function for // the UpdateRole from account-session micro service func UpdateRole(ctx context.Context, req roleproto.UpdateRoleRequest) (*roleproto.RoleResponse, error) { - ctx = common.CreateMetadata(ctx) - conn, err := ClientFunc(services.AccountSession) + ctx, conn, err := getConnection(ctx, services.AccountSession) if err != nil { - return nil, fmt.Errorf("Failed to create client connection: %v", err) + return nil, err } asService := NewRolesClientFunc(conn) @@ -85,10 +81,9 @@ func UpdateRole(ctx context.Context, req roleproto.UpdateRoleRequest) (*roleprot // DeleteRole defines the RPC call function for the DeleteRole from account-session microservice func DeleteRole(ctx context.Context, req roleproto.DeleteRoleRequest) (*roleproto.RoleResponse, error) { - ctx = common.CreateMetadata(ctx) - conn, err := ClientFunc(services.AccountSession) + ctx, conn, err := getConnection(ctx, services.AccountSession) if err != nil { - return nil, fmt.Errorf("Failed to create client connection: %v", err) + return nil, err } asService := NewRolesClientFunc(conn) diff --git a/svc-api/rpc/sessions.go b/svc-api/rpc/sessions.go index d938b4e1d..1f2657da1 100644 --- a/svc-api/rpc/sessions.go +++ b/svc-api/rpc/sessions.go @@ -66,10 +66,9 @@ func DoSessionCreationRequest(ctx context.Context, req sessionproto.SessionCreat // DeleteSessionRequest will do the rpc call to delete session func DeleteSessionRequest(ctx context.Context, sessionID, sessionToken string) (*sessionproto.SessionResponse, error) { - ctx = common.CreateMetadata(ctx) - conn, err := ClientFunc(services.AccountSession) + ctx, conn, err := getConnection(ctx, services.AccountSession) if err != nil { - return nil, fmt.Errorf("Failed to create client connection: %v", err) + return nil, err } asService := NewSessionClientFunc(conn) @@ -88,10 +87,9 @@ func DeleteSessionRequest(ctx context.Context, sessionID, sessionToken string) ( // GetSessionRequest will do the rpc call to get session func GetSessionRequest(ctx context.Context, sessionID, sessionToken string) (*sessionproto.SessionResponse, error) { - ctx = common.CreateMetadata(ctx) - conn, err := ClientFunc(services.AccountSession) + ctx, conn, err := getConnection(ctx, services.AccountSession) if err != nil { - return nil, fmt.Errorf("Failed to create client connection: %v", err) + return nil, err } asService := NewSessionClientFunc(conn) @@ -110,10 +108,9 @@ func GetSessionRequest(ctx context.Context, sessionID, sessionToken string) (*se // GetAllActiveSessionRequest will do the rpc call to get session func GetAllActiveSessionRequest(ctx context.Context, sessionID, sessionToken string) (*sessionproto.SessionResponse, error) { - ctx = common.CreateMetadata(ctx) - conn, err := ClientFunc(services.AccountSession) + ctx, conn, err := getConnection(ctx, services.AccountSession) if err != nil { - return nil, fmt.Errorf("Failed to create client connection: %v", err) + return nil, err } asService := NewSessionClientFunc(conn) @@ -132,10 +129,9 @@ func GetAllActiveSessionRequest(ctx context.Context, sessionID, sessionToken str // GetSessionServiceRequest will do the rpc call to check session func GetSessionServiceRequest(ctx context.Context) (*sessionproto.SessionResponse, error) { - ctx = common.CreateMetadata(ctx) - conn, err := ClientFunc(services.AccountSession) + ctx, conn, err := getConnection(ctx, services.AccountSession) if err != nil { - return nil, fmt.Errorf("Failed to create client connection: %v", err) + return nil, err } asService := NewSessionClientFunc(conn) diff --git a/svc-api/rpc/system.go b/svc-api/rpc/system.go index f4e170f89..6add90f7b 100644 --- a/svc-api/rpc/system.go +++ b/svc-api/rpc/system.go @@ -19,7 +19,6 @@ import ( "context" "fmt" - "github.com/ODIM-Project/ODIM/lib-utilities/common" systemsproto "github.com/ODIM-Project/ODIM/lib-utilities/proto/systems" "github.com/ODIM-Project/ODIM/lib-utilities/services" ) @@ -31,10 +30,9 @@ var ( // GetSystemsCollection will do the rpc call to collect Systems from odimra func GetSystemsCollection(ctx context.Context, req systemsproto.GetSystemsRequest) (*systemsproto.SystemsResponse, error) { - ctx = common.CreateMetadata(ctx) - conn, err := ClientFunc(services.Systems) + ctx, conn, err := getConnection(ctx, services.Systems) if err != nil { - return nil, fmt.Errorf("Failed to create client connection: %v", err) + return nil, err } asService := NewSystemsClientFunc(conn) @@ -48,10 +46,9 @@ func GetSystemsCollection(ctx context.Context, req systemsproto.GetSystemsReques // GetSystemRequestRPC will do the rpc calls for the svc-systems func GetSystemRequestRPC(ctx context.Context, req systemsproto.GetSystemsRequest) (*systemsproto.SystemsResponse, error) { - ctx = common.CreateMetadata(ctx) - conn, err := ClientFunc(services.Systems) + ctx, conn, err := getConnection(ctx, services.Systems) if err != nil { - return nil, fmt.Errorf("Failed to create client connection: %v", err) + return nil, err } asService := NewSystemsClientFunc(conn) @@ -65,10 +62,9 @@ func GetSystemRequestRPC(ctx context.Context, req systemsproto.GetSystemsRequest // GetSystemResource will do the rpc call to collect System Resource func GetSystemResource(ctx context.Context, req systemsproto.GetSystemsRequest) (*systemsproto.SystemsResponse, error) { - ctx = common.CreateMetadata(ctx) - conn, err := ClientFunc(services.Systems) + ctx, conn, err := getConnection(ctx, services.Systems) if err != nil { - return nil, fmt.Errorf("Failed to create client connection: %v", err) + return nil, err } asService := NewSystemsClientFunc(conn) @@ -82,10 +78,9 @@ func GetSystemResource(ctx context.Context, req systemsproto.GetSystemsRequest) // ComputerSystemReset will do the rpc call to reset the computer system func ComputerSystemReset(ctx context.Context, req systemsproto.ComputerSystemResetRequest) (*systemsproto.SystemsResponse, error) { - ctx = common.CreateMetadata(ctx) - conn, err := ClientFunc(services.Systems) + ctx, conn, err := getConnection(ctx, services.Systems) if err != nil { - return nil, fmt.Errorf("Failed to create client connection: %v", err) + return nil, err } asService := NewSystemsClientFunc(conn) @@ -99,10 +94,9 @@ func ComputerSystemReset(ctx context.Context, req systemsproto.ComputerSystemRes // SetDefaultBootOrder will do the rpc call to set the default boot order of computer system func SetDefaultBootOrder(ctx context.Context, req systemsproto.DefaultBootOrderRequest) (*systemsproto.SystemsResponse, error) { - ctx = common.CreateMetadata(ctx) - conn, err := ClientFunc(services.Systems) + ctx, conn, err := getConnection(ctx, services.Systems) if err != nil { - return nil, fmt.Errorf("Failed to create client connection: %v", err) + return nil, err } asService := NewSystemsClientFunc(conn) @@ -116,10 +110,9 @@ func SetDefaultBootOrder(ctx context.Context, req systemsproto.DefaultBootOrderR // ChangeBiosSettings will do the rpc call to change bios settings func ChangeBiosSettings(ctx context.Context, req systemsproto.BiosSettingsRequest) (*systemsproto.SystemsResponse, error) { - ctx = common.CreateMetadata(ctx) - conn, err := ClientFunc(services.Systems) + ctx, conn, err := getConnection(ctx, services.Systems) if err != nil { - return nil, fmt.Errorf("Failed to create client connection: %v", err) + return nil, err } asService := NewSystemsClientFunc(conn) @@ -133,10 +126,9 @@ func ChangeBiosSettings(ctx context.Context, req systemsproto.BiosSettingsReques // ChangeBootOrderSettings will do the rpc call to change Boot Order settings func ChangeBootOrderSettings(ctx context.Context, req systemsproto.BootOrderSettingsRequest) (*systemsproto.SystemsResponse, error) { - ctx = common.CreateMetadata(ctx) - conn, err := ClientFunc(services.Systems) + ctx, conn, err := getConnection(ctx, services.Systems) if err != nil { - return nil, fmt.Errorf("Failed to create client connection: %v", err) + return nil, err } asService := NewSystemsClientFunc(conn) @@ -150,10 +142,9 @@ func ChangeBootOrderSettings(ctx context.Context, req systemsproto.BootOrderSett // CreateVolume will do the rpc call to create a volume under storage func CreateVolume(ctx context.Context, req systemsproto.VolumeRequest) (*systemsproto.SystemsResponse, error) { - ctx = common.CreateMetadata(ctx) - conn, err := ClientFunc(services.Systems) + ctx, conn, err := getConnection(ctx, services.Systems) if err != nil { - return nil, fmt.Errorf("Failed to create client connection: %v", err) + return nil, err } asService := NewSystemsClientFunc(conn) @@ -167,10 +158,9 @@ func CreateVolume(ctx context.Context, req systemsproto.VolumeRequest) (*systems // DeleteVolume will do the rpc call to DeleteVolume a volume under storage func DeleteVolume(ctx context.Context, req systemsproto.VolumeRequest) (*systemsproto.SystemsResponse, error) { - ctx = common.CreateMetadata(ctx) - conn, err := ClientFunc(services.Systems) + ctx, conn, err := getConnection(ctx, services.Systems) if err != nil { - return nil, fmt.Errorf("Failed to create client connection: %v", err) + return nil, err } asService := NewSystemsClientFunc(conn) @@ -184,10 +174,9 @@ func DeleteVolume(ctx context.Context, req systemsproto.VolumeRequest) (*systems // UpdateSecureBoot will do the rpc call to UpdateSecureBoot func UpdateSecureBoot(ctx context.Context, req systemsproto.SecureBootRequest) (*systemsproto.SystemsResponse, error) { - ctx = common.CreateMetadata(ctx) - conn, err := ClientFunc(services.Systems) + ctx, conn, err := getConnection(ctx, services.Systems) if err != nil { - return nil, fmt.Errorf("Failed to create client connection: %v", err) + return nil, err } asService := NewSystemsClientFunc(conn) @@ -201,10 +190,9 @@ func UpdateSecureBoot(ctx context.Context, req systemsproto.SecureBootRequest) ( // ResetSecureBoot will do the rpc call to ResetSecureBoot func ResetSecureBoot(ctx context.Context, req systemsproto.SecureBootRequest) (*systemsproto.SystemsResponse, error) { - ctx = common.CreateMetadata(ctx) - conn, err := ClientFunc(services.Systems) + ctx, conn, err := getConnection(ctx, services.Systems) if err != nil { - return nil, fmt.Errorf("Failed to create client connection: %v", err) + return nil, err } asService := NewSystemsClientFunc(conn) diff --git a/svc-api/rpc/task.go b/svc-api/rpc/task.go index 4ffa0603c..c7ce961fe 100644 --- a/svc-api/rpc/task.go +++ b/svc-api/rpc/task.go @@ -34,10 +34,9 @@ var ( // DeleteTaskRequest will do the rpc calls for the svc-task DeleteTask func DeleteTaskRequest(ctx context.Context, req *taskproto.GetTaskRequest) (*taskproto.TaskResponse, error) { - ctx = common.CreateMetadata(ctx) - conn, connErr := ClientFunc(services.Tasks) - if connErr != nil { - return nil, fmt.Errorf("Failed to create client connection: %v", connErr) + ctx, conn, err := getConnection(ctx, services.Tasks) + if err != nil { + return nil, err } asService := NewGetTaskServiceClientFunc(conn) @@ -59,10 +58,9 @@ func DeleteTaskRequest(ctx context.Context, req *taskproto.GetTaskRequest) (*tas // GetTaskRequest will do the rpc calls for the svc-task GetTaskStatus func GetTaskRequest(ctx context.Context, req *taskproto.GetTaskRequest) (*taskproto.TaskResponse, error) { - ctx = common.CreateMetadata(ctx) - conn, connErr := ClientFunc(services.Tasks) - if connErr != nil { - return nil, fmt.Errorf("Failed to create client connection: %v", connErr) + ctx, conn, err := getConnection(ctx, services.Tasks) + if err != nil { + return nil, err } asService := NewGetTaskServiceClientFunc(conn) @@ -84,10 +82,9 @@ func GetTaskRequest(ctx context.Context, req *taskproto.GetTaskRequest) (*taskpr // GetSubTasks will do the rpc calls for the svc-task GetSubTasks func GetSubTasks(ctx context.Context, req *taskproto.GetTaskRequest) (*taskproto.TaskResponse, error) { - ctx = common.CreateMetadata(ctx) - conn, connErr := ClientFunc(services.Tasks) - if connErr != nil { - return nil, fmt.Errorf("Failed to create client connection: %v", connErr) + ctx, conn, err := getConnection(ctx, services.Tasks) + if err != nil { + return nil, err } tService := NewGetTaskServiceClientFunc(conn) @@ -109,10 +106,9 @@ func GetSubTasks(ctx context.Context, req *taskproto.GetTaskRequest) (*taskproto // GetSubTask will do the rpc calls for the svc-task GetSubTask func GetSubTask(ctx context.Context, req *taskproto.GetTaskRequest) (*taskproto.TaskResponse, error) { - ctx = common.CreateMetadata(ctx) - conn, connErr := ClientFunc(services.Tasks) - if connErr != nil { - return nil, fmt.Errorf("Failed to create client connection: %v", connErr) + ctx, conn, err := getConnection(ctx, services.Tasks) + if err != nil { + return nil, err } tService := NewGetTaskServiceClientFunc(conn) @@ -134,10 +130,9 @@ func GetSubTask(ctx context.Context, req *taskproto.GetTaskRequest) (*taskproto. // GetTaskMonitor will do the rpc calls for the svc-task GetTaskMonitor func GetTaskMonitor(ctx context.Context, req *taskproto.GetTaskRequest) (*taskproto.TaskResponse, error) { - ctx = common.CreateMetadata(ctx) - conn, connErr := ClientFunc(services.Tasks) - if connErr != nil { - return nil, fmt.Errorf("Failed to create client connection: %v", connErr) + ctx, conn, err := getConnection(ctx, services.Tasks) + if err != nil { + return nil, err } tService := NewGetTaskServiceClientFunc(conn) @@ -159,10 +154,9 @@ func GetTaskMonitor(ctx context.Context, req *taskproto.GetTaskRequest) (*taskpr // TaskCollection will perform the rpc call to svc-task TaskCollection func TaskCollection(ctx context.Context, req *taskproto.GetTaskRequest) (*taskproto.TaskResponse, error) { - ctx = common.CreateMetadata(ctx) - conn, connErr := ClientFunc(services.Tasks) - if connErr != nil { - return nil, fmt.Errorf("Failed to create client connection: %v", connErr) + ctx, conn, err := getConnection(ctx, services.Tasks) + if err != nil { + return nil, err } tService := NewGetTaskServiceClientFunc(conn) @@ -184,10 +178,9 @@ func TaskCollection(ctx context.Context, req *taskproto.GetTaskRequest) (*taskpr // GetTaskService will perform the rpc call to svc-task GetTaskService func GetTaskService(ctx context.Context, req *taskproto.GetTaskRequest) (*taskproto.TaskResponse, error) { - ctx = common.CreateMetadata(ctx) - conn, connErr := ClientFunc(services.Tasks) - if connErr != nil { - return nil, fmt.Errorf("Failed to create client connection: %v", connErr) + ctx, conn, err := getConnection(ctx, services.Tasks) + if err != nil { + return nil, err } tService := NewGetTaskServiceClientFunc(conn) diff --git a/svc-api/rpc/telemetry.go b/svc-api/rpc/telemetry.go index fa860c201..ab8715231 100644 --- a/svc-api/rpc/telemetry.go +++ b/svc-api/rpc/telemetry.go @@ -19,7 +19,6 @@ import ( "context" "fmt" - "github.com/ODIM-Project/ODIM/lib-utilities/common" teleproto "github.com/ODIM-Project/ODIM/lib-utilities/proto/telemetry" "github.com/ODIM-Project/ODIM/lib-utilities/services" ) @@ -32,10 +31,9 @@ var ( // DoGetTelemetryService defines the RPC call function for // the GetTelemetryService from telemetry micro service func DoGetTelemetryService(ctx context.Context, req teleproto.TelemetryRequest) (*teleproto.TelemetryResponse, error) { - ctx = common.CreateMetadata(ctx) - conn, err := ClientFunc(services.Telemetry) + ctx, conn, err := getConnection(ctx, services.Telemetry) if err != nil { - return nil, fmt.Errorf("Failed to create client connection: %v", err) + return nil, err } telemetry := NewTelemetryClientFunc(conn) @@ -51,10 +49,9 @@ func DoGetTelemetryService(ctx context.Context, req teleproto.TelemetryRequest) // DoGetMetricDefinitionCollection defines the RPC call function for // the GetMetricDefinitionCollection from telemetry micro service func DoGetMetricDefinitionCollection(ctx context.Context, req teleproto.TelemetryRequest) (*teleproto.TelemetryResponse, error) { - ctx = common.CreateMetadata(ctx) - conn, err := ClientFunc(services.Telemetry) + ctx, conn, err := getConnection(ctx, services.Telemetry) if err != nil { - return nil, fmt.Errorf("Failed to create client connection: %v", err) + return nil, err } telemetry := NewTelemetryClientFunc(conn) @@ -69,10 +66,9 @@ func DoGetMetricDefinitionCollection(ctx context.Context, req teleproto.Telemetr // DoGetMetricReportDefinitionCollection defines the RPC call function for // the GetMetricReportDefinitionCollection from telemetry micro service func DoGetMetricReportDefinitionCollection(ctx context.Context, req teleproto.TelemetryRequest) (*teleproto.TelemetryResponse, error) { - ctx = common.CreateMetadata(ctx) - conn, err := ClientFunc(services.Telemetry) + ctx, conn, err := getConnection(ctx, services.Telemetry) if err != nil { - return nil, fmt.Errorf("Failed to create client connection: %v", err) + return nil, err } telemetry := NewTelemetryClientFunc(conn) @@ -87,10 +83,9 @@ func DoGetMetricReportDefinitionCollection(ctx context.Context, req teleproto.Te // DoGetMetricReportCollection defines the RPC call function for // the GetMetricReportCollection from telemetry micro service func DoGetMetricReportCollection(ctx context.Context, req teleproto.TelemetryRequest) (*teleproto.TelemetryResponse, error) { - ctx = common.CreateMetadata(ctx) - conn, err := ClientFunc(services.Telemetry) + ctx, conn, err := getConnection(ctx, services.Telemetry) if err != nil { - return nil, fmt.Errorf("Failed to create client connection: %v", err) + return nil, err } telemetry := NewTelemetryClientFunc(conn) @@ -106,10 +101,9 @@ func DoGetMetricReportCollection(ctx context.Context, req teleproto.TelemetryReq // DoGetTriggerCollection defines the RPC call function for // the GetTriggerCollection from telemetry micro service func DoGetTriggerCollection(ctx context.Context, req teleproto.TelemetryRequest) (*teleproto.TelemetryResponse, error) { - ctx = common.CreateMetadata(ctx) - conn, err := ClientFunc(services.Telemetry) + ctx, conn, err := getConnection(ctx, services.Telemetry) if err != nil { - return nil, fmt.Errorf("Failed to create client connection: %v", err) + return nil, err } telemetry := NewTelemetryClientFunc(conn) @@ -125,10 +119,9 @@ func DoGetTriggerCollection(ctx context.Context, req teleproto.TelemetryRequest) // DoGetMetricDefinition defines the RPC call function for // the GetMetricDefinition from telemetry micro service func DoGetMetricDefinition(ctx context.Context, req teleproto.TelemetryRequest) (*teleproto.TelemetryResponse, error) { - ctx = common.CreateMetadata(ctx) - conn, err := ClientFunc(services.Telemetry) + ctx, conn, err := getConnection(ctx, services.Telemetry) if err != nil { - return nil, fmt.Errorf("Failed to create client connection: %v", err) + return nil, err } telemetry := NewTelemetryClientFunc(conn) @@ -144,10 +137,9 @@ func DoGetMetricDefinition(ctx context.Context, req teleproto.TelemetryRequest) // DoGetMetricReportDefinition defines the RPC call function for // the GetMetricReportDefinition from telemetry micro service func DoGetMetricReportDefinition(ctx context.Context, req teleproto.TelemetryRequest) (*teleproto.TelemetryResponse, error) { - ctx = common.CreateMetadata(ctx) - conn, err := ClientFunc(services.Telemetry) + ctx, conn, err := getConnection(ctx, services.Telemetry) if err != nil { - return nil, fmt.Errorf("Failed to create client connection: %v", err) + return nil, err } telemetry := NewTelemetryClientFunc(conn) @@ -163,10 +155,9 @@ func DoGetMetricReportDefinition(ctx context.Context, req teleproto.TelemetryReq // DoGetMetricReport defines the RPC call function for // the GetMetricReport from telemetry micro service func DoGetMetricReport(ctx context.Context, req teleproto.TelemetryRequest) (*teleproto.TelemetryResponse, error) { - ctx = common.CreateMetadata(ctx) - conn, err := ClientFunc(services.Telemetry) + ctx, conn, err := getConnection(ctx, services.Telemetry) if err != nil { - return nil, fmt.Errorf("Failed to create client connection: %v", err) + return nil, err } telemetry := NewTelemetryClientFunc(conn) @@ -182,10 +173,9 @@ func DoGetMetricReport(ctx context.Context, req teleproto.TelemetryRequest) (*te // DoGetTrigger defines the RPC call function for // the GetTrigger from telemetry micro service func DoGetTrigger(ctx context.Context, req teleproto.TelemetryRequest) (*teleproto.TelemetryResponse, error) { - ctx = common.CreateMetadata(ctx) - conn, err := ClientFunc(services.Telemetry) + ctx, conn, err := getConnection(ctx, services.Telemetry) if err != nil { - return nil, fmt.Errorf("Failed to create client connection: %v", err) + return nil, err } telemetry := NewTelemetryClientFunc(conn) @@ -201,10 +191,9 @@ func DoGetTrigger(ctx context.Context, req teleproto.TelemetryRequest) (*telepro // DoUpdateTrigger defines the RPC call function for // the UpdateTrigger from telemetry micro service func DoUpdateTrigger(ctx context.Context, req teleproto.TelemetryRequest) (*teleproto.TelemetryResponse, error) { - ctx = common.CreateMetadata(ctx) - conn, err := ClientFunc(services.Telemetry) + ctx, conn, err := getConnection(ctx, services.Telemetry) if err != nil { - return nil, fmt.Errorf("Failed to create client connection: %v", err) + return nil, err } telemetry := NewTelemetryClientFunc(conn) From 3c9b21a0e7404a5506642cecc38212e1fbbb1f04 Mon Sep 17 00:00:00 2001 From: Banoshi Date: Fri, 16 Jun 2023 02:42:09 +0530 Subject: [PATCH 06/19] ran go tools --- svc-api/rpc/account.go | 3 +++ svc-api/rpc/aggregator.go | 1 - 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/svc-api/rpc/account.go b/svc-api/rpc/account.go index d33a62894..6726e1d69 100644 --- a/svc-api/rpc/account.go +++ b/svc-api/rpc/account.go @@ -56,6 +56,7 @@ func DoAccountCreationRequest(ctx context.Context, req accountproto.CreateAccoun if err != nil { return nil, fmt.Errorf("Failed to create client connection: %v", err) } + account := NewAccountClientFunc(conn) resp, err := account.Create(ctx, &req) @@ -74,6 +75,7 @@ func DoGetAllAccountRequest(ctx context.Context, req accountproto.AccountRequest if err != nil { return nil, fmt.Errorf("Failed to create client connection: %v", err) } + account := NewAccountClientFunc(conn) resp, err := account.GetAllAccounts(ctx, &req) @@ -129,6 +131,7 @@ func DoAccountDeleteRequest(ctx context.Context, req accountproto.DeleteAccountR if err != nil { return nil, fmt.Errorf("Failed to create client connection: %v", err) } + account := NewAccountClientFunc(conn) resp, err := account.Delete(ctx, &req) diff --git a/svc-api/rpc/aggregator.go b/svc-api/rpc/aggregator.go index 4bd6f7cf4..4c917f639 100644 --- a/svc-api/rpc/aggregator.go +++ b/svc-api/rpc/aggregator.go @@ -56,7 +56,6 @@ func DoResetRequest(ctx context.Context, req aggregatorproto.AggregatorRequest) if err != nil { return nil, fmt.Errorf("Failed to create client connection: %v", err) } - aggregator := NewAggregatorClientFunc(conn) resp, err := aggregator.Reset(ctx, &req) From db600adc995005c5c82f298377cbce1599a4d1c2 Mon Sep 17 00:00:00 2001 From: Banoshi Date: Fri, 16 Jun 2023 02:53:30 +0530 Subject: [PATCH 07/19] refactor code --- svc-api/rpc/account.go | 40 +++++++-------- svc-api/rpc/aggregator.go | 101 +++++++++++++++++++++++--------------- svc-api/rpc/chassis.go | 31 +++++++----- svc-api/rpc/events.go | 31 +++++++----- svc-api/rpc/fabrics.go | 16 +++--- svc-api/rpc/licenses.go | 21 +++++--- svc-api/rpc/managers.go | 46 ++++++++++------- svc-api/rpc/role.go | 21 +++++--- svc-api/rpc/sessions.go | 20 +++++--- svc-api/rpc/system.go | 56 ++++++++++++--------- svc-api/rpc/task.go | 49 ++++++++++-------- svc-api/rpc/telemetry.go | 51 +++++++++++-------- 12 files changed, 286 insertions(+), 197 deletions(-) diff --git a/svc-api/rpc/account.go b/svc-api/rpc/account.go index 2f832404a..6726e1d69 100644 --- a/svc-api/rpc/account.go +++ b/svc-api/rpc/account.go @@ -22,7 +22,6 @@ import ( "github.com/ODIM-Project/ODIM/lib-utilities/common" accountproto "github.com/ODIM-Project/ODIM/lib-utilities/proto/account" "github.com/ODIM-Project/ODIM/lib-utilities/services" - "google.golang.org/grpc" ) // helper functions @@ -34,9 +33,10 @@ var ( // DoGetAccountServiceRequest defines the RPC call function for // the GetAccountService from account-session micro service func DoGetAccountServiceRequest(ctx context.Context, req accountproto.AccountRequest) (*accountproto.AccountResponse, error) { - ctx, conn, err := getConnection(ctx, services.AccountSession) + ctx = common.CreateMetadata(ctx) + conn, err := ClientFunc(services.AccountSession) if err != nil { - return nil, err + return nil, fmt.Errorf("Failed to create client connection: %v", err) } account := NewAccountClientFunc(conn) @@ -51,9 +51,10 @@ func DoGetAccountServiceRequest(ctx context.Context, req accountproto.AccountReq // DoAccountCreationRequest defines the RPC call function for // the AccountCreation from account-session micro service func DoAccountCreationRequest(ctx context.Context, req accountproto.CreateAccountRequest) (*accountproto.AccountResponse, error) { - ctx, conn, err := getConnection(ctx, services.AccountSession) + ctx = common.CreateMetadata(ctx) + conn, err := ClientFunc(services.AccountSession) if err != nil { - return nil, err + return nil, fmt.Errorf("Failed to create client connection: %v", err) } account := NewAccountClientFunc(conn) @@ -69,9 +70,10 @@ func DoAccountCreationRequest(ctx context.Context, req accountproto.CreateAccoun // DoGetAllAccountRequest defines the RPC call function for // the GetAllAccount from account-session micro service func DoGetAllAccountRequest(ctx context.Context, req accountproto.AccountRequest) (*accountproto.AccountResponse, error) { - ctx, conn, err := getConnection(ctx, services.AccountSession) + ctx = common.CreateMetadata(ctx) + conn, err := ClientFunc(services.AccountSession) if err != nil { - return nil, err + return nil, fmt.Errorf("Failed to create client connection: %v", err) } account := NewAccountClientFunc(conn) @@ -87,9 +89,10 @@ func DoGetAllAccountRequest(ctx context.Context, req accountproto.AccountRequest // DoGetAccountRequest defines the RPC call function for // the GetAccount from account-session micro service func DoGetAccountRequest(ctx context.Context, req accountproto.GetAccountRequest) (*accountproto.AccountResponse, error) { - ctx, conn, err := getConnection(ctx, services.AccountSession) + ctx = common.CreateMetadata(ctx) + conn, err := ClientFunc(services.AccountSession) if err != nil { - return nil, err + return nil, fmt.Errorf("Failed to create client connection: %v", err) } account := NewAccountClientFunc(conn) @@ -105,9 +108,10 @@ func DoGetAccountRequest(ctx context.Context, req accountproto.GetAccountRequest // DoUpdateAccountRequest defines the RPC call function for // the UpdateAccount from account-session micro service func DoUpdateAccountRequest(ctx context.Context, req accountproto.UpdateAccountRequest) (*accountproto.AccountResponse, error) { - ctx, conn, err := getConnection(ctx, services.AccountSession) + ctx = common.CreateMetadata(ctx) + conn, err := ClientFunc(services.AccountSession) if err != nil { - return nil, err + return nil, fmt.Errorf("Failed to create client connection: %v", err) } account := NewAccountClientFunc(conn) @@ -122,9 +126,10 @@ func DoUpdateAccountRequest(ctx context.Context, req accountproto.UpdateAccountR // DoAccountDeleteRequest defines the RPC call function for // the AccountDelete from account-session micro service func DoAccountDeleteRequest(ctx context.Context, req accountproto.DeleteAccountRequest) (*accountproto.AccountResponse, error) { - ctx, conn, err := getConnection(ctx, services.AccountSession) + ctx = common.CreateMetadata(ctx) + conn, err := ClientFunc(services.AccountSession) if err != nil { - return nil, err + return nil, fmt.Errorf("Failed to create client connection: %v", err) } account := NewAccountClientFunc(conn) @@ -136,12 +141,3 @@ func DoAccountDeleteRequest(ctx context.Context, req accountproto.DeleteAccountR defer conn.Close() return resp, err } - -func getConnection(ctx context.Context, service string) (context.Context, *grpc.ClientConn, error) { - ctx = common.CreateMetadata(ctx) - conn, err := ClientFunc(service) - if err != nil { - return ctx, nil, fmt.Errorf("Failed to create client connection: %v", err) - } - return ctx, conn, nil -} diff --git a/svc-api/rpc/aggregator.go b/svc-api/rpc/aggregator.go index fa82bb638..4c917f639 100644 --- a/svc-api/rpc/aggregator.go +++ b/svc-api/rpc/aggregator.go @@ -19,6 +19,7 @@ import ( "context" "fmt" + "github.com/ODIM-Project/ODIM/lib-utilities/common" aggregatorproto "github.com/ODIM-Project/ODIM/lib-utilities/proto/aggregator" "github.com/ODIM-Project/ODIM/lib-utilities/services" ) @@ -31,9 +32,10 @@ var ( // DoGetAggregationService defines the RPC call function for // the GetAggregationService from aggregator micro service func DoGetAggregationService(ctx context.Context, req aggregatorproto.AggregatorRequest) (*aggregatorproto.AggregatorResponse, error) { - ctx, conn, err := getConnection(ctx, services.Aggregator) + ctx = common.CreateMetadata(ctx) + conn, err := ClientFunc(services.Aggregator) if err != nil { - return nil, err + return nil, fmt.Errorf("Failed to create client connection: %v", err) } aggregator := NewAggregatorClientFunc(conn) @@ -49,9 +51,10 @@ func DoGetAggregationService(ctx context.Context, req aggregatorproto.Aggregator // DoResetRequest defines the RPC call function for // the Reset from aggregator micro service func DoResetRequest(ctx context.Context, req aggregatorproto.AggregatorRequest) (*aggregatorproto.AggregatorResponse, error) { - ctx, conn, err := getConnection(ctx, services.Aggregator) + ctx = common.CreateMetadata(ctx) + conn, err := ClientFunc(services.Aggregator) if err != nil { - return nil, err + return nil, fmt.Errorf("Failed to create client connection: %v", err) } aggregator := NewAggregatorClientFunc(conn) @@ -66,9 +69,10 @@ func DoResetRequest(ctx context.Context, req aggregatorproto.AggregatorRequest) // DoSetDefaultBootOrderRequest defines the RPC call function for // the SetDefaultBootOrder from aggregator micro service func DoSetDefaultBootOrderRequest(ctx context.Context, req aggregatorproto.AggregatorRequest) (*aggregatorproto.AggregatorResponse, error) { - ctx, conn, err := getConnection(ctx, services.Aggregator) + ctx = common.CreateMetadata(ctx) + conn, err := ClientFunc(services.Aggregator) if err != nil { - return nil, err + return nil, fmt.Errorf("Failed to create client connection: %v", err) } aggregator := NewAggregatorClientFunc(conn) @@ -84,9 +88,10 @@ func DoSetDefaultBootOrderRequest(ctx context.Context, req aggregatorproto.Aggre // DoAddAggregationSource defines the RPC call function for // the AddAggregationSource from aggregator micro service func DoAddAggregationSource(ctx context.Context, req aggregatorproto.AggregatorRequest) (*aggregatorproto.AggregatorResponse, error) { - ctx, conn, err := getConnection(ctx, services.Aggregator) + ctx = common.CreateMetadata(ctx) + conn, err := ClientFunc(services.Aggregator) if err != nil { - return nil, err + return nil, fmt.Errorf("Failed to create client connection: %v", err) } aggregator := NewAggregatorClientFunc(conn) @@ -102,9 +107,10 @@ func DoAddAggregationSource(ctx context.Context, req aggregatorproto.AggregatorR // DoGetAllAggregationSource defines the RPC call function for // the GetAllAggregationSource from aggregator micro service func DoGetAllAggregationSource(ctx context.Context, req aggregatorproto.AggregatorRequest) (*aggregatorproto.AggregatorResponse, error) { - ctx, conn, err := getConnection(ctx, services.Aggregator) + ctx = common.CreateMetadata(ctx) + conn, err := ClientFunc(services.Aggregator) if err != nil { - return nil, err + return nil, fmt.Errorf("Failed to create client connection: %v", err) } aggregator := NewAggregatorClientFunc(conn) @@ -120,9 +126,10 @@ func DoGetAllAggregationSource(ctx context.Context, req aggregatorproto.Aggregat // DoGetAggregationSource defines the RPC call function for // the GetAggregationSource from aggregator micro service func DoGetAggregationSource(ctx context.Context, req aggregatorproto.AggregatorRequest) (*aggregatorproto.AggregatorResponse, error) { - ctx, conn, err := getConnection(ctx, services.Aggregator) + ctx = common.CreateMetadata(ctx) + conn, err := ClientFunc(services.Aggregator) if err != nil { - return nil, err + return nil, fmt.Errorf("Failed to create client connection: %v", err) } aggregator := NewAggregatorClientFunc(conn) @@ -138,9 +145,10 @@ func DoGetAggregationSource(ctx context.Context, req aggregatorproto.AggregatorR // DoUpdateAggregationSource defines the RPC call function for // the UpdateAggregationSource from aggregator micro service func DoUpdateAggregationSource(ctx context.Context, req aggregatorproto.AggregatorRequest) (*aggregatorproto.AggregatorResponse, error) { - ctx, conn, err := getConnection(ctx, services.Aggregator) + ctx = common.CreateMetadata(ctx) + conn, err := ClientFunc(services.Aggregator) if err != nil { - return nil, err + return nil, fmt.Errorf("Failed to create client connection: %v", err) } aggregator := NewAggregatorClientFunc(conn) @@ -156,9 +164,10 @@ func DoUpdateAggregationSource(ctx context.Context, req aggregatorproto.Aggregat // DoDeleteAggregationSource defines the RPC call function for // the DeleteAggregationSource from aggregator micro service func DoDeleteAggregationSource(ctx context.Context, req aggregatorproto.AggregatorRequest) (*aggregatorproto.AggregatorResponse, error) { - ctx, conn, err := getConnection(ctx, services.Aggregator) + ctx = common.CreateMetadata(ctx) + conn, err := ClientFunc(services.Aggregator) if err != nil { - return nil, err + return nil, fmt.Errorf("Failed to create client connection: %v", err) } aggregator := NewAggregatorClientFunc(conn) @@ -174,9 +183,10 @@ func DoDeleteAggregationSource(ctx context.Context, req aggregatorproto.Aggregat // DoCreateAggregate defines the RPC call function for // the CreateAggregate from aggregator micro service func DoCreateAggregate(ctx context.Context, req aggregatorproto.AggregatorRequest) (*aggregatorproto.AggregatorResponse, error) { - ctx, conn, err := getConnection(ctx, services.Aggregator) + ctx = common.CreateMetadata(ctx) + conn, err := ClientFunc(services.Aggregator) if err != nil { - return nil, err + return nil, fmt.Errorf("Failed to create client connection: %v", err) } aggregator := NewAggregatorClientFunc(conn) @@ -192,9 +202,10 @@ func DoCreateAggregate(ctx context.Context, req aggregatorproto.AggregatorReques // DoGetAggregateCollection defines the RPC call function for // the get aggregate collections from aggregator micro service func DoGetAggregateCollection(ctx context.Context, req aggregatorproto.AggregatorRequest) (*aggregatorproto.AggregatorResponse, error) { - ctx, conn, err := getConnection(ctx, services.Aggregator) + ctx = common.CreateMetadata(ctx) + conn, err := ClientFunc(services.Aggregator) if err != nil { - return nil, err + return nil, fmt.Errorf("Failed to create client connection: %v", err) } aggregator := NewAggregatorClientFunc(conn) @@ -210,9 +221,10 @@ func DoGetAggregateCollection(ctx context.Context, req aggregatorproto.Aggregato // DoGeteAggregate defines the RPC call function for // the get aggregate from aggregator micro service func DoGeteAggregate(ctx context.Context, req aggregatorproto.AggregatorRequest) (*aggregatorproto.AggregatorResponse, error) { - ctx, conn, err := getConnection(ctx, services.Aggregator) + ctx = common.CreateMetadata(ctx) + conn, err := ClientFunc(services.Aggregator) if err != nil { - return nil, err + return nil, fmt.Errorf("Failed to create client connection: %v", err) } aggregator := NewAggregatorClientFunc(conn) @@ -228,9 +240,10 @@ func DoGeteAggregate(ctx context.Context, req aggregatorproto.AggregatorRequest) // DoDeleteAggregate defines the RPC call function for // the delete aggregate from aggregator micro service func DoDeleteAggregate(ctx context.Context, req aggregatorproto.AggregatorRequest) (*aggregatorproto.AggregatorResponse, error) { - ctx, conn, err := getConnection(ctx, services.Aggregator) + ctx = common.CreateMetadata(ctx) + conn, err := ClientFunc(services.Aggregator) if err != nil { - return nil, err + return nil, fmt.Errorf("Failed to create client connection: %v", err) } aggregator := NewAggregatorClientFunc(conn) @@ -246,9 +259,10 @@ func DoDeleteAggregate(ctx context.Context, req aggregatorproto.AggregatorReques // DoAddElementsToAggregate defines the RPC call function for // the add elements to an aggregate from aggregator micro service func DoAddElementsToAggregate(ctx context.Context, req aggregatorproto.AggregatorRequest) (*aggregatorproto.AggregatorResponse, error) { - ctx, conn, err := getConnection(ctx, services.Aggregator) + ctx = common.CreateMetadata(ctx) + conn, err := ClientFunc(services.Aggregator) if err != nil { - return nil, err + return nil, fmt.Errorf("Failed to create client connection: %v", err) } aggregator := NewAggregatorClientFunc(conn) @@ -264,9 +278,10 @@ func DoAddElementsToAggregate(ctx context.Context, req aggregatorproto.Aggregato // DoRemoveElementsFromAggregate defines the RPC call function for // the remove elements from an aggregate from aggregator micro service func DoRemoveElementsFromAggregate(ctx context.Context, req aggregatorproto.AggregatorRequest) (*aggregatorproto.AggregatorResponse, error) { - ctx, conn, err := getConnection(ctx, services.Aggregator) + ctx = common.CreateMetadata(ctx) + conn, err := ClientFunc(services.Aggregator) if err != nil { - return nil, err + return nil, fmt.Errorf("Failed to create client connection: %v", err) } aggregator := NewAggregatorClientFunc(conn) @@ -282,9 +297,10 @@ func DoRemoveElementsFromAggregate(ctx context.Context, req aggregatorproto.Aggr // DoResetAggregateElements defines the RPC call function for // the reset elements of an aggregate from aggregator micro service func DoResetAggregateElements(ctx context.Context, req aggregatorproto.AggregatorRequest) (*aggregatorproto.AggregatorResponse, error) { - ctx, conn, err := getConnection(ctx, services.Aggregator) + ctx = common.CreateMetadata(ctx) + conn, err := ClientFunc(services.Aggregator) if err != nil { - return nil, err + return nil, fmt.Errorf("Failed to create client connection: %v", err) } aggregator := NewAggregatorClientFunc(conn) @@ -300,9 +316,10 @@ func DoResetAggregateElements(ctx context.Context, req aggregatorproto.Aggregato // DoSetDefaultBootOrderAggregateElements defines the RPC call function for // the set default boot order elements of an aggregate from aggregator micro service func DoSetDefaultBootOrderAggregateElements(ctx context.Context, req aggregatorproto.AggregatorRequest) (*aggregatorproto.AggregatorResponse, error) { - ctx, conn, err := getConnection(ctx, services.Aggregator) + ctx = common.CreateMetadata(ctx) + conn, err := ClientFunc(services.Aggregator) if err != nil { - return nil, err + return nil, fmt.Errorf("Failed to create client connection: %v", err) } aggregator := NewAggregatorClientFunc(conn) @@ -318,9 +335,10 @@ func DoSetDefaultBootOrderAggregateElements(ctx context.Context, req aggregatorp // DoGetAllConnectionMethods defines the RPC call function for // the get connection method collection from aggregator micro service func DoGetAllConnectionMethods(ctx context.Context, req aggregatorproto.AggregatorRequest) (*aggregatorproto.AggregatorResponse, error) { - ctx, conn, err := getConnection(ctx, services.Aggregator) + ctx = common.CreateMetadata(ctx) + conn, err := ClientFunc(services.Aggregator) if err != nil { - return nil, err + return nil, fmt.Errorf("Failed to create client connection: %v", err) } aggregator := NewAggregatorClientFunc(conn) @@ -336,9 +354,10 @@ func DoGetAllConnectionMethods(ctx context.Context, req aggregatorproto.Aggregat // DoGetConnectionMethod defines the RPC call function for // the get on connection method from aggregator micro service func DoGetConnectionMethod(ctx context.Context, req aggregatorproto.AggregatorRequest) (*aggregatorproto.AggregatorResponse, error) { - ctx, conn, err := getConnection(ctx, services.Aggregator) + ctx = common.CreateMetadata(ctx) + conn, err := ClientFunc(services.Aggregator) if err != nil { - return nil, err + return nil, fmt.Errorf("Failed to create client connection: %v", err) } aggregator := NewAggregatorClientFunc(conn) @@ -354,9 +373,10 @@ func DoGetConnectionMethod(ctx context.Context, req aggregatorproto.AggregatorRe // DoGetResetActionInfoService defines the RPC call function for // the GetResetActionInfoService from aggregator micro service func DoGetResetActionInfoService(ctx context.Context, req aggregatorproto.AggregatorRequest) (*aggregatorproto.AggregatorResponse, error) { - ctx, conn, err := getConnection(ctx, services.Aggregator) + ctx = common.CreateMetadata(ctx) + conn, err := ClientFunc(services.Aggregator) if err != nil { - return nil, err + return nil, fmt.Errorf("Failed to create client connection: %v", err) } aggregator := NewAggregatorClientFunc(conn) @@ -372,9 +392,10 @@ func DoGetResetActionInfoService(ctx context.Context, req aggregatorproto.Aggreg // DoGetSetDefaultBootOrderActionInfo defines the RPC call function for // the GetSetDefaultBootOrderActionInfo from aggregator micro service func DoGetSetDefaultBootOrderActionInfo(ctx context.Context, req aggregatorproto.AggregatorRequest) (*aggregatorproto.AggregatorResponse, error) { - ctx, conn, err := getConnection(ctx, services.Aggregator) + ctx = common.CreateMetadata(ctx) + conn, err := ClientFunc(services.Aggregator) if err != nil { - return nil, err + return nil, fmt.Errorf("Failed to create client connection: %v", err) } aggregator := NewAggregatorClientFunc(conn) diff --git a/svc-api/rpc/chassis.go b/svc-api/rpc/chassis.go index cf4baa35c..c742b2c1f 100644 --- a/svc-api/rpc/chassis.go +++ b/svc-api/rpc/chassis.go @@ -20,6 +20,7 @@ import ( "context" "fmt" + "github.com/ODIM-Project/ODIM/lib-utilities/common" chassisproto "github.com/ODIM-Project/ODIM/lib-utilities/proto/chassis" "github.com/ODIM-Project/ODIM/lib-utilities/services" ) @@ -31,9 +32,10 @@ var ( // GetChassisCollection will do the rpc call to collect all chassis func GetChassisCollection(ctx context.Context, req chassisproto.GetChassisRequest) (*chassisproto.GetChassisResponse, error) { - ctx, conn, err := getConnection(ctx, services.Systems) + ctx = common.CreateMetadata(ctx) + conn, err := ClientFunc(services.Systems) if err != nil { - return nil, err + return nil, fmt.Errorf("Failed to create client connection: %v", err) } asService := NewChassisClientFunc(conn) @@ -47,9 +49,10 @@ func GetChassisCollection(ctx context.Context, req chassisproto.GetChassisReques // GetChassisResource will do the rpc call to collect Chassis Resource func GetChassisResource(ctx context.Context, req chassisproto.GetChassisRequest) (*chassisproto.GetChassisResponse, error) { - ctx, conn, err := getConnection(ctx, services.Systems) + ctx = common.CreateMetadata(ctx) + conn, err := ClientFunc(services.Systems) if err != nil { - return nil, err + return nil, fmt.Errorf("Failed to create client connection: %v", err) } asService := NewChassisClientFunc(conn) @@ -63,9 +66,10 @@ func GetChassisResource(ctx context.Context, req chassisproto.GetChassisRequest) // GetChassis will do the rpc call to System Resource func GetChassis(ctx context.Context, req chassisproto.GetChassisRequest) (*chassisproto.GetChassisResponse, error) { - ctx, conn, err := getConnection(ctx, services.Systems) + ctx = common.CreateMetadata(ctx) + conn, err := ClientFunc(services.Systems) if err != nil { - return nil, err + return nil, fmt.Errorf("Failed to create client connection: %v", err) } asService := NewChassisClientFunc(conn) @@ -79,9 +83,10 @@ func GetChassis(ctx context.Context, req chassisproto.GetChassisRequest) (*chass // CreateChassis will do the rpc call to create a Chassis func CreateChassis(ctx context.Context, req chassisproto.CreateChassisRequest) (*chassisproto.GetChassisResponse, error) { - ctx, conn, err := getConnection(ctx, services.Systems) + ctx = common.CreateMetadata(ctx) + conn, err := ClientFunc(services.Systems) if err != nil { - return nil, err + return nil, fmt.Errorf("Failed to create client connection: %v", err) } service := NewChassisClientFunc(conn) @@ -95,9 +100,10 @@ func CreateChassis(ctx context.Context, req chassisproto.CreateChassisRequest) ( // DeleteChassis will do the rpc call to delete a chassis func DeleteChassis(ctx context.Context, req chassisproto.DeleteChassisRequest) (*chassisproto.GetChassisResponse, error) { - ctx, conn, err := getConnection(ctx, services.Systems) + ctx = common.CreateMetadata(ctx) + conn, err := ClientFunc(services.Systems) if err != nil { - return nil, err + return nil, fmt.Errorf("Failed to create client connection: %v", err) } service := NewChassisClientFunc(conn) @@ -111,9 +117,10 @@ func DeleteChassis(ctx context.Context, req chassisproto.DeleteChassisRequest) ( // UpdateChassis will do the rpc call to update a chassis func UpdateChassis(ctx context.Context, req chassisproto.UpdateChassisRequest) (*chassisproto.GetChassisResponse, error) { - ctx, conn, err := getConnection(ctx, services.Systems) + ctx = common.CreateMetadata(ctx) + conn, err := ClientFunc(services.Systems) if err != nil { - return nil, err + return nil, fmt.Errorf("Failed to create client connection: %v", err) } service := NewChassisClientFunc(conn) diff --git a/svc-api/rpc/events.go b/svc-api/rpc/events.go index 6e3b1d7b4..38c651634 100644 --- a/svc-api/rpc/events.go +++ b/svc-api/rpc/events.go @@ -19,6 +19,7 @@ import ( "context" "fmt" + "github.com/ODIM-Project/ODIM/lib-utilities/common" eventsproto "github.com/ODIM-Project/ODIM/lib-utilities/proto/events" "github.com/ODIM-Project/ODIM/lib-utilities/services" ) @@ -31,9 +32,10 @@ var ( // DoGetEventService defines the RPC call function for // the GetEventService from events micro service func DoGetEventService(ctx context.Context, req eventsproto.EventSubRequest) (*eventsproto.EventSubResponse, error) { - ctx, conn, err := getConnection(ctx, services.Events) + ctx = common.CreateMetadata(ctx) + conn, err := ClientFunc(services.Events) if err != nil { - return nil, err + return nil, fmt.Errorf("Failed to create client connection: %v", err) } events := NewEventsClientFunc(conn) @@ -49,9 +51,10 @@ func DoGetEventService(ctx context.Context, req eventsproto.EventSubRequest) (*e // DoCreateEventSubscription defines the RPC call function for // the CreateEventSubscription from events micro service func DoCreateEventSubscription(ctx context.Context, req eventsproto.EventSubRequest) (*eventsproto.EventSubResponse, error) { - ctx, conn, err := getConnection(ctx, services.Events) + ctx = common.CreateMetadata(ctx) + conn, err := ClientFunc(services.Events) if err != nil { - return nil, err + return nil, fmt.Errorf("Failed to create client connection: %v", err) } events := NewEventsClientFunc(conn) @@ -67,9 +70,10 @@ func DoCreateEventSubscription(ctx context.Context, req eventsproto.EventSubRequ // DoSubmitTestEvent defines the RPC call function for // the SubmitTestEvent from events micro service func DoSubmitTestEvent(ctx context.Context, req eventsproto.EventSubRequest) (*eventsproto.EventSubResponse, error) { - ctx, conn, err := getConnection(ctx, services.Events) + ctx = common.CreateMetadata(ctx) + conn, err := ClientFunc(services.Events) if err != nil { - return nil, err + return nil, fmt.Errorf("Failed to create client connection: %v", err) } events := NewEventsClientFunc(conn) @@ -85,9 +89,10 @@ func DoSubmitTestEvent(ctx context.Context, req eventsproto.EventSubRequest) (*e // DoGetEventSubscription defines the RPC call function for // the DoGetEventSubscription from events micro service func DoGetEventSubscription(ctx context.Context, req eventsproto.EventRequest) (*eventsproto.EventSubResponse, error) { - ctx, conn, err := getConnection(ctx, services.Events) + ctx = common.CreateMetadata(ctx) + conn, err := ClientFunc(services.Events) if err != nil { - return nil, err + return nil, fmt.Errorf("Failed to create client connection: %v", err) } events := NewEventsClientFunc(conn) @@ -103,9 +108,10 @@ func DoGetEventSubscription(ctx context.Context, req eventsproto.EventRequest) ( // DoDeleteEventSubscription defines the RPC call function for // the DoDeleteEventSubscription from events micro service func DoDeleteEventSubscription(ctx context.Context, req eventsproto.EventRequest) (*eventsproto.EventSubResponse, error) { - ctx, conn, err := getConnection(ctx, services.Events) + ctx = common.CreateMetadata(ctx) + conn, err := ClientFunc(services.Events) if err != nil { - return nil, err + return nil, fmt.Errorf("Failed to create client connection: %v", err) } events := NewEventsClientFunc(conn) @@ -121,9 +127,10 @@ func DoDeleteEventSubscription(ctx context.Context, req eventsproto.EventRequest // DoGetEventSubscriptionsCollection defines the RPC call function for // the DoGetEventSubscription from events micro service func DoGetEventSubscriptionsCollection(ctx context.Context, req eventsproto.EventRequest) (*eventsproto.EventSubResponse, error) { - ctx, conn, err := getConnection(ctx, services.Events) + ctx = common.CreateMetadata(ctx) + conn, err := ClientFunc(services.Events) if err != nil { - return nil, err + return nil, fmt.Errorf("Failed to create client connection: %v", err) } events := NewEventsClientFunc(conn) diff --git a/svc-api/rpc/fabrics.go b/svc-api/rpc/fabrics.go index 0e54497cc..9f899d589 100644 --- a/svc-api/rpc/fabrics.go +++ b/svc-api/rpc/fabrics.go @@ -19,6 +19,7 @@ import ( "context" "fmt" + "github.com/ODIM-Project/ODIM/lib-utilities/common" fabricsproto "github.com/ODIM-Project/ODIM/lib-utilities/proto/fabrics" "github.com/ODIM-Project/ODIM/lib-utilities/services" ) @@ -31,9 +32,10 @@ var ( // GetFabricResource defines the RPC call function for // the GetFabricResource from fabrics micro service func GetFabricResource(ctx context.Context, req fabricsproto.FabricRequest) (*fabricsproto.FabricResponse, error) { - ctx, conn, err := getConnection(ctx, services.Fabrics) + ctx = common.CreateMetadata(ctx) + conn, err := ClientFunc(services.Fabrics) if err != nil { - return nil, err + return nil, fmt.Errorf("Failed to create client connection: %v", err) } fab := NewFabricsClientFunc(conn) @@ -48,9 +50,10 @@ func GetFabricResource(ctx context.Context, req fabricsproto.FabricRequest) (*fa // UpdateFabricResource defines the RPC call function for creating/updating // the Fabric Resource such as Endpoints, Zones from fabrics micro service func UpdateFabricResource(ctx context.Context, req fabricsproto.FabricRequest) (*fabricsproto.FabricResponse, error) { - ctx, conn, err := getConnection(ctx, services.Fabrics) + ctx = common.CreateMetadata(ctx) + conn, err := ClientFunc(services.Fabrics) if err != nil { - return nil, err + return nil, fmt.Errorf("Failed to create client connection: %v", err) } fab := NewFabricsClientFunc(conn) @@ -66,9 +69,10 @@ func UpdateFabricResource(ctx context.Context, req fabricsproto.FabricRequest) ( // DeleteFabricResource defines the RPC call function for // the DeleteFabricResource from fabrics micro service func DeleteFabricResource(ctx context.Context, req fabricsproto.FabricRequest) (*fabricsproto.FabricResponse, error) { - ctx, conn, err := getConnection(ctx, services.Fabrics) + ctx = common.CreateMetadata(ctx) + conn, err := ClientFunc(services.Fabrics) if err != nil { - return nil, err + return nil, fmt.Errorf("Failed to create client connection: %v", err) } fab := NewFabricsClientFunc(conn) diff --git a/svc-api/rpc/licenses.go b/svc-api/rpc/licenses.go index d8682cb96..1aa6f0455 100644 --- a/svc-api/rpc/licenses.go +++ b/svc-api/rpc/licenses.go @@ -18,15 +18,17 @@ import ( "context" "fmt" + "github.com/ODIM-Project/ODIM/lib-utilities/common" licenseproto "github.com/ODIM-Project/ODIM/lib-utilities/proto/licenses" "github.com/ODIM-Project/ODIM/lib-utilities/services" ) // GetLicenseService will do the rpc call to get License Service Information func GetLicenseService(ctx context.Context, req licenseproto.GetLicenseServiceRequest) (*licenseproto.GetLicenseResponse, error) { - ctx, conn, err := getConnection(ctx, services.Licenses) + ctx = common.CreateMetadata(ctx) + conn, err := services.ODIMService.Client(services.Licenses) if err != nil { - return nil, err + return nil, fmt.Errorf("Failed to create client connection: %v", err) } defer conn.Close() licenseService := licenseproto.NewLicensesClient(conn) @@ -39,9 +41,10 @@ func GetLicenseService(ctx context.Context, req licenseproto.GetLicenseServiceRe // GetLicenseCollection will do the rpc call to get License Service Information func GetLicenseCollection(ctx context.Context, req licenseproto.GetLicenseRequest) (*licenseproto.GetLicenseResponse, error) { - ctx, conn, err := getConnection(ctx, services.Licenses) + ctx = common.CreateMetadata(ctx) + conn, err := services.ODIMService.Client(services.Licenses) if err != nil { - return nil, err + return nil, fmt.Errorf("Failed to create client connection: %v", err) } defer conn.Close() licenseService := licenseproto.NewLicensesClient(conn) @@ -54,9 +57,10 @@ func GetLicenseCollection(ctx context.Context, req licenseproto.GetLicenseReques // GetLicenseResource will do the rpc call to get License Service Information func GetLicenseResource(ctx context.Context, req licenseproto.GetLicenseResourceRequest) (*licenseproto.GetLicenseResponse, error) { - ctx, conn, err := getConnection(ctx, services.Licenses) + ctx = common.CreateMetadata(ctx) + conn, err := services.ODIMService.Client(services.Licenses) if err != nil { - return nil, err + return nil, fmt.Errorf("Failed to create client connection: %v", err) } defer conn.Close() licenseService := licenseproto.NewLicensesClient(conn) @@ -69,9 +73,10 @@ func GetLicenseResource(ctx context.Context, req licenseproto.GetLicenseResource // InstallLicenseService will do the rpc call to install License func InstallLicenseService(ctx context.Context, req licenseproto.InstallLicenseRequest) (*licenseproto.GetLicenseResponse, error) { - ctx, conn, err := getConnection(ctx, services.Licenses) + ctx = common.CreateMetadata(ctx) + conn, err := services.ODIMService.Client(services.Licenses) if err != nil { - return nil, err + return nil, fmt.Errorf("Failed to create client connection: %v", err) } defer conn.Close() licenseService := licenseproto.NewLicensesClient(conn) diff --git a/svc-api/rpc/managers.go b/svc-api/rpc/managers.go index 9100d6806..a027773a2 100644 --- a/svc-api/rpc/managers.go +++ b/svc-api/rpc/managers.go @@ -19,6 +19,7 @@ import ( "context" "fmt" + "github.com/ODIM-Project/ODIM/lib-utilities/common" managersproto "github.com/ODIM-Project/ODIM/lib-utilities/proto/managers" "github.com/ODIM-Project/ODIM/lib-utilities/services" ) @@ -30,9 +31,10 @@ var ( // GetManagersCollection will do the rpc call to collect Managers func GetManagersCollection(ctx context.Context, req managersproto.ManagerRequest) (*managersproto.ManagerResponse, error) { - ctx, conn, err := getConnection(ctx, services.Managers) + ctx = common.CreateMetadata(ctx) + conn, err := ClientFunc(services.Managers) if err != nil { - return nil, err + return nil, fmt.Errorf("Failed to create client connection: %v", err) } asService := NewManagersClientFunc(conn) @@ -46,9 +48,10 @@ func GetManagersCollection(ctx context.Context, req managersproto.ManagerRequest // GetManagers will do the rpc calls for the svc-managers func GetManagers(ctx context.Context, req managersproto.ManagerRequest) (*managersproto.ManagerResponse, error) { - ctx, conn, err := getConnection(ctx, services.Managers) + ctx = common.CreateMetadata(ctx) + conn, err := ClientFunc(services.Managers) if err != nil { - return nil, err + return nil, fmt.Errorf("Failed to create client connection: %v", err) } asService := NewManagersClientFunc(conn) @@ -62,9 +65,10 @@ func GetManagers(ctx context.Context, req managersproto.ManagerRequest) (*manage // GetManagersResource will do the rpc calls for the svc-managers func GetManagersResource(ctx context.Context, req managersproto.ManagerRequest) (*managersproto.ManagerResponse, error) { - ctx, conn, err := getConnection(ctx, services.Managers) + ctx = common.CreateMetadata(ctx) + conn, err := ClientFunc(services.Managers) if err != nil { - return nil, err + return nil, fmt.Errorf("Failed to create client connection: %v", err) } asService := NewManagersClientFunc(conn) @@ -78,9 +82,10 @@ func GetManagersResource(ctx context.Context, req managersproto.ManagerRequest) // VirtualMediaInsert will do the rpc calls for the svc-managers func VirtualMediaInsert(ctx context.Context, req managersproto.ManagerRequest) (*managersproto.ManagerResponse, error) { - ctx, conn, err := getConnection(ctx, services.Managers) + ctx = common.CreateMetadata(ctx) + conn, err := ClientFunc(services.Managers) if err != nil { - return nil, err + return nil, fmt.Errorf("Failed to create client connection: %v", err) } asService := NewManagersClientFunc(conn) @@ -94,9 +99,10 @@ func VirtualMediaInsert(ctx context.Context, req managersproto.ManagerRequest) ( // VirtualMediaEject will do the rpc calls for the svc-managers func VirtualMediaEject(ctx context.Context, req managersproto.ManagerRequest) (*managersproto.ManagerResponse, error) { - ctx, conn, err := getConnection(ctx, services.Managers) + ctx = common.CreateMetadata(ctx) + conn, err := ClientFunc(services.Managers) if err != nil { - return nil, err + return nil, fmt.Errorf("Failed to create client connection: %v", err) } asService := NewManagersClientFunc(conn) @@ -110,9 +116,10 @@ func VirtualMediaEject(ctx context.Context, req managersproto.ManagerRequest) (* // GetRemoteAccountService will do the rpc call to collect BMC accounts func GetRemoteAccountService(ctx context.Context, req managersproto.ManagerRequest) (*managersproto.ManagerResponse, error) { - ctx, conn, err := getConnection(ctx, services.Managers) + ctx = common.CreateMetadata(ctx) + conn, err := ClientFunc(services.Managers) if err != nil { - return nil, err + return nil, fmt.Errorf("Failed to create client connection: %v", err) } mService := NewManagersClientFunc(conn) @@ -126,9 +133,10 @@ func GetRemoteAccountService(ctx context.Context, req managersproto.ManagerReque // CreateRemoteAccountService will do the rpc call to create a new BMC account func CreateRemoteAccountService(ctx context.Context, req managersproto.ManagerRequest) (*managersproto.ManagerResponse, error) { - ctx, conn, err := getConnection(ctx, services.Managers) + ctx = common.CreateMetadata(ctx) + conn, err := ClientFunc(services.Managers) if err != nil { - return nil, err + return nil, fmt.Errorf("Failed to create client connection: %v", err) } mService := NewManagersClientFunc(conn) @@ -142,9 +150,10 @@ func CreateRemoteAccountService(ctx context.Context, req managersproto.ManagerRe // UpdateRemoteAccountService will do rpc call to update BMC account func UpdateRemoteAccountService(ctx context.Context, req managersproto.ManagerRequest) (*managersproto.ManagerResponse, error) { - ctx, conn, err := getConnection(ctx, services.Managers) + ctx = common.CreateMetadata(ctx) + conn, err := ClientFunc(services.Managers) if err != nil { - return nil, err + return nil, fmt.Errorf("Failed to create client connection: %v", err) } mService := NewManagersClientFunc(conn) @@ -158,9 +167,10 @@ func UpdateRemoteAccountService(ctx context.Context, req managersproto.ManagerRe // DeleteRemoteAccountService will do the rpc call to delete an existing BMC account func DeleteRemoteAccountService(ctx context.Context, req managersproto.ManagerRequest) (*managersproto.ManagerResponse, error) { - ctx, conn, err := getConnection(ctx, services.Managers) + ctx = common.CreateMetadata(ctx) + conn, err := ClientFunc(services.Managers) if err != nil { - return nil, err + return nil, fmt.Errorf("Failed to create client connection: %v", err) } mService := NewManagersClientFunc(conn) diff --git a/svc-api/rpc/role.go b/svc-api/rpc/role.go index a70c07be5..955e25e54 100644 --- a/svc-api/rpc/role.go +++ b/svc-api/rpc/role.go @@ -19,6 +19,7 @@ import ( "context" "fmt" + "github.com/ODIM-Project/ODIM/lib-utilities/common" roleproto "github.com/ODIM-Project/ODIM/lib-utilities/proto/role" "github.com/ODIM-Project/ODIM/lib-utilities/services" ) @@ -31,9 +32,10 @@ var ( // GetRole defines the RPC call function for // the GetRole from account-session micro service func GetRole(ctx context.Context, req roleproto.GetRoleRequest) (*roleproto.RoleResponse, error) { - ctx, conn, err := getConnection(ctx, services.AccountSession) + ctx = common.CreateMetadata(ctx) + conn, err := ClientFunc(services.AccountSession) if err != nil { - return nil, err + return nil, fmt.Errorf("Failed to create client connection: %v", err) } asService := NewRolesClientFunc(conn) @@ -48,9 +50,10 @@ func GetRole(ctx context.Context, req roleproto.GetRoleRequest) (*roleproto.Role // GetAllRoles defines the RPC call function for // the GetAllRoles from account-session micro service func GetAllRoles(ctx context.Context, req roleproto.GetRoleRequest) (*roleproto.RoleResponse, error) { - ctx, conn, err := getConnection(ctx, services.AccountSession) + ctx = common.CreateMetadata(ctx) + conn, err := ClientFunc(services.AccountSession) if err != nil { - return nil, err + return nil, fmt.Errorf("Failed to create client connection: %v", err) } asService := NewRolesClientFunc(conn) @@ -65,9 +68,10 @@ func GetAllRoles(ctx context.Context, req roleproto.GetRoleRequest) (*roleproto. // UpdateRole defines the RPC call function for // the UpdateRole from account-session micro service func UpdateRole(ctx context.Context, req roleproto.UpdateRoleRequest) (*roleproto.RoleResponse, error) { - ctx, conn, err := getConnection(ctx, services.AccountSession) + ctx = common.CreateMetadata(ctx) + conn, err := ClientFunc(services.AccountSession) if err != nil { - return nil, err + return nil, fmt.Errorf("Failed to create client connection: %v", err) } asService := NewRolesClientFunc(conn) @@ -81,9 +85,10 @@ func UpdateRole(ctx context.Context, req roleproto.UpdateRoleRequest) (*roleprot // DeleteRole defines the RPC call function for the DeleteRole from account-session microservice func DeleteRole(ctx context.Context, req roleproto.DeleteRoleRequest) (*roleproto.RoleResponse, error) { - ctx, conn, err := getConnection(ctx, services.AccountSession) + ctx = common.CreateMetadata(ctx) + conn, err := ClientFunc(services.AccountSession) if err != nil { - return nil, err + return nil, fmt.Errorf("Failed to create client connection: %v", err) } asService := NewRolesClientFunc(conn) diff --git a/svc-api/rpc/sessions.go b/svc-api/rpc/sessions.go index 1f2657da1..d938b4e1d 100644 --- a/svc-api/rpc/sessions.go +++ b/svc-api/rpc/sessions.go @@ -66,9 +66,10 @@ func DoSessionCreationRequest(ctx context.Context, req sessionproto.SessionCreat // DeleteSessionRequest will do the rpc call to delete session func DeleteSessionRequest(ctx context.Context, sessionID, sessionToken string) (*sessionproto.SessionResponse, error) { - ctx, conn, err := getConnection(ctx, services.AccountSession) + ctx = common.CreateMetadata(ctx) + conn, err := ClientFunc(services.AccountSession) if err != nil { - return nil, err + return nil, fmt.Errorf("Failed to create client connection: %v", err) } asService := NewSessionClientFunc(conn) @@ -87,9 +88,10 @@ func DeleteSessionRequest(ctx context.Context, sessionID, sessionToken string) ( // GetSessionRequest will do the rpc call to get session func GetSessionRequest(ctx context.Context, sessionID, sessionToken string) (*sessionproto.SessionResponse, error) { - ctx, conn, err := getConnection(ctx, services.AccountSession) + ctx = common.CreateMetadata(ctx) + conn, err := ClientFunc(services.AccountSession) if err != nil { - return nil, err + return nil, fmt.Errorf("Failed to create client connection: %v", err) } asService := NewSessionClientFunc(conn) @@ -108,9 +110,10 @@ func GetSessionRequest(ctx context.Context, sessionID, sessionToken string) (*se // GetAllActiveSessionRequest will do the rpc call to get session func GetAllActiveSessionRequest(ctx context.Context, sessionID, sessionToken string) (*sessionproto.SessionResponse, error) { - ctx, conn, err := getConnection(ctx, services.AccountSession) + ctx = common.CreateMetadata(ctx) + conn, err := ClientFunc(services.AccountSession) if err != nil { - return nil, err + return nil, fmt.Errorf("Failed to create client connection: %v", err) } asService := NewSessionClientFunc(conn) @@ -129,9 +132,10 @@ func GetAllActiveSessionRequest(ctx context.Context, sessionID, sessionToken str // GetSessionServiceRequest will do the rpc call to check session func GetSessionServiceRequest(ctx context.Context) (*sessionproto.SessionResponse, error) { - ctx, conn, err := getConnection(ctx, services.AccountSession) + ctx = common.CreateMetadata(ctx) + conn, err := ClientFunc(services.AccountSession) if err != nil { - return nil, err + return nil, fmt.Errorf("Failed to create client connection: %v", err) } asService := NewSessionClientFunc(conn) diff --git a/svc-api/rpc/system.go b/svc-api/rpc/system.go index 6add90f7b..f4e170f89 100644 --- a/svc-api/rpc/system.go +++ b/svc-api/rpc/system.go @@ -19,6 +19,7 @@ import ( "context" "fmt" + "github.com/ODIM-Project/ODIM/lib-utilities/common" systemsproto "github.com/ODIM-Project/ODIM/lib-utilities/proto/systems" "github.com/ODIM-Project/ODIM/lib-utilities/services" ) @@ -30,9 +31,10 @@ var ( // GetSystemsCollection will do the rpc call to collect Systems from odimra func GetSystemsCollection(ctx context.Context, req systemsproto.GetSystemsRequest) (*systemsproto.SystemsResponse, error) { - ctx, conn, err := getConnection(ctx, services.Systems) + ctx = common.CreateMetadata(ctx) + conn, err := ClientFunc(services.Systems) if err != nil { - return nil, err + return nil, fmt.Errorf("Failed to create client connection: %v", err) } asService := NewSystemsClientFunc(conn) @@ -46,9 +48,10 @@ func GetSystemsCollection(ctx context.Context, req systemsproto.GetSystemsReques // GetSystemRequestRPC will do the rpc calls for the svc-systems func GetSystemRequestRPC(ctx context.Context, req systemsproto.GetSystemsRequest) (*systemsproto.SystemsResponse, error) { - ctx, conn, err := getConnection(ctx, services.Systems) + ctx = common.CreateMetadata(ctx) + conn, err := ClientFunc(services.Systems) if err != nil { - return nil, err + return nil, fmt.Errorf("Failed to create client connection: %v", err) } asService := NewSystemsClientFunc(conn) @@ -62,9 +65,10 @@ func GetSystemRequestRPC(ctx context.Context, req systemsproto.GetSystemsRequest // GetSystemResource will do the rpc call to collect System Resource func GetSystemResource(ctx context.Context, req systemsproto.GetSystemsRequest) (*systemsproto.SystemsResponse, error) { - ctx, conn, err := getConnection(ctx, services.Systems) + ctx = common.CreateMetadata(ctx) + conn, err := ClientFunc(services.Systems) if err != nil { - return nil, err + return nil, fmt.Errorf("Failed to create client connection: %v", err) } asService := NewSystemsClientFunc(conn) @@ -78,9 +82,10 @@ func GetSystemResource(ctx context.Context, req systemsproto.GetSystemsRequest) // ComputerSystemReset will do the rpc call to reset the computer system func ComputerSystemReset(ctx context.Context, req systemsproto.ComputerSystemResetRequest) (*systemsproto.SystemsResponse, error) { - ctx, conn, err := getConnection(ctx, services.Systems) + ctx = common.CreateMetadata(ctx) + conn, err := ClientFunc(services.Systems) if err != nil { - return nil, err + return nil, fmt.Errorf("Failed to create client connection: %v", err) } asService := NewSystemsClientFunc(conn) @@ -94,9 +99,10 @@ func ComputerSystemReset(ctx context.Context, req systemsproto.ComputerSystemRes // SetDefaultBootOrder will do the rpc call to set the default boot order of computer system func SetDefaultBootOrder(ctx context.Context, req systemsproto.DefaultBootOrderRequest) (*systemsproto.SystemsResponse, error) { - ctx, conn, err := getConnection(ctx, services.Systems) + ctx = common.CreateMetadata(ctx) + conn, err := ClientFunc(services.Systems) if err != nil { - return nil, err + return nil, fmt.Errorf("Failed to create client connection: %v", err) } asService := NewSystemsClientFunc(conn) @@ -110,9 +116,10 @@ func SetDefaultBootOrder(ctx context.Context, req systemsproto.DefaultBootOrderR // ChangeBiosSettings will do the rpc call to change bios settings func ChangeBiosSettings(ctx context.Context, req systemsproto.BiosSettingsRequest) (*systemsproto.SystemsResponse, error) { - ctx, conn, err := getConnection(ctx, services.Systems) + ctx = common.CreateMetadata(ctx) + conn, err := ClientFunc(services.Systems) if err != nil { - return nil, err + return nil, fmt.Errorf("Failed to create client connection: %v", err) } asService := NewSystemsClientFunc(conn) @@ -126,9 +133,10 @@ func ChangeBiosSettings(ctx context.Context, req systemsproto.BiosSettingsReques // ChangeBootOrderSettings will do the rpc call to change Boot Order settings func ChangeBootOrderSettings(ctx context.Context, req systemsproto.BootOrderSettingsRequest) (*systemsproto.SystemsResponse, error) { - ctx, conn, err := getConnection(ctx, services.Systems) + ctx = common.CreateMetadata(ctx) + conn, err := ClientFunc(services.Systems) if err != nil { - return nil, err + return nil, fmt.Errorf("Failed to create client connection: %v", err) } asService := NewSystemsClientFunc(conn) @@ -142,9 +150,10 @@ func ChangeBootOrderSettings(ctx context.Context, req systemsproto.BootOrderSett // CreateVolume will do the rpc call to create a volume under storage func CreateVolume(ctx context.Context, req systemsproto.VolumeRequest) (*systemsproto.SystemsResponse, error) { - ctx, conn, err := getConnection(ctx, services.Systems) + ctx = common.CreateMetadata(ctx) + conn, err := ClientFunc(services.Systems) if err != nil { - return nil, err + return nil, fmt.Errorf("Failed to create client connection: %v", err) } asService := NewSystemsClientFunc(conn) @@ -158,9 +167,10 @@ func CreateVolume(ctx context.Context, req systemsproto.VolumeRequest) (*systems // DeleteVolume will do the rpc call to DeleteVolume a volume under storage func DeleteVolume(ctx context.Context, req systemsproto.VolumeRequest) (*systemsproto.SystemsResponse, error) { - ctx, conn, err := getConnection(ctx, services.Systems) + ctx = common.CreateMetadata(ctx) + conn, err := ClientFunc(services.Systems) if err != nil { - return nil, err + return nil, fmt.Errorf("Failed to create client connection: %v", err) } asService := NewSystemsClientFunc(conn) @@ -174,9 +184,10 @@ func DeleteVolume(ctx context.Context, req systemsproto.VolumeRequest) (*systems // UpdateSecureBoot will do the rpc call to UpdateSecureBoot func UpdateSecureBoot(ctx context.Context, req systemsproto.SecureBootRequest) (*systemsproto.SystemsResponse, error) { - ctx, conn, err := getConnection(ctx, services.Systems) + ctx = common.CreateMetadata(ctx) + conn, err := ClientFunc(services.Systems) if err != nil { - return nil, err + return nil, fmt.Errorf("Failed to create client connection: %v", err) } asService := NewSystemsClientFunc(conn) @@ -190,9 +201,10 @@ func UpdateSecureBoot(ctx context.Context, req systemsproto.SecureBootRequest) ( // ResetSecureBoot will do the rpc call to ResetSecureBoot func ResetSecureBoot(ctx context.Context, req systemsproto.SecureBootRequest) (*systemsproto.SystemsResponse, error) { - ctx, conn, err := getConnection(ctx, services.Systems) + ctx = common.CreateMetadata(ctx) + conn, err := ClientFunc(services.Systems) if err != nil { - return nil, err + return nil, fmt.Errorf("Failed to create client connection: %v", err) } asService := NewSystemsClientFunc(conn) diff --git a/svc-api/rpc/task.go b/svc-api/rpc/task.go index c7ce961fe..4ffa0603c 100644 --- a/svc-api/rpc/task.go +++ b/svc-api/rpc/task.go @@ -34,9 +34,10 @@ var ( // DeleteTaskRequest will do the rpc calls for the svc-task DeleteTask func DeleteTaskRequest(ctx context.Context, req *taskproto.GetTaskRequest) (*taskproto.TaskResponse, error) { - ctx, conn, err := getConnection(ctx, services.Tasks) - if err != nil { - return nil, err + ctx = common.CreateMetadata(ctx) + conn, connErr := ClientFunc(services.Tasks) + if connErr != nil { + return nil, fmt.Errorf("Failed to create client connection: %v", connErr) } asService := NewGetTaskServiceClientFunc(conn) @@ -58,9 +59,10 @@ func DeleteTaskRequest(ctx context.Context, req *taskproto.GetTaskRequest) (*tas // GetTaskRequest will do the rpc calls for the svc-task GetTaskStatus func GetTaskRequest(ctx context.Context, req *taskproto.GetTaskRequest) (*taskproto.TaskResponse, error) { - ctx, conn, err := getConnection(ctx, services.Tasks) - if err != nil { - return nil, err + ctx = common.CreateMetadata(ctx) + conn, connErr := ClientFunc(services.Tasks) + if connErr != nil { + return nil, fmt.Errorf("Failed to create client connection: %v", connErr) } asService := NewGetTaskServiceClientFunc(conn) @@ -82,9 +84,10 @@ func GetTaskRequest(ctx context.Context, req *taskproto.GetTaskRequest) (*taskpr // GetSubTasks will do the rpc calls for the svc-task GetSubTasks func GetSubTasks(ctx context.Context, req *taskproto.GetTaskRequest) (*taskproto.TaskResponse, error) { - ctx, conn, err := getConnection(ctx, services.Tasks) - if err != nil { - return nil, err + ctx = common.CreateMetadata(ctx) + conn, connErr := ClientFunc(services.Tasks) + if connErr != nil { + return nil, fmt.Errorf("Failed to create client connection: %v", connErr) } tService := NewGetTaskServiceClientFunc(conn) @@ -106,9 +109,10 @@ func GetSubTasks(ctx context.Context, req *taskproto.GetTaskRequest) (*taskproto // GetSubTask will do the rpc calls for the svc-task GetSubTask func GetSubTask(ctx context.Context, req *taskproto.GetTaskRequest) (*taskproto.TaskResponse, error) { - ctx, conn, err := getConnection(ctx, services.Tasks) - if err != nil { - return nil, err + ctx = common.CreateMetadata(ctx) + conn, connErr := ClientFunc(services.Tasks) + if connErr != nil { + return nil, fmt.Errorf("Failed to create client connection: %v", connErr) } tService := NewGetTaskServiceClientFunc(conn) @@ -130,9 +134,10 @@ func GetSubTask(ctx context.Context, req *taskproto.GetTaskRequest) (*taskproto. // GetTaskMonitor will do the rpc calls for the svc-task GetTaskMonitor func GetTaskMonitor(ctx context.Context, req *taskproto.GetTaskRequest) (*taskproto.TaskResponse, error) { - ctx, conn, err := getConnection(ctx, services.Tasks) - if err != nil { - return nil, err + ctx = common.CreateMetadata(ctx) + conn, connErr := ClientFunc(services.Tasks) + if connErr != nil { + return nil, fmt.Errorf("Failed to create client connection: %v", connErr) } tService := NewGetTaskServiceClientFunc(conn) @@ -154,9 +159,10 @@ func GetTaskMonitor(ctx context.Context, req *taskproto.GetTaskRequest) (*taskpr // TaskCollection will perform the rpc call to svc-task TaskCollection func TaskCollection(ctx context.Context, req *taskproto.GetTaskRequest) (*taskproto.TaskResponse, error) { - ctx, conn, err := getConnection(ctx, services.Tasks) - if err != nil { - return nil, err + ctx = common.CreateMetadata(ctx) + conn, connErr := ClientFunc(services.Tasks) + if connErr != nil { + return nil, fmt.Errorf("Failed to create client connection: %v", connErr) } tService := NewGetTaskServiceClientFunc(conn) @@ -178,9 +184,10 @@ func TaskCollection(ctx context.Context, req *taskproto.GetTaskRequest) (*taskpr // GetTaskService will perform the rpc call to svc-task GetTaskService func GetTaskService(ctx context.Context, req *taskproto.GetTaskRequest) (*taskproto.TaskResponse, error) { - ctx, conn, err := getConnection(ctx, services.Tasks) - if err != nil { - return nil, err + ctx = common.CreateMetadata(ctx) + conn, connErr := ClientFunc(services.Tasks) + if connErr != nil { + return nil, fmt.Errorf("Failed to create client connection: %v", connErr) } tService := NewGetTaskServiceClientFunc(conn) diff --git a/svc-api/rpc/telemetry.go b/svc-api/rpc/telemetry.go index ab8715231..fa860c201 100644 --- a/svc-api/rpc/telemetry.go +++ b/svc-api/rpc/telemetry.go @@ -19,6 +19,7 @@ import ( "context" "fmt" + "github.com/ODIM-Project/ODIM/lib-utilities/common" teleproto "github.com/ODIM-Project/ODIM/lib-utilities/proto/telemetry" "github.com/ODIM-Project/ODIM/lib-utilities/services" ) @@ -31,9 +32,10 @@ var ( // DoGetTelemetryService defines the RPC call function for // the GetTelemetryService from telemetry micro service func DoGetTelemetryService(ctx context.Context, req teleproto.TelemetryRequest) (*teleproto.TelemetryResponse, error) { - ctx, conn, err := getConnection(ctx, services.Telemetry) + ctx = common.CreateMetadata(ctx) + conn, err := ClientFunc(services.Telemetry) if err != nil { - return nil, err + return nil, fmt.Errorf("Failed to create client connection: %v", err) } telemetry := NewTelemetryClientFunc(conn) @@ -49,9 +51,10 @@ func DoGetTelemetryService(ctx context.Context, req teleproto.TelemetryRequest) // DoGetMetricDefinitionCollection defines the RPC call function for // the GetMetricDefinitionCollection from telemetry micro service func DoGetMetricDefinitionCollection(ctx context.Context, req teleproto.TelemetryRequest) (*teleproto.TelemetryResponse, error) { - ctx, conn, err := getConnection(ctx, services.Telemetry) + ctx = common.CreateMetadata(ctx) + conn, err := ClientFunc(services.Telemetry) if err != nil { - return nil, err + return nil, fmt.Errorf("Failed to create client connection: %v", err) } telemetry := NewTelemetryClientFunc(conn) @@ -66,9 +69,10 @@ func DoGetMetricDefinitionCollection(ctx context.Context, req teleproto.Telemetr // DoGetMetricReportDefinitionCollection defines the RPC call function for // the GetMetricReportDefinitionCollection from telemetry micro service func DoGetMetricReportDefinitionCollection(ctx context.Context, req teleproto.TelemetryRequest) (*teleproto.TelemetryResponse, error) { - ctx, conn, err := getConnection(ctx, services.Telemetry) + ctx = common.CreateMetadata(ctx) + conn, err := ClientFunc(services.Telemetry) if err != nil { - return nil, err + return nil, fmt.Errorf("Failed to create client connection: %v", err) } telemetry := NewTelemetryClientFunc(conn) @@ -83,9 +87,10 @@ func DoGetMetricReportDefinitionCollection(ctx context.Context, req teleproto.Te // DoGetMetricReportCollection defines the RPC call function for // the GetMetricReportCollection from telemetry micro service func DoGetMetricReportCollection(ctx context.Context, req teleproto.TelemetryRequest) (*teleproto.TelemetryResponse, error) { - ctx, conn, err := getConnection(ctx, services.Telemetry) + ctx = common.CreateMetadata(ctx) + conn, err := ClientFunc(services.Telemetry) if err != nil { - return nil, err + return nil, fmt.Errorf("Failed to create client connection: %v", err) } telemetry := NewTelemetryClientFunc(conn) @@ -101,9 +106,10 @@ func DoGetMetricReportCollection(ctx context.Context, req teleproto.TelemetryReq // DoGetTriggerCollection defines the RPC call function for // the GetTriggerCollection from telemetry micro service func DoGetTriggerCollection(ctx context.Context, req teleproto.TelemetryRequest) (*teleproto.TelemetryResponse, error) { - ctx, conn, err := getConnection(ctx, services.Telemetry) + ctx = common.CreateMetadata(ctx) + conn, err := ClientFunc(services.Telemetry) if err != nil { - return nil, err + return nil, fmt.Errorf("Failed to create client connection: %v", err) } telemetry := NewTelemetryClientFunc(conn) @@ -119,9 +125,10 @@ func DoGetTriggerCollection(ctx context.Context, req teleproto.TelemetryRequest) // DoGetMetricDefinition defines the RPC call function for // the GetMetricDefinition from telemetry micro service func DoGetMetricDefinition(ctx context.Context, req teleproto.TelemetryRequest) (*teleproto.TelemetryResponse, error) { - ctx, conn, err := getConnection(ctx, services.Telemetry) + ctx = common.CreateMetadata(ctx) + conn, err := ClientFunc(services.Telemetry) if err != nil { - return nil, err + return nil, fmt.Errorf("Failed to create client connection: %v", err) } telemetry := NewTelemetryClientFunc(conn) @@ -137,9 +144,10 @@ func DoGetMetricDefinition(ctx context.Context, req teleproto.TelemetryRequest) // DoGetMetricReportDefinition defines the RPC call function for // the GetMetricReportDefinition from telemetry micro service func DoGetMetricReportDefinition(ctx context.Context, req teleproto.TelemetryRequest) (*teleproto.TelemetryResponse, error) { - ctx, conn, err := getConnection(ctx, services.Telemetry) + ctx = common.CreateMetadata(ctx) + conn, err := ClientFunc(services.Telemetry) if err != nil { - return nil, err + return nil, fmt.Errorf("Failed to create client connection: %v", err) } telemetry := NewTelemetryClientFunc(conn) @@ -155,9 +163,10 @@ func DoGetMetricReportDefinition(ctx context.Context, req teleproto.TelemetryReq // DoGetMetricReport defines the RPC call function for // the GetMetricReport from telemetry micro service func DoGetMetricReport(ctx context.Context, req teleproto.TelemetryRequest) (*teleproto.TelemetryResponse, error) { - ctx, conn, err := getConnection(ctx, services.Telemetry) + ctx = common.CreateMetadata(ctx) + conn, err := ClientFunc(services.Telemetry) if err != nil { - return nil, err + return nil, fmt.Errorf("Failed to create client connection: %v", err) } telemetry := NewTelemetryClientFunc(conn) @@ -173,9 +182,10 @@ func DoGetMetricReport(ctx context.Context, req teleproto.TelemetryRequest) (*te // DoGetTrigger defines the RPC call function for // the GetTrigger from telemetry micro service func DoGetTrigger(ctx context.Context, req teleproto.TelemetryRequest) (*teleproto.TelemetryResponse, error) { - ctx, conn, err := getConnection(ctx, services.Telemetry) + ctx = common.CreateMetadata(ctx) + conn, err := ClientFunc(services.Telemetry) if err != nil { - return nil, err + return nil, fmt.Errorf("Failed to create client connection: %v", err) } telemetry := NewTelemetryClientFunc(conn) @@ -191,9 +201,10 @@ func DoGetTrigger(ctx context.Context, req teleproto.TelemetryRequest) (*telepro // DoUpdateTrigger defines the RPC call function for // the UpdateTrigger from telemetry micro service func DoUpdateTrigger(ctx context.Context, req teleproto.TelemetryRequest) (*teleproto.TelemetryResponse, error) { - ctx, conn, err := getConnection(ctx, services.Telemetry) + ctx = common.CreateMetadata(ctx) + conn, err := ClientFunc(services.Telemetry) if err != nil { - return nil, err + return nil, fmt.Errorf("Failed to create client connection: %v", err) } telemetry := NewTelemetryClientFunc(conn) From ba9128cc3ccd5e5a731a979d2636dc098f12f98c Mon Sep 17 00:00:00 2001 From: Banoshi Date: Fri, 16 Jun 2023 02:42:09 +0530 Subject: [PATCH 08/19] ran go tools --- svc-api/rpc/account.go | 3 +++ svc-api/rpc/aggregator.go | 1 - 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/svc-api/rpc/account.go b/svc-api/rpc/account.go index d33a62894..6726e1d69 100644 --- a/svc-api/rpc/account.go +++ b/svc-api/rpc/account.go @@ -56,6 +56,7 @@ func DoAccountCreationRequest(ctx context.Context, req accountproto.CreateAccoun if err != nil { return nil, fmt.Errorf("Failed to create client connection: %v", err) } + account := NewAccountClientFunc(conn) resp, err := account.Create(ctx, &req) @@ -74,6 +75,7 @@ func DoGetAllAccountRequest(ctx context.Context, req accountproto.AccountRequest if err != nil { return nil, fmt.Errorf("Failed to create client connection: %v", err) } + account := NewAccountClientFunc(conn) resp, err := account.GetAllAccounts(ctx, &req) @@ -129,6 +131,7 @@ func DoAccountDeleteRequest(ctx context.Context, req accountproto.DeleteAccountR if err != nil { return nil, fmt.Errorf("Failed to create client connection: %v", err) } + account := NewAccountClientFunc(conn) resp, err := account.Delete(ctx, &req) diff --git a/svc-api/rpc/aggregator.go b/svc-api/rpc/aggregator.go index 4bd6f7cf4..4c917f639 100644 --- a/svc-api/rpc/aggregator.go +++ b/svc-api/rpc/aggregator.go @@ -56,7 +56,6 @@ func DoResetRequest(ctx context.Context, req aggregatorproto.AggregatorRequest) if err != nil { return nil, fmt.Errorf("Failed to create client connection: %v", err) } - aggregator := NewAggregatorClientFunc(conn) resp, err := aggregator.Reset(ctx, &req) From f11dd3a9eafedb4e50f6744b117e235a05c0a8bd Mon Sep 17 00:00:00 2001 From: Banoshi Date: Thu, 15 Jun 2023 00:25:52 +0530 Subject: [PATCH 09/19] remove code duplicates from svc-api --- lib-utilities/common/crypto_test.go | 18 +- lib-utilities/common/dbconn_test.go | 18 +- lib-utilities/common/jobqueue_test.go | 18 +- lib-utilities/common/mockconfig_test.go | 18 +- lib-utilities/common/responses.go | 28 ++ lib-utilities/common/workerpool_test.go | 18 +- lib-utilities/config/mockconfig_test.go | 18 +- lib-utilities/errors/error.go | 6 +- lib-utilities/errors/error_test.go | 18 +- lib-utilities/response/errorresponse.go | 2 +- lib-utilities/response/errorresponse_test.go | 18 +- .../response/successresponse_test.go | 18 +- lib-utilities/services/pluginTask.go | 144 +++--- svc-api/handle/account.go | 144 ++---- svc-api/handle/aggregator.go | 472 +++++------------- svc-api/handle/aggregator_test.go | 210 ++++---- svc-api/handle/chassis.go | 12 +- svc-api/handle/compositionservice.go | 241 +++------ svc-api/handle/compositionservice_test.go | 16 +- svc-api/handle/events.go | 110 +--- svc-api/handle/fabrics.go | 359 ++++--------- svc-api/handle/handlers.go | 60 +-- svc-api/handle/licenses.go | 33 +- svc-api/handle/managers.go | 249 +++------ svc-api/handle/role.go | 81 +-- svc-api/handle/systems.go | 307 +++--------- svc-api/handle/task.go | 43 +- svc-api/handle/telemetry.go | 187 ++----- svc-api/handle/update.go | 158 ++---- svc-api/messages/sessions.go | 2 +- svc-api/models/metadata.go | 8 +- svc-api/models/odata.go | 6 +- svc-api/models/serviceroot.go | 16 +- svc-api/models/version.go | 4 +- svc-api/response/accounts.go | 22 +- svc-api/response/error.go | 2 +- svc-api/response/list.go | 2 +- svc-api/response/registries.go | 6 +- svc-api/response/session.go | 8 +- svc-api/rpc/composition_service.go | 2 +- 40 files changed, 1024 insertions(+), 2078 deletions(-) diff --git a/lib-utilities/common/crypto_test.go b/lib-utilities/common/crypto_test.go index b77fea02a..0b376ef78 100644 --- a/lib-utilities/common/crypto_test.go +++ b/lib-utilities/common/crypto_test.go @@ -1,15 +1,15 @@ -//(C) Copyright [2020] Hewlett Packard Enterprise Development LP +// (C) Copyright [2020] Hewlett Packard Enterprise Development LP // -//Licensed under the Apache License, Version 2.0 (the "License"); you may -//not use this file except in compliance with the License. You may obtain -//a copy of the License at +// Licensed under the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. You may obtain +// a copy of the License at // -// http://www.apache.org/licenses/LICENSE-2.0 +// http://www.apache.org/licenses/LICENSE-2.0 // -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -//WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -//License for the specific language governing permissions and limitations +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +// License for the specific language governing permissions and limitations // under the License. package common diff --git a/lib-utilities/common/dbconn_test.go b/lib-utilities/common/dbconn_test.go index 58c7ef353..eff58d4d3 100644 --- a/lib-utilities/common/dbconn_test.go +++ b/lib-utilities/common/dbconn_test.go @@ -1,15 +1,15 @@ -//(C) Copyright [2020] Hewlett Packard Enterprise Development LP +// (C) Copyright [2020] Hewlett Packard Enterprise Development LP // -//Licensed under the Apache License, Version 2.0 (the "License"); you may -//not use this file except in compliance with the License. You may obtain -//a copy of the License at +// Licensed under the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. You may obtain +// a copy of the License at // -// http://www.apache.org/licenses/LICENSE-2.0 +// http://www.apache.org/licenses/LICENSE-2.0 // -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -//WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -//License for the specific language governing permissions and limitations +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +// License for the specific language governing permissions and limitations // under the License. package common diff --git a/lib-utilities/common/jobqueue_test.go b/lib-utilities/common/jobqueue_test.go index 772e8e0a4..7bb116657 100644 --- a/lib-utilities/common/jobqueue_test.go +++ b/lib-utilities/common/jobqueue_test.go @@ -1,15 +1,15 @@ -//(C) Copyright [2020] Hewlett Packard Enterprise Development LP +// (C) Copyright [2020] Hewlett Packard Enterprise Development LP // -//Licensed under the Apache License, Version 2.0 (the "License"); you may -//not use this file except in compliance with the License. You may obtain -//a copy of the License at +// Licensed under the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. You may obtain +// a copy of the License at // -// http://www.apache.org/licenses/LICENSE-2.0 +// http://www.apache.org/licenses/LICENSE-2.0 // -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -//WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -//License for the specific language governing permissions and limitations +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +// License for the specific language governing permissions and limitations // under the License. package common diff --git a/lib-utilities/common/mockconfig_test.go b/lib-utilities/common/mockconfig_test.go index f8e68602e..50275aaba 100644 --- a/lib-utilities/common/mockconfig_test.go +++ b/lib-utilities/common/mockconfig_test.go @@ -1,15 +1,15 @@ -//(C) Copyright [2020] Hewlett Packard Enterprise Development LP +// (C) Copyright [2020] Hewlett Packard Enterprise Development LP // -//Licensed under the Apache License, Version 2.0 (the "License"); you may -//not use this file except in compliance with the License. You may obtain -//a copy of the License at +// Licensed under the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. You may obtain +// a copy of the License at // -// http://www.apache.org/licenses/LICENSE-2.0 +// http://www.apache.org/licenses/LICENSE-2.0 // -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -//WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -//License for the specific language governing permissions and limitations +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +// License for the specific language governing permissions and limitations // under the License. package common diff --git a/lib-utilities/common/responses.go b/lib-utilities/common/responses.go index 4714500bf..aabc3483b 100644 --- a/lib-utilities/common/responses.go +++ b/lib-utilities/common/responses.go @@ -19,6 +19,7 @@ import ( "context" "net/http" + "github.com/ODIM-Project/ODIM/lib-utilities/response" iris "github.com/kataras/iris/v12" "google.golang.org/grpc/metadata" ) @@ -118,3 +119,30 @@ func CreateContext(transactionID, actionID, actionName, threadID, threadName, pr ctx = context.WithValue(ctx, ProcessName, processName) return ctx } + +// SendInvalidSessionResponse writes the response to client when no valid session is found +func SendInvalidSessionResponse(ctx iris.Context, errorMessage string) { + response := GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) + SetResponseHeader(ctx, response.Header) + ctx.StatusCode(http.StatusUnauthorized) + ctx.JSON(&response.Body) + return +} + +// SendFailedRPCCallResponse writes the response to client when a RPC call fails +func SendFailedRPCCallResponse(ctx iris.Context, errorMessage string) { + response := GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) + SetResponseHeader(ctx, response.Header) + ctx.StatusCode(http.StatusInternalServerError) + ctx.JSON(&response.Body) + return +} + +// SendMalformedJSONRequestErrResponse writes the response to client when the request contains malformed JSON structure +func SendMalformedJSONRequestErrResponse(ctx iris.Context, errorMessage string) { + response := GeneralError(http.StatusBadRequest, response.MalformedJSON, errorMessage, nil, nil) + SetResponseHeader(ctx, response.Header) + ctx.StatusCode(http.StatusBadRequest) + ctx.JSON(&response.Body) + return +} diff --git a/lib-utilities/common/workerpool_test.go b/lib-utilities/common/workerpool_test.go index 6c78e0495..8f4855753 100644 --- a/lib-utilities/common/workerpool_test.go +++ b/lib-utilities/common/workerpool_test.go @@ -1,15 +1,15 @@ -//(C) Copyright [2020] Hewlett Packard Enterprise Development LP +// (C) Copyright [2020] Hewlett Packard Enterprise Development LP // -//Licensed under the Apache License, Version 2.0 (the "License"); you may -//not use this file except in compliance with the License. You may obtain -//a copy of the License at +// Licensed under the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. You may obtain +// a copy of the License at // -// http://www.apache.org/licenses/LICENSE-2.0 +// http://www.apache.org/licenses/LICENSE-2.0 // -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -//WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -//License for the specific language governing permissions and limitations +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +// License for the specific language governing permissions and limitations // under the License. package common diff --git a/lib-utilities/config/mockconfig_test.go b/lib-utilities/config/mockconfig_test.go index cdab657ab..d7b9e97ae 100644 --- a/lib-utilities/config/mockconfig_test.go +++ b/lib-utilities/config/mockconfig_test.go @@ -1,15 +1,15 @@ -//(C) Copyright [2020] Hewlett Packard Enterprise Development LP +// (C) Copyright [2020] Hewlett Packard Enterprise Development LP // -//Licensed under the Apache License, Version 2.0 (the "License"); you may -//not use this file except in compliance with the License. You may obtain -//a copy of the License at +// Licensed under the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. You may obtain +// a copy of the License at // -// http://www.apache.org/licenses/LICENSE-2.0 +// http://www.apache.org/licenses/LICENSE-2.0 // -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -//WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -//License for the specific language governing permissions and limitations +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +// License for the specific language governing permissions and limitations // under the License. // package ... package config diff --git a/lib-utilities/errors/error.go b/lib-utilities/errors/error.go index b426d6b87..97f2fe729 100644 --- a/lib-utilities/errors/error.go +++ b/lib-utilities/errors/error.go @@ -21,19 +21,19 @@ import ( "net/http" ) -//CommonError struct definition +// CommonError struct definition type CommonError struct { Error ErrorClass `json:"error"` } -//ErrorClass struct definition +// ErrorClass struct definition type ErrorClass struct { Code string `json:"code"` Message string `json:"message"` MessageExtendedInfo []MsgExtendedInfo `json:"@Message.ExtendedInfo,omitempty"` } -//MsgExtendedInfo struct definition +// MsgExtendedInfo struct definition type MsgExtendedInfo struct { OdataType string `json:"@odata.type,omitempty"` MessageID string `json:"MessageId,omitempty"` diff --git a/lib-utilities/errors/error_test.go b/lib-utilities/errors/error_test.go index 91ed232f6..2a54eb8bf 100644 --- a/lib-utilities/errors/error_test.go +++ b/lib-utilities/errors/error_test.go @@ -1,15 +1,15 @@ -//(C) Copyright [2020] Hewlett Packard Enterprise Development LP +// (C) Copyright [2020] Hewlett Packard Enterprise Development LP // -//Licensed under the Apache License, Version 2.0 (the "License"); you may -//not use this file except in compliance with the License. You may obtain -//a copy of the License at +// Licensed under the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. You may obtain +// a copy of the License at // -// http://www.apache.org/licenses/LICENSE-2.0 +// http://www.apache.org/licenses/LICENSE-2.0 // -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -//WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -//License for the specific language governing permissions and limitations +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +// License for the specific language governing permissions and limitations // under the License. package errors diff --git a/lib-utilities/response/errorresponse.go b/lib-utilities/response/errorresponse.go index cea33da7e..ce838cda1 100644 --- a/lib-utilities/response/errorresponse.go +++ b/lib-utilities/response/errorresponse.go @@ -353,7 +353,7 @@ func (a *Args) CreateGenericErrorResponse() CommonError { return e } -//CreateInternalErrorResponse is used to create internal server error response +// CreateInternalErrorResponse is used to create internal server error response func (resp *RPC) CreateInternalErrorResponse(errorMessage string) { resp.StatusCode = http.StatusInternalServerError resp.StatusMessage = InternalError diff --git a/lib-utilities/response/errorresponse_test.go b/lib-utilities/response/errorresponse_test.go index 63baf6c42..02df0d902 100644 --- a/lib-utilities/response/errorresponse_test.go +++ b/lib-utilities/response/errorresponse_test.go @@ -1,15 +1,15 @@ -//(C) Copyright [2020] Hewlett Packard Enterprise Development LP +// (C) Copyright [2020] Hewlett Packard Enterprise Development LP // -//Licensed under the Apache License, Version 2.0 (the "License"); you may -//not use this file except in compliance with the License. You may obtain -//a copy of the License at +// Licensed under the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. You may obtain +// a copy of the License at // -// http://www.apache.org/licenses/LICENSE-2.0 +// http://www.apache.org/licenses/LICENSE-2.0 // -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -//WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -//License for the specific language governing permissions and limitations +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +// License for the specific language governing permissions and limitations // under the License. package response diff --git a/lib-utilities/response/successresponse_test.go b/lib-utilities/response/successresponse_test.go index 98270444b..48533c999 100644 --- a/lib-utilities/response/successresponse_test.go +++ b/lib-utilities/response/successresponse_test.go @@ -1,15 +1,15 @@ -//(C) Copyright [2020] Hewlett Packard Enterprise Development LP +// (C) Copyright [2020] Hewlett Packard Enterprise Development LP // -//Licensed under the Apache License, Version 2.0 (the "License"); you may -//not use this file except in compliance with the License. You may obtain -//a copy of the License at +// Licensed under the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. You may obtain +// a copy of the License at // -// http://www.apache.org/licenses/LICENSE-2.0 +// http://www.apache.org/licenses/LICENSE-2.0 // -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -//WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -//License for the specific language governing permissions and limitations +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +// License for the specific language governing permissions and limitations // under the License. package response diff --git a/lib-utilities/services/pluginTask.go b/lib-utilities/services/pluginTask.go index d0a16029b..600edb59a 100644 --- a/lib-utilities/services/pluginTask.go +++ b/lib-utilities/services/pluginTask.go @@ -1,72 +1,72 @@ -//(C) Copyright [2023] Hewlett Packard Enterprise Development LP -// -//Licensed under the Apache License, Version 2.0 (the "License"); you may -//not use this file except in compliance with the License. You may obtain -//a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -//WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -//License for the specific language governing permissions and limitations -// under the License. - -// Package services ... -package services - -import ( - "context" - "fmt" - "strings" - - redis "github.com/ODIM-Project/ODIM/lib-persistence-manager/persistencemgr" - "github.com/ODIM-Project/ODIM/lib-utilities/common" - "github.com/ODIM-Project/ODIM/lib-utilities/errors" -) - -// SavePluginTaskInfo saves the ip of plugin instance that handle the task, -// task id of task which created in odim, and the taskmon URL returned -// from plugin in DB -func SavePluginTaskInfo(ctx context.Context, pluginIP, pluginServerName, - odimTaskID, pluginTaskMonURL string) error { - - pluginTaskID := strings.TrimPrefix(pluginTaskMonURL, "/taskmon/") - pluginTaskInfo := common.PluginTask{ - IP: pluginIP, - PluginServerName: pluginServerName, - OdimTaskID: odimTaskID, - PluginTaskMonURL: pluginTaskMonURL, - } - - err := createPluginTask(ctx, pluginTaskID, pluginTaskInfo) - if err != nil { - return fmt.Errorf("Error while saving plugin task info in DB: %s", - err.Error()) - } - return nil -} - -// createPluginTask will insert plugin task info in DB -func createPluginTask(ctx context.Context, key string, - value interface{}) *errors.Error { - - table := "PluginTask" - connPool, err := redis.GetDBConnection(redis.InMemory) - if err != nil { - return errors.PackError(err.ErrNo(), "error while trying to connecting"+ - " to DB: ", err.Error()) - } - - if err = connPool.Create(table, key, value); err != nil { - return errors.PackError(err.ErrNo(), "error while trying to insert"+ - " plugin task: ", err.Error()) - } - - if err = connPool.AddMemberToSet(common.PluginTaskIndex, key); err != nil { - return errors.PackError(err.ErrNo(), "error while trying to add "+ - " plugin task to set: ", err.Error()) - } - - return nil -} +//(C) Copyright [2023] Hewlett Packard Enterprise Development LP +// +//Licensed under the Apache License, Version 2.0 (the "License"); you may +//not use this file except in compliance with the License. You may obtain +//a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +//Unless required by applicable law or agreed to in writing, software +//distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +//WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +//License for the specific language governing permissions and limitations +// under the License. + +// Package services ... +package services + +import ( + "context" + "fmt" + "strings" + + redis "github.com/ODIM-Project/ODIM/lib-persistence-manager/persistencemgr" + "github.com/ODIM-Project/ODIM/lib-utilities/common" + "github.com/ODIM-Project/ODIM/lib-utilities/errors" +) + +// SavePluginTaskInfo saves the ip of plugin instance that handle the task, +// task id of task which created in odim, and the taskmon URL returned +// from plugin in DB +func SavePluginTaskInfo(ctx context.Context, pluginIP, pluginServerName, + odimTaskID, pluginTaskMonURL string) error { + + pluginTaskID := strings.TrimPrefix(pluginTaskMonURL, "/taskmon/") + pluginTaskInfo := common.PluginTask{ + IP: pluginIP, + PluginServerName: pluginServerName, + OdimTaskID: odimTaskID, + PluginTaskMonURL: pluginTaskMonURL, + } + + err := createPluginTask(ctx, pluginTaskID, pluginTaskInfo) + if err != nil { + return fmt.Errorf("Error while saving plugin task info in DB: %s", + err.Error()) + } + return nil +} + +// createPluginTask will insert plugin task info in DB +func createPluginTask(ctx context.Context, key string, + value interface{}) *errors.Error { + + table := "PluginTask" + connPool, err := redis.GetDBConnection(redis.InMemory) + if err != nil { + return errors.PackError(err.ErrNo(), "error while trying to connecting"+ + " to DB: ", err.Error()) + } + + if err = connPool.Create(table, key, value); err != nil { + return errors.PackError(err.ErrNo(), "error while trying to insert"+ + " plugin task: ", err.Error()) + } + + if err = connPool.AddMemberToSet(common.PluginTaskIndex, key); err != nil { + return errors.PackError(err.ErrNo(), "error while trying to add "+ + " plugin task to set: ", err.Error()) + } + + return nil +} diff --git a/svc-api/handle/account.go b/svc-api/handle/account.go index 0103685ba..a43a991ba 100644 --- a/svc-api/handle/account.go +++ b/svc-api/handle/account.go @@ -18,12 +18,10 @@ package handle import ( "context" "encoding/json" - "net/http" "github.com/ODIM-Project/ODIM/lib-utilities/common" l "github.com/ODIM-Project/ODIM/lib-utilities/logs" accountproto "github.com/ODIM-Project/ODIM/lib-utilities/proto/account" - "github.com/ODIM-Project/ODIM/lib-utilities/response" iris "github.com/kataras/iris/v12" ) @@ -45,34 +43,25 @@ func (a *AccountRPCs) GetAccountService(ctx iris.Context) { defer ctx.Next() ctxt := ctx.Request().Context() req := accountproto.AccountRequest{ - SessionToken: ctx.Request().Header.Get("X-Auth-Token"), + SessionToken: ctx.Request().Header.Get(AuthTokenHeader), } l.LogWithFields(ctx).Debug("Incoming request received for the Get Account service") if req.SessionToken == "" { - errorMessage := "no X-Auth-Token found in request header" + errorMessage := invalidAuthTokenErrMsg l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + common.SendInvalidSessionResponse(ctx, errorMessage) } resp, err := a.GetServiceRPC(ctxt, req) if err != nil && resp == nil { - errorMessage := "something went wrong with the RPC calls: " + err.Error() + errorMessage := rpcCallFailedErrMsg + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) + common.SendFailedRPCCallResponse(ctx, errorMessage) return } l.LogWithFields(ctx).Debugf("Outgoing response for Getting Account service is %s and response status %d", string(resp.Body), int(resp.StatusCode)) ctx.ResponseWriter().Header().Set("Allow", "GET") - common.SetResponseHeader(ctx, resp.Header) - ctx.StatusCode(int(resp.StatusCode)) - ctx.Write(resp.Body) + sendAccountResponse(ctx, resp) } @@ -89,23 +78,15 @@ func (a *AccountRPCs) CreateAccount(ctx iris.Context) { if err != nil { errorMessage := "error while trying to get JSON body from the account create request body: " + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusBadRequest, response.MalformedJSON, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusBadRequest) - ctx.JSON(&response.Body) - return + common.SendMalformedJSONRequestErrResponse(ctx, errorMessage) } l.LogWithFields(ctxt).Debug("Incoming request for create account received") - sessionToken := ctx.Request().Header.Get("X-Auth-Token") + sessionToken := ctx.Request().Header.Get(AuthTokenHeader) if sessionToken == "" { - errorMessage := "no X-Auth-Token found in request header" + errorMessage := invalidAuthTokenErrMsg l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + common.SendInvalidSessionResponse(ctx, errorMessage) } // Marshalling the req to make account request @@ -118,18 +99,13 @@ func (a *AccountRPCs) CreateAccount(ctx iris.Context) { resp, err := a.CreateRPC(ctxt, createRequest) if err != nil && resp == nil { - errorMessage := "something went wrong with the RPC calls: " + err.Error() + errorMessage := rpcCallFailedErrMsg + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) + common.SendFailedRPCCallResponse(ctx, errorMessage) return } - common.SetResponseHeader(ctx, resp.Header) - ctx.StatusCode(int(resp.StatusCode)) - ctx.Write(resp.Body) + sendAccountResponse(ctx, resp) l.LogWithFields(ctxt).Debugf("Outgoing response for create account is %s and response status %d", string(resp.Body), int(resp.StatusCode)) } @@ -142,34 +118,25 @@ func (a *AccountRPCs) GetAllAccounts(ctx iris.Context) { defer ctx.Next() ctxt := ctx.Request().Context() req := accountproto.AccountRequest{ - SessionToken: ctx.Request().Header.Get("X-Auth-Token"), + SessionToken: ctx.Request().Header.Get(AuthTokenHeader), } l.LogWithFields(ctxt).Debug("Incoming request for get all accounts received") if req.SessionToken == "" { - errorMessage := "no X-Auth-Token found in request header" + errorMessage := invalidAuthTokenErrMsg l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + common.SendInvalidSessionResponse(ctx, errorMessage) } resp, err := a.GetAllAccountsRPC(ctxt, req) if err != nil && resp == nil { - errorMessage := "something went wrong with the RPC calls: " + err.Error() + errorMessage := rpcCallFailedErrMsg + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) + common.SendFailedRPCCallResponse(ctx, errorMessage) return } ctx.ResponseWriter().Header().Set("Allow", "GET, POST") - common.SetResponseHeader(ctx, resp.Header) - ctx.StatusCode(int(resp.StatusCode)) - ctx.Write(resp.Body) + sendAccountResponse(ctx, resp) l.LogWithFields(ctxt).Debugf("outgoing response for get all accounts is %s and response status %d", string(resp.Body), int(resp.StatusCode)) } @@ -183,35 +150,26 @@ func (a *AccountRPCs) GetAccount(ctx iris.Context) { defer ctx.Next() ctxt := ctx.Request().Context() req := accountproto.GetAccountRequest{ - SessionToken: ctx.Request().Header.Get("X-Auth-Token"), + SessionToken: ctx.Request().Header.Get(AuthTokenHeader), AccountID: ctx.Params().Get("id"), } l.LogWithFields(ctxt).Debugf("Incoming request for get account info received for %s", req.AccountID) if req.SessionToken == "" { - errorMessage := "no X-Auth-Token found in request header" + errorMessage := invalidAuthTokenErrMsg l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + common.SendInvalidSessionResponse(ctx, errorMessage) } resp, err := a.GetAccountRPC(ctxt, req) if err != nil && resp == nil { - errorMessage := "something went wrong with the RPC calls: " + err.Error() + errorMessage := rpcCallFailedErrMsg + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) + common.SendFailedRPCCallResponse(ctx, errorMessage) return } ctx.ResponseWriter().Header().Set("Allow", "GET, PATCH, DELETE") - common.SetResponseHeader(ctx, resp.Header) - ctx.StatusCode(int(resp.StatusCode)) - ctx.Write(resp.Body) + sendAccountResponse(ctx, resp) l.LogWithFields(ctxt).Debugf("outgoing response for get account is %s and response status %d", string(resp.Body), int(resp.StatusCode)) } @@ -231,24 +189,16 @@ func (a *AccountRPCs) UpdateAccount(ctx iris.Context) { if err != nil { errorMessage := "error while trying to get JSON body from the account update request body: " + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusBadRequest, response.MalformedJSON, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusBadRequest) - ctx.JSON(&response.Body) - return + common.SendMalformedJSONRequestErrResponse(ctx, errorMessage) } - sessionToken := ctx.Request().Header.Get("X-Auth-Token") + sessionToken := ctx.Request().Header.Get(AuthTokenHeader) accountID := ctx.Params().Get("id") l.LogWithFields(ctxt).Debugf("Incoming request for updating account received for %s", accountID) if sessionToken == "" { - errorMessage := "no X-Auth-Token found in request header" + errorMessage := invalidAuthTokenErrMsg l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + common.SendInvalidSessionResponse(ctx, errorMessage) } // Marshalling the req to make account request @@ -262,18 +212,13 @@ func (a *AccountRPCs) UpdateAccount(ctx iris.Context) { resp, err := a.UpdateRPC(ctxt, updateRequest) if err != nil && resp == nil { - errorMessage := "something went wrong with the RPC calls: " + err.Error() + errorMessage := rpcCallFailedErrMsg + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) + common.SendFailedRPCCallResponse(ctx, errorMessage) return } - common.SetResponseHeader(ctx, resp.Header) - ctx.StatusCode(int(resp.StatusCode)) - ctx.Write(resp.Body) + sendAccountResponse(ctx, resp) l.LogWithFields(ctxt).Debugf("outgoing response for updating account is %s and response status %d", string(resp.Body), int(resp.StatusCode)) } @@ -287,34 +232,31 @@ func (a *AccountRPCs) DeleteAccount(ctx iris.Context) { defer ctx.Next() ctxt := ctx.Request().Context() req := accountproto.DeleteAccountRequest{ - SessionToken: ctx.Request().Header.Get("X-Auth-Token"), + SessionToken: ctx.Request().Header.Get(AuthTokenHeader), AccountID: ctx.Params().Get("id"), } l.LogWithFields(ctxt).Debugf("Incoming request for deleting account received with %s", req.AccountID) if req.SessionToken == "" { - errorMessage := "no X-Auth-Token found in request header" + errorMessage := invalidAuthTokenErrMsg l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + common.SendInvalidSessionResponse(ctx, errorMessage) } resp, err := a.DeleteRPC(ctxt, req) if err != nil && resp == nil { - errorMessage := "something went wrong with the RPC calls: " + err.Error() + errorMessage := rpcCallFailedErrMsg + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) + common.SendFailedRPCCallResponse(ctx, errorMessage) return } + sendAccountResponse(ctx, resp) + l.LogWithFields(ctxt).Debugf("outgoing response for deleting account with %s and response status %d", req.AccountID, int(resp.StatusCode)) +} + +// sendAccountResponse writes the account response to client +func sendAccountResponse(ctx iris.Context, resp *accountproto.AccountResponse) { common.SetResponseHeader(ctx, resp.Header) ctx.StatusCode(int(resp.StatusCode)) ctx.Write(resp.Body) - l.LogWithFields(ctxt).Debugf("outgoing response for deleting account with %s and response status %d", req.AccountID, int(resp.StatusCode)) - } diff --git a/svc-api/handle/aggregator.go b/svc-api/handle/aggregator.go index 00f6d43de..4064aab21 100644 --- a/svc-api/handle/aggregator.go +++ b/svc-api/handle/aggregator.go @@ -51,37 +51,34 @@ type AggregatorRPCs struct { GetSetDefaultBootOrderActionInfoRPC func(context.Context, aggregatorproto.AggregatorRequest) (*aggregatorproto.AggregatorResponse, error) } +const ( + // AuthTokenHeader holds the key of X-Auth-Token header + AuthTokenHeader = "X-Auth-Token" + rpcCallFailedErrMsg = "something went wrong with the RPC calls: " + invalidAuthTokenErrMsg = "no X-Auth-Token found in request header" +) + // GetAggregationService is the handler for getting AggregationService details func (a *AggregatorRPCs) GetAggregationService(ctx iris.Context) { defer ctx.Next() ctxt := ctx.Request().Context() l.LogWithFields(ctxt).Debugf("Incoming request received for get aggregation service") req := aggregatorproto.AggregatorRequest{ - SessionToken: ctx.Request().Header.Get("X-Auth-Token"), + SessionToken: ctx.Request().Header.Get(AuthTokenHeader), } if req.SessionToken == "" { - errorMessage := "no X-Auth-Token found in request header" - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + errorMessage := invalidAuthTokenErrMsg + common.SendInvalidSessionResponse(ctx, errorMessage) } resp, err := a.GetAggregationServiceRPC(ctxt, req) if err != nil { - errorMessage := "something went wrong with the RPC calls: " + err.Error() + errorMessage := rpcCallFailedErrMsg + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) - return + common.SendFailedRPCCallResponse(ctx, errorMessage) } ctx.ResponseWriter().Header().Set("Allow", "GET") - common.SetResponseHeader(ctx, resp.Header) - ctx.StatusCode(int(resp.StatusCode)) - ctx.Write(resp.Body) + sendAggregatorResponse(ctx, resp) l.LogWithFields(ctxt).Debugf("outgoing response for get aggregation service is %s with response code %d", string(resp.Body), int(resp.StatusCode)) } @@ -96,23 +93,15 @@ func (a *AggregatorRPCs) Reset(ctx iris.Context) { var req interface{} err := ctx.ReadJSON(&req) if err != nil { - errorMessage := "error while trying to get JSON body from the request body: " + err.Error() + errorMessage := "error while trying to get JSON body from the request body: " + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusBadRequest, response.MalformedJSON, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusBadRequest) - ctx.JSON(&response.Body) - return + common.SendMalformedJSONRequestErrResponse(ctx, errorMessage) } - sessionToken := ctx.Request().Header.Get("X-Auth-Token") + sessionToken := ctx.Request().Header.Get(AuthTokenHeader) if sessionToken == "" { - errorMessage := "no X-Auth-Token found in request header" - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + errorMessage := invalidAuthTokenErrMsg + common.SendInvalidSessionResponse(ctx, errorMessage) } // marshalling the req to make aggregator delete request @@ -121,10 +110,7 @@ func (a *AggregatorRPCs) Reset(ctx iris.Context) { if err != nil { errorMessage := "error while trying to create JSON request body: " + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) + common.SendFailedRPCCallResponse(ctx, errorMessage) return } @@ -136,16 +122,11 @@ func (a *AggregatorRPCs) Reset(ctx iris.Context) { if err != nil { errorMessage := "RPC error: " + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) + common.SendFailedRPCCallResponse(ctx, errorMessage) return } - common.SetResponseHeader(ctx, resp.Header) - ctx.StatusCode(int(resp.StatusCode)) - ctx.Write(resp.Body) + sendAggregatorResponse(ctx, resp) l.LogWithFields(ctxt).Debugf("outgoing response for resetting compute system is %s and response code %d", string(resp.Body), int(resp.StatusCode)) } @@ -159,23 +140,15 @@ func (a *AggregatorRPCs) SetDefaultBootOrder(ctx iris.Context) { var req interface{} err := ctx.ReadJSON(&req) if err != nil { - errorMessage := "error while trying to get JSON body from the request body: " + err.Error() + errorMessage := "error while trying to get JSON body from the request body: " + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusBadRequest, response.MalformedJSON, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusBadRequest) - ctx.JSON(&response.Body) - return + common.SendMalformedJSONRequestErrResponse(ctx, errorMessage) } - sessionToken := ctx.Request().Header.Get("X-Auth-Token") + sessionToken := ctx.Request().Header.Get(AuthTokenHeader) if sessionToken == "" { - errorMessage := "no X-Auth-Token found in request header" - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + errorMessage := invalidAuthTokenErrMsg + common.SendInvalidSessionResponse(ctx, errorMessage) } // marshalling the req to make aggregator SetDefaultBootOrder request @@ -184,10 +157,7 @@ func (a *AggregatorRPCs) SetDefaultBootOrder(ctx iris.Context) { if err != nil { errorMessage := "error while trying to create JSON request body: " + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) + common.SendFailedRPCCallResponse(ctx, errorMessage) return } @@ -199,16 +169,11 @@ func (a *AggregatorRPCs) SetDefaultBootOrder(ctx iris.Context) { if err != nil { errorMessage := "RPC error: " + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) + common.SendFailedRPCCallResponse(ctx, errorMessage) return } - common.SetResponseHeader(ctx, resp.Header) - ctx.StatusCode(int(resp.StatusCode)) - ctx.Write(resp.Body) + sendAggregatorResponse(ctx, resp) } // AddAggregationSource is the handler for adding AggregationSource details @@ -221,22 +186,14 @@ func (a *AggregatorRPCs) AddAggregationSource(ctx iris.Context) { if err != nil { errorMessage := "error while trying to get JSON body from the aggregator request body: " + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusBadRequest, response.MalformedJSON, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusBadRequest) - ctx.JSON(&response.Body) - return + common.SendMalformedJSONRequestErrResponse(ctx, errorMessage) } - sessionToken := ctx.Request().Header.Get("X-Auth-Token") + sessionToken := ctx.Request().Header.Get(AuthTokenHeader) if sessionToken == "" { - errorMessage := "no X-Auth-Token found in request header" - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + errorMessage := invalidAuthTokenErrMsg + common.SendInvalidSessionResponse(ctx, errorMessage) } // marshalling the req to make aggregator add request @@ -251,16 +208,11 @@ func (a *AggregatorRPCs) AddAggregationSource(ctx iris.Context) { if err != nil { errorMessage := "RPC error: " + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) + common.SendFailedRPCCallResponse(ctx, errorMessage) return } - common.SetResponseHeader(ctx, resp.Header) - ctx.StatusCode(int(resp.StatusCode)) - ctx.Write(resp.Body) + sendAggregatorResponse(ctx, resp) } // GetAllAggregationSource is the handler for getting all AggregationSource details @@ -269,30 +221,21 @@ func (a *AggregatorRPCs) GetAllAggregationSource(ctx iris.Context) { ctxt := ctx.Request().Context() l.LogWithFields(ctxt).Debugf("Incoming request received for getting all aggregationsources") req := aggregatorproto.AggregatorRequest{ - SessionToken: ctx.Request().Header.Get("X-Auth-Token"), + SessionToken: ctx.Request().Header.Get(AuthTokenHeader), } if req.SessionToken == "" { - errorMessage := "no X-Auth-Token found in request header" - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + errorMessage := invalidAuthTokenErrMsg + common.SendInvalidSessionResponse(ctx, errorMessage) } resp, err := a.GetAllAggregationSourceRPC(ctxt, req) if err != nil { errorMessage := " RPC error:" + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) + common.SendFailedRPCCallResponse(ctx, errorMessage) return } ctx.ResponseWriter().Header().Set("Allow", "GET, POST") - common.SetResponseHeader(ctx, resp.Header) - ctx.StatusCode(int(resp.StatusCode)) - ctx.Write(resp.Body) + sendAggregatorResponse(ctx, resp) l.LogWithFields(ctxt).Debugf("Outgoing response for getting all aggregation sources is %s with response code %d", string(resp.Body), int(resp.StatusCode)) } @@ -301,32 +244,23 @@ func (a *AggregatorRPCs) GetAggregationSource(ctx iris.Context) { defer ctx.Next() ctxt := ctx.Request().Context() req := aggregatorproto.AggregatorRequest{ - SessionToken: ctx.Request().Header.Get("X-Auth-Token"), + SessionToken: ctx.Request().Header.Get(AuthTokenHeader), URL: ctx.Request().RequestURI, } l.LogWithFields(ctxt).Debugf("Incoming request received for getting aggregationsource with uri %s", req.URL) if req.SessionToken == "" { - errorMessage := "no X-Auth-Token found in request header" - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + errorMessage := invalidAuthTokenErrMsg + common.SendInvalidSessionResponse(ctx, errorMessage) } resp, err := a.GetAggregationSourceRPC(ctxt, req) if err != nil { errorMessage := " RPC error:" + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) + common.SendFailedRPCCallResponse(ctx, errorMessage) return } ctx.ResponseWriter().Header().Set("Allow", "GET, PATCH, DELETE") - common.SetResponseHeader(ctx, resp.Header) - ctx.StatusCode(int(resp.StatusCode)) - ctx.Write(resp.Body) + sendAggregatorResponse(ctx, resp) l.LogWithFields(ctxt).Debugf("Outgoing response for getting aggregation source is %s with response code %d", string(resp.Body), int(resp.StatusCode)) } @@ -339,22 +273,14 @@ func (a *AggregatorRPCs) UpdateAggregationSource(ctx iris.Context) { if err != nil { errorMessage := "error while trying to get JSON body from the aggregator request body: " + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusBadRequest, response.MalformedJSON, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusBadRequest) - ctx.JSON(&response.Body) - return + common.SendMalformedJSONRequestErrResponse(ctx, errorMessage) } - sessionToken := ctx.Request().Header.Get("X-Auth-Token") + sessionToken := ctx.Request().Header.Get(AuthTokenHeader) if sessionToken == "" { - errorMessage := "no X-Auth-Token found in request header" - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + errorMessage := invalidAuthTokenErrMsg + common.SendInvalidSessionResponse(ctx, errorMessage) } // marshalling the req to make aggregator add request @@ -371,16 +297,11 @@ func (a *AggregatorRPCs) UpdateAggregationSource(ctx iris.Context) { if err != nil { errorMessage := "RPC error: " + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) + common.SendFailedRPCCallResponse(ctx, errorMessage) return } - common.SetResponseHeader(ctx, resp.Header) - ctx.StatusCode(int(resp.StatusCode)) - ctx.Write(resp.Body) + sendAggregatorResponse(ctx, resp) l.LogWithFields(ctxt).Debugf("Outgoing response for updating aggregation source is %s with response code %d", string(resp.Body), int(resp.StatusCode)) } @@ -390,32 +311,23 @@ func (a *AggregatorRPCs) DeleteAggregationSource(ctx iris.Context) { defer ctx.Next() ctxt := ctx.Request().Context() req := aggregatorproto.AggregatorRequest{ - SessionToken: ctx.Request().Header.Get("X-Auth-Token"), + SessionToken: ctx.Request().Header.Get(AuthTokenHeader), URL: ctx.Request().RequestURI, } l.LogWithFields(ctxt).Debugf("Incoming request received for deleting aggregationsource with uri %s", req.URL) if req.SessionToken == "" { - errorMessage := "no X-Auth-Token found in request header" - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + errorMessage := invalidAuthTokenErrMsg + common.SendInvalidSessionResponse(ctx, errorMessage) } resp, err := a.DeleteAggregationSourceRPC(ctxt, req) if err != nil { errorMessage := " RPC error:" + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) + common.SendFailedRPCCallResponse(ctx, errorMessage) return } l.LogWithFields(ctxt).Debugf("Outgoing response for deleting aggregation source is %s with response code %d", string(resp.Body), int(resp.StatusCode)) - common.SetResponseHeader(ctx, resp.Header) - ctx.StatusCode(int(resp.StatusCode)) - ctx.Write(resp.Body) + sendAggregatorResponse(ctx, resp) } // CreateAggregate is the handler for creating an aggregate @@ -427,22 +339,14 @@ func (a *AggregatorRPCs) CreateAggregate(ctx iris.Context) { if err != nil { errorMessage := "error while trying to get JSON body from the aggregator request body: " + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusBadRequest, response.MalformedJSON, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusBadRequest) - ctx.JSON(&response.Body) - return + common.SendMalformedJSONRequestErrResponse(ctx, errorMessage) } - sessionToken := ctx.Request().Header.Get("X-Auth-Token") + sessionToken := ctx.Request().Header.Get(AuthTokenHeader) if sessionToken == "" { - errorMessage := "no X-Auth-Token found in request header" - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + errorMessage := invalidAuthTokenErrMsg + common.SendInvalidSessionResponse(ctx, errorMessage) } // marshalling the req to make aggregator create request @@ -456,16 +360,11 @@ func (a *AggregatorRPCs) CreateAggregate(ctx iris.Context) { if err != nil { errorMessage := "RPC error: " + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) + common.SendFailedRPCCallResponse(ctx, errorMessage) return } l.LogWithFields(ctxt).Debugf("Outgoing response for creating aggregate is %s with response code %d", string(resp.Body), int(resp.StatusCode)) - common.SetResponseHeader(ctx, resp.Header) - ctx.StatusCode(int(resp.StatusCode)) - ctx.Write(resp.Body) + sendAggregatorResponse(ctx, resp) } @@ -475,31 +374,21 @@ func (a *AggregatorRPCs) GetAggregateCollection(ctx iris.Context) { ctxt := ctx.Request().Context() l.LogWithFields(ctxt).Debug("Incoming request received for getting all aggregate collections") req := aggregatorproto.AggregatorRequest{ - SessionToken: ctx.Request().Header.Get("X-Auth-Token"), + SessionToken: ctx.Request().Header.Get(AuthTokenHeader), } if req.SessionToken == "" { - errorMessage := "no X-Auth-Token found in request header" - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + errorMessage := invalidAuthTokenErrMsg + common.SendInvalidSessionResponse(ctx, errorMessage) } resp, err := a.GetAggregateCollectionRPC(ctxt, req) if err != nil { - errorMessage := "something went wrong with the RPC calls: " + err.Error() + errorMessage := rpcCallFailedErrMsg + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) - return + common.SendFailedRPCCallResponse(ctx, errorMessage) } l.LogWithFields(ctxt).Debugf("Outgoing response for getting all aggregate collections is %s with response code %d", string(resp.Body), int(resp.StatusCode)) ctx.ResponseWriter().Header().Set("Allow", "GET, POST") - common.SetResponseHeader(ctx, resp.Header) - ctx.StatusCode(int(resp.StatusCode)) - ctx.Write(resp.Body) + sendAggregatorResponse(ctx, resp) } @@ -508,33 +397,23 @@ func (a *AggregatorRPCs) GetAggregate(ctx iris.Context) { defer ctx.Next() ctxt := ctx.Request().Context() req := aggregatorproto.AggregatorRequest{ - SessionToken: ctx.Request().Header.Get("X-Auth-Token"), + SessionToken: ctx.Request().Header.Get(AuthTokenHeader), URL: ctx.Request().RequestURI, } l.LogWithFields(ctxt).Debugf("Incoming request received for getting aggregate with request uri %s", req.URL) if req.SessionToken == "" { - errorMessage := "no X-Auth-Token found in request header" - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + errorMessage := invalidAuthTokenErrMsg + common.SendInvalidSessionResponse(ctx, errorMessage) } resp, err := a.GetAggregateRPC(ctxt, req) if err != nil { - errorMessage := "something went wrong with the RPC calls: " + err.Error() + errorMessage := rpcCallFailedErrMsg + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) - return + common.SendFailedRPCCallResponse(ctx, errorMessage) } l.LogWithFields(ctxt).Debugf("Outgoing response for getting aggregate is %s with response code %d", string(resp.Body), int(resp.StatusCode)) ctx.ResponseWriter().Header().Set("Allow", "GET, DELETE") - common.SetResponseHeader(ctx, resp.Header) - ctx.StatusCode(int(resp.StatusCode)) - ctx.Write(resp.Body) + sendAggregatorResponse(ctx, resp) } // DeleteAggregate is the handler for deleting an aggregate @@ -542,32 +421,22 @@ func (a *AggregatorRPCs) DeleteAggregate(ctx iris.Context) { defer ctx.Next() ctxt := ctx.Request().Context() req := aggregatorproto.AggregatorRequest{ - SessionToken: ctx.Request().Header.Get("X-Auth-Token"), + SessionToken: ctx.Request().Header.Get(AuthTokenHeader), URL: ctx.Request().RequestURI, } l.LogWithFields(ctxt).Debugf("Incoming request received for deleting aggregate with request uri %s", req.URL) if req.SessionToken == "" { - errorMessage := "no X-Auth-Token found in request header" - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + errorMessage := invalidAuthTokenErrMsg + common.SendInvalidSessionResponse(ctx, errorMessage) } resp, err := a.DeleteAggregateRPC(ctxt, req) if err != nil { - errorMessage := "something went wrong with the RPC calls: " + err.Error() + errorMessage := rpcCallFailedErrMsg + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) - return + common.SendFailedRPCCallResponse(ctx, errorMessage) } l.LogWithFields(ctxt).Debugf("Outgoing response for deleting aggregate is %s with response code %d", string(resp.Body), int(resp.StatusCode)) - common.SetResponseHeader(ctx, resp.Header) - ctx.StatusCode(int(resp.StatusCode)) - ctx.Write(resp.Body) + sendAggregatorResponse(ctx, resp) } // AddElementsToAggregate is the handler for adding elements to an aggregate @@ -579,22 +448,14 @@ func (a *AggregatorRPCs) AddElementsToAggregate(ctx iris.Context) { if err != nil { errorMessage := "error while trying to get JSON body from the aggregator request body: " + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusBadRequest, response.MalformedJSON, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusBadRequest) - ctx.JSON(&response.Body) - return + common.SendMalformedJSONRequestErrResponse(ctx, errorMessage) } - sessionToken := ctx.Request().Header.Get("X-Auth-Token") + sessionToken := ctx.Request().Header.Get(AuthTokenHeader) if sessionToken == "" { - errorMessage := "no X-Auth-Token found in request header" - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + errorMessage := invalidAuthTokenErrMsg + common.SendInvalidSessionResponse(ctx, errorMessage) } // marshalling the req to make aggregator add request @@ -609,18 +470,12 @@ func (a *AggregatorRPCs) AddElementsToAggregate(ctx iris.Context) { resp, err := a.AddElementsToAggregateRPC(ctxt, addRequest) if err != nil { - errorMessage := "something went wrong with the RPC calls: " + err.Error() + errorMessage := rpcCallFailedErrMsg + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) - return + common.SendFailedRPCCallResponse(ctx, errorMessage) } l.LogWithFields(ctxt).Debugf("Outgoing response for adding an element to an aggregate is %s with response code %d", string(resp.Body), int(resp.StatusCode)) - common.SetResponseHeader(ctx, resp.Header) - ctx.StatusCode(int(resp.StatusCode)) - ctx.Write(resp.Body) + sendAggregatorResponse(ctx, resp) } // RemoveElementsFromAggregate is the handler for removing elements from an aggregate @@ -632,22 +487,14 @@ func (a *AggregatorRPCs) RemoveElementsFromAggregate(ctx iris.Context) { if err != nil { errorMessage := "error while trying to get JSON body from the aggregator request body: " + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusBadRequest, response.MalformedJSON, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusBadRequest) - ctx.JSON(&response.Body) - return + common.SendMalformedJSONRequestErrResponse(ctx, errorMessage) } - sessionToken := ctx.Request().Header.Get("X-Auth-Token") + sessionToken := ctx.Request().Header.Get(AuthTokenHeader) if sessionToken == "" { - errorMessage := "no X-Auth-Token found in request header" - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + errorMessage := invalidAuthTokenErrMsg + common.SendInvalidSessionResponse(ctx, errorMessage) } // marshalling the req to make aggregator remove request @@ -661,18 +508,12 @@ func (a *AggregatorRPCs) RemoveElementsFromAggregate(ctx iris.Context) { l.LogWithFields(ctxt).Debugf("Incoming request received for deleting element with uri %s from the aggregation collections with request body %s", removeRequest.URL, string(removeRequest.RequestBody)) resp, err := a.RemoveElementsFromAggregateRPC(ctxt, removeRequest) if err != nil { - errorMessage := "something went wrong with the RPC calls: " + err.Error() + errorMessage := rpcCallFailedErrMsg + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) - return + common.SendFailedRPCCallResponse(ctx, errorMessage) } l.LogWithFields(ctxt).Debugf("Outgoing response for removing an element from an aggregate is %s with response code %d", string(resp.Body), int(resp.StatusCode)) - common.SetResponseHeader(ctx, resp.Header) - ctx.StatusCode(int(resp.StatusCode)) - ctx.Write(resp.Body) + sendAggregatorResponse(ctx, resp) } // ResetAggregateElements is the handler for resetting elements of an aggregate @@ -684,22 +525,14 @@ func (a *AggregatorRPCs) ResetAggregateElements(ctx iris.Context) { if err != nil { errorMessage := "error while trying to get JSON body from the aggregator request body: " + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusBadRequest, response.MalformedJSON, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusBadRequest) - ctx.JSON(&response.Body) - return + common.SendMalformedJSONRequestErrResponse(ctx, errorMessage) } - sessionToken := ctx.Request().Header.Get("X-Auth-Token") + sessionToken := ctx.Request().Header.Get(AuthTokenHeader) if sessionToken == "" { - errorMessage := "no X-Auth-Token found in request header" - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + errorMessage := invalidAuthTokenErrMsg + common.SendInvalidSessionResponse(ctx, errorMessage) } // marshalling the req to make aggregator reset elements request @@ -713,32 +546,22 @@ func (a *AggregatorRPCs) ResetAggregateElements(ctx iris.Context) { l.LogWithFields(ctxt).Debugf("Incoming request received for resetting aggregate elements with uri %s with request body %s", resetRequest.URL, string(resetRequest.RequestBody)) resp, err := a.ResetAggregateElementsRPC(ctxt, resetRequest) if err != nil { - errorMessage := "something went wrong with the RPC calls: " + err.Error() + errorMessage := rpcCallFailedErrMsg + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) - return + common.SendFailedRPCCallResponse(ctx, errorMessage) } l.LogWithFields(ctxt).Debugf("Outgoing response for resetting aggregate elements is %s with response code %d", string(resp.Body), int(resp.StatusCode)) - common.SetResponseHeader(ctx, resp.Header) - ctx.StatusCode(int(resp.StatusCode)) - ctx.Write(resp.Body) + sendAggregatorResponse(ctx, resp) } // SetDefaultBootOrderAggregateElements is the handler for SetDefaultBootOrder elements of an aggregate func (a *AggregatorRPCs) SetDefaultBootOrderAggregateElements(ctx iris.Context) { defer ctx.Next() ctxt := ctx.Request().Context() - sessionToken := ctx.Request().Header.Get("X-Auth-Token") + sessionToken := ctx.Request().Header.Get(AuthTokenHeader) if sessionToken == "" { - errorMessage := "no X-Auth-Token found in request header" - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + errorMessage := invalidAuthTokenErrMsg + common.SendInvalidSessionResponse(ctx, errorMessage) } bootOrderRequest := aggregatorproto.AggregatorRequest{ @@ -748,18 +571,12 @@ func (a *AggregatorRPCs) SetDefaultBootOrderAggregateElements(ctx iris.Context) l.LogWithFields(ctxt).Debugf("Incoming request received for setting default boot order for all the element of an aggregate with uri %s and request body %s", bootOrderRequest.URL, string(bootOrderRequest.RequestBody)) resp, err := a.SetDefaultBootOrderAggregateElementsRPC(ctxt, bootOrderRequest) if err != nil { - errorMessage := "something went wrong with the RPC calls: " + err.Error() + errorMessage := rpcCallFailedErrMsg + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) - return + common.SendFailedRPCCallResponse(ctx, errorMessage) } l.LogWithFields(ctxt).Debugf("Outgoing response for setting default boot order for all the elements of an aggregate is %s with response code %d", string(resp.Body), int(resp.StatusCode)) - common.SetResponseHeader(ctx, resp.Header) - ctx.StatusCode(int(resp.StatusCode)) - ctx.Write(resp.Body) + sendAggregatorResponse(ctx, resp) } // GetAllConnectionMethods is the handler for get all connection methods @@ -768,32 +585,22 @@ func (a *AggregatorRPCs) GetAllConnectionMethods(ctx iris.Context) { ctxt := ctx.Request().Context() l.LogWithFields(ctxt).Debugf("Incoming request received for getting all the connection methods") req := aggregatorproto.AggregatorRequest{ - SessionToken: ctx.Request().Header.Get("X-Auth-Token"), + SessionToken: ctx.Request().Header.Get(AuthTokenHeader), } if req.SessionToken == "" { - errorMessage := "no X-Auth-Token found in request header" - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + errorMessage := invalidAuthTokenErrMsg + common.SendInvalidSessionResponse(ctx, errorMessage) } resp, err := a.GetAllConnectionMethodsRPC(ctxt, req) if err != nil { - errorMessage := "something went wrong with the RPC calls: " + err.Error() + errorMessage := rpcCallFailedErrMsg + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) - return + common.SendFailedRPCCallResponse(ctx, errorMessage) } l.LogWithFields(ctxt).Debugf("Outgoing response for getting all the connection methods is %s with response code %d", string(resp.Body), int(resp.StatusCode)) ctx.ResponseWriter().Header().Set("Allow", "GET") - common.SetResponseHeader(ctx, resp.Header) - ctx.StatusCode(int(resp.StatusCode)) - ctx.Write(resp.Body) + sendAggregatorResponse(ctx, resp) } // GetConnectionMethod is the handler for get connection method @@ -801,33 +608,23 @@ func (a *AggregatorRPCs) GetConnectionMethod(ctx iris.Context) { defer ctx.Next() ctxt := ctx.Request().Context() req := aggregatorproto.AggregatorRequest{ - SessionToken: ctx.Request().Header.Get("X-Auth-Token"), + SessionToken: ctx.Request().Header.Get(AuthTokenHeader), URL: ctx.Request().RequestURI, } l.LogWithFields(ctxt).Debugf("Incoming request received for getting the connection methods with the request URL %s", req.URL) if req.SessionToken == "" { - errorMessage := "no X-Auth-Token found in request header" - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + errorMessage := invalidAuthTokenErrMsg + common.SendInvalidSessionResponse(ctx, errorMessage) } resp, err := a.GetConnectionMethodRPC(ctxt, req) if err != nil { - errorMessage := "something went wrong with the RPC calls: " + err.Error() + errorMessage := rpcCallFailedErrMsg + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) - return + common.SendFailedRPCCallResponse(ctx, errorMessage) } l.LogWithFields(ctxt).Debugf("Outgoing response for getting a collection method is %s with response code %d", string(resp.Body), int(resp.StatusCode)) ctx.ResponseWriter().Header().Set("Allow", "GET") - common.SetResponseHeader(ctx, resp.Header) - ctx.StatusCode(int(resp.StatusCode)) - ctx.Write(resp.Body) + sendAggregatorResponse(ctx, resp) } // GetResetActionInfoService is the handler for getting GetResetActionInfoService details @@ -836,15 +633,11 @@ func (a *AggregatorRPCs) GetResetActionInfoService(ctx iris.Context) { ctxt := ctx.Request().Context() l.LogWithFields(ctxt).Debugf("Incoming request received for getting reset action info") req := aggregatorproto.AggregatorRequest{ - SessionToken: ctx.Request().Header.Get("X-Auth-Token"), + SessionToken: ctx.Request().Header.Get(AuthTokenHeader), } if req.SessionToken == "" { - errorMessage := "no X-Auth-Token found in request header" - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + errorMessage := invalidAuthTokenErrMsg + common.SendInvalidSessionResponse(ctx, errorMessage) } resp, err := a.GetResetActionInfoServiceRPC(ctxt, req) if err != nil { @@ -858,9 +651,7 @@ func (a *AggregatorRPCs) GetResetActionInfoService(ctx iris.Context) { } l.LogWithFields(ctxt).Debugf("Outgoing response for getting a reset action information is %s with response code %d", string(resp.Body), int(resp.StatusCode)) ctx.ResponseWriter().Header().Set("Allow", "GET") - common.SetResponseHeader(ctx, resp.Header) - ctx.StatusCode(int(resp.StatusCode)) - ctx.Write(resp.Body) + sendAggregatorResponse(ctx, resp) } @@ -870,15 +661,11 @@ func (a *AggregatorRPCs) GetSetDefaultBootOrderActionInfo(ctx iris.Context) { ctxt := ctx.Request().Context() l.LogWithFields(ctxt).Debugf("Incoming request received for getting the action info for set default boot order") req := aggregatorproto.AggregatorRequest{ - SessionToken: ctx.Request().Header.Get("X-Auth-Token"), + SessionToken: ctx.Request().Header.Get(AuthTokenHeader), } if req.SessionToken == "" { - errorMessage := "no X-Auth-Token found in request header" - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + errorMessage := invalidAuthTokenErrMsg + common.SendInvalidSessionResponse(ctx, errorMessage) } resp, err := a.GetSetDefaultBootOrderActionInfoRPC(ctxt, req) if err != nil { @@ -892,8 +679,13 @@ func (a *AggregatorRPCs) GetSetDefaultBootOrderActionInfo(ctx iris.Context) { } l.LogWithFields(ctxt).Debugf("Outgoing response for getting a set default boot order action information is %s with response code %d", string(resp.Body), int(resp.StatusCode)) ctx.ResponseWriter().Header().Set("Allow", "GET") + sendAggregatorResponse(ctx, resp) + +} + +// sendSystemsResponse writes the aggregator response to client +func sendAggregatorResponse(ctx iris.Context, resp *aggregatorproto.AggregatorResponse) { common.SetResponseHeader(ctx, resp.Header) ctx.StatusCode(int(resp.StatusCode)) ctx.Write(resp.Body) - } diff --git a/svc-api/handle/aggregator_test.go b/svc-api/handle/aggregator_test.go index 0c97de643..74441c82c 100644 --- a/svc-api/handle/aggregator_test.go +++ b/svc-api/handle/aggregator_test.go @@ -41,117 +41,33 @@ func testDeleteComputeRPCWIthRPCError(ctx context.Context, req aggregatorproto.A return &aggregatorproto.AggregatorResponse{}, errors.New("Unable to RPC Call") } func testGetAggregationService(ctx context.Context, req aggregatorproto.AggregatorRequest) (*aggregatorproto.AggregatorResponse, error) { - var response = &aggregatorproto.AggregatorResponse{} - if req.SessionToken == "ValidToken" { - response = &aggregatorproto.AggregatorResponse{ - StatusCode: 200, - StatusMessage: "Success", - Body: []byte(`{"Response":"Success"}`), - } - } else if req.SessionToken == "InvalidToken" { - response = &aggregatorproto.AggregatorResponse{ - StatusCode: 401, - StatusMessage: "Unauthorized", Body: []byte(`{"Response":"Unauthorized"}`), - } - } else if req.SessionToken == "token" { - return &aggregatorproto.AggregatorResponse{}, errors.New("Unable to RPC Call") - } - return response, nil + response, err := getMockAggregatorResponse(ctx, req, 200, 401) + return response, err } func testAddAggregationSourceRPCCall(ctx context.Context, req aggregatorproto.AggregatorRequest) (*aggregatorproto.AggregatorResponse, error) { - var response = &aggregatorproto.AggregatorResponse{} - if req.SessionToken == "ValidToken" { - response = &aggregatorproto.AggregatorResponse{ - StatusCode: http.StatusAccepted, - StatusMessage: "Success", - Body: []byte(`{"Response":"Success"}`), - } - } else if req.SessionToken == "InvalidToken" { - response = &aggregatorproto.AggregatorResponse{ - StatusCode: http.StatusUnauthorized, - StatusMessage: "Unauthorized", Body: []byte(`{"Response":"Unauthorized"}`), - } - } else if req.SessionToken == "token" { - return &aggregatorproto.AggregatorResponse{}, errors.New("Unable to RPC Call") - } - return response, nil + response, err := getMockAggregatorResponse(ctx, req, http.StatusAccepted, http.StatusUnauthorized) + return response, err } func testGetAllAggregationSourceRPC(ctx context.Context, req aggregatorproto.AggregatorRequest) (*aggregatorproto.AggregatorResponse, error) { - var response = &aggregatorproto.AggregatorResponse{} - if req.SessionToken == "ValidToken" { - response = &aggregatorproto.AggregatorResponse{ - StatusCode: http.StatusOK, - StatusMessage: "Success", - Body: []byte(`{"Response":"Success"}`), - } - } else if req.SessionToken == "InvalidToken" { - response = &aggregatorproto.AggregatorResponse{ - StatusCode: http.StatusUnauthorized, - StatusMessage: "Unauthorized", Body: []byte(`{"Response":"Unauthorized"}`), - } - } else if req.SessionToken == "token" { - return &aggregatorproto.AggregatorResponse{}, errors.New("Unable to RPC Call") - } - return response, nil + response, err := getMockAggregatorResponse(ctx, req, http.StatusOK, http.StatusUnauthorized) + return response, err } func testUpdateAggregationSourceRPCCall(ctx context.Context, req aggregatorproto.AggregatorRequest) (*aggregatorproto.AggregatorResponse, error) { - var response = &aggregatorproto.AggregatorResponse{} - if req.SessionToken == "ValidToken" { - response = &aggregatorproto.AggregatorResponse{ - StatusCode: http.StatusOK, - StatusMessage: "Success", - Body: []byte(`{"Response":"Success"}`), - } - } else if req.SessionToken == "InvalidToken" { - response = &aggregatorproto.AggregatorResponse{ - StatusCode: http.StatusUnauthorized, - StatusMessage: "Unauthorized", Body: []byte(`{"Response":"Unauthorized"}`), - } - } else if req.SessionToken == "token" { - return &aggregatorproto.AggregatorResponse{}, errors.New("Unable to RPC Call") - } - return response, nil + response, err := getMockAggregatorResponse(ctx, req, http.StatusOK, http.StatusUnauthorized) + return response, err } func testGetAggregationSourceRPC(ctx context.Context, req aggregatorproto.AggregatorRequest) (*aggregatorproto.AggregatorResponse, error) { - var response = &aggregatorproto.AggregatorResponse{} - if req.SessionToken == "ValidToken" { - response = &aggregatorproto.AggregatorResponse{ - StatusCode: http.StatusOK, - StatusMessage: "Success", - Body: []byte(`{"Response":"Success"}`), - } - } else if req.SessionToken == "InvalidToken" { - response = &aggregatorproto.AggregatorResponse{ - StatusCode: http.StatusUnauthorized, - StatusMessage: "Unauthorized", Body: []byte(`{"Response":"Unauthorized"}`), - } - } else if req.SessionToken == "token" { - return &aggregatorproto.AggregatorResponse{}, errors.New("Unable to RPC Call") - } - return response, nil + response, err := getMockAggregatorResponse(ctx, req, http.StatusOK, http.StatusUnauthorized) + return response, err } func testDeleteAggregationSourceRPCCall(ctx context.Context, req aggregatorproto.AggregatorRequest) (*aggregatorproto.AggregatorResponse, error) { - var response = &aggregatorproto.AggregatorResponse{} - if req.SessionToken == "ValidToken" { - response = &aggregatorproto.AggregatorResponse{ - StatusCode: http.StatusAccepted, - StatusMessage: "Success", - Body: []byte(`{"Response":"Success"}`), - } - } else if req.SessionToken == "InvalidToken" { - response = &aggregatorproto.AggregatorResponse{ - StatusCode: http.StatusUnauthorized, - StatusMessage: "Unauthorized", Body: []byte(`{"Response":"Unauthorized"}`), - } - } else if req.SessionToken == "token" { - return &aggregatorproto.AggregatorResponse{}, errors.New("Unable to RPC Call") - } - return response, nil + response, err := getMockAggregatorResponse(ctx, req, http.StatusAccepted, http.StatusUnauthorized) + return response, err } func testAggregateRPCCall(ctx context.Context, req aggregatorproto.AggregatorRequest) (*aggregatorproto.AggregatorResponse, error) { @@ -346,9 +262,33 @@ func TestAddAggregationSource(t *testing.T) { redfishRoutes := testApp.Party("/redfish/v1/AggregationService/AggregationSources") redfishRoutes.Post("/", a.AddAggregationSource) test := httptest.New(t, testApp) - test.POST("/redfish/v1/AggregationService/AggregationSources").WithHeader("X-Auth-Token", "ValidToken").WithJSON(addAggregationSourceRequest).Expect().Status(http.StatusAccepted) - test.POST("/redfish/v1/AggregationService/AggregationSources").WithHeader("X-Auth-Token", "InvalidToken").WithJSON(addAggregationSourceRequest).Expect().Status(http.StatusUnauthorized) - test.POST("/redfish/v1/AggregationService/AggregationSources").WithHeader("X-Auth-Token", "token").WithJSON(addAggregationSourceRequest).Expect().Status(http.StatusInternalServerError) + tests := []struct { + name string + authToken string + expectedStatus int + }{ + { + name: "Success", + authToken: "ValidToken", + expectedStatus: http.StatusAccepted, + }, + { + name: "Unauthorized error", + authToken: "InvalidToken", + expectedStatus: http.StatusUnauthorized, + }, + { + name: "Internal server error", + authToken: "token", + expectedStatus: http.StatusInternalServerError, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + test.POST("/redfish/v1/AggregationService/AggregationSources").WithHeader("X-Auth-Token", tt.authToken).WithJSON(addAggregationSourceRequest).Expect().Status(tt.expectedStatus) + }) + } } func TestGetAllAggregationSource(t *testing.T) { @@ -425,31 +365,45 @@ func TestCreateAggregate(t *testing.T) { redfishRoutes := testApp.Party("/redfish/v1/AggregationService/Aggregates") redfishRoutes.Post("/", a.CreateAggregate) test := httptest.New(t, testApp) - // update status code after the code is added - // test with valid token - test.POST( - "/redfish/v1/AggregationService/Aggregates", - ).WithHeader("X-Auth-Token", "ValidToken").WithJSON(aggregateRequest).Expect().Status(http.StatusCreated) - - // test with Invalid token - test.POST( - "/redfish/v1/AggregationService/Aggregates", - ).WithHeader("X-Auth-Token", "InvalidToken").WithJSON(aggregateRequest).Expect().Status(http.StatusUnauthorized) - - // test without token - test.POST( - "/redfish/v1/AggregationService/Aggregates", - ).WithHeader("X-Auth-Token", "").WithJSON(aggregateRequest).Expect().Status(http.StatusUnauthorized) + tests := []struct { + name string + authToken string + expectedStatus int + }{ + { + name: "valid token", + authToken: "ValidToken", + expectedStatus: http.StatusCreated, + }, + { + name: "Invalid token", + authToken: "InvalidToken", + expectedStatus: http.StatusUnauthorized, + }, + { + name: "without token", + authToken: "", + expectedStatus: http.StatusUnauthorized, + }, + { + name: "RPC Error", + authToken: "token", + expectedStatus: http.StatusInternalServerError, + }, + } // test without RequestBody test.POST( "/redfish/v1/AggregationService/Aggregates", ).WithHeader("X-Auth-Token", "ValidToken").Expect().Status(http.StatusBadRequest) - // test for RPC Error - test.POST( - "/redfish/v1/AggregationService/Aggregates", - ).WithHeader("X-Auth-Token", "token").WithJSON(aggregateRequest).Expect().Status(http.StatusInternalServerError) + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + test.POST( + "/redfish/v1/AggregationService/Aggregates", + ).WithHeader("X-Auth-Token", tt.authToken).WithJSON(aggregateRequest).Expect().Status(tt.expectedStatus) + }) + } } func TestGetAggregateCollection(t *testing.T) { @@ -731,3 +685,23 @@ func TestGetConnectionMethod(t *testing.T) { "/redfish/v1/AggregationService/ConnectionMethods/74116e00-0a4a-53e6-a959-e6a7465d6358", ).WithHeader("X-Auth-Token", "token").Expect().Status(http.StatusInternalServerError) //TODO : replace with http.StatusInternalServerError } + +// getMockAggregatorResponse will return a mock aggregator response based on the token in request +func getMockAggregatorResponse(ctx context.Context, req aggregatorproto.AggregatorRequest, validTokenStatusCode, invalidTokenStatusCode int32) (*aggregatorproto.AggregatorResponse, error) { + var response = &aggregatorproto.AggregatorResponse{} + if req.SessionToken == "ValidToken" { + response = &aggregatorproto.AggregatorResponse{ + StatusCode: validTokenStatusCode, + StatusMessage: "Success", + Body: []byte(`{"Response":"Success"}`), + } + } else if req.SessionToken == "InvalidToken" { + response = &aggregatorproto.AggregatorResponse{ + StatusCode: invalidTokenStatusCode, + StatusMessage: "Unauthorized", Body: []byte(`{"Response":"Unauthorized"}`), + } + } else if req.SessionToken == "token" { + return &aggregatorproto.AggregatorResponse{}, errors.New("Unable to RPC Call") + } + return response, nil +} diff --git a/svc-api/handle/chassis.go b/svc-api/handle/chassis.go index 56136cd40..8de2d4b68 100644 --- a/svc-api/handle/chassis.go +++ b/svc-api/handle/chassis.go @@ -58,7 +58,7 @@ func (chassis *ChassisRPCs) CreateChassis(ctx iris.Context) { ctxt, chassisproto.CreateChassisRequest{ RequestBody: *requestBody, - SessionToken: ctx.Request().Header.Get("X-Auth-Token"), + SessionToken: ctx.Request().Header.Get(AuthTokenHeader), }, ) @@ -88,7 +88,7 @@ func (chassis *ChassisRPCs) GetChassisCollection(ctx iris.Context) { defer ctx.Next() ctxt := ctx.Request().Context() req := chassisproto.GetChassisRequest{ - SessionToken: ctx.Request().Header.Get("X-Auth-Token"), + SessionToken: ctx.Request().Header.Get(AuthTokenHeader), URL: ctx.Request().RequestURI} l.LogWithFields(ctxt).Debugf("Incoming request received for getting chassis collection with request uri %s", string(req.URL)) if req.SessionToken == "" { @@ -124,7 +124,7 @@ func (chassis *ChassisRPCs) GetChassisResource(ctx iris.Context) { defer ctx.Next() ctxt := ctx.Request().Context() req := chassisproto.GetChassisRequest{ - SessionToken: ctx.Request().Header.Get("X-Auth-Token"), + SessionToken: ctx.Request().Header.Get(AuthTokenHeader), RequestParam: ctx.Params().Get("id"), ResourceID: ctx.Params().Get("rid"), URL: ctx.Request().RequestURI} @@ -163,7 +163,7 @@ func (chassis *ChassisRPCs) GetChassis(ctx iris.Context) { defer ctx.Next() ctxt := ctx.Request().Context() req := chassisproto.GetChassisRequest{ - SessionToken: ctx.Request().Header.Get("X-Auth-Token"), + SessionToken: ctx.Request().Header.Get(AuthTokenHeader), RequestParam: ctx.Params().Get("id"), URL: ctx.Request().RequestURI} l.LogWithFields(ctxt).Debugf("Incoming request received for getting chassis with request uri %s and request params %s", req.URL, req.RequestParam) @@ -210,7 +210,7 @@ func (chassis *ChassisRPCs) UpdateChassis(ctx iris.Context) { } l.LogWithFields(ctxt).Debugf("Incoming request received for updating chassis with request body %s", string(*requestBody)) rr, rerr := chassis.UpdateChassisRPC(ctxt, chassisproto.UpdateChassisRequest{ - SessionToken: ctx.Request().Header.Get("X-Auth-Token"), + SessionToken: ctx.Request().Header.Get(AuthTokenHeader), URL: ctx.Request().RequestURI, RequestBody: *requestBody, }) @@ -232,7 +232,7 @@ func (chassis *ChassisRPCs) DeleteChassis(ctx iris.Context) { ctxt := ctx.Request().Context() l.LogWithFields(ctxt).Debugf("Incoming request received for deleting chassis with request uri %s", ctx.Request().RequestURI) rpcResp, rpcErr := chassis.DeleteChassisRPC(ctxt, chassisproto.DeleteChassisRequest{ - SessionToken: ctx.Request().Header.Get("X-Auth-Token"), + SessionToken: ctx.Request().Header.Get(AuthTokenHeader), URL: ctx.Request().RequestURI, }) diff --git a/svc-api/handle/compositionservice.go b/svc-api/handle/compositionservice.go index 1a7117d9a..626c04d26 100755 --- a/svc-api/handle/compositionservice.go +++ b/svc-api/handle/compositionservice.go @@ -12,7 +12,7 @@ //License for the specific language governing permissions and limitations // under the License. -//Package handle ... +// Package handle ... package handle import ( @@ -45,28 +45,21 @@ type CompositionServiceRPCs struct { GetCompositionReservationsRPC func(req compositionserviceproto.GetCompositionResourceRequest) (*compositionserviceproto.CompositionServiceResponse, error) } -//GetCompositionService fetches all composition service +// GetCompositionService fetches all composition service func (cs *CompositionServiceRPCs) GetCompositionService(ctx iris.Context) { defer ctx.Next() req := compositionserviceproto.GetCompositionServiceRequest{ - SessionToken: ctx.Request().Header.Get("X-Auth-Token"), + SessionToken: ctx.Request().Header.Get(AuthTokenHeader), URL: ctx.Request().RequestURI, } if req.SessionToken == "" { - errorMessage := "error: no X-Auth-Token found in request header" - l.Log.Error(errorMessage) - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + errorMessage := invalidAuthTokenErrorMsg + writeErrorResponse(ctx, http.StatusUnauthorized, response.NoValidSession, errorMessage) } resp, err := cs.GetCompositionServiceRPC(req) if err != nil { errorMessage := "error: RPC error:" + err.Error() - l.Log.Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) + writeErrorResponse(ctx, http.StatusInternalServerError, response.InternalError, errorMessage) return } @@ -79,24 +72,17 @@ func (cs *CompositionServiceRPCs) GetCompositionService(ctx iris.Context) { func (cs *CompositionServiceRPCs) GetResourceBlockCollection(ctx iris.Context) { defer ctx.Next() req := compositionserviceproto.GetCompositionResourceRequest{ - SessionToken: ctx.Request().Header.Get("X-Auth-Token"), + SessionToken: ctx.Request().Header.Get(AuthTokenHeader), URL: ctx.Request().RequestURI, } if req.SessionToken == "" { - errorMessage := "error: no X-Auth-Token found in request header" - l.Log.Error(errorMessage) - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + errorMessage := invalidAuthTokenErrorMsg + writeErrorResponse(ctx, http.StatusUnauthorized, response.NoValidSession, errorMessage) } resp, err := cs.GetResourceBlockCollectionRPC(req) if err != nil { errorMessage := "error: RPC error:" + err.Error() - l.Log.Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) + writeErrorResponse(ctx, http.StatusInternalServerError, response.InternalError, errorMessage) return } @@ -109,25 +95,18 @@ func (cs *CompositionServiceRPCs) GetResourceBlockCollection(ctx iris.Context) { func (cs *CompositionServiceRPCs) GetResourceBlock(ctx iris.Context) { defer ctx.Next() req := compositionserviceproto.GetCompositionResourceRequest{ - SessionToken: ctx.Request().Header.Get("X-Auth-Token"), + SessionToken: ctx.Request().Header.Get(AuthTokenHeader), URL: ctx.Request().RequestURI, ResourceID: ctx.Params().Get("id"), } if req.SessionToken == "" { - errorMessage := "error: no X-Auth-Token found in request header" - l.Log.Error(errorMessage) - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + errorMessage := invalidAuthTokenErrorMsg + writeErrorResponse(ctx, http.StatusUnauthorized, response.NoValidSession, errorMessage) } resp, err := cs.GetResourceBlockRPC(req) if err != nil { errorMessage := "error: RPC error:" + err.Error() - l.Log.Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) + writeErrorResponse(ctx, http.StatusInternalServerError, response.InternalError, errorMessage) return } @@ -143,30 +122,19 @@ func (cs *CompositionServiceRPCs) CreateResourceBlock(ctx iris.Context) { err := ctx.ReadJSON(&req) if err != nil { errorMessage := "error while trying to get JSON body from the create Resource Block request body: " + err.Error() - l.Log.Error(errorMessage) - response := common.GeneralError(http.StatusBadRequest, response.MalformedJSON, errorMessage, nil, nil) - ctx.StatusCode(http.StatusBadRequest) - ctx.JSON(&response.Body) - return + writeErrorResponse(ctx, http.StatusBadRequest, response.MalformedJSON, errorMessage) } request, err := json.Marshal(req) if err != nil { errorMessage := "error while trying to create JSON request body: " + err.Error() - l.Log.Error(errorMessage) - response := common.GeneralError(http.StatusBadRequest, response.MalformedJSON, errorMessage, nil, nil) - ctx.StatusCode(http.StatusBadRequest) - ctx.JSON(&response.Body) + writeErrorResponse(ctx, http.StatusBadRequest, response.MalformedJSON, errorMessage) return } - sessionToken := ctx.Request().Header.Get("X-Auth-Token") + sessionToken := ctx.Request().Header.Get(AuthTokenHeader) if sessionToken == "" { - errorMessage := "error: no X-Auth-Token found in request header" - l.Log.Error(errorMessage) - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + errorMessage := invalidAuthTokenErrorMsg + writeErrorResponse(ctx, http.StatusUnauthorized, response.NoValidSession, errorMessage) } blockReq := compositionserviceproto.CreateCompositionResourceRequest{ @@ -178,10 +146,7 @@ func (cs *CompositionServiceRPCs) CreateResourceBlock(ctx iris.Context) { resp, err := cs.CreateResourceBlockRPC(blockReq) if err != nil { errorMessage := "RPC error:" + err.Error() - l.Log.Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) + writeErrorResponse(ctx, http.StatusInternalServerError, response.InternalError, errorMessage) return } @@ -193,14 +158,10 @@ func (cs *CompositionServiceRPCs) CreateResourceBlock(ctx iris.Context) { // DeleteResourceBlock Remove Resource Block Instance func (cs *CompositionServiceRPCs) DeleteResourceBlock(ctx iris.Context) { defer ctx.Next() - sessionToken := ctx.Request().Header.Get("X-Auth-Token") + sessionToken := ctx.Request().Header.Get(AuthTokenHeader) if sessionToken == "" { - errorMessage := "error: no X-Auth-Token found in request header" - l.Log.Error(errorMessage) - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + errorMessage := invalidAuthTokenErrorMsg + writeErrorResponse(ctx, http.StatusUnauthorized, response.NoValidSession, errorMessage) } req := compositionserviceproto.DeleteCompositionResourceRequest{ @@ -211,10 +172,7 @@ func (cs *CompositionServiceRPCs) DeleteResourceBlock(ctx iris.Context) { resp, err := cs.DeleteResourceBlockRPC(req) if err != nil { errorMessage := "RPC error:" + err.Error() - l.Log.Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) + writeErrorResponse(ctx, http.StatusInternalServerError, response.InternalError, errorMessage) return } @@ -227,24 +185,17 @@ func (cs *CompositionServiceRPCs) DeleteResourceBlock(ctx iris.Context) { func (cs *CompositionServiceRPCs) GetResourceZoneCollection(ctx iris.Context) { defer ctx.Next() req := compositionserviceproto.GetCompositionResourceRequest{ - SessionToken: ctx.Request().Header.Get("X-Auth-Token"), + SessionToken: ctx.Request().Header.Get(AuthTokenHeader), URL: ctx.Request().RequestURI, } if req.SessionToken == "" { - errorMessage := "error: no X-Auth-Token found in request header" - l.Log.Error(errorMessage) - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + errorMessage := invalidAuthTokenErrorMsg + writeErrorResponse(ctx, http.StatusUnauthorized, response.NoValidSession, errorMessage) } resp, err := cs.GetResourceZoneCollectionRPC(req) if err != nil { errorMessage := "error: RPC error:" + err.Error() - l.Log.Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) + writeErrorResponse(ctx, http.StatusInternalServerError, response.InternalError, errorMessage) return } @@ -257,25 +208,18 @@ func (cs *CompositionServiceRPCs) GetResourceZoneCollection(ctx iris.Context) { func (cs *CompositionServiceRPCs) GetResourceZone(ctx iris.Context) { defer ctx.Next() req := compositionserviceproto.GetCompositionResourceRequest{ - SessionToken: ctx.Request().Header.Get("X-Auth-Token"), + SessionToken: ctx.Request().Header.Get(AuthTokenHeader), URL: ctx.Request().RequestURI, ResourceID: ctx.Params().Get("id"), } if req.SessionToken == "" { - errorMessage := "error: no X-Auth-Token found in request header" - l.Log.Error(errorMessage) - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + errorMessage := invalidAuthTokenErrorMsg + writeErrorResponse(ctx, http.StatusUnauthorized, response.NoValidSession, errorMessage) } resp, err := cs.GetResourceZoneRPC(req) if err != nil { errorMessage := "error: RPC error:" + err.Error() - l.Log.Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) + writeErrorResponse(ctx, http.StatusInternalServerError, response.InternalError, errorMessage) return } @@ -291,30 +235,19 @@ func (cs *CompositionServiceRPCs) CreateResourceZone(ctx iris.Context) { err := ctx.ReadJSON(&req) if err != nil { errorMessage := "error while trying to get JSON body from the create Resource zone request body: " + err.Error() - l.Log.Error(errorMessage) - response := common.GeneralError(http.StatusBadRequest, response.MalformedJSON, errorMessage, nil, nil) - ctx.StatusCode(http.StatusBadRequest) - ctx.JSON(&response.Body) - return + writeErrorResponse(ctx, http.StatusBadRequest, response.MalformedJSON, errorMessage) } request, err := json.Marshal(req) if err != nil { errorMessage := "error while trying to create JSON request body: " + err.Error() - l.Log.Error(errorMessage) - response := common.GeneralError(http.StatusBadRequest, response.MalformedJSON, errorMessage, nil, nil) - ctx.StatusCode(http.StatusBadRequest) - ctx.JSON(&response.Body) + writeErrorResponse(ctx, http.StatusBadRequest, response.MalformedJSON, errorMessage) return } - sessionToken := ctx.Request().Header.Get("X-Auth-Token") + sessionToken := ctx.Request().Header.Get(AuthTokenHeader) if sessionToken == "" { - errorMessage := "error: no X-Auth-Token found in request header" - l.Log.Error(errorMessage) - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + errorMessage := invalidAuthTokenErrorMsg + writeErrorResponse(ctx, http.StatusUnauthorized, response.NoValidSession, errorMessage) } zoneReq := compositionserviceproto.CreateCompositionResourceRequest{ @@ -326,10 +259,7 @@ func (cs *CompositionServiceRPCs) CreateResourceZone(ctx iris.Context) { resp, err := cs.CreateResourceZoneRPC(zoneReq) if err != nil { errorMessage := "RPC error:" + err.Error() - l.Log.Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) + writeErrorResponse(ctx, http.StatusInternalServerError, response.InternalError, errorMessage) return } @@ -341,14 +271,10 @@ func (cs *CompositionServiceRPCs) CreateResourceZone(ctx iris.Context) { // DeleteResourceZone remove Resource zone Instance func (cs *CompositionServiceRPCs) DeleteResourceZone(ctx iris.Context) { defer ctx.Next() - sessionToken := ctx.Request().Header.Get("X-Auth-Token") + sessionToken := ctx.Request().Header.Get(AuthTokenHeader) if sessionToken == "" { - errorMessage := "error: no X-Auth-Token found in request header" - l.Log.Error(errorMessage) - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + errorMessage := invalidAuthTokenErrorMsg + writeErrorResponse(ctx, http.StatusUnauthorized, response.NoValidSession, errorMessage) } req := compositionserviceproto.DeleteCompositionResourceRequest{ @@ -359,10 +285,7 @@ func (cs *CompositionServiceRPCs) DeleteResourceZone(ctx iris.Context) { resp, err := cs.DeleteResourceZoneRPC(req) if err != nil { errorMessage := "RPC error:" + err.Error() - l.Log.Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) + writeErrorResponse(ctx, http.StatusInternalServerError, response.InternalError, errorMessage) return } @@ -378,31 +301,20 @@ func (cs *CompositionServiceRPCs) Compose(ctx iris.Context) { err := ctx.ReadJSON(&req) if err != nil { errorMessage := "error while trying to get JSON body from the compose request body: " + err.Error() - l.Log.Error(errorMessage) - response := common.GeneralError(http.StatusBadRequest, response.MalformedJSON, errorMessage, nil, nil) - ctx.StatusCode(http.StatusBadRequest) - ctx.JSON(&response.Body) - return + writeErrorResponse(ctx, http.StatusBadRequest, response.MalformedJSON, errorMessage) } request, err := json.Marshal(req) if err != nil { errorMessage := "error while trying to create JSON request body: " + err.Error() - l.Log.Error(errorMessage) - response := common.GeneralError(http.StatusBadRequest, response.MalformedJSON, errorMessage, nil, nil) - ctx.StatusCode(http.StatusBadRequest) - ctx.JSON(&response.Body) + writeErrorResponse(ctx, http.StatusBadRequest, response.MalformedJSON, errorMessage) return } - sessionToken := ctx.Request().Header.Get("X-Auth-Token") + sessionToken := ctx.Request().Header.Get(AuthTokenHeader) if sessionToken == "" { - errorMessage := "error: no X-Auth-Token found in request header" - l.Log.Error(errorMessage) - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + errorMessage := invalidAuthTokenErrorMsg + writeErrorResponse(ctx, http.StatusUnauthorized, response.NoValidSession, errorMessage) } composeReq := compositionserviceproto.ComposeRequest{ @@ -414,10 +326,7 @@ func (cs *CompositionServiceRPCs) Compose(ctx iris.Context) { resp, err := cs.ComposeRPC(composeReq) if err != nil { errorMessage := "RPC error:" + err.Error() - l.Log.Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) + writeErrorResponse(ctx, http.StatusInternalServerError, response.InternalError, errorMessage) return } @@ -430,25 +339,18 @@ func (cs *CompositionServiceRPCs) Compose(ctx iris.Context) { func (cs *CompositionServiceRPCs) GetActivePool(ctx iris.Context) { defer ctx.Next() req := compositionserviceproto.GetCompositionResourceRequest{ - SessionToken: ctx.Request().Header.Get("X-Auth-Token"), + SessionToken: ctx.Request().Header.Get(AuthTokenHeader), URL: ctx.Request().RequestURI, } if req.SessionToken == "" { - errorMessage := "error: no X-Auth-Token found in request header" - l.Log.Error(errorMessage) - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + errorMessage := invalidAuthTokenErrorMsg + writeErrorResponse(ctx, http.StatusUnauthorized, response.NoValidSession, errorMessage) } resp, err := cs.GetActivePoolRPC(req) if err != nil { errorMessage := "RPC error:" + err.Error() - l.Log.Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) + writeErrorResponse(ctx, http.StatusInternalServerError, response.InternalError, errorMessage) return } @@ -461,25 +363,18 @@ func (cs *CompositionServiceRPCs) GetActivePool(ctx iris.Context) { func (cs *CompositionServiceRPCs) GetFreePool(ctx iris.Context) { defer ctx.Next() req := compositionserviceproto.GetCompositionResourceRequest{ - SessionToken: ctx.Request().Header.Get("X-Auth-Token"), + SessionToken: ctx.Request().Header.Get(AuthTokenHeader), URL: ctx.Request().RequestURI, } if req.SessionToken == "" { - errorMessage := "error: no X-Auth-Token found in request header" - l.Log.Error(errorMessage) - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + errorMessage := invalidAuthTokenErrorMsg + writeErrorResponse(ctx, http.StatusUnauthorized, response.NoValidSession, errorMessage) } resp, err := cs.GetFreePoolRPC(req) if err != nil { errorMessage := "RPC error:" + err.Error() - l.Log.Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) + writeErrorResponse(ctx, http.StatusInternalServerError, response.InternalError, errorMessage) return } @@ -492,25 +387,18 @@ func (cs *CompositionServiceRPCs) GetFreePool(ctx iris.Context) { func (cs *CompositionServiceRPCs) GetCompositionReservations(ctx iris.Context) { defer ctx.Next() req := compositionserviceproto.GetCompositionResourceRequest{ - SessionToken: ctx.Request().Header.Get("X-Auth-Token"), + SessionToken: ctx.Request().Header.Get(AuthTokenHeader), URL: ctx.Request().RequestURI, } if req.SessionToken == "" { - errorMessage := "error: no X-Auth-Token found in request header" - l.Log.Error(errorMessage) - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + errorMessage := invalidAuthTokenErrorMsg + writeErrorResponse(ctx, http.StatusUnauthorized, response.NoValidSession, errorMessage) } resp, err := cs.GetCompositionReservationsRPC(req) if err != nil { errorMessage := "RPC error:" + err.Error() - l.Log.Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) + writeErrorResponse(ctx, http.StatusInternalServerError, response.InternalError, errorMessage) return } @@ -518,3 +406,12 @@ func (cs *CompositionServiceRPCs) GetCompositionReservations(ctx iris.Context) { ctx.StatusCode(int(resp.StatusCode)) ctx.Write(resp.Body) } + +// writeErrorResponse writes error response to client +func writeErrorResponse(ctx iris.Context, statusCode int32, statusMsg, errorMessage string) { + l.Log.Error(errorMessage) + response := common.GeneralError(statusCode, statusMsg, errorMessage, nil, nil) + ctx.StatusCode(int(statusCode)) + ctx.JSON(&response.Body) + return +} diff --git a/svc-api/handle/compositionservice_test.go b/svc-api/handle/compositionservice_test.go index f75426910..f4da70661 100644 --- a/svc-api/handle/compositionservice_test.go +++ b/svc-api/handle/compositionservice_test.go @@ -1,15 +1,15 @@ -//(C) Copyright [2020] Hewlett Packard Enterprise Development LP +// (C) Copyright [2020] Hewlett Packard Enterprise Development LP // -//Licensed under the Apache License, Version 2.0 (the "License"); you may -//not use this file except in compliance with the License. You may obtain -//a copy of the License at +// Licensed under the Apache License, Version 2.0 (the "License"); you may +// not use this file except in compliance with the License. You may obtain +// a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -//WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -//License for the specific language governing permissions and limitations +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +// License for the specific language governing permissions and limitations // under the License. package handle diff --git a/svc-api/handle/events.go b/svc-api/handle/events.go index 4f3086b52..7f9afb7f8 100644 --- a/svc-api/handle/events.go +++ b/svc-api/handle/events.go @@ -18,12 +18,10 @@ package handle import ( "context" "encoding/json" - "net/http" "github.com/ODIM-Project/ODIM/lib-utilities/common" l "github.com/ODIM-Project/ODIM/lib-utilities/logs" eventsproto "github.com/ODIM-Project/ODIM/lib-utilities/proto/events" - "github.com/ODIM-Project/ODIM/lib-utilities/response" iris "github.com/kataras/iris/v12" ) @@ -43,24 +41,16 @@ func (e *EventsRPCs) GetEventService(ctx iris.Context) { ctxt := ctx.Request().Context() l.LogWithFields(ctxt).Debug("Incoming request received for the Get Event service") req := eventsproto.EventSubRequest{ - SessionToken: ctx.Request().Header.Get("X-Auth-Token"), + SessionToken: ctx.Request().Header.Get(AuthTokenHeader), } if req.SessionToken == "" { - errorMessage := "no X-Auth-Token found in request header" - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + errorMessage := invalidAuthTokenErrMsg + common.SendInvalidSessionResponse(ctx, errorMessage) } resp, err := e.GetEventServiceRPC(ctxt, req) if err != nil { l.LogWithFields(ctxt).Error(err.Error()) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, err.Error(), nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) - return + common.SendFailedRPCCallResponse(ctx, err.Error()) } l.LogWithFields(ctxt).Debugf("Outgoing response for Getting Event service is %s and response status %d", string(resp.Body), int(resp.StatusCode)) ctx.ResponseWriter().Header().Set("Allow", "GET") @@ -80,32 +70,20 @@ func (e *EventsRPCs) CreateEventSubscription(ctx iris.Context) { if err != nil { errorMessage := "error while trying to get JSON body from the event subscription request body: " + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusBadRequest, response.MalformedJSON, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusBadRequest) - ctx.JSON(&response.Body) - return + common.SendMalformedJSONRequestErrResponse(ctx, errorMessage) } - req.SessionToken = ctx.Request().Header.Get("X-Auth-Token") + req.SessionToken = ctx.Request().Header.Get(AuthTokenHeader) if req.SessionToken == "" { - errorMessage := "no X-Auth-Token found in request header" - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + errorMessage := invalidAuthTokenErrMsg + common.SendInvalidSessionResponse(ctx, errorMessage) } req.PostBody, _ = json.Marshal(&SubscriptionReq) l.LogWithFields(ctxt).Debugf("Incoming request received for creating event subscription with request body %s", string(req.PostBody)) resp, err := e.CreateEventSubscriptionRPC(ctxt, req) if err != nil { l.LogWithFields(ctxt).Error(err.Error()) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, err.Error(), nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) - return + common.SendFailedRPCCallResponse(ctx, err.Error()) } l.LogWithFields(ctxt).Debugf("Outgoing response for creating event subscription is %s with response code %d", string(resp.Body), int(resp.StatusCode)) common.SetResponseHeader(ctx, resp.Header) @@ -124,33 +102,21 @@ func (e *EventsRPCs) SubmitTestEvent(ctx iris.Context) { if err != nil { errorMessage := "error while trying to get JSON body from the SubmitTestEvent request body: " + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusBadRequest, response.MalformedJSON, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusBadRequest) - ctx.JSON(&response.Body) - return + common.SendMalformedJSONRequestErrResponse(ctx, errorMessage) } - req.SessionToken = ctx.Request().Header.Get("X-Auth-Token") + req.SessionToken = ctx.Request().Header.Get(AuthTokenHeader) if req.SessionToken == "" { - errorMessage := "no X-Auth-Token found in request header" - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + errorMessage := invalidAuthTokenErrMsg + common.SendInvalidSessionResponse(ctx, errorMessage) } req.PostBody, _ = json.Marshal(&SubmitTestEventReq) l.LogWithFields(ctxt).Debugf("Incoming request received for submit test event with request body %s", string(req.PostBody)) resp, err := e.SubmitTestEventRPC(ctxt, req) if err != nil { l.LogWithFields(ctxt).Error(err.Error()) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, err.Error(), nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) - return + common.SendFailedRPCCallResponse(ctx, err.Error()) } l.LogWithFields(ctxt).Debugf("Outgoing response for submit test event is %s with response code %d", string(resp.Body), int(resp.StatusCode)) common.SetResponseHeader(ctx, resp.Header) @@ -164,25 +130,17 @@ func (e *EventsRPCs) GetEventSubscription(ctx iris.Context) { ctxt := ctx.Request().Context() var req eventsproto.EventRequest req.EventSubscriptionID = ctx.Params().Get("id") - req.SessionToken = ctx.Request().Header.Get("X-Auth-Token") + req.SessionToken = ctx.Request().Header.Get(AuthTokenHeader) l.LogWithFields(ctxt).Debugf("Incoming request received for getting event subscription with id %s", req.EventSubscriptionID) if req.SessionToken == "" { - errorMessage := "no X-Auth-Token found in request header" - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + errorMessage := invalidAuthTokenErrMsg + common.SendInvalidSessionResponse(ctx, errorMessage) } resp, err := e.GetEventSubscriptionRPC(ctxt, req) if err != nil { l.LogWithFields(ctxt).Error(err.Error()) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, err.Error(), nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response) - return + common.SendFailedRPCCallResponse(ctx, err.Error()) } l.LogWithFields(ctxt).Debugf("Outgoing response for getting event subscription is %s with response code %d", string(resp.Body), int(resp.StatusCode)) ctx.ResponseWriter().Header().Set("Allow", "GET, DELETE") @@ -197,25 +155,17 @@ func (e *EventsRPCs) DeleteEventSubscription(ctx iris.Context) { ctxt := ctx.Request().Context() var req eventsproto.EventRequest req.EventSubscriptionID = ctx.Params().Get("id") - req.SessionToken = ctx.Request().Header.Get("X-Auth-Token") + req.SessionToken = ctx.Request().Header.Get(AuthTokenHeader) l.LogWithFields(ctxt).Debugf("Incoming request received for deleting event subscription with id %s", req.EventSubscriptionID) if req.SessionToken == "" { - errorMessage := "no X-Auth-Token found in request header" - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + errorMessage := invalidAuthTokenErrMsg + common.SendInvalidSessionResponse(ctx, errorMessage) } resp, err := e.DeleteEventSubscriptionRPC(ctxt, req) if err != nil { l.LogWithFields(ctxt).Error(err.Error()) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, err.Error(), nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) - return + common.SendFailedRPCCallResponse(ctx, err.Error()) } l.LogWithFields(ctxt).Debugf("Outgoing response for deleting event subscription is %s with response code %d", string(resp.Body), int(resp.StatusCode)) common.SetResponseHeader(ctx, resp.Header) @@ -228,25 +178,17 @@ func (e *EventsRPCs) GetEventSubscriptionsCollection(ctx iris.Context) { defer ctx.Next() ctxt := ctx.Request().Context() var req eventsproto.EventRequest - req.SessionToken = ctx.Request().Header.Get("X-Auth-Token") + req.SessionToken = ctx.Request().Header.Get(AuthTokenHeader) l.LogWithFields(ctxt).Debugf("Incoming request received for getting all the event subscription collections") if req.SessionToken == "" { - errorMessage := "no X-Auth-Token found in request header" - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + errorMessage := invalidAuthTokenErrMsg + common.SendInvalidSessionResponse(ctx, errorMessage) } resp, err := e.GetEventSubscriptionsCollectionRPC(ctxt, req) if err != nil { l.LogWithFields(ctxt).Error(err.Error()) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, err.Error(), nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) - return + common.SendFailedRPCCallResponse(ctx, err.Error()) } l.LogWithFields(ctxt).Debugf("Outgoing response for getting event subscription collections is %s with response code %d", string(resp.Body), int(resp.StatusCode)) ctx.ResponseWriter().Header().Set("Allow", "GET, POST") diff --git a/svc-api/handle/fabrics.go b/svc-api/handle/fabrics.go index dabbef14d..5c8d21140 100644 --- a/svc-api/handle/fabrics.go +++ b/svc-api/handle/fabrics.go @@ -18,12 +18,10 @@ package handle import ( "context" "encoding/json" - "net/http" "github.com/ODIM-Project/ODIM/lib-utilities/common" l "github.com/ODIM-Project/ODIM/lib-utilities/logs" fabricsproto "github.com/ODIM-Project/ODIM/lib-utilities/proto/fabrics" - "github.com/ODIM-Project/ODIM/lib-utilities/response" iris "github.com/kataras/iris/v12" ) @@ -34,42 +32,34 @@ type FabricRPCs struct { DeleteFabricResourceRPC func(context.Context, fabricsproto.FabricRequest) (*fabricsproto.FabricResponse, error) } +const ( + rpcFailedErrMsg = "RPC error: " +) + // GetFabricCollection defines the GetFabricCollection iris handler. // The method extracts given Fabric Resource func (f *FabricRPCs) GetFabricCollection(ctx iris.Context) { defer ctx.Next() ctxt := ctx.Request().Context() - req := fabricsproto.FabricRequest{ - SessionToken: ctx.Request().Header.Get("X-Auth-Token"), - URL: ctx.Request().RequestURI, - } + req := getFabricRequest(ctx) l.LogWithFields(ctxt).Debugf("Incoming request received for getting fabric collection with request url %s", req.URL) if req.SessionToken == "" { - errorMessage := "error: no X-Auth-Token found in request header" - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + errorMessage := invalidAuthTokenErrorMsg + common.SendInvalidSessionResponse(ctx, errorMessage) } resp, err := f.GetFabricResourceRPC(ctxt, req) if err != nil && resp == nil { - errorMessage := "RPC error: " + err.Error() + errorMessage := rpcFailedErrMsg + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) + common.SendFailedRPCCallResponse(ctx, errorMessage) return } resp.Header = map[string]string{ "Allow": `"GET"`, } l.LogWithFields(ctxt).Debugf("Outgoing response for getting all fabric collection is %s with status code %d", string(resp.Body), int(resp.StatusCode)) - common.SetResponseHeader(ctx, resp.Header) - ctx.StatusCode(int(resp.StatusCode)) - ctx.Write(resp.Body) + sendFabricResponse(ctx, resp) } // GetFabric defines the GetFabric iris handler. @@ -77,37 +67,25 @@ func (f *FabricRPCs) GetFabricCollection(ctx iris.Context) { func (f *FabricRPCs) GetFabric(ctx iris.Context) { defer ctx.Next() ctxt := ctx.Request().Context() - req := fabricsproto.FabricRequest{ - SessionToken: ctx.Request().Header.Get("X-Auth-Token"), - URL: ctx.Request().RequestURI, - } + req := getFabricRequest(ctx) l.LogWithFields(ctxt).Debugf("Incoming request received for creating fabric with request url %s", req.URL) if req.SessionToken == "" { - errorMessage := "error: no X-Auth-Token found in request header" - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + errorMessage := invalidAuthTokenErrorMsg + common.SendInvalidSessionResponse(ctx, errorMessage) } resp, err := f.GetFabricResourceRPC(ctxt, req) if err != nil && resp == nil { - errorMessage := "RPC error: " + err.Error() + errorMessage := rpcFailedErrMsg + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) + common.SendFailedRPCCallResponse(ctx, errorMessage) return } resp.Header = map[string]string{ "Allow": `"GET"`, } l.LogWithFields(ctxt).Debugf("Outgoing response for creating fabric is %s with status code %d", string(resp.Body), int(resp.StatusCode)) - common.SetResponseHeader(ctx, resp.Header) - ctx.StatusCode(int(resp.StatusCode)) - ctx.Write(resp.Body) + sendFabricResponse(ctx, resp) } // GetFabricSwitchCollection defines the GetFabricSwitchCollection iris handler. @@ -115,37 +93,25 @@ func (f *FabricRPCs) GetFabric(ctx iris.Context) { func (f *FabricRPCs) GetFabricSwitchCollection(ctx iris.Context) { defer ctx.Next() ctxt := ctx.Request().Context() - req := fabricsproto.FabricRequest{ - SessionToken: ctx.Request().Header.Get("X-Auth-Token"), - URL: ctx.Request().RequestURI, - } + req := getFabricRequest(ctx) l.LogWithFields(ctxt).Debugf("Incoming request received for getting fabric switch collection with request url %s", req.URL) if req.SessionToken == "" { - errorMessage := "error: no X-Auth-Token found in request header" - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + errorMessage := invalidAuthTokenErrorMsg + common.SendInvalidSessionResponse(ctx, errorMessage) } resp, err := f.GetFabricResourceRPC(ctxt, req) if err != nil && resp == nil { - errorMessage := "RPC error: " + err.Error() + errorMessage := rpcFailedErrMsg + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) + common.SendFailedRPCCallResponse(ctx, errorMessage) return } resp.Header = map[string]string{ "Allow": `"GET"`, } l.LogWithFields(ctxt).Debugf("Outgoing response for getting all fabric switch collection is %s with status code %d", string(resp.Body), int(resp.StatusCode)) - common.SetResponseHeader(ctx, resp.Header) - ctx.StatusCode(int(resp.StatusCode)) - ctx.Write(resp.Body) + sendFabricResponse(ctx, resp) } // GetFabricSwitch defines the GetFabricSwitch iris handler. @@ -153,37 +119,25 @@ func (f *FabricRPCs) GetFabricSwitchCollection(ctx iris.Context) { func (f *FabricRPCs) GetFabricSwitch(ctx iris.Context) { defer ctx.Next() ctxt := ctx.Request().Context() - req := fabricsproto.FabricRequest{ - SessionToken: ctx.Request().Header.Get("X-Auth-Token"), - URL: ctx.Request().RequestURI, - } + req := getFabricRequest(ctx) l.LogWithFields(ctxt).Debugf("Incoming request received for creating fabric switch with request url %s", req.URL) if req.SessionToken == "" { - errorMessage := "error: no X-Auth-Token found in request header" - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + errorMessage := invalidAuthTokenErrorMsg + common.SendInvalidSessionResponse(ctx, errorMessage) } resp, err := f.GetFabricResourceRPC(ctxt, req) if err != nil && resp == nil { - errorMessage := "RPC error: " + err.Error() + errorMessage := rpcFailedErrMsg + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) + common.SendFailedRPCCallResponse(ctx, errorMessage) return } resp.Header = map[string]string{ "Allow": `"GET"`, } l.LogWithFields(ctxt).Debugf("Outgoing response for creating fabric switch is %s with status code %d", string(resp.Body), int(resp.StatusCode)) - common.SetResponseHeader(ctx, resp.Header) - ctx.StatusCode(int(resp.StatusCode)) - ctx.Write(resp.Body) + sendFabricResponse(ctx, resp) } // GetSwitchPortCollection defines the GetSwitchPortCollection iris handler. @@ -191,37 +145,25 @@ func (f *FabricRPCs) GetFabricSwitch(ctx iris.Context) { func (f *FabricRPCs) GetSwitchPortCollection(ctx iris.Context) { defer ctx.Next() ctxt := ctx.Request().Context() - req := fabricsproto.FabricRequest{ - SessionToken: ctx.Request().Header.Get("X-Auth-Token"), - URL: ctx.Request().RequestURI, - } + req := getFabricRequest(ctx) l.LogWithFields(ctxt).Debugf("Incoming request received for getting switch port collection with request url %s", req.URL) if req.SessionToken == "" { - errorMessage := "error: no X-Auth-Token found in request header" - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + errorMessage := invalidAuthTokenErrorMsg + common.SendInvalidSessionResponse(ctx, errorMessage) } resp, err := f.GetFabricResourceRPC(ctxt, req) if err != nil && resp == nil { - errorMessage := "RPC error: " + err.Error() + errorMessage := rpcFailedErrMsg + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) + common.SendFailedRPCCallResponse(ctx, errorMessage) return } resp.Header = map[string]string{ "Allow": `"GET"`, } l.LogWithFields(ctxt).Debugf("Outgoing response for getting switch port collection is %s with status code %d", string(resp.Body), int(resp.StatusCode)) - common.SetResponseHeader(ctx, resp.Header) - ctx.StatusCode(int(resp.StatusCode)) - ctx.Write(resp.Body) + sendFabricResponse(ctx, resp) } // GetSwitchPort defines the GetSwitchPort iris handler. @@ -229,37 +171,25 @@ func (f *FabricRPCs) GetSwitchPortCollection(ctx iris.Context) { func (f *FabricRPCs) GetSwitchPort(ctx iris.Context) { defer ctx.Next() ctxt := ctx.Request().Context() - req := fabricsproto.FabricRequest{ - SessionToken: ctx.Request().Header.Get("X-Auth-Token"), - URL: ctx.Request().RequestURI, - } + req := getFabricRequest(ctx) l.LogWithFields(ctxt).Debugf("Incoming request received for getting switch port with request url %s", req.URL) if req.SessionToken == "" { - errorMessage := "error: no X-Auth-Token found in request header" - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + errorMessage := invalidAuthTokenErrorMsg + common.SendInvalidSessionResponse(ctx, errorMessage) } resp, err := f.GetFabricResourceRPC(ctxt, req) if err != nil && resp == nil { - errorMessage := "RPC error: " + err.Error() + errorMessage := rpcFailedErrMsg + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) + common.SendFailedRPCCallResponse(ctx, errorMessage) return } resp.Header = map[string]string{ "Allow": `"GET", "PATCH"`, } l.LogWithFields(ctxt).Debugf("Outgoing response for getting switch port is %s with status code %d", string(resp.Body), int(resp.StatusCode)) - common.SetResponseHeader(ctx, resp.Header) - ctx.StatusCode(int(resp.StatusCode)) - ctx.Write(resp.Body) + sendFabricResponse(ctx, resp) } // GetFabricZoneCollection defines the GetFabricZoneCollection iris handler. @@ -267,37 +197,25 @@ func (f *FabricRPCs) GetSwitchPort(ctx iris.Context) { func (f *FabricRPCs) GetFabricZoneCollection(ctx iris.Context) { defer ctx.Next() ctxt := ctx.Request().Context() - req := fabricsproto.FabricRequest{ - SessionToken: ctx.Request().Header.Get("X-Auth-Token"), - URL: ctx.Request().RequestURI, - } + req := getFabricRequest(ctx) l.LogWithFields(ctxt).Debugf("Incoming request received for getting fabric zone collection with request url %s", req.URL) if req.SessionToken == "" { - errorMessage := "error: no X-Auth-Token found in request header" - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + errorMessage := invalidAuthTokenErrorMsg + common.SendInvalidSessionResponse(ctx, errorMessage) } resp, err := f.GetFabricResourceRPC(ctxt, req) if err != nil && resp == nil { - errorMessage := "RPC error: " + err.Error() + errorMessage := rpcFailedErrMsg + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) + common.SendFailedRPCCallResponse(ctx, errorMessage) return } resp.Header = map[string]string{ "Allow": `"GET", "POST"`, } l.LogWithFields(ctxt).Debugf("Outgoing response for getting fabric zone collection is %s with status code %d", string(resp.Body), int(resp.StatusCode)) - common.SetResponseHeader(ctx, resp.Header) - ctx.StatusCode(int(resp.StatusCode)) - ctx.Write(resp.Body) + sendFabricResponse(ctx, resp) } // GetFabricZone defines the GetFabricZone iris handler. @@ -305,37 +223,25 @@ func (f *FabricRPCs) GetFabricZoneCollection(ctx iris.Context) { func (f *FabricRPCs) GetFabricZone(ctx iris.Context) { defer ctx.Next() ctxt := ctx.Request().Context() - req := fabricsproto.FabricRequest{ - SessionToken: ctx.Request().Header.Get("X-Auth-Token"), - URL: ctx.Request().RequestURI, - } + req := getFabricRequest(ctx) l.LogWithFields(ctxt).Debugf("Incoming request received for getting fabric zone with request url %s", req.URL) if req.SessionToken == "" { - errorMessage := "error: no X-Auth-Token found in request header" - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + errorMessage := invalidAuthTokenErrorMsg + common.SendInvalidSessionResponse(ctx, errorMessage) } resp, err := f.GetFabricResourceRPC(ctxt, req) if err != nil && resp == nil { - errorMessage := "RPC error: " + err.Error() + errorMessage := rpcFailedErrMsg + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) + common.SendFailedRPCCallResponse(ctx, errorMessage) return } resp.Header = map[string]string{ "Allow": `"GET", "PUT", "PATCH", "DELETE"`, } l.LogWithFields(ctxt).Debugf("Outgoing response for getting fabric zone is %s with status code %d", string(resp.Body), int(resp.StatusCode)) - common.SetResponseHeader(ctx, resp.Header) - ctx.StatusCode(int(resp.StatusCode)) - ctx.Write(resp.Body) + sendFabricResponse(ctx, resp) } // GetFabricEndPointCollection defines the GetFabricEndPointCollection iris handler. @@ -343,37 +249,25 @@ func (f *FabricRPCs) GetFabricZone(ctx iris.Context) { func (f *FabricRPCs) GetFabricEndPointCollection(ctx iris.Context) { defer ctx.Next() ctxt := ctx.Request().Context() - req := fabricsproto.FabricRequest{ - SessionToken: ctx.Request().Header.Get("X-Auth-Token"), - URL: ctx.Request().RequestURI, - } + req := getFabricRequest(ctx) l.LogWithFields(ctxt).Debugf("Incoming request received for getting fabric endpoint collection with request url %s", req.URL) if req.SessionToken == "" { - errorMessage := "error: no X-Auth-Token found in request header" - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + errorMessage := invalidAuthTokenErrorMsg + common.SendInvalidSessionResponse(ctx, errorMessage) } resp, err := f.GetFabricResourceRPC(ctxt, req) if err != nil && resp == nil { - errorMessage := "RPC error: " + err.Error() + errorMessage := rpcFailedErrMsg + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) + common.SendFailedRPCCallResponse(ctx, errorMessage) return } resp.Header = map[string]string{ "Allow": `"GET", "POST"`, } l.LogWithFields(ctxt).Debugf("Outgoing response for getting fabric endpoint collection is %s with status code %d", string(resp.Body), int(resp.StatusCode)) - common.SetResponseHeader(ctx, resp.Header) - ctx.StatusCode(int(resp.StatusCode)) - ctx.Write(resp.Body) + sendFabricResponse(ctx, resp) } // GetFabricEndPoints defines the GetFabricEndPoints iris handler. @@ -381,37 +275,25 @@ func (f *FabricRPCs) GetFabricEndPointCollection(ctx iris.Context) { func (f *FabricRPCs) GetFabricEndPoints(ctx iris.Context) { defer ctx.Next() ctxt := ctx.Request().Context() - req := fabricsproto.FabricRequest{ - SessionToken: ctx.Request().Header.Get("X-Auth-Token"), - URL: ctx.Request().RequestURI, - } + req := getFabricRequest(ctx) l.LogWithFields(ctxt).Debugf("Incoming request received for getting fabric endpoint with request url %s", req.URL) if req.SessionToken == "" { - errorMessage := "error: no X-Auth-Token found in request header" - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + errorMessage := invalidAuthTokenErrorMsg + common.SendInvalidSessionResponse(ctx, errorMessage) } resp, err := f.GetFabricResourceRPC(ctxt, req) if err != nil && resp == nil { - errorMessage := "RPC error: " + err.Error() + errorMessage := rpcFailedErrMsg + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) + common.SendFailedRPCCallResponse(ctx, errorMessage) return } resp.Header = map[string]string{ "Allow": `"GET", "PUT", "PATCH", "DELETE"`, } l.LogWithFields(ctxt).Debugf("Outgoing response for getting fabric endpoint is %s with status code %d", string(resp.Body), int(resp.StatusCode)) - common.SetResponseHeader(ctx, resp.Header) - ctx.StatusCode(int(resp.StatusCode)) - ctx.Write(resp.Body) + sendFabricResponse(ctx, resp) } // GetFabricAddressPoolCollection defines the GetFabricAddressPoolCollection iris handler. @@ -419,37 +301,25 @@ func (f *FabricRPCs) GetFabricEndPoints(ctx iris.Context) { func (f *FabricRPCs) GetFabricAddressPoolCollection(ctx iris.Context) { defer ctx.Next() ctxt := ctx.Request().Context() - req := fabricsproto.FabricRequest{ - SessionToken: ctx.Request().Header.Get("X-Auth-Token"), - URL: ctx.Request().RequestURI, - } + req := getFabricRequest(ctx) l.LogWithFields(ctxt).Debugf("Incoming request received for getting fabric address pool collection with request url %s", req.URL) if req.SessionToken == "" { - errorMessage := "error: no X-Auth-Token found in request header" - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + errorMessage := invalidAuthTokenErrorMsg + common.SendInvalidSessionResponse(ctx, errorMessage) } resp, err := f.GetFabricResourceRPC(ctxt, req) if err != nil && resp == nil { - errorMessage := "RPC error: " + err.Error() + errorMessage := rpcFailedErrMsg + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) + common.SendFailedRPCCallResponse(ctx, errorMessage) return } resp.Header = map[string]string{ "Allow": `"GET", "POST"`, } l.LogWithFields(ctxt).Debugf("Outgoing response for getting fabric address pool collection is %s with status code %d", string(resp.Body), int(resp.StatusCode)) - common.SetResponseHeader(ctx, resp.Header) - ctx.StatusCode(int(resp.StatusCode)) - ctx.Write(resp.Body) + sendFabricResponse(ctx, resp) } // GetFabricAddressPool defines the GetFabricAddressPool iris handler. @@ -457,37 +327,25 @@ func (f *FabricRPCs) GetFabricAddressPoolCollection(ctx iris.Context) { func (f *FabricRPCs) GetFabricAddressPool(ctx iris.Context) { defer ctx.Next() ctxt := ctx.Request().Context() - req := fabricsproto.FabricRequest{ - SessionToken: ctx.Request().Header.Get("X-Auth-Token"), - URL: ctx.Request().RequestURI, - } + req := getFabricRequest(ctx) l.LogWithFields(ctxt).Debugf("Incoming request received for getting fabric address pool with request url %s", req.URL) if req.SessionToken == "" { - errorMessage := "error: no X-Auth-Token found in request header" - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + errorMessage := invalidAuthTokenErrorMsg + common.SendInvalidSessionResponse(ctx, errorMessage) } resp, err := f.GetFabricResourceRPC(ctxt, req) if err != nil && resp == nil { - errorMessage := "RPC error: " + err.Error() + errorMessage := rpcFailedErrMsg + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) + common.SendFailedRPCCallResponse(ctx, errorMessage) return } resp.Header = map[string]string{ "Allow": `"GET", "PUT", "PATCH", "DELETE"`, } l.LogWithFields(ctxt).Debugf("Outgoing response for getting fabric address pool is %s with status code %d", string(resp.Body), int(resp.StatusCode)) - common.SetResponseHeader(ctx, resp.Header) - ctx.StatusCode(int(resp.StatusCode)) - ctx.Write(resp.Body) + sendFabricResponse(ctx, resp) } // UpdateFabricResource defines the UpdateFabricResource iris handler. @@ -496,29 +354,21 @@ func (f *FabricRPCs) UpdateFabricResource(ctx iris.Context) { defer ctx.Next() ctxt := ctx.Request().Context() req := fabricsproto.FabricRequest{ - SessionToken: ctx.Request().Header.Get("X-Auth-Token"), + SessionToken: ctx.Request().Header.Get(AuthTokenHeader), URL: ctx.Request().RequestURI, Method: ctx.Request().Method, } if req.SessionToken == "" { - errorMessage := "error: no X-Auth-Token found in request header" - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + errorMessage := invalidAuthTokenErrorMsg + common.SendInvalidSessionResponse(ctx, errorMessage) } var createReq interface{} err := ctx.ReadJSON(&createReq) if err != nil { errorMessage := "error while trying to get JSON body from the request body: " + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusBadRequest, response.MalformedJSON, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusBadRequest) - ctx.JSON(&response.Body) - return + common.SendMalformedJSONRequestErrResponse(ctx, errorMessage) } // marshalling the req to make fabric UpdateFabricResource request @@ -527,28 +377,20 @@ func (f *FabricRPCs) UpdateFabricResource(ctx iris.Context) { if err != nil { errorMessage := "error while trying to create JSON request body: " + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) + common.SendFailedRPCCallResponse(ctx, errorMessage) return } l.LogWithFields(ctxt).Debugf("Incoming request received for updating fabric resources with request url %s and request body %s", req.URL, string(request)) req.RequestBody = request resp, err := f.UpdateFabricResourceRPC(ctxt, req) if err != nil && resp == nil { - errorMessage := "RPC error: " + err.Error() + errorMessage := rpcFailedErrMsg + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) + common.SendFailedRPCCallResponse(ctx, errorMessage) return } l.LogWithFields(ctxt).Debugf("Outgoing response for updating fabric resource is %s with status code %d", string(resp.Body), int(resp.StatusCode)) - common.SetResponseHeader(ctx, resp.Header) - ctx.StatusCode(int(resp.StatusCode)) - ctx.Write(resp.Body) + sendFabricResponse(ctx, resp) } // DeleteFabricResource defines the DeleteFabricResource iris handler. @@ -556,32 +398,35 @@ func (f *FabricRPCs) UpdateFabricResource(ctx iris.Context) { func (f *FabricRPCs) DeleteFabricResource(ctx iris.Context) { defer ctx.Next() ctxt := ctx.Request().Context() - req := fabricsproto.FabricRequest{ - SessionToken: ctx.Request().Header.Get("X-Auth-Token"), - URL: ctx.Request().RequestURI, - } + req := getFabricRequest(ctx) l.LogWithFields(ctxt).Debugf("Incoming request received for deleting fabric resources with request url %s", req.URL) if req.SessionToken == "" { - errorMessage := "error: no X-Auth-Token found in request header" - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + errorMessage := invalidAuthTokenErrorMsg + common.SendInvalidSessionResponse(ctx, errorMessage) } resp, err := f.DeleteFabricResourceRPC(ctxt, req) if err != nil && resp == nil { - errorMessage := "RPC error: " + err.Error() + errorMessage := rpcFailedErrMsg + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) + common.SendFailedRPCCallResponse(ctx, errorMessage) return } l.LogWithFields(ctxt).Debugf("Outgoing response for deleting fabric resource is %s with status code %d", string(resp.Body), int(resp.StatusCode)) + sendFabricResponse(ctx, resp) +} + +// sendFabricResponse writes the fabric response to client +func sendFabricResponse(ctx iris.Context, resp *fabricsproto.FabricResponse) { common.SetResponseHeader(ctx, resp.Header) ctx.StatusCode(int(resp.StatusCode)) ctx.Write(resp.Body) } + +// getFabricRequest will extract the request from the context and return +func getFabricRequest(ctx iris.Context) fabricsproto.FabricRequest { + return fabricsproto.FabricRequest{ + SessionToken: ctx.Request().Header.Get(AuthTokenHeader), + URL: ctx.Request().RequestURI, + } +} diff --git a/svc-api/handle/handlers.go b/svc-api/handle/handlers.go index 503c78211..33f0366b6 100755 --- a/svc-api/handle/handlers.go +++ b/svc-api/handle/handlers.go @@ -819,13 +819,10 @@ func (r *Registry) GetRegistryFileCollection(ctx iris.Context) { defer ctx.Next() ctxt := ctx.Request().Context() // Authorize the request here - sessionToken := ctx.Request().Header.Get("X-Auth-Token") + sessionToken := ctx.Request().Header.Get(AuthTokenHeader) if sessionToken == "" { - errorMessage := "error: no X-Auth-Token found in request header" - response := common.GeneralError(http.StatusUnauthorized, errResponse.NoValidSession, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) + errorMessage := invalidAuthTokenErrorMsg + common.SendInvalidSessionResponse(ctx, errorMessage) return } authResp, err := r.Auth(ctxt, sessionToken, []string{common.PrivilegeLogin}, []string{}) @@ -834,11 +831,7 @@ func (r *Registry) GetRegistryFileCollection(ctx iris.Context) { if err != nil { errMsg = errMsg + ": " + err.Error() } - l.LogWithFields(ctxt).Error(errMsg) - ctx.StatusCode(int(authResp.StatusCode)) - common.SetResponseHeader(ctx, authResp.Header) - ctx.JSON(authResp.Body) - return + sendAuthErrorResponse(ctxt, ctx, errMsg, authResp) } //Get the Registrystore location @@ -894,7 +887,7 @@ func (r *Registry) GetRegistryFileCollection(ctx iris.Context) { func (r *Registry) GetMessageRegistryFileID(ctx iris.Context) { defer ctx.Next() ctxt := ctx.Request().Context() - sessionToken := ctx.Request().Header.Get("X-Auth-Token") + sessionToken := ctx.Request().Header.Get(AuthTokenHeader) regFileID := ctx.Params().Get("id") if strings.Contains(regFileID, ".json") { r.GetMessageRegistryFile(ctx) @@ -912,11 +905,8 @@ func (r *Registry) GetMessageRegistryFileID(ctx iris.Context) { } regFileID = strings.Replace(regFileID, "#", "%23", -1) if sessionToken == "" { - errorMessage := "error: no X-Auth-Token found in request header" - response := common.GeneralError(http.StatusUnauthorized, errResponse.NoValidSession, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) + errorMessage := invalidAuthTokenErrorMsg + common.SendInvalidSessionResponse(ctx, errorMessage) return } authResp, err := r.Auth(ctxt, sessionToken, []string{common.PrivilegeLogin}, []string{}) @@ -925,11 +915,7 @@ func (r *Registry) GetMessageRegistryFileID(ctx iris.Context) { if err != nil { errMsg = errMsg + ": " + err.Error() } - l.LogWithFields(ctxt).Error(errMsg) - ctx.StatusCode(int(authResp.StatusCode)) - common.SetResponseHeader(ctx, authResp.Header) - ctx.JSON(authResp.Body) - return + sendAuthErrorResponse(ctxt, ctx, errMsg, authResp) } var headers = map[string]string{ "Allow": "GET", @@ -997,7 +983,7 @@ func (r *Registry) GetMessageRegistryFileID(ctx iris.Context) { func (r *Registry) GetMessageRegistryFile(ctx iris.Context) { defer ctx.Next() ctxt := ctx.Request().Context() - sessionToken := ctx.Request().Header.Get("X-Auth-Token") + sessionToken := ctx.Request().Header.Get(AuthTokenHeader) regFileID := ctx.Params().Get("id") if strings.HasPrefix(regFileID, "#") { reqURI := ctx.Request().RequestURI @@ -1012,11 +998,8 @@ func (r *Registry) GetMessageRegistryFile(ctx iris.Context) { regFileID = strings.Replace(regFileID, "#", "%23", -1) l.LogWithFields(ctxt).Debugf("Retriveing message registry file with file id %s", regFileID) if sessionToken == "" { - errorMessage := "error: no X-Auth-Token found in request header" - response := common.GeneralError(http.StatusUnauthorized, errResponse.NoValidSession, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) + errorMessage := invalidAuthTokenErrorMsg + common.SendInvalidSessionResponse(ctx, errorMessage) return } authResp, err := r.Auth(ctxt, sessionToken, []string{common.PrivilegeLogin}, []string{}) @@ -1025,11 +1008,7 @@ func (r *Registry) GetMessageRegistryFile(ctx iris.Context) { if err != nil { errMsg = errMsg + ": " + err.Error() } - l.LogWithFields(ctxt).Error(errMsg) - ctx.StatusCode(int(authResp.StatusCode)) - common.SetResponseHeader(ctx, authResp.Header) - ctx.JSON(authResp.Body) - return + sendAuthErrorResponse(ctxt, ctx, errMsg, authResp) } var headers = map[string]string{ "Allow": "GET", @@ -1063,11 +1042,7 @@ func (r *Registry) GetMessageRegistryFile(ctx iris.Context) { l.LogWithFields(ctxt).Error(err.Error()) errorMessage := "error: Resource not found" l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, errResponse.InternalError, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) - return + common.SendFailedRPCCallResponse(ctx, errorMessage) } common.SetResponseHeader(ctx, headers) ctx.JSON(data) @@ -1401,3 +1376,12 @@ func RoleMethodNotAllowed(ctx iris.Context) { fillMethodNotAllowedErrorResponse(ctx) return } + +// sendAuthErrorResponse writes the response for an RPC call when authentication of session fails +func sendAuthErrorResponse(ctxt context.Context, ctx iris.Context, errorMessage string, authResp errResponse.RPC) { + l.LogWithFields(ctxt).Error(errorMessage) + ctx.StatusCode(int(authResp.StatusCode)) + common.SetResponseHeader(ctx, authResp.Header) + ctx.JSON(authResp.Body) + return +} diff --git a/svc-api/handle/licenses.go b/svc-api/handle/licenses.go index de6fadadf..344497f0e 100644 --- a/svc-api/handle/licenses.go +++ b/svc-api/handle/licenses.go @@ -40,12 +40,12 @@ func (lcns *LicenseRPCs) GetLicenseService(ctx iris.Context) { defer ctx.Next() ctxt := ctx.Request().Context() req := licenseproto.GetLicenseServiceRequest{ - SessionToken: ctx.Request().Header.Get("X-Auth-Token"), + SessionToken: ctx.Request().Header.Get(AuthTokenHeader), URL: ctx.Request().RequestURI, } l.LogWithFields(ctxt).Debug("Incoming request received for the Get License service") if req.SessionToken == "" { - errorMessage := "error: no X-Auth-Token found in request header" + errorMessage := invalidAuthTokenErrorMsg l.LogWithFields(ctxt).Error(errorMessage) response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) ctx.StatusCode(http.StatusUnauthorized) @@ -63,9 +63,7 @@ func (lcns *LicenseRPCs) GetLicenseService(ctx iris.Context) { } l.LogWithFields(ctx).Debugf("Outgoing response for Getting License service is %s and response status %d", string(resp.Body), int(resp.StatusCode)) ctx.ResponseWriter().Header().Set("Allow", "GET") - common.SetResponseHeader(ctx, resp.Header) - ctx.StatusCode(int(resp.StatusCode)) - ctx.Write(resp.Body) + sendGetLicenseResponse(ctx, resp) } // GetLicenseCollection fetches all licenses @@ -73,12 +71,12 @@ func (lcns *LicenseRPCs) GetLicenseCollection(ctx iris.Context) { defer ctx.Next() ctxt := ctx.Request().Context() req := licenseproto.GetLicenseRequest{ - SessionToken: ctx.Request().Header.Get("X-Auth-Token"), + SessionToken: ctx.Request().Header.Get(AuthTokenHeader), URL: ctx.Request().RequestURI, } l.LogWithFields(ctxt).Debugf("Incoming request received for getting license collection with request url %s", req.URL) if req.SessionToken == "" { - errorMessage := "error: no X-Auth-Token found in request header" + errorMessage := invalidAuthTokenErrorMsg l.LogWithFields(ctxt).Error(errorMessage) response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) ctx.StatusCode(http.StatusUnauthorized) @@ -96,9 +94,7 @@ func (lcns *LicenseRPCs) GetLicenseCollection(ctx iris.Context) { } l.LogWithFields(ctxt).Debugf("Outgoing response for getting license collection is %s with status code %d", string(resp.Body), int(resp.StatusCode)) ctx.ResponseWriter().Header().Set("Allow", "GET, POST") - common.SetResponseHeader(ctx, resp.Header) - ctx.StatusCode(int(resp.StatusCode)) - ctx.Write(resp.Body) + sendGetLicenseResponse(ctx, resp) } // GetLicenseResource fetches license resource @@ -106,12 +102,12 @@ func (lcns *LicenseRPCs) GetLicenseResource(ctx iris.Context) { defer ctx.Next() ctxt := ctx.Request().Context() req := licenseproto.GetLicenseResourceRequest{ - SessionToken: ctx.Request().Header.Get("X-Auth-Token"), + SessionToken: ctx.Request().Header.Get(AuthTokenHeader), URL: ctx.Request().RequestURI, } l.LogWithFields(ctxt).Debugf("Incoming request received for getting license resource with request url %s", req.URL) if req.SessionToken == "" { - errorMessage := "error: no X-Auth-Token found in request header" + errorMessage := invalidAuthTokenErrorMsg l.LogWithFields(ctxt).Error(errorMessage) response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) ctx.StatusCode(http.StatusUnauthorized) @@ -129,9 +125,7 @@ func (lcns *LicenseRPCs) GetLicenseResource(ctx iris.Context) { } l.LogWithFields(ctxt).Debugf("Outgoing response for getting license resource is %s with status code %d", string(resp.Body), int(resp.StatusCode)) ctx.ResponseWriter().Header().Set("Allow", "GET") - common.SetResponseHeader(ctx, resp.Header) - ctx.StatusCode(int(resp.StatusCode)) - ctx.Write(resp.Body) + sendGetLicenseResponse(ctx, resp) } // InstallLicenseService installs license @@ -161,12 +155,12 @@ func (lcns *LicenseRPCs) InstallLicenseService(ctx iris.Context) { } l.LogWithFields(ctxt).Debugf("Incoming request received for installing license service with request body %s", string(request)) req := licenseproto.InstallLicenseRequest{ - SessionToken: ctx.Request().Header.Get("X-Auth-Token"), + SessionToken: ctx.Request().Header.Get(AuthTokenHeader), URL: ctx.Request().RequestURI, RequestBody: request, } if req.SessionToken == "" { - errorMessage := "error: no X-Auth-Token found in request header" + errorMessage := invalidAuthTokenErrorMsg l.LogWithFields(ctxt).Error(errorMessage) response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) ctx.StatusCode(http.StatusUnauthorized) @@ -183,6 +177,11 @@ func (lcns *LicenseRPCs) InstallLicenseService(ctx iris.Context) { return } l.LogWithFields(ctxt).Debugf("Outgoing response for installing license service is %s with status code %d", string(resp.Body), int(resp.StatusCode)) + sendGetLicenseResponse(ctx, resp) +} + +// sendGetLicenseResponse writes the license response to client +func sendGetLicenseResponse(ctx iris.Context, resp *licenseproto.GetLicenseResponse) { common.SetResponseHeader(ctx, resp.Header) ctx.StatusCode(int(resp.StatusCode)) ctx.Write(resp.Body) diff --git a/svc-api/handle/managers.go b/svc-api/handle/managers.go index acd0fa34d..82c51c544 100644 --- a/svc-api/handle/managers.go +++ b/svc-api/handle/managers.go @@ -18,12 +18,10 @@ package handle import ( "context" "encoding/json" - "net/http" "github.com/ODIM-Project/ODIM/lib-utilities/common" l "github.com/ODIM-Project/ODIM/lib-utilities/logs" managersproto "github.com/ODIM-Project/ODIM/lib-utilities/proto/managers" - "github.com/ODIM-Project/ODIM/lib-utilities/response" iris "github.com/kataras/iris/v12" ) @@ -45,32 +43,22 @@ func (mgr *ManagersRPCs) GetManagersCollection(ctx iris.Context) { defer ctx.Next() ctxt := ctx.Request().Context() req := managersproto.ManagerRequest{ - SessionToken: ctx.Request().Header.Get("X-Auth-Token"), + SessionToken: ctx.Request().Header.Get(AuthTokenHeader), } l.LogWithFields(ctxt).Debug("Incoming request received for the getting all Managers collection") if req.SessionToken == "" { - errorMessage := "error: no X-Auth-Token found in request header" - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + errorMessage := invalidAuthTokenErrorMsg + common.SendInvalidSessionResponse(ctx, errorMessage) } resp, err := mgr.GetManagersCollectionRPC(ctxt, req) if err != nil { errorMessage := "error: RPC error:" + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) - return + common.SendFailedRPCCallResponse(ctx, errorMessage) } l.LogWithFields(ctx).Debugf("Outgoing response for Getting Managers collection is %s and response status %d", string(resp.Body), int(resp.StatusCode)) ctx.ResponseWriter().Header().Set("Allow", "GET") - common.SetResponseHeader(ctx, resp.Header) - ctx.StatusCode(int(resp.StatusCode)) - ctx.Write(resp.Body) + sendManagersResponse(ctx, resp) } // GetManager fetches computer managers details @@ -78,34 +66,24 @@ func (mgr *ManagersRPCs) GetManager(ctx iris.Context) { defer ctx.Next() ctxt := ctx.Request().Context() req := managersproto.ManagerRequest{ - SessionToken: ctx.Request().Header.Get("X-Auth-Token"), + SessionToken: ctx.Request().Header.Get(AuthTokenHeader), ManagerID: ctx.Params().Get("id"), URL: ctx.Request().RequestURI, } l.LogWithFields(ctxt).Debugf("Incoming request received for the getting a Managers with id %s", req.ManagerID) if req.SessionToken == "" { - errorMessage := "error: no X-Auth-Token found in request header" - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + errorMessage := invalidAuthTokenErrorMsg + common.SendInvalidSessionResponse(ctx, errorMessage) } resp, err := mgr.GetManagersRPC(ctxt, req) if err != nil { errorMessage := "RPC error:" + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) - return + common.SendFailedRPCCallResponse(ctx, errorMessage) } l.LogWithFields(ctx).Debugf("Outgoing response for getting Manager is %s and response status %d", string(resp.Body), int(resp.StatusCode)) ctx.ResponseWriter().Header().Set("Allow", "GET") - common.SetResponseHeader(ctx, resp.Header) - ctx.StatusCode(int(resp.StatusCode)) - ctx.Write(resp.Body) + sendManagersResponse(ctx, resp) } // GetManagersResource defines the GetManagersResource iris handler. @@ -115,36 +93,21 @@ func (mgr *ManagersRPCs) GetManager(ctx iris.Context) { func (mgr *ManagersRPCs) GetManagersResource(ctx iris.Context) { defer ctx.Next() ctxt := ctx.Request().Context() - req := managersproto.ManagerRequest{ - SessionToken: ctx.Request().Header.Get("X-Auth-Token"), - ManagerID: ctx.Params().Get("id"), - ResourceID: ctx.Params().Get("rid"), - URL: ctx.Request().RequestURI, - } + req := getManagerRequest(ctx) l.LogWithFields(ctxt).Debugf("Incoming request received for the getting a Managers resources with id %s and resource id %s", req.ManagerID, req.ResourceID) if req.SessionToken == "" { - errorMessage := "error: no X-Auth-Token found in request header" - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + errorMessage := invalidAuthTokenErrorMsg + common.SendInvalidSessionResponse(ctx, errorMessage) } resp, err := mgr.GetManagersResourceRPC(ctxt, req) if err != nil { errorMessage := "error: RPC error:" + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) - return + common.SendFailedRPCCallResponse(ctx, errorMessage) } l.LogWithFields(ctx).Debugf("Outgoing response for getting Manager resource is %s and response status %d", string(resp.Body), int(resp.StatusCode)) ctx.ResponseWriter().Header().Set("Allow", "GET") - common.SetResponseHeader(ctx, resp.Header) - ctx.StatusCode(int(resp.StatusCode)) - ctx.Write(resp.Body) + sendManagersResponse(ctx, resp) } // VirtualMediaInsert defines the Insert virtual media iris handler @@ -159,25 +122,17 @@ func (mgr *ManagersRPCs) VirtualMediaInsert(ctx iris.Context) { if err != nil { errorMessage := "while trying to get JSON body from the virtual media actions request body: " + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusBadRequest, response.MalformedJSON, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusBadRequest) - ctx.JSON(&response.Body) - return + common.SendMalformedJSONRequestErrResponse(ctx, errorMessage) } request, err := json.Marshal(reqIn) if err != nil { errorMessage := "while trying to create JSON request body: " + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) - return + common.SendFailedRPCCallResponse(ctx, errorMessage) } req := managersproto.ManagerRequest{ - SessionToken: ctx.Request().Header.Get("X-Auth-Token"), + SessionToken: ctx.Request().Header.Get(AuthTokenHeader), ManagerID: ctx.Params().Get("id"), ResourceID: ctx.Params().Get("rid"), URL: ctx.Request().RequestURI, @@ -185,27 +140,17 @@ func (mgr *ManagersRPCs) VirtualMediaInsert(ctx iris.Context) { } l.LogWithFields(ctxt).Debugf("Incoming request received for the virtual media insert with id %s and request body %s", req.ManagerID, string(request)) if req.SessionToken == "" { - errorMessage := "no X-Auth-Token found in request header" - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + errorMessage := invalidAuthTokenErrMsg + common.SendInvalidSessionResponse(ctx, errorMessage) } resp, err := mgr.VirtualMediaInsertRPC(ctxt, req) if err != nil { errorMessage := "RPC error:" + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) - return + common.SendFailedRPCCallResponse(ctx, errorMessage) } l.LogWithFields(ctx).Debugf("Outgoing response for virtual media insert is %s and response status %d", string(resp.Body), int(resp.StatusCode)) - common.SetResponseHeader(ctx, resp.Header) - ctx.StatusCode(int(resp.StatusCode)) - ctx.Write(resp.Body) + sendManagersResponse(ctx, resp) } // VirtualMediaEject defines the eject virtual media iris handler @@ -215,35 +160,20 @@ func (mgr *ManagersRPCs) VirtualMediaInsert(ctx iris.Context) { func (mgr *ManagersRPCs) VirtualMediaEject(ctx iris.Context) { defer ctx.Next() ctxt := ctx.Request().Context() - req := managersproto.ManagerRequest{ - SessionToken: ctx.Request().Header.Get("X-Auth-Token"), - ManagerID: ctx.Params().Get("id"), - ResourceID: ctx.Params().Get("rid"), - URL: ctx.Request().RequestURI, - } + req := getManagerRequest(ctx) l.LogWithFields(ctxt).Debugf("Incoming request received for the virtual media eject with id %s", req.ManagerID) if req.SessionToken == "" { - errorMessage := "no X-Auth-Token found in request header" - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + errorMessage := invalidAuthTokenErrMsg + common.SendInvalidSessionResponse(ctx, errorMessage) } resp, err := mgr.VirtualMediaEjectRPC(ctxt, req) if err != nil { errorMessage := "RPC error:" + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) - return + common.SendFailedRPCCallResponse(ctx, errorMessage) } l.LogWithFields(ctx).Debugf("Outgoing response for virtual media eject is %s and response status %d", string(resp.Body), int(resp.StatusCode)) - common.SetResponseHeader(ctx, resp.Header) - ctx.StatusCode(int(resp.StatusCode)) - ctx.Write(resp.Body) + sendManagersResponse(ctx, resp) } // GetRemoteAccountService defines the GetRemoteAccountService iris handler. @@ -253,30 +183,17 @@ func (mgr *ManagersRPCs) VirtualMediaEject(ctx iris.Context) { func (mgr *ManagersRPCs) GetRemoteAccountService(ctx iris.Context) { defer ctx.Next() ctxt := ctx.Request().Context() - req := managersproto.ManagerRequest{ - SessionToken: ctx.Request().Header.Get("X-Auth-Token"), - ManagerID: ctx.Params().Get("id"), - ResourceID: ctx.Params().Get("rid"), - URL: ctx.Request().RequestURI, - } + req := getManagerRequest(ctx) l.LogWithFields(ctxt).Debugf("Incoming request received for the getting remote account service with id %s", req.ManagerID) if req.SessionToken == "" { - errorMessage := "error: no X-Auth-Token found in request header" - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + errorMessage := invalidAuthTokenErrorMsg + common.SendInvalidSessionResponse(ctx, errorMessage) } resp, err := mgr.GetRemoteAccountServiceRPC(ctxt, req) if err != nil { errorMessage := "error: RPC error:" + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) - return + common.SendFailedRPCCallResponse(ctx, errorMessage) } switch req.URL { @@ -288,9 +205,7 @@ func (mgr *ManagersRPCs) GetRemoteAccountService(ctx iris.Context) { ctx.ResponseWriter().Header().Set("Allow", "GET") } l.LogWithFields(ctx).Debugf("Outgoing response for getting remote account service is %s and response status %d", string(resp.Body), int(resp.StatusCode)) - common.SetResponseHeader(ctx, resp.Header) - ctx.StatusCode(int(resp.StatusCode)) - ctx.Write(resp.Body) + sendManagersResponse(ctx, resp) } // CreateRemoteAccountService defines the CreateRemoteAccountService iris handler. @@ -305,25 +220,17 @@ func (mgr *ManagersRPCs) CreateRemoteAccountService(ctx iris.Context) { if err != nil { errorMessage := "while trying to get JSON body from the create remote account request body: " + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusBadRequest, response.MalformedJSON, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusBadRequest) - ctx.JSON(&response.Body) - return + common.SendMalformedJSONRequestErrResponse(ctx, errorMessage) } request, err := json.Marshal(reqIn) if err != nil { errorMessage := "while trying to create JSON request body in create remote account: " + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) - return + common.SendFailedRPCCallResponse(ctx, errorMessage) } req := managersproto.ManagerRequest{ - SessionToken: ctx.Request().Header.Get("X-Auth-Token"), + SessionToken: ctx.Request().Header.Get(AuthTokenHeader), ManagerID: ctx.Params().Get("id"), ResourceID: ctx.Params().Get("rid"), URL: ctx.Request().RequestURI, @@ -331,27 +238,17 @@ func (mgr *ManagersRPCs) CreateRemoteAccountService(ctx iris.Context) { } l.LogWithFields(ctxt).Debugf("Incoming request received for the creating remote account with id %s and request body %s", req.ManagerID, string(request)) if req.SessionToken == "" { - errorMessage := "error: no X-Auth-Token found in request header" - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + errorMessage := invalidAuthTokenErrorMsg + common.SendInvalidSessionResponse(ctx, errorMessage) } resp, err := mgr.CreateRemoteAccountServiceRPC(ctxt, req) if err != nil { errorMessage := "error: RPC error:" + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) - return + common.SendFailedRPCCallResponse(ctx, errorMessage) } l.LogWithFields(ctx).Debugf("Outgoing response for getting remote account service is %s and response status %d", string(resp.Body), int(resp.StatusCode)) - common.SetResponseHeader(ctx, resp.Header) - ctx.StatusCode(int(resp.StatusCode)) - ctx.Write(resp.Body) + sendManagersResponse(ctx, resp) } // UpdateRemoteAccountService defines the UpdateRemoteAccountService iris handler. @@ -366,25 +263,17 @@ func (mgr *ManagersRPCs) UpdateRemoteAccountService(ctx iris.Context) { if err != nil { errorMessage := "while trying to get JSON body from the update remote account request body: " + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusBadRequest, response.MalformedJSON, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusBadRequest) - ctx.JSON(&response.Body) - return + common.SendMalformedJSONRequestErrResponse(ctx, errorMessage) } request, err := json.Marshal(reqIn) if err != nil { errorMessage := "while trying to update JSON request body in update remote account: " + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) - return + common.SendFailedRPCCallResponse(ctx, errorMessage) } req := managersproto.ManagerRequest{ - SessionToken: ctx.Request().Header.Get("X-Auth-Token"), + SessionToken: ctx.Request().Header.Get(AuthTokenHeader), ManagerID: ctx.Params().Get("id"), ResourceID: ctx.Params().Get("rid"), URL: ctx.Request().RequestURI, @@ -392,27 +281,17 @@ func (mgr *ManagersRPCs) UpdateRemoteAccountService(ctx iris.Context) { } l.LogWithFields(ctxt).Debugf("Incoming request received for the updating remote account service with id %s and request body %s", req.ManagerID, string(request)) if req.SessionToken == "" { - errorMessage := "error: no X-Auth-Token found in request header" - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + errorMessage := invalidAuthTokenErrorMsg + common.SendInvalidSessionResponse(ctx, errorMessage) } resp, err := mgr.UpdateRemoteAccountServiceRPC(ctxt, req) if err != nil { errorMessage := "error: RPC error:" + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) - return + common.SendFailedRPCCallResponse(ctx, errorMessage) } l.LogWithFields(ctx).Debugf("Outgoing response for updating remote account service is %s and response status %d", string(resp.Body), int(resp.StatusCode)) - common.SetResponseHeader(ctx, resp.Header) - ctx.StatusCode(int(resp.StatusCode)) - ctx.Write(resp.Body) + sendManagersResponse(ctx, resp) } // DeleteRemoteAccountService defines the DeleteRemoteAccountService iris handler. @@ -422,33 +301,35 @@ func (mgr *ManagersRPCs) UpdateRemoteAccountService(ctx iris.Context) { func (mgr *ManagersRPCs) DeleteRemoteAccountService(ctx iris.Context) { defer ctx.Next() ctxt := ctx.Request().Context() - req := managersproto.ManagerRequest{ - SessionToken: ctx.Request().Header.Get("X-Auth-Token"), - ManagerID: ctx.Params().Get("id"), - ResourceID: ctx.Params().Get("rid"), - URL: ctx.Request().RequestURI, - } + req := getManagerRequest(ctx) l.LogWithFields(ctxt).Debugf("Incoming request received for the deleting remote account service with id %s", req.ManagerID) if req.SessionToken == "" { - errorMessage := "error: no X-Auth-Token found in request header" - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + errorMessage := invalidAuthTokenErrorMsg + common.SendInvalidSessionResponse(ctx, errorMessage) } resp, err := mgr.DeleteRemoteAccountServiceRPC(ctxt, req) if err != nil { errorMessage := "error: RPC error:" + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) - return + common.SendFailedRPCCallResponse(ctx, errorMessage) } l.LogWithFields(ctx).Debugf("Outgoing response for deleting remote account service is %s and response status %d", string(resp.Body), int(resp.StatusCode)) + sendManagersResponse(ctx, resp) +} + +// sendManagersResponse writes the managers response to client +func sendManagersResponse(ctx iris.Context, resp *managersproto.ManagerResponse) { common.SetResponseHeader(ctx, resp.Header) ctx.StatusCode(int(resp.StatusCode)) ctx.Write(resp.Body) } + +// getManagerRequest will extract the request from the context and return +func getManagerRequest(ctx iris.Context) managersproto.ManagerRequest { + return managersproto.ManagerRequest{ + SessionToken: ctx.Request().Header.Get(AuthTokenHeader), + ManagerID: ctx.Params().Get("id"), + ResourceID: ctx.Params().Get("rid"), + URL: ctx.Request().RequestURI, + } +} diff --git a/svc-api/handle/role.go b/svc-api/handle/role.go index b393ea707..1222efb09 100644 --- a/svc-api/handle/role.go +++ b/svc-api/handle/role.go @@ -18,12 +18,10 @@ package handle import ( "context" "encoding/json" - "net/http" "github.com/ODIM-Project/ODIM/lib-utilities/common" l "github.com/ODIM-Project/ODIM/lib-utilities/logs" roleproto "github.com/ODIM-Project/ODIM/lib-utilities/proto/role" - "github.com/ODIM-Project/ODIM/lib-utilities/response" iris "github.com/kataras/iris/v12" ) @@ -45,29 +43,19 @@ func (r *RoleRPCs) GetAllRoles(ctx iris.Context) { l.LogWithFields(ctxt).Debug("Incoming request received for the getting all roles") req := roleproto.GetRoleRequest{SessionToken: ctx.Request().Header.Get("X-Auth-Token")} if req.SessionToken == "" { - errorMessage := "error: no X-Auth-Token found in request header" - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + errorMessage := invalidAuthTokenErrorMsg + common.SendInvalidSessionResponse(ctx, errorMessage) } resp, err := r.GetAllRolesRPC(ctxt, req) if err != nil { errorMessage := "RPC error: " + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) - return + common.SendFailedRPCCallResponse(ctx, errorMessage) } l.LogWithFields(ctx).Debugf("Outgoing response for Getting all roles is %s and response status %d", string(resp.Body), int(resp.StatusCode)) ctx.ResponseWriter().Header().Set("Allow", "GET") - common.SetResponseHeader(ctx, resp.Header) - ctx.StatusCode(int(resp.StatusCode)) - ctx.Write(resp.Body) + sendRoleResponse(ctx, resp) } // GetRole defines the GetRole iris handler. @@ -80,12 +68,8 @@ func (r *RoleRPCs) GetRole(ctx iris.Context) { ctxt := ctx.Request().Context() req := roleproto.GetRoleRequest{SessionToken: ctx.Request().Header.Get("X-Auth-Token")} if req.SessionToken == "" { - errorMessage := "error: no X-Auth-Token found in request header" - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + errorMessage := invalidAuthTokenErrorMsg + common.SendInvalidSessionResponse(ctx, errorMessage) } req.Id = ctx.Params().Get("id") l.LogWithFields(ctxt).Debugf("Incoming request received for the getting a role with id %s", req.Id) @@ -93,11 +77,7 @@ func (r *RoleRPCs) GetRole(ctx iris.Context) { if err != nil { errorMessage := "RPC error:" + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) - return + common.SendFailedRPCCallResponse(ctx, errorMessage) } if req.Id == common.RoleAdmin || req.Id == common.RoleClient || req.Id == common.RoleMonitor { ctx.ResponseWriter().Header().Set("Allow", "GET, PATCH") @@ -105,9 +85,7 @@ func (r *RoleRPCs) GetRole(ctx iris.Context) { ctx.ResponseWriter().Header().Set("Allow", "GET, PATCH, DELETE") } l.LogWithFields(ctx).Debugf("Outgoing response for Getting a role is %s and response status %d", string(resp.Body), int(resp.StatusCode)) - common.SetResponseHeader(ctx, resp.Header) - ctx.StatusCode(int(resp.StatusCode)) - ctx.Write(resp.Body) + sendRoleResponse(ctx, resp) } // UpdateRole defines the UpdateRole iris handler. @@ -126,21 +104,13 @@ func (r *RoleRPCs) UpdateRole(ctx iris.Context) { if err != nil { l.LogWithFields(ctxt).Error("Error while trying to collect data from request: " + err.Error()) errorMessage := "error while trying to get JSON body from the role update request body: " + err.Error() - response := common.GeneralError(http.StatusBadRequest, response.MalformedJSON, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusBadRequest) - ctx.JSON(response.Body) - return + common.SendMalformedJSONRequestErrResponse(ctx, errorMessage) } req.SessionToken = ctx.Request().Header.Get("X-Auth-Token") if req.SessionToken == "" { - errorMessage := "error: no X-Auth-Token found in request header" - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + errorMessage := invalidAuthTokenErrorMsg + common.SendInvalidSessionResponse(ctx, errorMessage) } req.Id = ctx.Params().Get("id") l.LogWithFields(ctxt).Debugf("Incoming request received for the updating a role with id %s", req.Id) @@ -149,16 +119,10 @@ func (r *RoleRPCs) UpdateRole(ctx iris.Context) { if err != nil { errorMessage := "RPC error:" + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) - return + common.SendFailedRPCCallResponse(ctx, errorMessage) } l.LogWithFields(ctx).Debugf("Outgoing response for updating a role is %s and response status %d", string(resp.Body), int(resp.StatusCode)) - common.SetResponseHeader(ctx, resp.Header) - ctx.StatusCode(int(resp.StatusCode)) - ctx.Write(resp.Body) + sendRoleResponse(ctx, resp) } // DeleteRole ... @@ -169,12 +133,8 @@ func (r *RoleRPCs) DeleteRole(ctx iris.Context) { req.SessionToken = ctx.Request().Header.Get("X-Auth-Token") if req.SessionToken == "" { - errorMessage := "error: no X-Auth-Token found in request header" - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + errorMessage := invalidAuthTokenErrorMsg + common.SendInvalidSessionResponse(ctx, errorMessage) } req.ID = ctx.Params().Get("id") l.LogWithFields(ctxt).Debugf("Incoming request received for the deleting a role with id %s", req.ID) @@ -182,13 +142,14 @@ func (r *RoleRPCs) DeleteRole(ctx iris.Context) { if err != nil { errorMessage := "error: something went wrong with the RPC calls: " + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) - return + common.SendFailedRPCCallResponse(ctx, errorMessage) } l.LogWithFields(ctx).Debugf("Outgoing response for deleting a role is %s and response status %d", string(resp.Body), int(resp.StatusCode)) + sendRoleResponse(ctx, resp) +} + +// sendRoleResponse writes the role response to client +func sendRoleResponse(ctx iris.Context, resp *roleproto.RoleResponse) { common.SetResponseHeader(ctx, resp.Header) ctx.StatusCode(int(resp.StatusCode)) ctx.Write(resp.Body) diff --git a/svc-api/handle/systems.go b/svc-api/handle/systems.go index 569545dc6..abbc7e98d 100644 --- a/svc-api/handle/systems.go +++ b/svc-api/handle/systems.go @@ -18,12 +18,10 @@ package handle import ( "context" "encoding/json" - "net/http" "github.com/ODIM-Project/ODIM/lib-utilities/common" l "github.com/ODIM-Project/ODIM/lib-utilities/logs" systemsproto "github.com/ODIM-Project/ODIM/lib-utilities/proto/systems" - "github.com/ODIM-Project/ODIM/lib-utilities/response" iris "github.com/kataras/iris/v12" ) @@ -47,33 +45,23 @@ func (sys *SystemRPCs) GetSystemsCollection(ctx iris.Context) { ctxt := ctx.Request().Context() defer ctx.Next() req := systemsproto.GetSystemsRequest{ - SessionToken: ctx.Request().Header.Get("X-Auth-Token"), + SessionToken: ctx.Request().Header.Get(AuthTokenHeader), URL: ctx.Request().RequestURI, } l.LogWithFields(ctxt).Debugf("Incoming request received for getting systems collection %s", req.URL) if req.SessionToken == "" { - errorMessage := "error: no X-Auth-Token found in request header" - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + errorMessage := invalidAuthTokenErrorMsg + common.SendInvalidSessionResponse(ctx, errorMessage) } resp, err := sys.GetSystemsCollectionRPC(ctxt, req) if err != nil { errorMessage := "error: RPC error:" + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) - return + common.SendFailedRPCCallResponse(ctx, errorMessage) } l.LogWithFields(ctxt).Debugf("Outgoing response for getting systems collection is %s with status code %d", string(resp.Body), int(resp.StatusCode)) ctx.ResponseWriter().Header().Set("Allow", "GET") - common.SetResponseHeader(ctx, resp.Header) - ctx.StatusCode(int(resp.StatusCode)) - ctx.Write(resp.Body) + sendSystemsResponse(ctx, resp) } // GetSystem fetches computer system details @@ -81,35 +69,25 @@ func (sys *SystemRPCs) GetSystem(ctx iris.Context) { ctxt := ctx.Request().Context() defer ctx.Next() req := systemsproto.GetSystemsRequest{ - SessionToken: ctx.Request().Header.Get("X-Auth-Token"), + SessionToken: ctx.Request().Header.Get(AuthTokenHeader), RequestParam: ctx.Params().Get("id"), ResourceID: ctx.Params().Get("rid"), URL: ctx.Request().RequestURI, } l.LogWithFields(ctxt).Debugf("Incoming request received for getting system with URL %s", req.URL) if req.SessionToken == "" { - errorMessage := "error: no X-Auth-Token found in request header" - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + errorMessage := invalidAuthTokenErrorMsg + common.SendInvalidSessionResponse(ctx, errorMessage) } resp, err := sys.GetSystemRPC(ctxt, req) if err != nil { - errorMessage := "RPC error:" + err.Error() + errorMessage := rpcFailedErrMsg + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) - return + common.SendFailedRPCCallResponse(ctx, errorMessage) } l.LogWithFields(ctxt).Debugf("Outgoing response for getting system details is %s with status code %d", string(resp.Body), int(resp.StatusCode)) ctx.ResponseWriter().Header().Set("Allow", "GET, PATCH") - common.SetResponseHeader(ctx, resp.Header) - ctx.StatusCode(int(resp.StatusCode)) - ctx.Write(resp.Body) + sendSystemsResponse(ctx, resp) } // GetSystemResource defines the GetSystemResource iris handler. @@ -120,29 +98,21 @@ func (sys *SystemRPCs) GetSystemResource(ctx iris.Context) { ctxt := ctx.Request().Context() defer ctx.Next() req := systemsproto.GetSystemsRequest{ - SessionToken: ctx.Request().Header.Get("X-Auth-Token"), + SessionToken: ctx.Request().Header.Get(AuthTokenHeader), RequestParam: ctx.Params().Get("id"), ResourceID: ctx.Params().Get("rid"), URL: ctx.Request().RequestURI, } l.LogWithFields(ctxt).Debugf("Incoming request received for getting system resources with URL %s", req.URL) if req.SessionToken == "" { - errorMessage := "error: no X-Auth-Token found in request header" - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + errorMessage := invalidAuthTokenErrorMsg + common.SendInvalidSessionResponse(ctx, errorMessage) } resp, err := sys.GetSystemResourceRPC(ctxt, req) if err != nil { errorMessage := "error: RPC error:" + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) - return + common.SendFailedRPCCallResponse(ctx, errorMessage) } storageID := ctx.Params().Get("id2") @@ -159,9 +129,7 @@ func (sys *SystemRPCs) GetSystemResource(ctx iris.Context) { ctx.ResponseWriter().Header().Set("Allow", "GET") } l.LogWithFields(ctxt).Debugf("Outgoing response for getting systems resources is %s with status code %d", string(resp.Body), int(resp.StatusCode)) - common.SetResponseHeader(ctx, resp.Header) - ctx.StatusCode(int(resp.StatusCode)) - ctx.Write(resp.Body) + sendSystemsResponse(ctx, resp) } // ComputerSystemReset resets the indivitual computer systems @@ -173,21 +141,13 @@ func (sys *SystemRPCs) ComputerSystemReset(ctx iris.Context) { if err != nil { errorMessage := "error while trying to get JSON body from the system reset request body: " + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusBadRequest, response.MalformedJSON, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusBadRequest) - ctx.JSON(&response.Body) - return + common.SendMalformedJSONRequestErrResponse(ctx, errorMessage) } systemID := ctx.Params().Get("id") - sessionToken := ctx.Request().Header.Get("X-Auth-Token") + sessionToken := ctx.Request().Header.Get(AuthTokenHeader) if sessionToken == "" { - errorMessage := "error: no X-Auth-Token found in request header" - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + errorMessage := invalidAuthTokenErrorMsg + common.SendInvalidSessionResponse(ctx, errorMessage) } // Marshalling the req to make reset request @@ -200,18 +160,12 @@ func (sys *SystemRPCs) ComputerSystemReset(ctx iris.Context) { l.LogWithFields(ctxt).Debugf("Incoming request received for computer system reset with request body %s", string(request)) resp, err := sys.SystemResetRPC(ctxt, resetRequest) if err != nil { - errorMessage := "RPC error:" + err.Error() + errorMessage := rpcFailedErrMsg + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) - return + common.SendFailedRPCCallResponse(ctx, errorMessage) } l.LogWithFields(ctxt).Debugf("Outgoing response for computer system reset is %s with status code %d", string(resp.Body), int(resp.StatusCode)) - common.SetResponseHeader(ctx, resp.Header) - ctx.StatusCode(int(resp.StatusCode)) - ctx.Write(resp.Body) + sendSystemsResponse(ctx, resp) } // SetDefaultBootOrder is the handler to set default boot order @@ -222,30 +176,20 @@ func (sys *SystemRPCs) SetDefaultBootOrder(ctx iris.Context) { ctxt := ctx.Request().Context() var req systemsproto.DefaultBootOrderRequest req.SystemID = ctx.Params().Get("id") - req.SessionToken = ctx.Request().Header.Get("X-Auth-Token") + req.SessionToken = ctx.Request().Header.Get(AuthTokenHeader) if req.SessionToken == "" { - errorMessage := "error: no X-Auth-Token found in request header" - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + errorMessage := invalidAuthTokenErrorMsg + common.SendInvalidSessionResponse(ctx, errorMessage) } l.LogWithFields(ctxt).Debugf("Incoming request received for setting default boot order with request id %s", req.SystemID) resp, err := sys.SetDefaultBootOrderRPC(ctxt, req) if err != nil { - errorMessage := "RPC error:" + err.Error() + errorMessage := rpcFailedErrMsg + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) - return + common.SendFailedRPCCallResponse(ctx, errorMessage) } l.LogWithFields(ctxt).Debugf("Outgoing response for setting default boot order is %s with status code %d", string(resp.Body), int(resp.StatusCode)) - common.SetResponseHeader(ctx, resp.Header) - ctx.StatusCode(int(resp.StatusCode)) - ctx.Write(resp.Body) + sendSystemsResponse(ctx, resp) } // ChangeBiosSettings is the handler to set change bios settings @@ -259,31 +203,20 @@ func (sys *SystemRPCs) ChangeBiosSettings(ctx iris.Context) { if err != nil { errorMessage := "error while trying to get JSON body from bios setting request body: " + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusBadRequest, response.MalformedJSON, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusBadRequest) - ctx.JSON(&response.Body) - return + common.SendMalformedJSONRequestErrResponse(ctx, errorMessage) } request, err := json.Marshal(req) if err != nil { errorMessage := "error while trying to create JSON request body: " + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) + common.SendFailedRPCCallResponse(ctx, errorMessage) return } l.LogWithFields(ctxt).Debugf("Incoming request received for changing bios setting with request body %s", string(request)) - sessionToken := ctx.Request().Header.Get("X-Auth-Token") + sessionToken := ctx.Request().Header.Get(AuthTokenHeader) if sessionToken == "" { - errorMessage := "error: no X-Auth-Token found in request header" - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + errorMessage := invalidAuthTokenErrorMsg + common.SendInvalidSessionResponse(ctx, errorMessage) } biosRequest := systemsproto.BiosSettingsRequest{ SessionToken: sessionToken, @@ -292,18 +225,12 @@ func (sys *SystemRPCs) ChangeBiosSettings(ctx iris.Context) { } resp, err := sys.ChangeBiosSettingsRPC(ctxt, biosRequest) if err != nil { - errorMessage := "RPC error:" + err.Error() + errorMessage := rpcFailedErrMsg + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) - return + common.SendFailedRPCCallResponse(ctx, errorMessage) } l.LogWithFields(ctxt).Debugf("Outgoing response for changing bios setting is %s with status code %d", string(resp.Body), int(resp.StatusCode)) - common.SetResponseHeader(ctx, resp.Header) - ctx.StatusCode(int(resp.StatusCode)) - ctx.Write(resp.Body) + sendSystemsResponse(ctx, resp) } // ChangeBootOrderSettings is the handler to set change boot order settings @@ -317,31 +244,20 @@ func (sys *SystemRPCs) ChangeBootOrderSettings(ctx iris.Context) { if err != nil { errorMessage := "error while trying to get JSON body from change boot order setting request body: " + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusBadRequest, response.MalformedJSON, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusBadRequest) - ctx.JSON(&response.Body) - return + common.SendMalformedJSONRequestErrResponse(ctx, errorMessage) } request, err := json.Marshal(req) if err != nil { errorMessage := "error while trying to create JSON request body: " + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) + common.SendFailedRPCCallResponse(ctx, errorMessage) return } l.LogWithFields(ctxt).Debugf("Incoming request received for changing boot order setting with request body %s", string(request)) - sessionToken := ctx.Request().Header.Get("X-Auth-Token") + sessionToken := ctx.Request().Header.Get(AuthTokenHeader) if sessionToken == "" { - errorMessage := "error: no X-Auth-Token found in request header" - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + errorMessage := invalidAuthTokenErrorMsg + common.SendInvalidSessionResponse(ctx, errorMessage) } bootOrderRequest := systemsproto.BootOrderSettingsRequest{ SessionToken: sessionToken, @@ -350,18 +266,12 @@ func (sys *SystemRPCs) ChangeBootOrderSettings(ctx iris.Context) { } resp, err := sys.ChangeBootOrderSettingsRPC(ctxt, bootOrderRequest) if err != nil { - errorMessage := "RPC error:" + err.Error() + errorMessage := rpcFailedErrMsg + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) - return + common.SendFailedRPCCallResponse(ctx, errorMessage) } l.LogWithFields(ctxt).Debugf("Outgoing response for getting changing boot order setting is %s with status code %d", string(resp.Body), int(resp.StatusCode)) - common.SetResponseHeader(ctx, resp.Header) - ctx.StatusCode(int(resp.StatusCode)) - ctx.Write(resp.Body) + sendSystemsResponse(ctx, resp) } // UpdateSecureBoot is the handler to set change boot order settings @@ -375,31 +285,20 @@ func (sys *SystemRPCs) UpdateSecureBoot(ctx iris.Context) { if err != nil { errorMessage := "error while trying to get JSON body from update SecureBoot request body: " + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusBadRequest, response.MalformedJSON, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusBadRequest) - ctx.JSON(&response.Body) - return + common.SendMalformedJSONRequestErrResponse(ctx, errorMessage) } request, err := json.Marshal(req) if err != nil { errorMessage := "error while trying to create JSON request body: " + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) + common.SendFailedRPCCallResponse(ctx, errorMessage) return } l.LogWithFields(ctxt).Debugf("Incoming request received for updating SecureBoot with request body %s", string(request)) - sessionToken := ctx.Request().Header.Get("X-Auth-Token") + sessionToken := ctx.Request().Header.Get(AuthTokenHeader) if sessionToken == "" { - errorMessage := "error: no X-Auth-Token found in request header" - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + errorMessage := invalidAuthTokenErrorMsg + common.SendInvalidSessionResponse(ctx, errorMessage) } secureBootRequest := systemsproto.SecureBootRequest{ SessionToken: sessionToken, @@ -408,18 +307,12 @@ func (sys *SystemRPCs) UpdateSecureBoot(ctx iris.Context) { } resp, err := sys.UpdateSecureBootRPC(ctxt, secureBootRequest) if err != nil { - errorMessage := "RPC error:" + err.Error() + errorMessage := rpcFailedErrMsg + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) - return + common.SendFailedRPCCallResponse(ctx, errorMessage) } l.LogWithFields(ctxt).Debugf("Outgoing response for updating SecureBoot is %s with status code %d", string(resp.Body), int(resp.StatusCode)) - common.SetResponseHeader(ctx, resp.Header) - ctx.StatusCode(int(resp.StatusCode)) - ctx.Write(resp.Body) + sendSystemsResponse(ctx, resp) } // ResetSecureBoot shall reset the UEFI Secure Boot key databases. @@ -434,31 +327,20 @@ func (sys *SystemRPCs) ResetSecureBoot(ctx iris.Context) { if err != nil { errorMessage := "error while trying to get JSON body from reset SecureBoot key databases request body: " + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusBadRequest, response.MalformedJSON, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusBadRequest) - ctx.JSON(&response.Body) - return + common.SendMalformedJSONRequestErrResponse(ctx, errorMessage) } request, err := json.Marshal(req) if err != nil { errorMessage := "error while trying to create JSON request body: " + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) + common.SendFailedRPCCallResponse(ctx, errorMessage) return } l.LogWithFields(ctxt).Debugf("Incoming request received for resetting SecureBoot with request body %s", string(request)) - sessionToken := ctx.Request().Header.Get("X-Auth-Token") + sessionToken := ctx.Request().Header.Get(AuthTokenHeader) if sessionToken == "" { - errorMessage := "error: no X-Auth-Token found in request header" - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + errorMessage := invalidAuthTokenErrorMsg + common.SendInvalidSessionResponse(ctx, errorMessage) } secureBootRequest := systemsproto.SecureBootRequest{ SessionToken: sessionToken, @@ -467,18 +349,12 @@ func (sys *SystemRPCs) ResetSecureBoot(ctx iris.Context) { } resp, err := sys.ResetSecureBootRPC(ctxt, secureBootRequest) if err != nil { - errorMessage := "RPC error:" + err.Error() + errorMessage := rpcFailedErrMsg + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) - return + common.SendFailedRPCCallResponse(ctx, errorMessage) } l.LogWithFields(ctxt).Debugf("Outgoing response for updating SecureBoot is %s with status code %d", string(resp.Body), int(resp.StatusCode)) - common.SetResponseHeader(ctx, resp.Header) - ctx.StatusCode(int(resp.StatusCode)) - ctx.Write(resp.Body) + sendSystemsResponse(ctx, resp) } // CreateVolume is the handler to create a volume under storage @@ -492,31 +368,20 @@ func (sys *SystemRPCs) CreateVolume(ctx iris.Context) { if err != nil { errorMessage := "error while trying to get JSON body from the create volume request body: " + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusBadRequest, response.MalformedJSON, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusBadRequest) - ctx.JSON(&response.Body) - return + common.SendMalformedJSONRequestErrResponse(ctx, errorMessage) } request, err := json.Marshal(req) if err != nil { errorMessage := "error while trying to create JSON request body: " + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) + common.SendFailedRPCCallResponse(ctx, errorMessage) return } l.LogWithFields(ctxt).Debugf("Incoming request received for creating volume with request body %s", string(request)) - sessionToken := ctx.Request().Header.Get("X-Auth-Token") + sessionToken := ctx.Request().Header.Get(AuthTokenHeader) if sessionToken == "" { - errorMessage := "error: no X-Auth-Token found in request header" - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + errorMessage := invalidAuthTokenErrorMsg + common.SendInvalidSessionResponse(ctx, errorMessage) } volRequest := systemsproto.VolumeRequest{ SessionToken: sessionToken, @@ -526,18 +391,12 @@ func (sys *SystemRPCs) CreateVolume(ctx iris.Context) { } resp, err := sys.CreateVolumeRPC(ctxt, volRequest) if err != nil { - errorMessage := "RPC error:" + err.Error() + errorMessage := rpcFailedErrMsg + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) - return + common.SendFailedRPCCallResponse(ctx, errorMessage) } l.LogWithFields(ctxt).Debugf("Outgoing response for creating a volume is %s with status code %d", string(resp.Body), int(resp.StatusCode)) - common.SetResponseHeader(ctx, resp.Header) - ctx.StatusCode(int(resp.StatusCode)) - ctx.Write(resp.Body) + sendSystemsResponse(ctx, resp) } // DeleteVolume is the handler to delete a volume under storage @@ -552,21 +411,14 @@ func (sys *SystemRPCs) DeleteVolume(ctx iris.Context) { if err != nil { errorMessage := "error while trying to create JSON request body: " + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) + common.SendFailedRPCCallResponse(ctx, errorMessage) return } l.LogWithFields(ctxt).Debugf("Incoming request received for deleting volume with request body %s", string(request)) - sessionToken := ctx.Request().Header.Get("X-Auth-Token") + sessionToken := ctx.Request().Header.Get(AuthTokenHeader) if sessionToken == "" { - errorMessage := "error: no X-Auth-Token found in request header" - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + errorMessage := invalidAuthTokenErrorMsg + common.SendInvalidSessionResponse(ctx, errorMessage) } volRequest := systemsproto.VolumeRequest{ SessionToken: sessionToken, @@ -577,15 +429,16 @@ func (sys *SystemRPCs) DeleteVolume(ctx iris.Context) { } resp, err := sys.DeleteVolumeRPC(ctxt, volRequest) if err != nil { - errorMessage := "RPC error:" + err.Error() + errorMessage := rpcFailedErrMsg + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) - return + common.SendFailedRPCCallResponse(ctx, errorMessage) } l.LogWithFields(ctxt).Debugf("Outgoing response for deleting a volume is %s with status code %d", string(resp.Body), int(resp.StatusCode)) + sendSystemsResponse(ctx, resp) +} + +// sendSystemsResponse writes the systems response to client +func sendSystemsResponse(ctx iris.Context, resp *systemsproto.SystemsResponse) { common.SetResponseHeader(ctx, resp.Header) ctx.StatusCode(int(resp.StatusCode)) ctx.Write(resp.Body) diff --git a/svc-api/handle/task.go b/svc-api/handle/task.go index 7762675d3..10f8123f4 100644 --- a/svc-api/handle/task.go +++ b/svc-api/handle/task.go @@ -45,7 +45,7 @@ func (task *TaskRPCs) DeleteTask(ctx iris.Context) { ctxt := ctx.Request().Context() req := &taskproto.GetTaskRequest{ TaskID: ctx.Params().Get("TaskID"), - SessionToken: ctx.Request().Header.Get("X-Auth-Token"), + SessionToken: ctx.Request().Header.Get(AuthTokenHeader), } l.LogWithFields(ctxt).Debugf("Incoming request received for deleting task with taskid %s", req.TaskID) response, err := task.DeleteTaskRPC(ctxt, req) @@ -60,9 +60,7 @@ func (task *TaskRPCs) DeleteTask(ctx iris.Context) { return } l.LogWithFields(ctxt).Debugf("Outgoing response for deleting task is %s with status code %d", string(response.Body), int(response.StatusCode)) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(int(response.StatusCode)) - ctx.Write(response.Body) + sendTaskResponse(ctx, response) } // GetTaskStatus fetches task status @@ -73,7 +71,7 @@ func (task *TaskRPCs) GetTaskStatus(ctx iris.Context) { ctxt := ctx.Request().Context() req := &taskproto.GetTaskRequest{ TaskID: ctx.Params().Get("TaskID"), - SessionToken: ctx.Request().Header.Get("X-Auth-Token"), + SessionToken: ctx.Request().Header.Get(AuthTokenHeader), } l.LogWithFields(ctxt).Debugf("Incoming request received for getting task status with taskid %s", req.TaskID) response, err := task.GetTaskRPC(ctxt, req) @@ -89,9 +87,7 @@ func (task *TaskRPCs) GetTaskStatus(ctx iris.Context) { } l.LogWithFields(ctxt).Debugf("Outgoing response for getting task is %s with status code %d", string(response.Body), int(response.StatusCode)) ctx.ResponseWriter().Header().Set("Allow", "GET, DELETE") - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(int(response.StatusCode)) - ctx.Write(response.Body) + sendTaskResponse(ctx, response) } // GetSubTasks fetches sub task collection under given umbralla tasks @@ -102,7 +98,7 @@ func (task *TaskRPCs) GetSubTasks(ctx iris.Context) { ctxt := ctx.Request().Context() req := &taskproto.GetTaskRequest{ TaskID: ctx.Params().Get("TaskID"), - SessionToken: ctx.Request().Header.Get("X-Auth-Token"), + SessionToken: ctx.Request().Header.Get(AuthTokenHeader), } response, err := task.GetSubTasksRPC(ctxt, req) common.SetResponseHeader(ctx, response.Header) @@ -117,9 +113,7 @@ func (task *TaskRPCs) GetSubTasks(ctx iris.Context) { } l.LogWithFields(ctxt).Debugf("Outgoing response for getting sub tasks is %s with status code %d", string(response.Body), int(response.StatusCode)) ctx.ResponseWriter().Header().Set("Allow", "GET") - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(int(response.StatusCode)) - ctx.Write(response.Body) + sendTaskResponse(ctx, response) } // GetSubTask fetches sub task details @@ -131,7 +125,7 @@ func (task *TaskRPCs) GetSubTask(ctx iris.Context) { req := &taskproto.GetTaskRequest{ TaskID: ctx.Params().Get("TaskID"), SubTaskID: ctx.Params().Get("subTaskID"), - SessionToken: ctx.Request().Header.Get("X-Auth-Token"), + SessionToken: ctx.Request().Header.Get(AuthTokenHeader), } l.LogWithFields(ctxt).Debugf("Incoming request received for getting sub task information with taskid %s and subtaskid %s", req.TaskID, req.SubTaskID) response, err := task.GetSubTaskRPC(ctxt, req) @@ -147,9 +141,7 @@ func (task *TaskRPCs) GetSubTask(ctx iris.Context) { } l.LogWithFields(ctxt).Debugf("Outgoing response for getting sub task information is %s with status code %d", string(response.Body), int(response.StatusCode)) ctx.ResponseWriter().Header().Set("Allow", "GET") - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(int(response.StatusCode)) - ctx.Write(response.Body) + sendTaskResponse(ctx, response) } // GetTaskMonitor fetches task monitor @@ -160,7 +152,7 @@ func (task *TaskRPCs) GetTaskMonitor(ctx iris.Context) { ctxt := ctx.Request().Context() req := &taskproto.GetTaskRequest{ TaskID: ctx.Params().Get("TaskID"), - SessionToken: ctx.Request().Header.Get("X-Auth-Token"), + SessionToken: ctx.Request().Header.Get(AuthTokenHeader), } l.LogWithFields(ctxt).Debugf("Incoming request received for getting task mon for taskid %s", req.TaskID) response, err := task.GetTaskMonitorRPC(ctxt, req) @@ -176,9 +168,7 @@ func (task *TaskRPCs) GetTaskMonitor(ctx iris.Context) { } l.LogWithFields(ctxt).Debugf("Outgoing response for getting task monitoring information is %s with status code %d", string(response.Body), int(response.StatusCode)) ctx.ResponseWriter().Header().Set("Allow", "GET") - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(int(response.StatusCode)) - ctx.Write(response.Body) + sendTaskResponse(ctx, response) } // TaskCollection fetches all tasks available in DB @@ -188,7 +178,7 @@ func (task *TaskRPCs) TaskCollection(ctx iris.Context) { defer ctx.Next() ctxt := ctx.Request().Context() req := &taskproto.GetTaskRequest{ - SessionToken: ctx.Request().Header.Get("X-Auth-Token"), + SessionToken: ctx.Request().Header.Get(AuthTokenHeader), } l.LogWithFields(ctxt).Debugf("Incoming request received for getting task all the available tasks collection") if req.SessionToken == "" { @@ -212,9 +202,7 @@ func (task *TaskRPCs) TaskCollection(ctx iris.Context) { } l.LogWithFields(ctxt).Debugf("Outgoing response for getting task collections is %s with status code %d", string(response.Body), int(response.StatusCode)) ctx.ResponseWriter().Header().Set("Allow", "GET") - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(int(response.StatusCode)) - ctx.Write(response.Body) + sendTaskResponse(ctx, response) } @@ -225,7 +213,7 @@ func (task *TaskRPCs) GetTaskService(ctx iris.Context) { defer ctx.Next() ctxt := ctx.Request().Context() req := &taskproto.GetTaskRequest{ - SessionToken: ctx.Request().Header.Get("X-Auth-Token"), + SessionToken: ctx.Request().Header.Get(AuthTokenHeader), } response, err := task.GetTaskServiceRPC(ctxt, req) common.SetResponseHeader(ctx, response.Header) @@ -240,6 +228,11 @@ func (task *TaskRPCs) GetTaskService(ctx iris.Context) { } l.LogWithFields(ctxt).Debugf("Outgoing response for getting task service is %s with status code %d", string(response.Body), int(response.StatusCode)) ctx.ResponseWriter().Header().Set("Allow", "GET") + sendTaskResponse(ctx, response) +} + +// sendTaskResponse writes the task response to client +func sendTaskResponse(ctx iris.Context, response *taskproto.TaskResponse) { common.SetResponseHeader(ctx, response.Header) ctx.StatusCode(int(response.StatusCode)) ctx.Write(response.Body) diff --git a/svc-api/handle/telemetry.go b/svc-api/handle/telemetry.go index 72ba2f188..2f6ce03e5 100644 --- a/svc-api/handle/telemetry.go +++ b/svc-api/handle/telemetry.go @@ -17,12 +17,10 @@ package handle import ( "context" - "net/http" "github.com/ODIM-Project/ODIM/lib-utilities/common" l "github.com/ODIM-Project/ODIM/lib-utilities/logs" telemetryproto "github.com/ODIM-Project/ODIM/lib-utilities/proto/telemetry" - "github.com/ODIM-Project/ODIM/lib-utilities/response" iris "github.com/kataras/iris/v12" ) @@ -40,31 +38,28 @@ type TelemetryRPCs struct { UpdateTriggerRPC func(context.Context, telemetryproto.TelemetryRequest) (*telemetryproto.TelemetryResponse, error) } +const ( + rpcCallFailedErrorMsg = "error: something went wrong with the RPC calls: " + invalidAuthTokenErrorMsg = "error: no X-Auth-Token found in request header" +) + // GetTelemetryService is the handler for getting TelemetryService details func (a *TelemetryRPCs) GetTelemetryService(ctx iris.Context) { defer ctx.Next() ctxt := ctx.Request().Context() req := telemetryproto.TelemetryRequest{ - SessionToken: ctx.Request().Header.Get("X-Auth-Token"), + SessionToken: ctx.Request().Header.Get(AuthTokenHeader), } l.LogWithFields(ctxt).Debug("Incoming request received for getting telemetry service details") if req.SessionToken == "" { - errorMessage := "error: no X-Auth-Token found in request header" - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + errorMessage := invalidAuthTokenErrorMsg + common.SendInvalidSessionResponse(ctx, errorMessage) } resp, err := a.GetTelemetryServiceRPC(ctxt, req) if err != nil { - errorMessage := "error: something went wrong with the RPC calls: " + err.Error() + errorMessage := rpcCallFailedErrorMsg + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) - return + common.SendFailedRPCCallResponse(ctx, errorMessage) } l.LogWithFields(ctxt).Debugf("Outgoing response for getting telemetry service is %s with status code %d", string(resp.Body), int(resp.StatusCode)) ctx.ResponseWriter().Header().Set("Allow", "GET") @@ -79,27 +74,19 @@ func (a *TelemetryRPCs) GetMetricDefinitionCollection(ctx iris.Context) { defer ctx.Next() ctxt := ctx.Request().Context() req := telemetryproto.TelemetryRequest{ - SessionToken: ctx.Request().Header.Get("X-Auth-Token"), + SessionToken: ctx.Request().Header.Get(AuthTokenHeader), URL: ctx.Request().RequestURI, } l.LogWithFields(ctxt).Debugf("Incoming request received for getting metric definition collection details with request URI %s", req.URL) if req.SessionToken == "" { - errorMessage := "error: no X-Auth-Token found in request header" - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + errorMessage := invalidAuthTokenErrorMsg + common.SendInvalidSessionResponse(ctx, errorMessage) } resp, err := a.GetMetricDefinitionCollectionRPC(ctxt, req) if err != nil { - errorMessage := "error: something went wrong with the RPC calls: " + err.Error() + errorMessage := rpcCallFailedErrorMsg + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) - return + common.SendFailedRPCCallResponse(ctx, errorMessage) } l.LogWithFields(ctxt).Debugf("Outgoing response for getting metric definition collection is %s with status code %d", string(resp.Body), int(resp.StatusCode)) ctx.ResponseWriter().Header().Set("Allow", "GET") @@ -114,27 +101,19 @@ func (a *TelemetryRPCs) GetMetricReportDefinitionCollection(ctx iris.Context) { defer ctx.Next() ctxt := ctx.Request().Context() req := telemetryproto.TelemetryRequest{ - SessionToken: ctx.Request().Header.Get("X-Auth-Token"), + SessionToken: ctx.Request().Header.Get(AuthTokenHeader), URL: ctx.Request().RequestURI, } l.LogWithFields(ctxt).Debugf("Incoming request received for getting metric report definition collection details with request URI %s", req.URL) if req.SessionToken == "" { - errorMessage := "error: no X-Auth-Token found in request header" - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + errorMessage := invalidAuthTokenErrorMsg + common.SendInvalidSessionResponse(ctx, errorMessage) } resp, err := a.GetMetricReportDefinitionCollectionRPC(ctxt, req) if err != nil { - errorMessage := "error: something went wrong with the RPC calls: " + err.Error() + errorMessage := rpcCallFailedErrorMsg + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) - return + common.SendFailedRPCCallResponse(ctx, errorMessage) } l.LogWithFields(ctxt).Debugf("Outgoing response for getting metric report definition collection is %s with status code %d", string(resp.Body), int(resp.StatusCode)) ctx.ResponseWriter().Header().Set("Allow", "GET") @@ -149,27 +128,19 @@ func (a *TelemetryRPCs) GetMetricReportCollection(ctx iris.Context) { defer ctx.Next() ctxt := ctx.Request().Context() req := telemetryproto.TelemetryRequest{ - SessionToken: ctx.Request().Header.Get("X-Auth-Token"), + SessionToken: ctx.Request().Header.Get(AuthTokenHeader), URL: ctx.Request().RequestURI, } l.LogWithFields(ctxt).Debugf("Incoming request received for getting metric report collection details with request URI %s", req.URL) if req.SessionToken == "" { - errorMessage := "error: no X-Auth-Token found in request header" - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + errorMessage := invalidAuthTokenErrorMsg + common.SendInvalidSessionResponse(ctx, errorMessage) } resp, err := a.GetMetricReportCollectionRPC(ctxt, req) if err != nil { - errorMessage := "error: something went wrong with the RPC calls: " + err.Error() + errorMessage := rpcCallFailedErrorMsg + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) - return + common.SendFailedRPCCallResponse(ctx, errorMessage) } l.LogWithFields(ctxt).Debugf("Outgoing response for getting metric report collection is %s with status code %d", string(resp.Body), int(resp.StatusCode)) ctx.ResponseWriter().Header().Set("Allow", "GET") @@ -184,27 +155,19 @@ func (a *TelemetryRPCs) GetTriggerCollection(ctx iris.Context) { defer ctx.Next() ctxt := ctx.Request().Context() req := telemetryproto.TelemetryRequest{ - SessionToken: ctx.Request().Header.Get("X-Auth-Token"), + SessionToken: ctx.Request().Header.Get(AuthTokenHeader), URL: ctx.Request().RequestURI, } l.LogWithFields(ctxt).Debugf("Incoming request received for getting trigger collection details with request URI %s", req.URL) if req.SessionToken == "" { - errorMessage := "error: no X-Auth-Token found in request header" - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + errorMessage := invalidAuthTokenErrorMsg + common.SendInvalidSessionResponse(ctx, errorMessage) } resp, err := a.GetTriggerCollectionRPC(ctxt, req) if err != nil { - errorMessage := "error: something went wrong with the RPC calls: " + err.Error() + errorMessage := rpcCallFailedErrorMsg + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) - return + common.SendFailedRPCCallResponse(ctx, errorMessage) } l.LogWithFields(ctxt).Debugf("Outgoing response for getting trigger collection is %s with status code %d", string(resp.Body), int(resp.StatusCode)) ctx.ResponseWriter().Header().Set("Allow", "GET") @@ -219,27 +182,19 @@ func (a *TelemetryRPCs) GetMetricDefinition(ctx iris.Context) { defer ctx.Next() ctxt := ctx.Request().Context() req := telemetryproto.TelemetryRequest{ - SessionToken: ctx.Request().Header.Get("X-Auth-Token"), + SessionToken: ctx.Request().Header.Get(AuthTokenHeader), URL: ctx.Request().RequestURI, } l.LogWithFields(ctxt).Debugf("Incoming request received for getting metric definition details with request URI %s", req.URL) if req.SessionToken == "" { - errorMessage := "error: no X-Auth-Token found in request header" - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + errorMessage := invalidAuthTokenErrorMsg + common.SendInvalidSessionResponse(ctx, errorMessage) } resp, err := a.GetMetricDefinitionRPC(ctxt, req) if err != nil { - errorMessage := "error: something went wrong with the RPC calls: " + err.Error() + errorMessage := rpcCallFailedErrorMsg + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) - return + common.SendFailedRPCCallResponse(ctx, errorMessage) } l.LogWithFields(ctxt).Debugf("Outgoing response for getting metric definition is %s with status code %d", string(resp.Body), int(resp.StatusCode)) ctx.ResponseWriter().Header().Set("Allow", "GET") @@ -254,27 +209,19 @@ func (a *TelemetryRPCs) GetMetricReportDefinition(ctx iris.Context) { defer ctx.Next() ctxt := ctx.Request().Context() req := telemetryproto.TelemetryRequest{ - SessionToken: ctx.Request().Header.Get("X-Auth-Token"), + SessionToken: ctx.Request().Header.Get(AuthTokenHeader), URL: ctx.Request().RequestURI, } l.LogWithFields(ctxt).Debugf("Incoming request received for getting metric report definition details with request URI %s", req.URL) if req.SessionToken == "" { - errorMessage := "error: no X-Auth-Token found in request header" - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + errorMessage := invalidAuthTokenErrorMsg + common.SendInvalidSessionResponse(ctx, errorMessage) } resp, err := a.GetMetricReportDefinitionRPC(ctxt, req) if err != nil { - errorMessage := "error: something went wrong with the RPC calls: " + err.Error() + errorMessage := rpcCallFailedErrorMsg + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) - return + common.SendFailedRPCCallResponse(ctx, errorMessage) } l.LogWithFields(ctxt).Debugf("Outgoing response for getting metric report definition is %s with status code %d", string(resp.Body), int(resp.StatusCode)) ctx.ResponseWriter().Header().Set("Allow", "GET") @@ -289,27 +236,19 @@ func (a *TelemetryRPCs) GetMetricReport(ctx iris.Context) { defer ctx.Next() ctxt := ctx.Request().Context() req := telemetryproto.TelemetryRequest{ - SessionToken: ctx.Request().Header.Get("X-Auth-Token"), + SessionToken: ctx.Request().Header.Get(AuthTokenHeader), URL: ctx.Request().RequestURI, } l.LogWithFields(ctxt).Debugf("Incoming request received for getting metric report details with request URI %s", req.URL) if req.SessionToken == "" { - errorMessage := "error: no X-Auth-Token found in request header" - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + errorMessage := invalidAuthTokenErrorMsg + common.SendInvalidSessionResponse(ctx, errorMessage) } resp, err := a.GetMetricReportRPC(ctxt, req) if err != nil { - errorMessage := "error: something went wrong with the RPC calls: " + err.Error() + errorMessage := rpcCallFailedErrorMsg + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) - return + common.SendFailedRPCCallResponse(ctx, errorMessage) } l.LogWithFields(ctxt).Debugf("Outgoing response for getting metric definition collection is %s with status code %d", string(resp.Body), int(resp.StatusCode)) ctx.ResponseWriter().Header().Set("Allow", "GET") @@ -324,27 +263,19 @@ func (a *TelemetryRPCs) GetTrigger(ctx iris.Context) { defer ctx.Next() ctxt := ctx.Request().Context() req := telemetryproto.TelemetryRequest{ - SessionToken: ctx.Request().Header.Get("X-Auth-Token"), + SessionToken: ctx.Request().Header.Get(AuthTokenHeader), URL: ctx.Request().RequestURI, } if req.SessionToken == "" { - errorMessage := "error: no X-Auth-Token found in request header" - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + errorMessage := invalidAuthTokenErrorMsg + common.SendInvalidSessionResponse(ctx, errorMessage) } l.LogWithFields(ctxt).Debugf("Incoming request received for getting trigger details with request URI %s", req.URL) resp, err := a.GetTriggerRPC(ctxt, req) if err != nil { - errorMessage := "error: something went wrong with the RPC calls: " + err.Error() + errorMessage := rpcCallFailedErrorMsg + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) - return + common.SendFailedRPCCallResponse(ctx, errorMessage) } l.LogWithFields(ctxt).Debugf("Outgoing response for getting trigger details is %s with status code %d", string(resp.Body), int(resp.StatusCode)) ctx.ResponseWriter().Header().Set("Allow", "GET, PATCH") @@ -359,26 +290,18 @@ func (a *TelemetryRPCs) UpdateTrigger(ctx iris.Context) { defer ctx.Next() ctxt := ctx.Request().Context() req := telemetryproto.TelemetryRequest{ - SessionToken: ctx.Request().Header.Get("X-Auth-Token"), + SessionToken: ctx.Request().Header.Get(AuthTokenHeader), } l.LogWithFields(ctxt).Debug("Incoming request received for updating trigger") if req.SessionToken == "" { - errorMessage := "error: no X-Auth-Token found in request header" - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + errorMessage := invalidAuthTokenErrorMsg + common.SendInvalidSessionResponse(ctx, errorMessage) } resp, err := a.UpdateTriggerRPC(ctxt, req) if err != nil { - errorMessage := "error: something went wrong with the RPC calls: " + err.Error() + errorMessage := rpcCallFailedErrorMsg + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) - return + common.SendFailedRPCCallResponse(ctx, errorMessage) } l.LogWithFields(ctxt).Debugf("Outgoing response for updating trigger is %s with status code %d", string(resp.Body), int(resp.StatusCode)) common.SetResponseHeader(ctx, resp.Header) diff --git a/svc-api/handle/update.go b/svc-api/handle/update.go index 137b5f844..dda85f05a 100644 --- a/svc-api/handle/update.go +++ b/svc-api/handle/update.go @@ -46,33 +46,22 @@ func (a *UpdateRPCs) GetUpdateService(ctx iris.Context) { defer ctx.Next() ctxt := ctx.Request().Context() req := updateproto.UpdateRequest{ - SessionToken: ctx.Request().Header.Get("X-Auth-Token"), + SessionToken: ctx.Request().Header.Get(AuthTokenHeader), } l.LogWithFields(ctxt).Debug("Incoming request received for getting update service details") if req.SessionToken == "" { - errorMessage := "error: no X-Auth-Token found in request header" - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + errorMessage := invalidAuthTokenErrorMsg + common.SendInvalidSessionResponse(ctx, errorMessage) } resp, err := a.GetUpdateServiceRPC(ctxt, req) if err != nil { - errorMessage := "error: something went wrong with the RPC calls: " + err.Error() + errorMessage := rpcCallFailedErrorMsg + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) - return + common.SendFailedRPCCallResponse(ctx, errorMessage) } l.LogWithFields(ctxt).Debugf("Outgoing response for getting update service is %s with status code %d", string(resp.Body), int(resp.StatusCode)) ctx.ResponseWriter().Header().Set("Allow", "GET") - common.SetResponseHeader(ctx, resp.Header) - ctx.StatusCode(int(resp.StatusCode)) - ctx.Write(resp.Body) - + sendUpdateResponse(ctx, resp) } // GetFirmwareInventoryCollection is a handler for firmware inventory collection @@ -80,32 +69,22 @@ func (a *UpdateRPCs) GetFirmwareInventoryCollection(ctx iris.Context) { defer ctx.Next() ctxt := ctx.Request().Context() req := updateproto.UpdateRequest{ - SessionToken: ctx.Request().Header.Get("X-Auth-Token"), + SessionToken: ctx.Request().Header.Get(AuthTokenHeader), } l.LogWithFields(ctxt).Debug("Incoming request received for getting firmware inventory collection") if req.SessionToken == "" { - errorMessage := "error: no X-Auth-Token found in request header" - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + errorMessage := invalidAuthTokenErrorMsg + common.SendInvalidSessionResponse(ctx, errorMessage) } resp, err := a.GetFirmwareInventoryCollectionRPC(ctxt, req) if err != nil { - errorMessage := "error: something went wrong with the RPC calls: " + err.Error() + errorMessage := rpcCallFailedErrorMsg + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) - return + common.SendFailedRPCCallResponse(ctx, errorMessage) } l.LogWithFields(ctxt).Debugf("Outgoing response for getting firmware inventory collection is %s with status code %d", string(resp.Body), int(resp.StatusCode)) ctx.ResponseWriter().Header().Set("Allow", "GET") - common.SetResponseHeader(ctx, resp.Header) - ctx.StatusCode(int(resp.StatusCode)) - ctx.Write(resp.Body) + sendUpdateResponse(ctx, resp) } @@ -114,32 +93,22 @@ func (a *UpdateRPCs) GetSoftwareInventoryCollection(ctx iris.Context) { defer ctx.Next() ctxt := ctx.Request().Context() req := updateproto.UpdateRequest{ - SessionToken: ctx.Request().Header.Get("X-Auth-Token"), + SessionToken: ctx.Request().Header.Get(AuthTokenHeader), } l.LogWithFields(ctxt).Debug("Incoming request received for software inventory collection") if req.SessionToken == "" { - errorMessage := "error: no X-Auth-Token found in request header" - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + errorMessage := invalidAuthTokenErrorMsg + common.SendInvalidSessionResponse(ctx, errorMessage) } resp, err := a.GetSoftwareInventoryCollectionRPC(ctxt, req) if err != nil { - errorMessage := "error: something went wrong with the RPC calls: " + err.Error() + errorMessage := rpcCallFailedErrorMsg + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) - return + common.SendFailedRPCCallResponse(ctx, errorMessage) } l.LogWithFields(ctxt).Debugf("Outgoing response for getting software inventory collection is %s with status code %d", string(resp.Body), int(resp.StatusCode)) ctx.ResponseWriter().Header().Set("Allow", "GET") - common.SetResponseHeader(ctx, resp.Header) - ctx.StatusCode(int(resp.StatusCode)) - ctx.Write(resp.Body) + sendUpdateResponse(ctx, resp) } @@ -148,34 +117,24 @@ func (a *UpdateRPCs) GetFirmwareInventory(ctx iris.Context) { defer ctx.Next() ctxt := ctx.Request().Context() req := updateproto.UpdateRequest{ - SessionToken: ctx.Request().Header.Get("X-Auth-Token"), + SessionToken: ctx.Request().Header.Get(AuthTokenHeader), ResourceID: ctx.Params().Get("firmwareInventory_id"), URL: ctx.Request().RequestURI, } l.LogWithFields(ctxt).Debugf("Incoming request received for getting firmware inventory with url %s", req.URL) if req.SessionToken == "" { - errorMessage := "error: no X-Auth-Token found in request header" - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + errorMessage := invalidAuthTokenErrorMsg + common.SendInvalidSessionResponse(ctx, errorMessage) } resp, err := a.GetFirmwareInventoryRPC(ctxt, req) if err != nil { - errorMessage := "error: something went wrong with the RPC calls: " + err.Error() + errorMessage := rpcCallFailedErrorMsg + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) - return + common.SendFailedRPCCallResponse(ctx, errorMessage) } l.LogWithFields(ctxt).Debugf("Outgoing response for getting firmware inventory details is %s with status code %d", string(resp.Body), int(resp.StatusCode)) ctx.ResponseWriter().Header().Set("Allow", "GET") - common.SetResponseHeader(ctx, resp.Header) - ctx.StatusCode(int(resp.StatusCode)) - ctx.Write(resp.Body) + sendUpdateResponse(ctx, resp) } @@ -184,34 +143,24 @@ func (a *UpdateRPCs) GetSoftwareInventory(ctx iris.Context) { defer ctx.Next() ctxt := ctx.Request().Context() req := updateproto.UpdateRequest{ - SessionToken: ctx.Request().Header.Get("X-Auth-Token"), + SessionToken: ctx.Request().Header.Get(AuthTokenHeader), ResourceID: ctx.Params().Get("softwareInventory_id"), URL: ctx.Request().RequestURI, } l.LogWithFields(ctxt).Debugf("Incoming request received for getting software inventory with url %s", req.URL) if req.SessionToken == "" { - errorMessage := "error: no X-Auth-Token found in request header" - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + errorMessage := invalidAuthTokenErrorMsg + common.SendInvalidSessionResponse(ctx, errorMessage) } resp, err := a.GetSoftwareInventoryRPC(ctxt, req) if err != nil { - errorMessage := "error: something went wrong with the RPC calls: " + err.Error() + errorMessage := rpcCallFailedErrorMsg + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) - return + common.SendFailedRPCCallResponse(ctx, errorMessage) } l.LogWithFields(ctxt).Debugf("Outgoing response for getting software inventory details is %s with status code %d", string(resp.Body), int(resp.StatusCode)) ctx.ResponseWriter().Header().Set("Allow", "GET") - common.SetResponseHeader(ctx, resp.Header) - ctx.StatusCode(int(resp.StatusCode)) - ctx.Write(resp.Body) + sendUpdateResponse(ctx, resp) } @@ -224,20 +173,12 @@ func (a *UpdateRPCs) SimpleUpdate(ctx iris.Context) { if err != nil { errorMessage := "error while trying to get JSON body from the simple update request body: " + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusBadRequest, response.MalformedJSON, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusBadRequest) - ctx.JSON(&response.Body) - return + common.SendMalformedJSONRequestErrResponse(ctx, errorMessage) } - sessionToken := ctx.Request().Header.Get("X-Auth-Token") + sessionToken := ctx.Request().Header.Get(AuthTokenHeader) if sessionToken == "" { - errorMessage := "error: no X-Auth-Token found in request header" - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + errorMessage := invalidAuthTokenErrorMsg + common.SendInvalidSessionResponse(ctx, errorMessage) } // Marshalling the req to make reset request request, err := json.Marshal(req) @@ -257,16 +198,10 @@ func (a *UpdateRPCs) SimpleUpdate(ctx iris.Context) { if err != nil { errorMessage := "RPC error:" + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) - return + common.SendFailedRPCCallResponse(ctx, errorMessage) } l.LogWithFields(ctxt).Debugf("Outgoing response for simple update action is %s with status code %d", string(resp.Body), int(resp.StatusCode)) - common.SetResponseHeader(ctx, resp.Header) - ctx.StatusCode(int(resp.StatusCode)) - ctx.Write(resp.Body) + sendUpdateResponse(ctx, resp) } func validateSimpleUpdateRequest(ctx context.Context, requestBody []byte) response.RPC { @@ -319,14 +254,10 @@ func (a *UpdateRPCs) StartUpdate(ctx iris.Context) { defer ctx.Next() ctxt := ctx.Request().Context() l.LogWithFields(ctxt).Debug("Incoming request received for start update action") - sessionToken := ctx.Request().Header.Get("X-Auth-Token") + sessionToken := ctx.Request().Header.Get(AuthTokenHeader) if sessionToken == "" { - errorMessage := "error: no X-Auth-Token found in request header" - response := common.GeneralError(http.StatusUnauthorized, response.NoValidSession, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusUnauthorized) - ctx.JSON(&response.Body) - return + errorMessage := invalidAuthTokenErrorMsg + common.SendInvalidSessionResponse(ctx, errorMessage) } updateRequest := updateproto.UpdateRequest{ SessionToken: sessionToken, @@ -335,13 +266,14 @@ func (a *UpdateRPCs) StartUpdate(ctx iris.Context) { if err != nil { errorMessage := "RPC error:" + err.Error() l.LogWithFields(ctxt).Error(errorMessage) - response := common.GeneralError(http.StatusInternalServerError, response.InternalError, errorMessage, nil, nil) - common.SetResponseHeader(ctx, response.Header) - ctx.StatusCode(http.StatusInternalServerError) - ctx.JSON(&response.Body) - return + common.SendFailedRPCCallResponse(ctx, errorMessage) } l.LogWithFields(ctxt).Debugf("Outgoing response for start update action is %s with status code %d", string(resp.Body), int(resp.StatusCode)) + sendUpdateResponse(ctx, resp) +} + +// sendUpdateResponse writes the update response to client +func sendUpdateResponse(ctx iris.Context, resp *updateproto.UpdateResponse) { common.SetResponseHeader(ctx, resp.Header) ctx.StatusCode(int(resp.StatusCode)) ctx.Write(resp.Body) diff --git a/svc-api/messages/sessions.go b/svc-api/messages/sessions.go index 33672a53f..95004f2f6 100644 --- a/svc-api/messages/sessions.go +++ b/svc-api/messages/sessions.go @@ -12,7 +12,7 @@ //License for the specific language governing permissions and limitations // under the License. -//Package messages ... +// Package messages ... package messages // SessionCreateRequest ... diff --git a/svc-api/models/metadata.go b/svc-api/models/metadata.go index d78abea85..c07b87eba 100644 --- a/svc-api/models/metadata.go +++ b/svc-api/models/metadata.go @@ -12,12 +12,12 @@ //License for the specific language governing permissions and limitations // under the License. -//Package models ... +// Package models ... package models import "encoding/xml" -//Metadata struct definition +// Metadata struct definition type Metadata struct { XMLName xml.Name `xml:"edmx:Edmx"` Xmlnsedmx string `xml:"xmlns:edmx,attr"` @@ -25,14 +25,14 @@ type Metadata struct { TopReference []Reference } -//Reference strcut definition +// Reference strcut definition type Reference struct { XMLName xml.Name `xml:"edmx:Reference"` URI string `xml:"Uri,attr"` TopInclude []Include `xml:"edmx:Include"` } -//Include struct definition +// Include struct definition type Include struct { Namespace string `xml:"Namespace,attr"` Alias string `xml:"Alias,attr,omitempty"` diff --git a/svc-api/models/odata.go b/svc-api/models/odata.go index c09eb1fde..ed71ff6ad 100644 --- a/svc-api/models/odata.go +++ b/svc-api/models/odata.go @@ -12,17 +12,17 @@ //License for the specific language governing permissions and limitations // under the License. -//Package models ... +// Package models ... package models -//Odata struct definition +// Odata struct definition type Odata struct { RedfishCopyright string `json:"@Redfish.Copyright"` OdataContext string `json:"@odata.context"` Value []*Value `json:"value"` } -//Value struct definition +// Value struct definition type Value struct { Name string `json:"name"` Kind string `json:"kind"` diff --git a/svc-api/models/serviceroot.go b/svc-api/models/serviceroot.go index 255f1403d..bad3aef11 100644 --- a/svc-api/models/serviceroot.go +++ b/svc-api/models/serviceroot.go @@ -12,10 +12,10 @@ //License for the specific language governing permissions and limitations // under the License. -//Package models ... +// Package models ... package models -//ServiceRoot struct definition +// ServiceRoot struct definition type ServiceRoot struct { OdataContext string `json:"@odata.context"` Etag string `json:"@odata.etag,omitempty"` @@ -63,7 +63,7 @@ type ServiceRoot struct { LicenseService *Service `json:"LicenseService,omitempty"` } -//PFSupported struct definition +// PFSupported struct definition type PFSupported struct { ExcerptQuery bool `json:"ExcerptQuery"` ExpandQuery *ExpandQuery `json:"ExpandQuery:omitempty"` @@ -72,7 +72,7 @@ type PFSupported struct { SelectQuery bool `json:"SelectQuery"` } -//ExpandQuery struct definition +// ExpandQuery struct definition type ExpandQuery struct { ExpandAll bool `json:"ExpandAll"` Levels bool `json:"Levels"` @@ -81,21 +81,21 @@ type ExpandQuery struct { NoLinks bool `json:"NoLinks"` } -//Service struct definition +// Service struct definition type Service struct { OdataID string `json:"@odata.id"` } -//Links struct definition +// Links struct definition type Links struct { Sessions Sessions `json:"Sessions"` } -//Sessions struct definition +// Sessions struct definition type Sessions struct { OdataID string `json:"@odata.id"` } -//OEM struct definition +// OEM struct definition type OEM struct { } diff --git a/svc-api/models/version.go b/svc-api/models/version.go index cc2c16bf1..fe01d7826 100644 --- a/svc-api/models/version.go +++ b/svc-api/models/version.go @@ -12,10 +12,10 @@ //License for the specific language governing permissions and limitations // under the License. -//Package models ... +// Package models ... package models -//Version struct definition +// Version struct definition type Version struct { V1 string `json:"v1"` } diff --git a/svc-api/response/accounts.go b/svc-api/response/accounts.go index b0f83ff0c..9bec29dd3 100644 --- a/svc-api/response/accounts.go +++ b/svc-api/response/accounts.go @@ -12,14 +12,14 @@ //License for the specific language governing permissions and limitations // under the License. -//Package response ... +// Package response ... package response import ( dmtf "github.com/ODIM-Project/ODIM/lib-dmtf/model" ) -//User struct is used to ommit password for display purposes +// User struct is used to ommit password for display purposes type User struct { OdataContext string `json:"@odata.context"` Etag string `json:"@odata.etag,omitempty"` @@ -35,21 +35,21 @@ type User struct { OEM OEM `json:"Oem"` } -//OEM struct definition +// OEM struct definition type OEM struct { } -//Links struct definition +// Links struct definition type Links struct { Role Role `json:"Role"` } -//Role struct definition +// Role struct definition type Role struct { OdataID string `json:"@odata.id"` } -//AccountService struct definition +// AccountService struct definition type AccountService struct { OdataType string `json:"@odata.type"` ID string `json:"Id"` @@ -84,23 +84,23 @@ type AccountService struct { TACACSplus *TACACSplus `json:"TACACSplus,omitempty"` } -//Accounts struct definition +// Accounts struct definition type Accounts struct { OdataID string `json:"@odata.id"` } -//OAuth2 struct definition +// OAuth2 struct definition type OAuth2 struct { } -//ActiveDirectory struct definition +// ActiveDirectory struct definition type ActiveDirectory struct { } -//LDAP struct definition +// LDAP struct definition type LDAP struct { } -//TACACSplus struct definition +// TACACSplus struct definition type TACACSplus struct { } diff --git a/svc-api/response/error.go b/svc-api/response/error.go index afdb02e1b..0e26ac67b 100644 --- a/svc-api/response/error.go +++ b/svc-api/response/error.go @@ -12,7 +12,7 @@ //License for the specific language governing permissions and limitations // under the License. -//Package response ... +// Package response ... package response // CommonError struct definition diff --git a/svc-api/response/list.go b/svc-api/response/list.go index 6b9947f6d..c538f1b49 100644 --- a/svc-api/response/list.go +++ b/svc-api/response/list.go @@ -12,7 +12,7 @@ //License for the specific language governing permissions and limitations // under the License. -//Package response defines the response structs +// Package response defines the response structs package response // ListResponse define list for odimra diff --git a/svc-api/response/registries.go b/svc-api/response/registries.go index 90f615eba..25c5a290d 100644 --- a/svc-api/response/registries.go +++ b/svc-api/response/registries.go @@ -12,10 +12,10 @@ //License for the specific language governing permissions and limitations // under the License. -//Package response ... +// Package response ... package response -//MessageRegistryFileID defines the message registry file id +// MessageRegistryFileID defines the message registry file id type MessageRegistryFileID struct { ID string `json:"Id"` OdataContext string `json:"@odata.context"` @@ -29,7 +29,7 @@ type MessageRegistryFileID struct { Registry string `json:"Registry"` } -//Location defines the locations/Paths of the file to retrieve. +// Location defines the locations/Paths of the file to retrieve. type Location struct { ArchiveFile string `json:"ArchiveFile,omitempty"` ArchiveURI string `json:"ArchiveUri,omitempty"` diff --git a/svc-api/response/session.go b/svc-api/response/session.go index cfbd1a7b2..03f7f5c72 100644 --- a/svc-api/response/session.go +++ b/svc-api/response/session.go @@ -12,7 +12,7 @@ //License for the specific language governing permissions and limitations // under the License. -//Package response ... +// Package response ... package response // RedfishSessionResponse will have all the @@ -45,7 +45,7 @@ type Session struct { UserName string `json:"UserName"` } -//SessionService struct definition +// SessionService struct definition type SessionService struct { OdataType string `json:"@odata.type"` ID string `json:"Id"` @@ -60,12 +60,12 @@ type SessionService struct { Etag string `json:"@odata.etag,omitempty"` } -//Sessions struct definition +// Sessions struct definition type Sessions struct { OdataID string `json:"@odata.id"` } -//Status struct definition +// Status struct definition type Status struct { State string `json:"State"` Health string `json:"Health"` diff --git a/svc-api/rpc/composition_service.go b/svc-api/rpc/composition_service.go index 97e32ff5f..18fb4f692 100755 --- a/svc-api/rpc/composition_service.go +++ b/svc-api/rpc/composition_service.go @@ -12,7 +12,7 @@ //License for the specific language governing permissions and limitations // under the License. -//Package rpc ... +// Package rpc ... package rpc import ( From 889b3e5cf97ee258695e63cf96c30439a4e46b9e Mon Sep 17 00:00:00 2001 From: Banoshi Date: Thu, 15 Jun 2023 11:36:25 +0530 Subject: [PATCH 10/19] refactor rpc files --- svc-api/rpc/account.go | 40 ++++++++------- svc-api/rpc/aggregator.go | 101 +++++++++++++++----------------------- svc-api/rpc/chassis.go | 31 +++++------- svc-api/rpc/events.go | 31 +++++------- svc-api/rpc/fabrics.go | 16 +++--- svc-api/rpc/licenses.go | 21 +++----- svc-api/rpc/managers.go | 46 +++++++---------- svc-api/rpc/role.go | 21 +++----- svc-api/rpc/sessions.go | 20 +++----- svc-api/rpc/system.go | 56 +++++++++------------ svc-api/rpc/task.go | 49 ++++++++---------- svc-api/rpc/telemetry.go | 51 ++++++++----------- 12 files changed, 197 insertions(+), 286 deletions(-) diff --git a/svc-api/rpc/account.go b/svc-api/rpc/account.go index 6726e1d69..2f832404a 100644 --- a/svc-api/rpc/account.go +++ b/svc-api/rpc/account.go @@ -22,6 +22,7 @@ import ( "github.com/ODIM-Project/ODIM/lib-utilities/common" accountproto "github.com/ODIM-Project/ODIM/lib-utilities/proto/account" "github.com/ODIM-Project/ODIM/lib-utilities/services" + "google.golang.org/grpc" ) // helper functions @@ -33,10 +34,9 @@ var ( // DoGetAccountServiceRequest defines the RPC call function for // the GetAccountService from account-session micro service func DoGetAccountServiceRequest(ctx context.Context, req accountproto.AccountRequest) (*accountproto.AccountResponse, error) { - ctx = common.CreateMetadata(ctx) - conn, err := ClientFunc(services.AccountSession) + ctx, conn, err := getConnection(ctx, services.AccountSession) if err != nil { - return nil, fmt.Errorf("Failed to create client connection: %v", err) + return nil, err } account := NewAccountClientFunc(conn) @@ -51,10 +51,9 @@ func DoGetAccountServiceRequest(ctx context.Context, req accountproto.AccountReq // DoAccountCreationRequest defines the RPC call function for // the AccountCreation from account-session micro service func DoAccountCreationRequest(ctx context.Context, req accountproto.CreateAccountRequest) (*accountproto.AccountResponse, error) { - ctx = common.CreateMetadata(ctx) - conn, err := ClientFunc(services.AccountSession) + ctx, conn, err := getConnection(ctx, services.AccountSession) if err != nil { - return nil, fmt.Errorf("Failed to create client connection: %v", err) + return nil, err } account := NewAccountClientFunc(conn) @@ -70,10 +69,9 @@ func DoAccountCreationRequest(ctx context.Context, req accountproto.CreateAccoun // DoGetAllAccountRequest defines the RPC call function for // the GetAllAccount from account-session micro service func DoGetAllAccountRequest(ctx context.Context, req accountproto.AccountRequest) (*accountproto.AccountResponse, error) { - ctx = common.CreateMetadata(ctx) - conn, err := ClientFunc(services.AccountSession) + ctx, conn, err := getConnection(ctx, services.AccountSession) if err != nil { - return nil, fmt.Errorf("Failed to create client connection: %v", err) + return nil, err } account := NewAccountClientFunc(conn) @@ -89,10 +87,9 @@ func DoGetAllAccountRequest(ctx context.Context, req accountproto.AccountRequest // DoGetAccountRequest defines the RPC call function for // the GetAccount from account-session micro service func DoGetAccountRequest(ctx context.Context, req accountproto.GetAccountRequest) (*accountproto.AccountResponse, error) { - ctx = common.CreateMetadata(ctx) - conn, err := ClientFunc(services.AccountSession) + ctx, conn, err := getConnection(ctx, services.AccountSession) if err != nil { - return nil, fmt.Errorf("Failed to create client connection: %v", err) + return nil, err } account := NewAccountClientFunc(conn) @@ -108,10 +105,9 @@ func DoGetAccountRequest(ctx context.Context, req accountproto.GetAccountRequest // DoUpdateAccountRequest defines the RPC call function for // the UpdateAccount from account-session micro service func DoUpdateAccountRequest(ctx context.Context, req accountproto.UpdateAccountRequest) (*accountproto.AccountResponse, error) { - ctx = common.CreateMetadata(ctx) - conn, err := ClientFunc(services.AccountSession) + ctx, conn, err := getConnection(ctx, services.AccountSession) if err != nil { - return nil, fmt.Errorf("Failed to create client connection: %v", err) + return nil, err } account := NewAccountClientFunc(conn) @@ -126,10 +122,9 @@ func DoUpdateAccountRequest(ctx context.Context, req accountproto.UpdateAccountR // DoAccountDeleteRequest defines the RPC call function for // the AccountDelete from account-session micro service func DoAccountDeleteRequest(ctx context.Context, req accountproto.DeleteAccountRequest) (*accountproto.AccountResponse, error) { - ctx = common.CreateMetadata(ctx) - conn, err := ClientFunc(services.AccountSession) + ctx, conn, err := getConnection(ctx, services.AccountSession) if err != nil { - return nil, fmt.Errorf("Failed to create client connection: %v", err) + return nil, err } account := NewAccountClientFunc(conn) @@ -141,3 +136,12 @@ func DoAccountDeleteRequest(ctx context.Context, req accountproto.DeleteAccountR defer conn.Close() return resp, err } + +func getConnection(ctx context.Context, service string) (context.Context, *grpc.ClientConn, error) { + ctx = common.CreateMetadata(ctx) + conn, err := ClientFunc(service) + if err != nil { + return ctx, nil, fmt.Errorf("Failed to create client connection: %v", err) + } + return ctx, conn, nil +} diff --git a/svc-api/rpc/aggregator.go b/svc-api/rpc/aggregator.go index 4c917f639..fa82bb638 100644 --- a/svc-api/rpc/aggregator.go +++ b/svc-api/rpc/aggregator.go @@ -19,7 +19,6 @@ import ( "context" "fmt" - "github.com/ODIM-Project/ODIM/lib-utilities/common" aggregatorproto "github.com/ODIM-Project/ODIM/lib-utilities/proto/aggregator" "github.com/ODIM-Project/ODIM/lib-utilities/services" ) @@ -32,10 +31,9 @@ var ( // DoGetAggregationService defines the RPC call function for // the GetAggregationService from aggregator micro service func DoGetAggregationService(ctx context.Context, req aggregatorproto.AggregatorRequest) (*aggregatorproto.AggregatorResponse, error) { - ctx = common.CreateMetadata(ctx) - conn, err := ClientFunc(services.Aggregator) + ctx, conn, err := getConnection(ctx, services.Aggregator) if err != nil { - return nil, fmt.Errorf("Failed to create client connection: %v", err) + return nil, err } aggregator := NewAggregatorClientFunc(conn) @@ -51,10 +49,9 @@ func DoGetAggregationService(ctx context.Context, req aggregatorproto.Aggregator // DoResetRequest defines the RPC call function for // the Reset from aggregator micro service func DoResetRequest(ctx context.Context, req aggregatorproto.AggregatorRequest) (*aggregatorproto.AggregatorResponse, error) { - ctx = common.CreateMetadata(ctx) - conn, err := ClientFunc(services.Aggregator) + ctx, conn, err := getConnection(ctx, services.Aggregator) if err != nil { - return nil, fmt.Errorf("Failed to create client connection: %v", err) + return nil, err } aggregator := NewAggregatorClientFunc(conn) @@ -69,10 +66,9 @@ func DoResetRequest(ctx context.Context, req aggregatorproto.AggregatorRequest) // DoSetDefaultBootOrderRequest defines the RPC call function for // the SetDefaultBootOrder from aggregator micro service func DoSetDefaultBootOrderRequest(ctx context.Context, req aggregatorproto.AggregatorRequest) (*aggregatorproto.AggregatorResponse, error) { - ctx = common.CreateMetadata(ctx) - conn, err := ClientFunc(services.Aggregator) + ctx, conn, err := getConnection(ctx, services.Aggregator) if err != nil { - return nil, fmt.Errorf("Failed to create client connection: %v", err) + return nil, err } aggregator := NewAggregatorClientFunc(conn) @@ -88,10 +84,9 @@ func DoSetDefaultBootOrderRequest(ctx context.Context, req aggregatorproto.Aggre // DoAddAggregationSource defines the RPC call function for // the AddAggregationSource from aggregator micro service func DoAddAggregationSource(ctx context.Context, req aggregatorproto.AggregatorRequest) (*aggregatorproto.AggregatorResponse, error) { - ctx = common.CreateMetadata(ctx) - conn, err := ClientFunc(services.Aggregator) + ctx, conn, err := getConnection(ctx, services.Aggregator) if err != nil { - return nil, fmt.Errorf("Failed to create client connection: %v", err) + return nil, err } aggregator := NewAggregatorClientFunc(conn) @@ -107,10 +102,9 @@ func DoAddAggregationSource(ctx context.Context, req aggregatorproto.AggregatorR // DoGetAllAggregationSource defines the RPC call function for // the GetAllAggregationSource from aggregator micro service func DoGetAllAggregationSource(ctx context.Context, req aggregatorproto.AggregatorRequest) (*aggregatorproto.AggregatorResponse, error) { - ctx = common.CreateMetadata(ctx) - conn, err := ClientFunc(services.Aggregator) + ctx, conn, err := getConnection(ctx, services.Aggregator) if err != nil { - return nil, fmt.Errorf("Failed to create client connection: %v", err) + return nil, err } aggregator := NewAggregatorClientFunc(conn) @@ -126,10 +120,9 @@ func DoGetAllAggregationSource(ctx context.Context, req aggregatorproto.Aggregat // DoGetAggregationSource defines the RPC call function for // the GetAggregationSource from aggregator micro service func DoGetAggregationSource(ctx context.Context, req aggregatorproto.AggregatorRequest) (*aggregatorproto.AggregatorResponse, error) { - ctx = common.CreateMetadata(ctx) - conn, err := ClientFunc(services.Aggregator) + ctx, conn, err := getConnection(ctx, services.Aggregator) if err != nil { - return nil, fmt.Errorf("Failed to create client connection: %v", err) + return nil, err } aggregator := NewAggregatorClientFunc(conn) @@ -145,10 +138,9 @@ func DoGetAggregationSource(ctx context.Context, req aggregatorproto.AggregatorR // DoUpdateAggregationSource defines the RPC call function for // the UpdateAggregationSource from aggregator micro service func DoUpdateAggregationSource(ctx context.Context, req aggregatorproto.AggregatorRequest) (*aggregatorproto.AggregatorResponse, error) { - ctx = common.CreateMetadata(ctx) - conn, err := ClientFunc(services.Aggregator) + ctx, conn, err := getConnection(ctx, services.Aggregator) if err != nil { - return nil, fmt.Errorf("Failed to create client connection: %v", err) + return nil, err } aggregator := NewAggregatorClientFunc(conn) @@ -164,10 +156,9 @@ func DoUpdateAggregationSource(ctx context.Context, req aggregatorproto.Aggregat // DoDeleteAggregationSource defines the RPC call function for // the DeleteAggregationSource from aggregator micro service func DoDeleteAggregationSource(ctx context.Context, req aggregatorproto.AggregatorRequest) (*aggregatorproto.AggregatorResponse, error) { - ctx = common.CreateMetadata(ctx) - conn, err := ClientFunc(services.Aggregator) + ctx, conn, err := getConnection(ctx, services.Aggregator) if err != nil { - return nil, fmt.Errorf("Failed to create client connection: %v", err) + return nil, err } aggregator := NewAggregatorClientFunc(conn) @@ -183,10 +174,9 @@ func DoDeleteAggregationSource(ctx context.Context, req aggregatorproto.Aggregat // DoCreateAggregate defines the RPC call function for // the CreateAggregate from aggregator micro service func DoCreateAggregate(ctx context.Context, req aggregatorproto.AggregatorRequest) (*aggregatorproto.AggregatorResponse, error) { - ctx = common.CreateMetadata(ctx) - conn, err := ClientFunc(services.Aggregator) + ctx, conn, err := getConnection(ctx, services.Aggregator) if err != nil { - return nil, fmt.Errorf("Failed to create client connection: %v", err) + return nil, err } aggregator := NewAggregatorClientFunc(conn) @@ -202,10 +192,9 @@ func DoCreateAggregate(ctx context.Context, req aggregatorproto.AggregatorReques // DoGetAggregateCollection defines the RPC call function for // the get aggregate collections from aggregator micro service func DoGetAggregateCollection(ctx context.Context, req aggregatorproto.AggregatorRequest) (*aggregatorproto.AggregatorResponse, error) { - ctx = common.CreateMetadata(ctx) - conn, err := ClientFunc(services.Aggregator) + ctx, conn, err := getConnection(ctx, services.Aggregator) if err != nil { - return nil, fmt.Errorf("Failed to create client connection: %v", err) + return nil, err } aggregator := NewAggregatorClientFunc(conn) @@ -221,10 +210,9 @@ func DoGetAggregateCollection(ctx context.Context, req aggregatorproto.Aggregato // DoGeteAggregate defines the RPC call function for // the get aggregate from aggregator micro service func DoGeteAggregate(ctx context.Context, req aggregatorproto.AggregatorRequest) (*aggregatorproto.AggregatorResponse, error) { - ctx = common.CreateMetadata(ctx) - conn, err := ClientFunc(services.Aggregator) + ctx, conn, err := getConnection(ctx, services.Aggregator) if err != nil { - return nil, fmt.Errorf("Failed to create client connection: %v", err) + return nil, err } aggregator := NewAggregatorClientFunc(conn) @@ -240,10 +228,9 @@ func DoGeteAggregate(ctx context.Context, req aggregatorproto.AggregatorRequest) // DoDeleteAggregate defines the RPC call function for // the delete aggregate from aggregator micro service func DoDeleteAggregate(ctx context.Context, req aggregatorproto.AggregatorRequest) (*aggregatorproto.AggregatorResponse, error) { - ctx = common.CreateMetadata(ctx) - conn, err := ClientFunc(services.Aggregator) + ctx, conn, err := getConnection(ctx, services.Aggregator) if err != nil { - return nil, fmt.Errorf("Failed to create client connection: %v", err) + return nil, err } aggregator := NewAggregatorClientFunc(conn) @@ -259,10 +246,9 @@ func DoDeleteAggregate(ctx context.Context, req aggregatorproto.AggregatorReques // DoAddElementsToAggregate defines the RPC call function for // the add elements to an aggregate from aggregator micro service func DoAddElementsToAggregate(ctx context.Context, req aggregatorproto.AggregatorRequest) (*aggregatorproto.AggregatorResponse, error) { - ctx = common.CreateMetadata(ctx) - conn, err := ClientFunc(services.Aggregator) + ctx, conn, err := getConnection(ctx, services.Aggregator) if err != nil { - return nil, fmt.Errorf("Failed to create client connection: %v", err) + return nil, err } aggregator := NewAggregatorClientFunc(conn) @@ -278,10 +264,9 @@ func DoAddElementsToAggregate(ctx context.Context, req aggregatorproto.Aggregato // DoRemoveElementsFromAggregate defines the RPC call function for // the remove elements from an aggregate from aggregator micro service func DoRemoveElementsFromAggregate(ctx context.Context, req aggregatorproto.AggregatorRequest) (*aggregatorproto.AggregatorResponse, error) { - ctx = common.CreateMetadata(ctx) - conn, err := ClientFunc(services.Aggregator) + ctx, conn, err := getConnection(ctx, services.Aggregator) if err != nil { - return nil, fmt.Errorf("Failed to create client connection: %v", err) + return nil, err } aggregator := NewAggregatorClientFunc(conn) @@ -297,10 +282,9 @@ func DoRemoveElementsFromAggregate(ctx context.Context, req aggregatorproto.Aggr // DoResetAggregateElements defines the RPC call function for // the reset elements of an aggregate from aggregator micro service func DoResetAggregateElements(ctx context.Context, req aggregatorproto.AggregatorRequest) (*aggregatorproto.AggregatorResponse, error) { - ctx = common.CreateMetadata(ctx) - conn, err := ClientFunc(services.Aggregator) + ctx, conn, err := getConnection(ctx, services.Aggregator) if err != nil { - return nil, fmt.Errorf("Failed to create client connection: %v", err) + return nil, err } aggregator := NewAggregatorClientFunc(conn) @@ -316,10 +300,9 @@ func DoResetAggregateElements(ctx context.Context, req aggregatorproto.Aggregato // DoSetDefaultBootOrderAggregateElements defines the RPC call function for // the set default boot order elements of an aggregate from aggregator micro service func DoSetDefaultBootOrderAggregateElements(ctx context.Context, req aggregatorproto.AggregatorRequest) (*aggregatorproto.AggregatorResponse, error) { - ctx = common.CreateMetadata(ctx) - conn, err := ClientFunc(services.Aggregator) + ctx, conn, err := getConnection(ctx, services.Aggregator) if err != nil { - return nil, fmt.Errorf("Failed to create client connection: %v", err) + return nil, err } aggregator := NewAggregatorClientFunc(conn) @@ -335,10 +318,9 @@ func DoSetDefaultBootOrderAggregateElements(ctx context.Context, req aggregatorp // DoGetAllConnectionMethods defines the RPC call function for // the get connection method collection from aggregator micro service func DoGetAllConnectionMethods(ctx context.Context, req aggregatorproto.AggregatorRequest) (*aggregatorproto.AggregatorResponse, error) { - ctx = common.CreateMetadata(ctx) - conn, err := ClientFunc(services.Aggregator) + ctx, conn, err := getConnection(ctx, services.Aggregator) if err != nil { - return nil, fmt.Errorf("Failed to create client connection: %v", err) + return nil, err } aggregator := NewAggregatorClientFunc(conn) @@ -354,10 +336,9 @@ func DoGetAllConnectionMethods(ctx context.Context, req aggregatorproto.Aggregat // DoGetConnectionMethod defines the RPC call function for // the get on connection method from aggregator micro service func DoGetConnectionMethod(ctx context.Context, req aggregatorproto.AggregatorRequest) (*aggregatorproto.AggregatorResponse, error) { - ctx = common.CreateMetadata(ctx) - conn, err := ClientFunc(services.Aggregator) + ctx, conn, err := getConnection(ctx, services.Aggregator) if err != nil { - return nil, fmt.Errorf("Failed to create client connection: %v", err) + return nil, err } aggregator := NewAggregatorClientFunc(conn) @@ -373,10 +354,9 @@ func DoGetConnectionMethod(ctx context.Context, req aggregatorproto.AggregatorRe // DoGetResetActionInfoService defines the RPC call function for // the GetResetActionInfoService from aggregator micro service func DoGetResetActionInfoService(ctx context.Context, req aggregatorproto.AggregatorRequest) (*aggregatorproto.AggregatorResponse, error) { - ctx = common.CreateMetadata(ctx) - conn, err := ClientFunc(services.Aggregator) + ctx, conn, err := getConnection(ctx, services.Aggregator) if err != nil { - return nil, fmt.Errorf("Failed to create client connection: %v", err) + return nil, err } aggregator := NewAggregatorClientFunc(conn) @@ -392,10 +372,9 @@ func DoGetResetActionInfoService(ctx context.Context, req aggregatorproto.Aggreg // DoGetSetDefaultBootOrderActionInfo defines the RPC call function for // the GetSetDefaultBootOrderActionInfo from aggregator micro service func DoGetSetDefaultBootOrderActionInfo(ctx context.Context, req aggregatorproto.AggregatorRequest) (*aggregatorproto.AggregatorResponse, error) { - ctx = common.CreateMetadata(ctx) - conn, err := ClientFunc(services.Aggregator) + ctx, conn, err := getConnection(ctx, services.Aggregator) if err != nil { - return nil, fmt.Errorf("Failed to create client connection: %v", err) + return nil, err } aggregator := NewAggregatorClientFunc(conn) diff --git a/svc-api/rpc/chassis.go b/svc-api/rpc/chassis.go index c742b2c1f..cf4baa35c 100644 --- a/svc-api/rpc/chassis.go +++ b/svc-api/rpc/chassis.go @@ -20,7 +20,6 @@ import ( "context" "fmt" - "github.com/ODIM-Project/ODIM/lib-utilities/common" chassisproto "github.com/ODIM-Project/ODIM/lib-utilities/proto/chassis" "github.com/ODIM-Project/ODIM/lib-utilities/services" ) @@ -32,10 +31,9 @@ var ( // GetChassisCollection will do the rpc call to collect all chassis func GetChassisCollection(ctx context.Context, req chassisproto.GetChassisRequest) (*chassisproto.GetChassisResponse, error) { - ctx = common.CreateMetadata(ctx) - conn, err := ClientFunc(services.Systems) + ctx, conn, err := getConnection(ctx, services.Systems) if err != nil { - return nil, fmt.Errorf("Failed to create client connection: %v", err) + return nil, err } asService := NewChassisClientFunc(conn) @@ -49,10 +47,9 @@ func GetChassisCollection(ctx context.Context, req chassisproto.GetChassisReques // GetChassisResource will do the rpc call to collect Chassis Resource func GetChassisResource(ctx context.Context, req chassisproto.GetChassisRequest) (*chassisproto.GetChassisResponse, error) { - ctx = common.CreateMetadata(ctx) - conn, err := ClientFunc(services.Systems) + ctx, conn, err := getConnection(ctx, services.Systems) if err != nil { - return nil, fmt.Errorf("Failed to create client connection: %v", err) + return nil, err } asService := NewChassisClientFunc(conn) @@ -66,10 +63,9 @@ func GetChassisResource(ctx context.Context, req chassisproto.GetChassisRequest) // GetChassis will do the rpc call to System Resource func GetChassis(ctx context.Context, req chassisproto.GetChassisRequest) (*chassisproto.GetChassisResponse, error) { - ctx = common.CreateMetadata(ctx) - conn, err := ClientFunc(services.Systems) + ctx, conn, err := getConnection(ctx, services.Systems) if err != nil { - return nil, fmt.Errorf("Failed to create client connection: %v", err) + return nil, err } asService := NewChassisClientFunc(conn) @@ -83,10 +79,9 @@ func GetChassis(ctx context.Context, req chassisproto.GetChassisRequest) (*chass // CreateChassis will do the rpc call to create a Chassis func CreateChassis(ctx context.Context, req chassisproto.CreateChassisRequest) (*chassisproto.GetChassisResponse, error) { - ctx = common.CreateMetadata(ctx) - conn, err := ClientFunc(services.Systems) + ctx, conn, err := getConnection(ctx, services.Systems) if err != nil { - return nil, fmt.Errorf("Failed to create client connection: %v", err) + return nil, err } service := NewChassisClientFunc(conn) @@ -100,10 +95,9 @@ func CreateChassis(ctx context.Context, req chassisproto.CreateChassisRequest) ( // DeleteChassis will do the rpc call to delete a chassis func DeleteChassis(ctx context.Context, req chassisproto.DeleteChassisRequest) (*chassisproto.GetChassisResponse, error) { - ctx = common.CreateMetadata(ctx) - conn, err := ClientFunc(services.Systems) + ctx, conn, err := getConnection(ctx, services.Systems) if err != nil { - return nil, fmt.Errorf("Failed to create client connection: %v", err) + return nil, err } service := NewChassisClientFunc(conn) @@ -117,10 +111,9 @@ func DeleteChassis(ctx context.Context, req chassisproto.DeleteChassisRequest) ( // UpdateChassis will do the rpc call to update a chassis func UpdateChassis(ctx context.Context, req chassisproto.UpdateChassisRequest) (*chassisproto.GetChassisResponse, error) { - ctx = common.CreateMetadata(ctx) - conn, err := ClientFunc(services.Systems) + ctx, conn, err := getConnection(ctx, services.Systems) if err != nil { - return nil, fmt.Errorf("Failed to create client connection: %v", err) + return nil, err } service := NewChassisClientFunc(conn) diff --git a/svc-api/rpc/events.go b/svc-api/rpc/events.go index 38c651634..6e3b1d7b4 100644 --- a/svc-api/rpc/events.go +++ b/svc-api/rpc/events.go @@ -19,7 +19,6 @@ import ( "context" "fmt" - "github.com/ODIM-Project/ODIM/lib-utilities/common" eventsproto "github.com/ODIM-Project/ODIM/lib-utilities/proto/events" "github.com/ODIM-Project/ODIM/lib-utilities/services" ) @@ -32,10 +31,9 @@ var ( // DoGetEventService defines the RPC call function for // the GetEventService from events micro service func DoGetEventService(ctx context.Context, req eventsproto.EventSubRequest) (*eventsproto.EventSubResponse, error) { - ctx = common.CreateMetadata(ctx) - conn, err := ClientFunc(services.Events) + ctx, conn, err := getConnection(ctx, services.Events) if err != nil { - return nil, fmt.Errorf("Failed to create client connection: %v", err) + return nil, err } events := NewEventsClientFunc(conn) @@ -51,10 +49,9 @@ func DoGetEventService(ctx context.Context, req eventsproto.EventSubRequest) (*e // DoCreateEventSubscription defines the RPC call function for // the CreateEventSubscription from events micro service func DoCreateEventSubscription(ctx context.Context, req eventsproto.EventSubRequest) (*eventsproto.EventSubResponse, error) { - ctx = common.CreateMetadata(ctx) - conn, err := ClientFunc(services.Events) + ctx, conn, err := getConnection(ctx, services.Events) if err != nil { - return nil, fmt.Errorf("Failed to create client connection: %v", err) + return nil, err } events := NewEventsClientFunc(conn) @@ -70,10 +67,9 @@ func DoCreateEventSubscription(ctx context.Context, req eventsproto.EventSubRequ // DoSubmitTestEvent defines the RPC call function for // the SubmitTestEvent from events micro service func DoSubmitTestEvent(ctx context.Context, req eventsproto.EventSubRequest) (*eventsproto.EventSubResponse, error) { - ctx = common.CreateMetadata(ctx) - conn, err := ClientFunc(services.Events) + ctx, conn, err := getConnection(ctx, services.Events) if err != nil { - return nil, fmt.Errorf("Failed to create client connection: %v", err) + return nil, err } events := NewEventsClientFunc(conn) @@ -89,10 +85,9 @@ func DoSubmitTestEvent(ctx context.Context, req eventsproto.EventSubRequest) (*e // DoGetEventSubscription defines the RPC call function for // the DoGetEventSubscription from events micro service func DoGetEventSubscription(ctx context.Context, req eventsproto.EventRequest) (*eventsproto.EventSubResponse, error) { - ctx = common.CreateMetadata(ctx) - conn, err := ClientFunc(services.Events) + ctx, conn, err := getConnection(ctx, services.Events) if err != nil { - return nil, fmt.Errorf("Failed to create client connection: %v", err) + return nil, err } events := NewEventsClientFunc(conn) @@ -108,10 +103,9 @@ func DoGetEventSubscription(ctx context.Context, req eventsproto.EventRequest) ( // DoDeleteEventSubscription defines the RPC call function for // the DoDeleteEventSubscription from events micro service func DoDeleteEventSubscription(ctx context.Context, req eventsproto.EventRequest) (*eventsproto.EventSubResponse, error) { - ctx = common.CreateMetadata(ctx) - conn, err := ClientFunc(services.Events) + ctx, conn, err := getConnection(ctx, services.Events) if err != nil { - return nil, fmt.Errorf("Failed to create client connection: %v", err) + return nil, err } events := NewEventsClientFunc(conn) @@ -127,10 +121,9 @@ func DoDeleteEventSubscription(ctx context.Context, req eventsproto.EventRequest // DoGetEventSubscriptionsCollection defines the RPC call function for // the DoGetEventSubscription from events micro service func DoGetEventSubscriptionsCollection(ctx context.Context, req eventsproto.EventRequest) (*eventsproto.EventSubResponse, error) { - ctx = common.CreateMetadata(ctx) - conn, err := ClientFunc(services.Events) + ctx, conn, err := getConnection(ctx, services.Events) if err != nil { - return nil, fmt.Errorf("Failed to create client connection: %v", err) + return nil, err } events := NewEventsClientFunc(conn) diff --git a/svc-api/rpc/fabrics.go b/svc-api/rpc/fabrics.go index 9f899d589..0e54497cc 100644 --- a/svc-api/rpc/fabrics.go +++ b/svc-api/rpc/fabrics.go @@ -19,7 +19,6 @@ import ( "context" "fmt" - "github.com/ODIM-Project/ODIM/lib-utilities/common" fabricsproto "github.com/ODIM-Project/ODIM/lib-utilities/proto/fabrics" "github.com/ODIM-Project/ODIM/lib-utilities/services" ) @@ -32,10 +31,9 @@ var ( // GetFabricResource defines the RPC call function for // the GetFabricResource from fabrics micro service func GetFabricResource(ctx context.Context, req fabricsproto.FabricRequest) (*fabricsproto.FabricResponse, error) { - ctx = common.CreateMetadata(ctx) - conn, err := ClientFunc(services.Fabrics) + ctx, conn, err := getConnection(ctx, services.Fabrics) if err != nil { - return nil, fmt.Errorf("Failed to create client connection: %v", err) + return nil, err } fab := NewFabricsClientFunc(conn) @@ -50,10 +48,9 @@ func GetFabricResource(ctx context.Context, req fabricsproto.FabricRequest) (*fa // UpdateFabricResource defines the RPC call function for creating/updating // the Fabric Resource such as Endpoints, Zones from fabrics micro service func UpdateFabricResource(ctx context.Context, req fabricsproto.FabricRequest) (*fabricsproto.FabricResponse, error) { - ctx = common.CreateMetadata(ctx) - conn, err := ClientFunc(services.Fabrics) + ctx, conn, err := getConnection(ctx, services.Fabrics) if err != nil { - return nil, fmt.Errorf("Failed to create client connection: %v", err) + return nil, err } fab := NewFabricsClientFunc(conn) @@ -69,10 +66,9 @@ func UpdateFabricResource(ctx context.Context, req fabricsproto.FabricRequest) ( // DeleteFabricResource defines the RPC call function for // the DeleteFabricResource from fabrics micro service func DeleteFabricResource(ctx context.Context, req fabricsproto.FabricRequest) (*fabricsproto.FabricResponse, error) { - ctx = common.CreateMetadata(ctx) - conn, err := ClientFunc(services.Fabrics) + ctx, conn, err := getConnection(ctx, services.Fabrics) if err != nil { - return nil, fmt.Errorf("Failed to create client connection: %v", err) + return nil, err } fab := NewFabricsClientFunc(conn) diff --git a/svc-api/rpc/licenses.go b/svc-api/rpc/licenses.go index 1aa6f0455..d8682cb96 100644 --- a/svc-api/rpc/licenses.go +++ b/svc-api/rpc/licenses.go @@ -18,17 +18,15 @@ import ( "context" "fmt" - "github.com/ODIM-Project/ODIM/lib-utilities/common" licenseproto "github.com/ODIM-Project/ODIM/lib-utilities/proto/licenses" "github.com/ODIM-Project/ODIM/lib-utilities/services" ) // GetLicenseService will do the rpc call to get License Service Information func GetLicenseService(ctx context.Context, req licenseproto.GetLicenseServiceRequest) (*licenseproto.GetLicenseResponse, error) { - ctx = common.CreateMetadata(ctx) - conn, err := services.ODIMService.Client(services.Licenses) + ctx, conn, err := getConnection(ctx, services.Licenses) if err != nil { - return nil, fmt.Errorf("Failed to create client connection: %v", err) + return nil, err } defer conn.Close() licenseService := licenseproto.NewLicensesClient(conn) @@ -41,10 +39,9 @@ func GetLicenseService(ctx context.Context, req licenseproto.GetLicenseServiceRe // GetLicenseCollection will do the rpc call to get License Service Information func GetLicenseCollection(ctx context.Context, req licenseproto.GetLicenseRequest) (*licenseproto.GetLicenseResponse, error) { - ctx = common.CreateMetadata(ctx) - conn, err := services.ODIMService.Client(services.Licenses) + ctx, conn, err := getConnection(ctx, services.Licenses) if err != nil { - return nil, fmt.Errorf("Failed to create client connection: %v", err) + return nil, err } defer conn.Close() licenseService := licenseproto.NewLicensesClient(conn) @@ -57,10 +54,9 @@ func GetLicenseCollection(ctx context.Context, req licenseproto.GetLicenseReques // GetLicenseResource will do the rpc call to get License Service Information func GetLicenseResource(ctx context.Context, req licenseproto.GetLicenseResourceRequest) (*licenseproto.GetLicenseResponse, error) { - ctx = common.CreateMetadata(ctx) - conn, err := services.ODIMService.Client(services.Licenses) + ctx, conn, err := getConnection(ctx, services.Licenses) if err != nil { - return nil, fmt.Errorf("Failed to create client connection: %v", err) + return nil, err } defer conn.Close() licenseService := licenseproto.NewLicensesClient(conn) @@ -73,10 +69,9 @@ func GetLicenseResource(ctx context.Context, req licenseproto.GetLicenseResource // InstallLicenseService will do the rpc call to install License func InstallLicenseService(ctx context.Context, req licenseproto.InstallLicenseRequest) (*licenseproto.GetLicenseResponse, error) { - ctx = common.CreateMetadata(ctx) - conn, err := services.ODIMService.Client(services.Licenses) + ctx, conn, err := getConnection(ctx, services.Licenses) if err != nil { - return nil, fmt.Errorf("Failed to create client connection: %v", err) + return nil, err } defer conn.Close() licenseService := licenseproto.NewLicensesClient(conn) diff --git a/svc-api/rpc/managers.go b/svc-api/rpc/managers.go index a027773a2..9100d6806 100644 --- a/svc-api/rpc/managers.go +++ b/svc-api/rpc/managers.go @@ -19,7 +19,6 @@ import ( "context" "fmt" - "github.com/ODIM-Project/ODIM/lib-utilities/common" managersproto "github.com/ODIM-Project/ODIM/lib-utilities/proto/managers" "github.com/ODIM-Project/ODIM/lib-utilities/services" ) @@ -31,10 +30,9 @@ var ( // GetManagersCollection will do the rpc call to collect Managers func GetManagersCollection(ctx context.Context, req managersproto.ManagerRequest) (*managersproto.ManagerResponse, error) { - ctx = common.CreateMetadata(ctx) - conn, err := ClientFunc(services.Managers) + ctx, conn, err := getConnection(ctx, services.Managers) if err != nil { - return nil, fmt.Errorf("Failed to create client connection: %v", err) + return nil, err } asService := NewManagersClientFunc(conn) @@ -48,10 +46,9 @@ func GetManagersCollection(ctx context.Context, req managersproto.ManagerRequest // GetManagers will do the rpc calls for the svc-managers func GetManagers(ctx context.Context, req managersproto.ManagerRequest) (*managersproto.ManagerResponse, error) { - ctx = common.CreateMetadata(ctx) - conn, err := ClientFunc(services.Managers) + ctx, conn, err := getConnection(ctx, services.Managers) if err != nil { - return nil, fmt.Errorf("Failed to create client connection: %v", err) + return nil, err } asService := NewManagersClientFunc(conn) @@ -65,10 +62,9 @@ func GetManagers(ctx context.Context, req managersproto.ManagerRequest) (*manage // GetManagersResource will do the rpc calls for the svc-managers func GetManagersResource(ctx context.Context, req managersproto.ManagerRequest) (*managersproto.ManagerResponse, error) { - ctx = common.CreateMetadata(ctx) - conn, err := ClientFunc(services.Managers) + ctx, conn, err := getConnection(ctx, services.Managers) if err != nil { - return nil, fmt.Errorf("Failed to create client connection: %v", err) + return nil, err } asService := NewManagersClientFunc(conn) @@ -82,10 +78,9 @@ func GetManagersResource(ctx context.Context, req managersproto.ManagerRequest) // VirtualMediaInsert will do the rpc calls for the svc-managers func VirtualMediaInsert(ctx context.Context, req managersproto.ManagerRequest) (*managersproto.ManagerResponse, error) { - ctx = common.CreateMetadata(ctx) - conn, err := ClientFunc(services.Managers) + ctx, conn, err := getConnection(ctx, services.Managers) if err != nil { - return nil, fmt.Errorf("Failed to create client connection: %v", err) + return nil, err } asService := NewManagersClientFunc(conn) @@ -99,10 +94,9 @@ func VirtualMediaInsert(ctx context.Context, req managersproto.ManagerRequest) ( // VirtualMediaEject will do the rpc calls for the svc-managers func VirtualMediaEject(ctx context.Context, req managersproto.ManagerRequest) (*managersproto.ManagerResponse, error) { - ctx = common.CreateMetadata(ctx) - conn, err := ClientFunc(services.Managers) + ctx, conn, err := getConnection(ctx, services.Managers) if err != nil { - return nil, fmt.Errorf("Failed to create client connection: %v", err) + return nil, err } asService := NewManagersClientFunc(conn) @@ -116,10 +110,9 @@ func VirtualMediaEject(ctx context.Context, req managersproto.ManagerRequest) (* // GetRemoteAccountService will do the rpc call to collect BMC accounts func GetRemoteAccountService(ctx context.Context, req managersproto.ManagerRequest) (*managersproto.ManagerResponse, error) { - ctx = common.CreateMetadata(ctx) - conn, err := ClientFunc(services.Managers) + ctx, conn, err := getConnection(ctx, services.Managers) if err != nil { - return nil, fmt.Errorf("Failed to create client connection: %v", err) + return nil, err } mService := NewManagersClientFunc(conn) @@ -133,10 +126,9 @@ func GetRemoteAccountService(ctx context.Context, req managersproto.ManagerReque // CreateRemoteAccountService will do the rpc call to create a new BMC account func CreateRemoteAccountService(ctx context.Context, req managersproto.ManagerRequest) (*managersproto.ManagerResponse, error) { - ctx = common.CreateMetadata(ctx) - conn, err := ClientFunc(services.Managers) + ctx, conn, err := getConnection(ctx, services.Managers) if err != nil { - return nil, fmt.Errorf("Failed to create client connection: %v", err) + return nil, err } mService := NewManagersClientFunc(conn) @@ -150,10 +142,9 @@ func CreateRemoteAccountService(ctx context.Context, req managersproto.ManagerRe // UpdateRemoteAccountService will do rpc call to update BMC account func UpdateRemoteAccountService(ctx context.Context, req managersproto.ManagerRequest) (*managersproto.ManagerResponse, error) { - ctx = common.CreateMetadata(ctx) - conn, err := ClientFunc(services.Managers) + ctx, conn, err := getConnection(ctx, services.Managers) if err != nil { - return nil, fmt.Errorf("Failed to create client connection: %v", err) + return nil, err } mService := NewManagersClientFunc(conn) @@ -167,10 +158,9 @@ func UpdateRemoteAccountService(ctx context.Context, req managersproto.ManagerRe // DeleteRemoteAccountService will do the rpc call to delete an existing BMC account func DeleteRemoteAccountService(ctx context.Context, req managersproto.ManagerRequest) (*managersproto.ManagerResponse, error) { - ctx = common.CreateMetadata(ctx) - conn, err := ClientFunc(services.Managers) + ctx, conn, err := getConnection(ctx, services.Managers) if err != nil { - return nil, fmt.Errorf("Failed to create client connection: %v", err) + return nil, err } mService := NewManagersClientFunc(conn) diff --git a/svc-api/rpc/role.go b/svc-api/rpc/role.go index 955e25e54..a70c07be5 100644 --- a/svc-api/rpc/role.go +++ b/svc-api/rpc/role.go @@ -19,7 +19,6 @@ import ( "context" "fmt" - "github.com/ODIM-Project/ODIM/lib-utilities/common" roleproto "github.com/ODIM-Project/ODIM/lib-utilities/proto/role" "github.com/ODIM-Project/ODIM/lib-utilities/services" ) @@ -32,10 +31,9 @@ var ( // GetRole defines the RPC call function for // the GetRole from account-session micro service func GetRole(ctx context.Context, req roleproto.GetRoleRequest) (*roleproto.RoleResponse, error) { - ctx = common.CreateMetadata(ctx) - conn, err := ClientFunc(services.AccountSession) + ctx, conn, err := getConnection(ctx, services.AccountSession) if err != nil { - return nil, fmt.Errorf("Failed to create client connection: %v", err) + return nil, err } asService := NewRolesClientFunc(conn) @@ -50,10 +48,9 @@ func GetRole(ctx context.Context, req roleproto.GetRoleRequest) (*roleproto.Role // GetAllRoles defines the RPC call function for // the GetAllRoles from account-session micro service func GetAllRoles(ctx context.Context, req roleproto.GetRoleRequest) (*roleproto.RoleResponse, error) { - ctx = common.CreateMetadata(ctx) - conn, err := ClientFunc(services.AccountSession) + ctx, conn, err := getConnection(ctx, services.AccountSession) if err != nil { - return nil, fmt.Errorf("Failed to create client connection: %v", err) + return nil, err } asService := NewRolesClientFunc(conn) @@ -68,10 +65,9 @@ func GetAllRoles(ctx context.Context, req roleproto.GetRoleRequest) (*roleproto. // UpdateRole defines the RPC call function for // the UpdateRole from account-session micro service func UpdateRole(ctx context.Context, req roleproto.UpdateRoleRequest) (*roleproto.RoleResponse, error) { - ctx = common.CreateMetadata(ctx) - conn, err := ClientFunc(services.AccountSession) + ctx, conn, err := getConnection(ctx, services.AccountSession) if err != nil { - return nil, fmt.Errorf("Failed to create client connection: %v", err) + return nil, err } asService := NewRolesClientFunc(conn) @@ -85,10 +81,9 @@ func UpdateRole(ctx context.Context, req roleproto.UpdateRoleRequest) (*roleprot // DeleteRole defines the RPC call function for the DeleteRole from account-session microservice func DeleteRole(ctx context.Context, req roleproto.DeleteRoleRequest) (*roleproto.RoleResponse, error) { - ctx = common.CreateMetadata(ctx) - conn, err := ClientFunc(services.AccountSession) + ctx, conn, err := getConnection(ctx, services.AccountSession) if err != nil { - return nil, fmt.Errorf("Failed to create client connection: %v", err) + return nil, err } asService := NewRolesClientFunc(conn) diff --git a/svc-api/rpc/sessions.go b/svc-api/rpc/sessions.go index d938b4e1d..1f2657da1 100644 --- a/svc-api/rpc/sessions.go +++ b/svc-api/rpc/sessions.go @@ -66,10 +66,9 @@ func DoSessionCreationRequest(ctx context.Context, req sessionproto.SessionCreat // DeleteSessionRequest will do the rpc call to delete session func DeleteSessionRequest(ctx context.Context, sessionID, sessionToken string) (*sessionproto.SessionResponse, error) { - ctx = common.CreateMetadata(ctx) - conn, err := ClientFunc(services.AccountSession) + ctx, conn, err := getConnection(ctx, services.AccountSession) if err != nil { - return nil, fmt.Errorf("Failed to create client connection: %v", err) + return nil, err } asService := NewSessionClientFunc(conn) @@ -88,10 +87,9 @@ func DeleteSessionRequest(ctx context.Context, sessionID, sessionToken string) ( // GetSessionRequest will do the rpc call to get session func GetSessionRequest(ctx context.Context, sessionID, sessionToken string) (*sessionproto.SessionResponse, error) { - ctx = common.CreateMetadata(ctx) - conn, err := ClientFunc(services.AccountSession) + ctx, conn, err := getConnection(ctx, services.AccountSession) if err != nil { - return nil, fmt.Errorf("Failed to create client connection: %v", err) + return nil, err } asService := NewSessionClientFunc(conn) @@ -110,10 +108,9 @@ func GetSessionRequest(ctx context.Context, sessionID, sessionToken string) (*se // GetAllActiveSessionRequest will do the rpc call to get session func GetAllActiveSessionRequest(ctx context.Context, sessionID, sessionToken string) (*sessionproto.SessionResponse, error) { - ctx = common.CreateMetadata(ctx) - conn, err := ClientFunc(services.AccountSession) + ctx, conn, err := getConnection(ctx, services.AccountSession) if err != nil { - return nil, fmt.Errorf("Failed to create client connection: %v", err) + return nil, err } asService := NewSessionClientFunc(conn) @@ -132,10 +129,9 @@ func GetAllActiveSessionRequest(ctx context.Context, sessionID, sessionToken str // GetSessionServiceRequest will do the rpc call to check session func GetSessionServiceRequest(ctx context.Context) (*sessionproto.SessionResponse, error) { - ctx = common.CreateMetadata(ctx) - conn, err := ClientFunc(services.AccountSession) + ctx, conn, err := getConnection(ctx, services.AccountSession) if err != nil { - return nil, fmt.Errorf("Failed to create client connection: %v", err) + return nil, err } asService := NewSessionClientFunc(conn) diff --git a/svc-api/rpc/system.go b/svc-api/rpc/system.go index f4e170f89..6add90f7b 100644 --- a/svc-api/rpc/system.go +++ b/svc-api/rpc/system.go @@ -19,7 +19,6 @@ import ( "context" "fmt" - "github.com/ODIM-Project/ODIM/lib-utilities/common" systemsproto "github.com/ODIM-Project/ODIM/lib-utilities/proto/systems" "github.com/ODIM-Project/ODIM/lib-utilities/services" ) @@ -31,10 +30,9 @@ var ( // GetSystemsCollection will do the rpc call to collect Systems from odimra func GetSystemsCollection(ctx context.Context, req systemsproto.GetSystemsRequest) (*systemsproto.SystemsResponse, error) { - ctx = common.CreateMetadata(ctx) - conn, err := ClientFunc(services.Systems) + ctx, conn, err := getConnection(ctx, services.Systems) if err != nil { - return nil, fmt.Errorf("Failed to create client connection: %v", err) + return nil, err } asService := NewSystemsClientFunc(conn) @@ -48,10 +46,9 @@ func GetSystemsCollection(ctx context.Context, req systemsproto.GetSystemsReques // GetSystemRequestRPC will do the rpc calls for the svc-systems func GetSystemRequestRPC(ctx context.Context, req systemsproto.GetSystemsRequest) (*systemsproto.SystemsResponse, error) { - ctx = common.CreateMetadata(ctx) - conn, err := ClientFunc(services.Systems) + ctx, conn, err := getConnection(ctx, services.Systems) if err != nil { - return nil, fmt.Errorf("Failed to create client connection: %v", err) + return nil, err } asService := NewSystemsClientFunc(conn) @@ -65,10 +62,9 @@ func GetSystemRequestRPC(ctx context.Context, req systemsproto.GetSystemsRequest // GetSystemResource will do the rpc call to collect System Resource func GetSystemResource(ctx context.Context, req systemsproto.GetSystemsRequest) (*systemsproto.SystemsResponse, error) { - ctx = common.CreateMetadata(ctx) - conn, err := ClientFunc(services.Systems) + ctx, conn, err := getConnection(ctx, services.Systems) if err != nil { - return nil, fmt.Errorf("Failed to create client connection: %v", err) + return nil, err } asService := NewSystemsClientFunc(conn) @@ -82,10 +78,9 @@ func GetSystemResource(ctx context.Context, req systemsproto.GetSystemsRequest) // ComputerSystemReset will do the rpc call to reset the computer system func ComputerSystemReset(ctx context.Context, req systemsproto.ComputerSystemResetRequest) (*systemsproto.SystemsResponse, error) { - ctx = common.CreateMetadata(ctx) - conn, err := ClientFunc(services.Systems) + ctx, conn, err := getConnection(ctx, services.Systems) if err != nil { - return nil, fmt.Errorf("Failed to create client connection: %v", err) + return nil, err } asService := NewSystemsClientFunc(conn) @@ -99,10 +94,9 @@ func ComputerSystemReset(ctx context.Context, req systemsproto.ComputerSystemRes // SetDefaultBootOrder will do the rpc call to set the default boot order of computer system func SetDefaultBootOrder(ctx context.Context, req systemsproto.DefaultBootOrderRequest) (*systemsproto.SystemsResponse, error) { - ctx = common.CreateMetadata(ctx) - conn, err := ClientFunc(services.Systems) + ctx, conn, err := getConnection(ctx, services.Systems) if err != nil { - return nil, fmt.Errorf("Failed to create client connection: %v", err) + return nil, err } asService := NewSystemsClientFunc(conn) @@ -116,10 +110,9 @@ func SetDefaultBootOrder(ctx context.Context, req systemsproto.DefaultBootOrderR // ChangeBiosSettings will do the rpc call to change bios settings func ChangeBiosSettings(ctx context.Context, req systemsproto.BiosSettingsRequest) (*systemsproto.SystemsResponse, error) { - ctx = common.CreateMetadata(ctx) - conn, err := ClientFunc(services.Systems) + ctx, conn, err := getConnection(ctx, services.Systems) if err != nil { - return nil, fmt.Errorf("Failed to create client connection: %v", err) + return nil, err } asService := NewSystemsClientFunc(conn) @@ -133,10 +126,9 @@ func ChangeBiosSettings(ctx context.Context, req systemsproto.BiosSettingsReques // ChangeBootOrderSettings will do the rpc call to change Boot Order settings func ChangeBootOrderSettings(ctx context.Context, req systemsproto.BootOrderSettingsRequest) (*systemsproto.SystemsResponse, error) { - ctx = common.CreateMetadata(ctx) - conn, err := ClientFunc(services.Systems) + ctx, conn, err := getConnection(ctx, services.Systems) if err != nil { - return nil, fmt.Errorf("Failed to create client connection: %v", err) + return nil, err } asService := NewSystemsClientFunc(conn) @@ -150,10 +142,9 @@ func ChangeBootOrderSettings(ctx context.Context, req systemsproto.BootOrderSett // CreateVolume will do the rpc call to create a volume under storage func CreateVolume(ctx context.Context, req systemsproto.VolumeRequest) (*systemsproto.SystemsResponse, error) { - ctx = common.CreateMetadata(ctx) - conn, err := ClientFunc(services.Systems) + ctx, conn, err := getConnection(ctx, services.Systems) if err != nil { - return nil, fmt.Errorf("Failed to create client connection: %v", err) + return nil, err } asService := NewSystemsClientFunc(conn) @@ -167,10 +158,9 @@ func CreateVolume(ctx context.Context, req systemsproto.VolumeRequest) (*systems // DeleteVolume will do the rpc call to DeleteVolume a volume under storage func DeleteVolume(ctx context.Context, req systemsproto.VolumeRequest) (*systemsproto.SystemsResponse, error) { - ctx = common.CreateMetadata(ctx) - conn, err := ClientFunc(services.Systems) + ctx, conn, err := getConnection(ctx, services.Systems) if err != nil { - return nil, fmt.Errorf("Failed to create client connection: %v", err) + return nil, err } asService := NewSystemsClientFunc(conn) @@ -184,10 +174,9 @@ func DeleteVolume(ctx context.Context, req systemsproto.VolumeRequest) (*systems // UpdateSecureBoot will do the rpc call to UpdateSecureBoot func UpdateSecureBoot(ctx context.Context, req systemsproto.SecureBootRequest) (*systemsproto.SystemsResponse, error) { - ctx = common.CreateMetadata(ctx) - conn, err := ClientFunc(services.Systems) + ctx, conn, err := getConnection(ctx, services.Systems) if err != nil { - return nil, fmt.Errorf("Failed to create client connection: %v", err) + return nil, err } asService := NewSystemsClientFunc(conn) @@ -201,10 +190,9 @@ func UpdateSecureBoot(ctx context.Context, req systemsproto.SecureBootRequest) ( // ResetSecureBoot will do the rpc call to ResetSecureBoot func ResetSecureBoot(ctx context.Context, req systemsproto.SecureBootRequest) (*systemsproto.SystemsResponse, error) { - ctx = common.CreateMetadata(ctx) - conn, err := ClientFunc(services.Systems) + ctx, conn, err := getConnection(ctx, services.Systems) if err != nil { - return nil, fmt.Errorf("Failed to create client connection: %v", err) + return nil, err } asService := NewSystemsClientFunc(conn) diff --git a/svc-api/rpc/task.go b/svc-api/rpc/task.go index 4ffa0603c..c7ce961fe 100644 --- a/svc-api/rpc/task.go +++ b/svc-api/rpc/task.go @@ -34,10 +34,9 @@ var ( // DeleteTaskRequest will do the rpc calls for the svc-task DeleteTask func DeleteTaskRequest(ctx context.Context, req *taskproto.GetTaskRequest) (*taskproto.TaskResponse, error) { - ctx = common.CreateMetadata(ctx) - conn, connErr := ClientFunc(services.Tasks) - if connErr != nil { - return nil, fmt.Errorf("Failed to create client connection: %v", connErr) + ctx, conn, err := getConnection(ctx, services.Tasks) + if err != nil { + return nil, err } asService := NewGetTaskServiceClientFunc(conn) @@ -59,10 +58,9 @@ func DeleteTaskRequest(ctx context.Context, req *taskproto.GetTaskRequest) (*tas // GetTaskRequest will do the rpc calls for the svc-task GetTaskStatus func GetTaskRequest(ctx context.Context, req *taskproto.GetTaskRequest) (*taskproto.TaskResponse, error) { - ctx = common.CreateMetadata(ctx) - conn, connErr := ClientFunc(services.Tasks) - if connErr != nil { - return nil, fmt.Errorf("Failed to create client connection: %v", connErr) + ctx, conn, err := getConnection(ctx, services.Tasks) + if err != nil { + return nil, err } asService := NewGetTaskServiceClientFunc(conn) @@ -84,10 +82,9 @@ func GetTaskRequest(ctx context.Context, req *taskproto.GetTaskRequest) (*taskpr // GetSubTasks will do the rpc calls for the svc-task GetSubTasks func GetSubTasks(ctx context.Context, req *taskproto.GetTaskRequest) (*taskproto.TaskResponse, error) { - ctx = common.CreateMetadata(ctx) - conn, connErr := ClientFunc(services.Tasks) - if connErr != nil { - return nil, fmt.Errorf("Failed to create client connection: %v", connErr) + ctx, conn, err := getConnection(ctx, services.Tasks) + if err != nil { + return nil, err } tService := NewGetTaskServiceClientFunc(conn) @@ -109,10 +106,9 @@ func GetSubTasks(ctx context.Context, req *taskproto.GetTaskRequest) (*taskproto // GetSubTask will do the rpc calls for the svc-task GetSubTask func GetSubTask(ctx context.Context, req *taskproto.GetTaskRequest) (*taskproto.TaskResponse, error) { - ctx = common.CreateMetadata(ctx) - conn, connErr := ClientFunc(services.Tasks) - if connErr != nil { - return nil, fmt.Errorf("Failed to create client connection: %v", connErr) + ctx, conn, err := getConnection(ctx, services.Tasks) + if err != nil { + return nil, err } tService := NewGetTaskServiceClientFunc(conn) @@ -134,10 +130,9 @@ func GetSubTask(ctx context.Context, req *taskproto.GetTaskRequest) (*taskproto. // GetTaskMonitor will do the rpc calls for the svc-task GetTaskMonitor func GetTaskMonitor(ctx context.Context, req *taskproto.GetTaskRequest) (*taskproto.TaskResponse, error) { - ctx = common.CreateMetadata(ctx) - conn, connErr := ClientFunc(services.Tasks) - if connErr != nil { - return nil, fmt.Errorf("Failed to create client connection: %v", connErr) + ctx, conn, err := getConnection(ctx, services.Tasks) + if err != nil { + return nil, err } tService := NewGetTaskServiceClientFunc(conn) @@ -159,10 +154,9 @@ func GetTaskMonitor(ctx context.Context, req *taskproto.GetTaskRequest) (*taskpr // TaskCollection will perform the rpc call to svc-task TaskCollection func TaskCollection(ctx context.Context, req *taskproto.GetTaskRequest) (*taskproto.TaskResponse, error) { - ctx = common.CreateMetadata(ctx) - conn, connErr := ClientFunc(services.Tasks) - if connErr != nil { - return nil, fmt.Errorf("Failed to create client connection: %v", connErr) + ctx, conn, err := getConnection(ctx, services.Tasks) + if err != nil { + return nil, err } tService := NewGetTaskServiceClientFunc(conn) @@ -184,10 +178,9 @@ func TaskCollection(ctx context.Context, req *taskproto.GetTaskRequest) (*taskpr // GetTaskService will perform the rpc call to svc-task GetTaskService func GetTaskService(ctx context.Context, req *taskproto.GetTaskRequest) (*taskproto.TaskResponse, error) { - ctx = common.CreateMetadata(ctx) - conn, connErr := ClientFunc(services.Tasks) - if connErr != nil { - return nil, fmt.Errorf("Failed to create client connection: %v", connErr) + ctx, conn, err := getConnection(ctx, services.Tasks) + if err != nil { + return nil, err } tService := NewGetTaskServiceClientFunc(conn) diff --git a/svc-api/rpc/telemetry.go b/svc-api/rpc/telemetry.go index fa860c201..ab8715231 100644 --- a/svc-api/rpc/telemetry.go +++ b/svc-api/rpc/telemetry.go @@ -19,7 +19,6 @@ import ( "context" "fmt" - "github.com/ODIM-Project/ODIM/lib-utilities/common" teleproto "github.com/ODIM-Project/ODIM/lib-utilities/proto/telemetry" "github.com/ODIM-Project/ODIM/lib-utilities/services" ) @@ -32,10 +31,9 @@ var ( // DoGetTelemetryService defines the RPC call function for // the GetTelemetryService from telemetry micro service func DoGetTelemetryService(ctx context.Context, req teleproto.TelemetryRequest) (*teleproto.TelemetryResponse, error) { - ctx = common.CreateMetadata(ctx) - conn, err := ClientFunc(services.Telemetry) + ctx, conn, err := getConnection(ctx, services.Telemetry) if err != nil { - return nil, fmt.Errorf("Failed to create client connection: %v", err) + return nil, err } telemetry := NewTelemetryClientFunc(conn) @@ -51,10 +49,9 @@ func DoGetTelemetryService(ctx context.Context, req teleproto.TelemetryRequest) // DoGetMetricDefinitionCollection defines the RPC call function for // the GetMetricDefinitionCollection from telemetry micro service func DoGetMetricDefinitionCollection(ctx context.Context, req teleproto.TelemetryRequest) (*teleproto.TelemetryResponse, error) { - ctx = common.CreateMetadata(ctx) - conn, err := ClientFunc(services.Telemetry) + ctx, conn, err := getConnection(ctx, services.Telemetry) if err != nil { - return nil, fmt.Errorf("Failed to create client connection: %v", err) + return nil, err } telemetry := NewTelemetryClientFunc(conn) @@ -69,10 +66,9 @@ func DoGetMetricDefinitionCollection(ctx context.Context, req teleproto.Telemetr // DoGetMetricReportDefinitionCollection defines the RPC call function for // the GetMetricReportDefinitionCollection from telemetry micro service func DoGetMetricReportDefinitionCollection(ctx context.Context, req teleproto.TelemetryRequest) (*teleproto.TelemetryResponse, error) { - ctx = common.CreateMetadata(ctx) - conn, err := ClientFunc(services.Telemetry) + ctx, conn, err := getConnection(ctx, services.Telemetry) if err != nil { - return nil, fmt.Errorf("Failed to create client connection: %v", err) + return nil, err } telemetry := NewTelemetryClientFunc(conn) @@ -87,10 +83,9 @@ func DoGetMetricReportDefinitionCollection(ctx context.Context, req teleproto.Te // DoGetMetricReportCollection defines the RPC call function for // the GetMetricReportCollection from telemetry micro service func DoGetMetricReportCollection(ctx context.Context, req teleproto.TelemetryRequest) (*teleproto.TelemetryResponse, error) { - ctx = common.CreateMetadata(ctx) - conn, err := ClientFunc(services.Telemetry) + ctx, conn, err := getConnection(ctx, services.Telemetry) if err != nil { - return nil, fmt.Errorf("Failed to create client connection: %v", err) + return nil, err } telemetry := NewTelemetryClientFunc(conn) @@ -106,10 +101,9 @@ func DoGetMetricReportCollection(ctx context.Context, req teleproto.TelemetryReq // DoGetTriggerCollection defines the RPC call function for // the GetTriggerCollection from telemetry micro service func DoGetTriggerCollection(ctx context.Context, req teleproto.TelemetryRequest) (*teleproto.TelemetryResponse, error) { - ctx = common.CreateMetadata(ctx) - conn, err := ClientFunc(services.Telemetry) + ctx, conn, err := getConnection(ctx, services.Telemetry) if err != nil { - return nil, fmt.Errorf("Failed to create client connection: %v", err) + return nil, err } telemetry := NewTelemetryClientFunc(conn) @@ -125,10 +119,9 @@ func DoGetTriggerCollection(ctx context.Context, req teleproto.TelemetryRequest) // DoGetMetricDefinition defines the RPC call function for // the GetMetricDefinition from telemetry micro service func DoGetMetricDefinition(ctx context.Context, req teleproto.TelemetryRequest) (*teleproto.TelemetryResponse, error) { - ctx = common.CreateMetadata(ctx) - conn, err := ClientFunc(services.Telemetry) + ctx, conn, err := getConnection(ctx, services.Telemetry) if err != nil { - return nil, fmt.Errorf("Failed to create client connection: %v", err) + return nil, err } telemetry := NewTelemetryClientFunc(conn) @@ -144,10 +137,9 @@ func DoGetMetricDefinition(ctx context.Context, req teleproto.TelemetryRequest) // DoGetMetricReportDefinition defines the RPC call function for // the GetMetricReportDefinition from telemetry micro service func DoGetMetricReportDefinition(ctx context.Context, req teleproto.TelemetryRequest) (*teleproto.TelemetryResponse, error) { - ctx = common.CreateMetadata(ctx) - conn, err := ClientFunc(services.Telemetry) + ctx, conn, err := getConnection(ctx, services.Telemetry) if err != nil { - return nil, fmt.Errorf("Failed to create client connection: %v", err) + return nil, err } telemetry := NewTelemetryClientFunc(conn) @@ -163,10 +155,9 @@ func DoGetMetricReportDefinition(ctx context.Context, req teleproto.TelemetryReq // DoGetMetricReport defines the RPC call function for // the GetMetricReport from telemetry micro service func DoGetMetricReport(ctx context.Context, req teleproto.TelemetryRequest) (*teleproto.TelemetryResponse, error) { - ctx = common.CreateMetadata(ctx) - conn, err := ClientFunc(services.Telemetry) + ctx, conn, err := getConnection(ctx, services.Telemetry) if err != nil { - return nil, fmt.Errorf("Failed to create client connection: %v", err) + return nil, err } telemetry := NewTelemetryClientFunc(conn) @@ -182,10 +173,9 @@ func DoGetMetricReport(ctx context.Context, req teleproto.TelemetryRequest) (*te // DoGetTrigger defines the RPC call function for // the GetTrigger from telemetry micro service func DoGetTrigger(ctx context.Context, req teleproto.TelemetryRequest) (*teleproto.TelemetryResponse, error) { - ctx = common.CreateMetadata(ctx) - conn, err := ClientFunc(services.Telemetry) + ctx, conn, err := getConnection(ctx, services.Telemetry) if err != nil { - return nil, fmt.Errorf("Failed to create client connection: %v", err) + return nil, err } telemetry := NewTelemetryClientFunc(conn) @@ -201,10 +191,9 @@ func DoGetTrigger(ctx context.Context, req teleproto.TelemetryRequest) (*telepro // DoUpdateTrigger defines the RPC call function for // the UpdateTrigger from telemetry micro service func DoUpdateTrigger(ctx context.Context, req teleproto.TelemetryRequest) (*teleproto.TelemetryResponse, error) { - ctx = common.CreateMetadata(ctx) - conn, err := ClientFunc(services.Telemetry) + ctx, conn, err := getConnection(ctx, services.Telemetry) if err != nil { - return nil, fmt.Errorf("Failed to create client connection: %v", err) + return nil, err } telemetry := NewTelemetryClientFunc(conn) From c279f249c46700ed18027535625f73be73e2b7bb Mon Sep 17 00:00:00 2001 From: Banoshi Date: Fri, 16 Jun 2023 02:53:30 +0530 Subject: [PATCH 11/19] refactor code --- svc-api/rpc/account.go | 40 +++++++-------- svc-api/rpc/aggregator.go | 101 +++++++++++++++++++++++--------------- svc-api/rpc/chassis.go | 31 +++++++----- svc-api/rpc/events.go | 31 +++++++----- svc-api/rpc/fabrics.go | 16 +++--- svc-api/rpc/licenses.go | 21 +++++--- svc-api/rpc/managers.go | 46 ++++++++++------- svc-api/rpc/role.go | 21 +++++--- svc-api/rpc/sessions.go | 20 +++++--- svc-api/rpc/system.go | 56 ++++++++++++--------- svc-api/rpc/task.go | 49 ++++++++++-------- svc-api/rpc/telemetry.go | 51 +++++++++++-------- 12 files changed, 286 insertions(+), 197 deletions(-) diff --git a/svc-api/rpc/account.go b/svc-api/rpc/account.go index 2f832404a..6726e1d69 100644 --- a/svc-api/rpc/account.go +++ b/svc-api/rpc/account.go @@ -22,7 +22,6 @@ import ( "github.com/ODIM-Project/ODIM/lib-utilities/common" accountproto "github.com/ODIM-Project/ODIM/lib-utilities/proto/account" "github.com/ODIM-Project/ODIM/lib-utilities/services" - "google.golang.org/grpc" ) // helper functions @@ -34,9 +33,10 @@ var ( // DoGetAccountServiceRequest defines the RPC call function for // the GetAccountService from account-session micro service func DoGetAccountServiceRequest(ctx context.Context, req accountproto.AccountRequest) (*accountproto.AccountResponse, error) { - ctx, conn, err := getConnection(ctx, services.AccountSession) + ctx = common.CreateMetadata(ctx) + conn, err := ClientFunc(services.AccountSession) if err != nil { - return nil, err + return nil, fmt.Errorf("Failed to create client connection: %v", err) } account := NewAccountClientFunc(conn) @@ -51,9 +51,10 @@ func DoGetAccountServiceRequest(ctx context.Context, req accountproto.AccountReq // DoAccountCreationRequest defines the RPC call function for // the AccountCreation from account-session micro service func DoAccountCreationRequest(ctx context.Context, req accountproto.CreateAccountRequest) (*accountproto.AccountResponse, error) { - ctx, conn, err := getConnection(ctx, services.AccountSession) + ctx = common.CreateMetadata(ctx) + conn, err := ClientFunc(services.AccountSession) if err != nil { - return nil, err + return nil, fmt.Errorf("Failed to create client connection: %v", err) } account := NewAccountClientFunc(conn) @@ -69,9 +70,10 @@ func DoAccountCreationRequest(ctx context.Context, req accountproto.CreateAccoun // DoGetAllAccountRequest defines the RPC call function for // the GetAllAccount from account-session micro service func DoGetAllAccountRequest(ctx context.Context, req accountproto.AccountRequest) (*accountproto.AccountResponse, error) { - ctx, conn, err := getConnection(ctx, services.AccountSession) + ctx = common.CreateMetadata(ctx) + conn, err := ClientFunc(services.AccountSession) if err != nil { - return nil, err + return nil, fmt.Errorf("Failed to create client connection: %v", err) } account := NewAccountClientFunc(conn) @@ -87,9 +89,10 @@ func DoGetAllAccountRequest(ctx context.Context, req accountproto.AccountRequest // DoGetAccountRequest defines the RPC call function for // the GetAccount from account-session micro service func DoGetAccountRequest(ctx context.Context, req accountproto.GetAccountRequest) (*accountproto.AccountResponse, error) { - ctx, conn, err := getConnection(ctx, services.AccountSession) + ctx = common.CreateMetadata(ctx) + conn, err := ClientFunc(services.AccountSession) if err != nil { - return nil, err + return nil, fmt.Errorf("Failed to create client connection: %v", err) } account := NewAccountClientFunc(conn) @@ -105,9 +108,10 @@ func DoGetAccountRequest(ctx context.Context, req accountproto.GetAccountRequest // DoUpdateAccountRequest defines the RPC call function for // the UpdateAccount from account-session micro service func DoUpdateAccountRequest(ctx context.Context, req accountproto.UpdateAccountRequest) (*accountproto.AccountResponse, error) { - ctx, conn, err := getConnection(ctx, services.AccountSession) + ctx = common.CreateMetadata(ctx) + conn, err := ClientFunc(services.AccountSession) if err != nil { - return nil, err + return nil, fmt.Errorf("Failed to create client connection: %v", err) } account := NewAccountClientFunc(conn) @@ -122,9 +126,10 @@ func DoUpdateAccountRequest(ctx context.Context, req accountproto.UpdateAccountR // DoAccountDeleteRequest defines the RPC call function for // the AccountDelete from account-session micro service func DoAccountDeleteRequest(ctx context.Context, req accountproto.DeleteAccountRequest) (*accountproto.AccountResponse, error) { - ctx, conn, err := getConnection(ctx, services.AccountSession) + ctx = common.CreateMetadata(ctx) + conn, err := ClientFunc(services.AccountSession) if err != nil { - return nil, err + return nil, fmt.Errorf("Failed to create client connection: %v", err) } account := NewAccountClientFunc(conn) @@ -136,12 +141,3 @@ func DoAccountDeleteRequest(ctx context.Context, req accountproto.DeleteAccountR defer conn.Close() return resp, err } - -func getConnection(ctx context.Context, service string) (context.Context, *grpc.ClientConn, error) { - ctx = common.CreateMetadata(ctx) - conn, err := ClientFunc(service) - if err != nil { - return ctx, nil, fmt.Errorf("Failed to create client connection: %v", err) - } - return ctx, conn, nil -} diff --git a/svc-api/rpc/aggregator.go b/svc-api/rpc/aggregator.go index fa82bb638..4c917f639 100644 --- a/svc-api/rpc/aggregator.go +++ b/svc-api/rpc/aggregator.go @@ -19,6 +19,7 @@ import ( "context" "fmt" + "github.com/ODIM-Project/ODIM/lib-utilities/common" aggregatorproto "github.com/ODIM-Project/ODIM/lib-utilities/proto/aggregator" "github.com/ODIM-Project/ODIM/lib-utilities/services" ) @@ -31,9 +32,10 @@ var ( // DoGetAggregationService defines the RPC call function for // the GetAggregationService from aggregator micro service func DoGetAggregationService(ctx context.Context, req aggregatorproto.AggregatorRequest) (*aggregatorproto.AggregatorResponse, error) { - ctx, conn, err := getConnection(ctx, services.Aggregator) + ctx = common.CreateMetadata(ctx) + conn, err := ClientFunc(services.Aggregator) if err != nil { - return nil, err + return nil, fmt.Errorf("Failed to create client connection: %v", err) } aggregator := NewAggregatorClientFunc(conn) @@ -49,9 +51,10 @@ func DoGetAggregationService(ctx context.Context, req aggregatorproto.Aggregator // DoResetRequest defines the RPC call function for // the Reset from aggregator micro service func DoResetRequest(ctx context.Context, req aggregatorproto.AggregatorRequest) (*aggregatorproto.AggregatorResponse, error) { - ctx, conn, err := getConnection(ctx, services.Aggregator) + ctx = common.CreateMetadata(ctx) + conn, err := ClientFunc(services.Aggregator) if err != nil { - return nil, err + return nil, fmt.Errorf("Failed to create client connection: %v", err) } aggregator := NewAggregatorClientFunc(conn) @@ -66,9 +69,10 @@ func DoResetRequest(ctx context.Context, req aggregatorproto.AggregatorRequest) // DoSetDefaultBootOrderRequest defines the RPC call function for // the SetDefaultBootOrder from aggregator micro service func DoSetDefaultBootOrderRequest(ctx context.Context, req aggregatorproto.AggregatorRequest) (*aggregatorproto.AggregatorResponse, error) { - ctx, conn, err := getConnection(ctx, services.Aggregator) + ctx = common.CreateMetadata(ctx) + conn, err := ClientFunc(services.Aggregator) if err != nil { - return nil, err + return nil, fmt.Errorf("Failed to create client connection: %v", err) } aggregator := NewAggregatorClientFunc(conn) @@ -84,9 +88,10 @@ func DoSetDefaultBootOrderRequest(ctx context.Context, req aggregatorproto.Aggre // DoAddAggregationSource defines the RPC call function for // the AddAggregationSource from aggregator micro service func DoAddAggregationSource(ctx context.Context, req aggregatorproto.AggregatorRequest) (*aggregatorproto.AggregatorResponse, error) { - ctx, conn, err := getConnection(ctx, services.Aggregator) + ctx = common.CreateMetadata(ctx) + conn, err := ClientFunc(services.Aggregator) if err != nil { - return nil, err + return nil, fmt.Errorf("Failed to create client connection: %v", err) } aggregator := NewAggregatorClientFunc(conn) @@ -102,9 +107,10 @@ func DoAddAggregationSource(ctx context.Context, req aggregatorproto.AggregatorR // DoGetAllAggregationSource defines the RPC call function for // the GetAllAggregationSource from aggregator micro service func DoGetAllAggregationSource(ctx context.Context, req aggregatorproto.AggregatorRequest) (*aggregatorproto.AggregatorResponse, error) { - ctx, conn, err := getConnection(ctx, services.Aggregator) + ctx = common.CreateMetadata(ctx) + conn, err := ClientFunc(services.Aggregator) if err != nil { - return nil, err + return nil, fmt.Errorf("Failed to create client connection: %v", err) } aggregator := NewAggregatorClientFunc(conn) @@ -120,9 +126,10 @@ func DoGetAllAggregationSource(ctx context.Context, req aggregatorproto.Aggregat // DoGetAggregationSource defines the RPC call function for // the GetAggregationSource from aggregator micro service func DoGetAggregationSource(ctx context.Context, req aggregatorproto.AggregatorRequest) (*aggregatorproto.AggregatorResponse, error) { - ctx, conn, err := getConnection(ctx, services.Aggregator) + ctx = common.CreateMetadata(ctx) + conn, err := ClientFunc(services.Aggregator) if err != nil { - return nil, err + return nil, fmt.Errorf("Failed to create client connection: %v", err) } aggregator := NewAggregatorClientFunc(conn) @@ -138,9 +145,10 @@ func DoGetAggregationSource(ctx context.Context, req aggregatorproto.AggregatorR // DoUpdateAggregationSource defines the RPC call function for // the UpdateAggregationSource from aggregator micro service func DoUpdateAggregationSource(ctx context.Context, req aggregatorproto.AggregatorRequest) (*aggregatorproto.AggregatorResponse, error) { - ctx, conn, err := getConnection(ctx, services.Aggregator) + ctx = common.CreateMetadata(ctx) + conn, err := ClientFunc(services.Aggregator) if err != nil { - return nil, err + return nil, fmt.Errorf("Failed to create client connection: %v", err) } aggregator := NewAggregatorClientFunc(conn) @@ -156,9 +164,10 @@ func DoUpdateAggregationSource(ctx context.Context, req aggregatorproto.Aggregat // DoDeleteAggregationSource defines the RPC call function for // the DeleteAggregationSource from aggregator micro service func DoDeleteAggregationSource(ctx context.Context, req aggregatorproto.AggregatorRequest) (*aggregatorproto.AggregatorResponse, error) { - ctx, conn, err := getConnection(ctx, services.Aggregator) + ctx = common.CreateMetadata(ctx) + conn, err := ClientFunc(services.Aggregator) if err != nil { - return nil, err + return nil, fmt.Errorf("Failed to create client connection: %v", err) } aggregator := NewAggregatorClientFunc(conn) @@ -174,9 +183,10 @@ func DoDeleteAggregationSource(ctx context.Context, req aggregatorproto.Aggregat // DoCreateAggregate defines the RPC call function for // the CreateAggregate from aggregator micro service func DoCreateAggregate(ctx context.Context, req aggregatorproto.AggregatorRequest) (*aggregatorproto.AggregatorResponse, error) { - ctx, conn, err := getConnection(ctx, services.Aggregator) + ctx = common.CreateMetadata(ctx) + conn, err := ClientFunc(services.Aggregator) if err != nil { - return nil, err + return nil, fmt.Errorf("Failed to create client connection: %v", err) } aggregator := NewAggregatorClientFunc(conn) @@ -192,9 +202,10 @@ func DoCreateAggregate(ctx context.Context, req aggregatorproto.AggregatorReques // DoGetAggregateCollection defines the RPC call function for // the get aggregate collections from aggregator micro service func DoGetAggregateCollection(ctx context.Context, req aggregatorproto.AggregatorRequest) (*aggregatorproto.AggregatorResponse, error) { - ctx, conn, err := getConnection(ctx, services.Aggregator) + ctx = common.CreateMetadata(ctx) + conn, err := ClientFunc(services.Aggregator) if err != nil { - return nil, err + return nil, fmt.Errorf("Failed to create client connection: %v", err) } aggregator := NewAggregatorClientFunc(conn) @@ -210,9 +221,10 @@ func DoGetAggregateCollection(ctx context.Context, req aggregatorproto.Aggregato // DoGeteAggregate defines the RPC call function for // the get aggregate from aggregator micro service func DoGeteAggregate(ctx context.Context, req aggregatorproto.AggregatorRequest) (*aggregatorproto.AggregatorResponse, error) { - ctx, conn, err := getConnection(ctx, services.Aggregator) + ctx = common.CreateMetadata(ctx) + conn, err := ClientFunc(services.Aggregator) if err != nil { - return nil, err + return nil, fmt.Errorf("Failed to create client connection: %v", err) } aggregator := NewAggregatorClientFunc(conn) @@ -228,9 +240,10 @@ func DoGeteAggregate(ctx context.Context, req aggregatorproto.AggregatorRequest) // DoDeleteAggregate defines the RPC call function for // the delete aggregate from aggregator micro service func DoDeleteAggregate(ctx context.Context, req aggregatorproto.AggregatorRequest) (*aggregatorproto.AggregatorResponse, error) { - ctx, conn, err := getConnection(ctx, services.Aggregator) + ctx = common.CreateMetadata(ctx) + conn, err := ClientFunc(services.Aggregator) if err != nil { - return nil, err + return nil, fmt.Errorf("Failed to create client connection: %v", err) } aggregator := NewAggregatorClientFunc(conn) @@ -246,9 +259,10 @@ func DoDeleteAggregate(ctx context.Context, req aggregatorproto.AggregatorReques // DoAddElementsToAggregate defines the RPC call function for // the add elements to an aggregate from aggregator micro service func DoAddElementsToAggregate(ctx context.Context, req aggregatorproto.AggregatorRequest) (*aggregatorproto.AggregatorResponse, error) { - ctx, conn, err := getConnection(ctx, services.Aggregator) + ctx = common.CreateMetadata(ctx) + conn, err := ClientFunc(services.Aggregator) if err != nil { - return nil, err + return nil, fmt.Errorf("Failed to create client connection: %v", err) } aggregator := NewAggregatorClientFunc(conn) @@ -264,9 +278,10 @@ func DoAddElementsToAggregate(ctx context.Context, req aggregatorproto.Aggregato // DoRemoveElementsFromAggregate defines the RPC call function for // the remove elements from an aggregate from aggregator micro service func DoRemoveElementsFromAggregate(ctx context.Context, req aggregatorproto.AggregatorRequest) (*aggregatorproto.AggregatorResponse, error) { - ctx, conn, err := getConnection(ctx, services.Aggregator) + ctx = common.CreateMetadata(ctx) + conn, err := ClientFunc(services.Aggregator) if err != nil { - return nil, err + return nil, fmt.Errorf("Failed to create client connection: %v", err) } aggregator := NewAggregatorClientFunc(conn) @@ -282,9 +297,10 @@ func DoRemoveElementsFromAggregate(ctx context.Context, req aggregatorproto.Aggr // DoResetAggregateElements defines the RPC call function for // the reset elements of an aggregate from aggregator micro service func DoResetAggregateElements(ctx context.Context, req aggregatorproto.AggregatorRequest) (*aggregatorproto.AggregatorResponse, error) { - ctx, conn, err := getConnection(ctx, services.Aggregator) + ctx = common.CreateMetadata(ctx) + conn, err := ClientFunc(services.Aggregator) if err != nil { - return nil, err + return nil, fmt.Errorf("Failed to create client connection: %v", err) } aggregator := NewAggregatorClientFunc(conn) @@ -300,9 +316,10 @@ func DoResetAggregateElements(ctx context.Context, req aggregatorproto.Aggregato // DoSetDefaultBootOrderAggregateElements defines the RPC call function for // the set default boot order elements of an aggregate from aggregator micro service func DoSetDefaultBootOrderAggregateElements(ctx context.Context, req aggregatorproto.AggregatorRequest) (*aggregatorproto.AggregatorResponse, error) { - ctx, conn, err := getConnection(ctx, services.Aggregator) + ctx = common.CreateMetadata(ctx) + conn, err := ClientFunc(services.Aggregator) if err != nil { - return nil, err + return nil, fmt.Errorf("Failed to create client connection: %v", err) } aggregator := NewAggregatorClientFunc(conn) @@ -318,9 +335,10 @@ func DoSetDefaultBootOrderAggregateElements(ctx context.Context, req aggregatorp // DoGetAllConnectionMethods defines the RPC call function for // the get connection method collection from aggregator micro service func DoGetAllConnectionMethods(ctx context.Context, req aggregatorproto.AggregatorRequest) (*aggregatorproto.AggregatorResponse, error) { - ctx, conn, err := getConnection(ctx, services.Aggregator) + ctx = common.CreateMetadata(ctx) + conn, err := ClientFunc(services.Aggregator) if err != nil { - return nil, err + return nil, fmt.Errorf("Failed to create client connection: %v", err) } aggregator := NewAggregatorClientFunc(conn) @@ -336,9 +354,10 @@ func DoGetAllConnectionMethods(ctx context.Context, req aggregatorproto.Aggregat // DoGetConnectionMethod defines the RPC call function for // the get on connection method from aggregator micro service func DoGetConnectionMethod(ctx context.Context, req aggregatorproto.AggregatorRequest) (*aggregatorproto.AggregatorResponse, error) { - ctx, conn, err := getConnection(ctx, services.Aggregator) + ctx = common.CreateMetadata(ctx) + conn, err := ClientFunc(services.Aggregator) if err != nil { - return nil, err + return nil, fmt.Errorf("Failed to create client connection: %v", err) } aggregator := NewAggregatorClientFunc(conn) @@ -354,9 +373,10 @@ func DoGetConnectionMethod(ctx context.Context, req aggregatorproto.AggregatorRe // DoGetResetActionInfoService defines the RPC call function for // the GetResetActionInfoService from aggregator micro service func DoGetResetActionInfoService(ctx context.Context, req aggregatorproto.AggregatorRequest) (*aggregatorproto.AggregatorResponse, error) { - ctx, conn, err := getConnection(ctx, services.Aggregator) + ctx = common.CreateMetadata(ctx) + conn, err := ClientFunc(services.Aggregator) if err != nil { - return nil, err + return nil, fmt.Errorf("Failed to create client connection: %v", err) } aggregator := NewAggregatorClientFunc(conn) @@ -372,9 +392,10 @@ func DoGetResetActionInfoService(ctx context.Context, req aggregatorproto.Aggreg // DoGetSetDefaultBootOrderActionInfo defines the RPC call function for // the GetSetDefaultBootOrderActionInfo from aggregator micro service func DoGetSetDefaultBootOrderActionInfo(ctx context.Context, req aggregatorproto.AggregatorRequest) (*aggregatorproto.AggregatorResponse, error) { - ctx, conn, err := getConnection(ctx, services.Aggregator) + ctx = common.CreateMetadata(ctx) + conn, err := ClientFunc(services.Aggregator) if err != nil { - return nil, err + return nil, fmt.Errorf("Failed to create client connection: %v", err) } aggregator := NewAggregatorClientFunc(conn) diff --git a/svc-api/rpc/chassis.go b/svc-api/rpc/chassis.go index cf4baa35c..c742b2c1f 100644 --- a/svc-api/rpc/chassis.go +++ b/svc-api/rpc/chassis.go @@ -20,6 +20,7 @@ import ( "context" "fmt" + "github.com/ODIM-Project/ODIM/lib-utilities/common" chassisproto "github.com/ODIM-Project/ODIM/lib-utilities/proto/chassis" "github.com/ODIM-Project/ODIM/lib-utilities/services" ) @@ -31,9 +32,10 @@ var ( // GetChassisCollection will do the rpc call to collect all chassis func GetChassisCollection(ctx context.Context, req chassisproto.GetChassisRequest) (*chassisproto.GetChassisResponse, error) { - ctx, conn, err := getConnection(ctx, services.Systems) + ctx = common.CreateMetadata(ctx) + conn, err := ClientFunc(services.Systems) if err != nil { - return nil, err + return nil, fmt.Errorf("Failed to create client connection: %v", err) } asService := NewChassisClientFunc(conn) @@ -47,9 +49,10 @@ func GetChassisCollection(ctx context.Context, req chassisproto.GetChassisReques // GetChassisResource will do the rpc call to collect Chassis Resource func GetChassisResource(ctx context.Context, req chassisproto.GetChassisRequest) (*chassisproto.GetChassisResponse, error) { - ctx, conn, err := getConnection(ctx, services.Systems) + ctx = common.CreateMetadata(ctx) + conn, err := ClientFunc(services.Systems) if err != nil { - return nil, err + return nil, fmt.Errorf("Failed to create client connection: %v", err) } asService := NewChassisClientFunc(conn) @@ -63,9 +66,10 @@ func GetChassisResource(ctx context.Context, req chassisproto.GetChassisRequest) // GetChassis will do the rpc call to System Resource func GetChassis(ctx context.Context, req chassisproto.GetChassisRequest) (*chassisproto.GetChassisResponse, error) { - ctx, conn, err := getConnection(ctx, services.Systems) + ctx = common.CreateMetadata(ctx) + conn, err := ClientFunc(services.Systems) if err != nil { - return nil, err + return nil, fmt.Errorf("Failed to create client connection: %v", err) } asService := NewChassisClientFunc(conn) @@ -79,9 +83,10 @@ func GetChassis(ctx context.Context, req chassisproto.GetChassisRequest) (*chass // CreateChassis will do the rpc call to create a Chassis func CreateChassis(ctx context.Context, req chassisproto.CreateChassisRequest) (*chassisproto.GetChassisResponse, error) { - ctx, conn, err := getConnection(ctx, services.Systems) + ctx = common.CreateMetadata(ctx) + conn, err := ClientFunc(services.Systems) if err != nil { - return nil, err + return nil, fmt.Errorf("Failed to create client connection: %v", err) } service := NewChassisClientFunc(conn) @@ -95,9 +100,10 @@ func CreateChassis(ctx context.Context, req chassisproto.CreateChassisRequest) ( // DeleteChassis will do the rpc call to delete a chassis func DeleteChassis(ctx context.Context, req chassisproto.DeleteChassisRequest) (*chassisproto.GetChassisResponse, error) { - ctx, conn, err := getConnection(ctx, services.Systems) + ctx = common.CreateMetadata(ctx) + conn, err := ClientFunc(services.Systems) if err != nil { - return nil, err + return nil, fmt.Errorf("Failed to create client connection: %v", err) } service := NewChassisClientFunc(conn) @@ -111,9 +117,10 @@ func DeleteChassis(ctx context.Context, req chassisproto.DeleteChassisRequest) ( // UpdateChassis will do the rpc call to update a chassis func UpdateChassis(ctx context.Context, req chassisproto.UpdateChassisRequest) (*chassisproto.GetChassisResponse, error) { - ctx, conn, err := getConnection(ctx, services.Systems) + ctx = common.CreateMetadata(ctx) + conn, err := ClientFunc(services.Systems) if err != nil { - return nil, err + return nil, fmt.Errorf("Failed to create client connection: %v", err) } service := NewChassisClientFunc(conn) diff --git a/svc-api/rpc/events.go b/svc-api/rpc/events.go index 6e3b1d7b4..38c651634 100644 --- a/svc-api/rpc/events.go +++ b/svc-api/rpc/events.go @@ -19,6 +19,7 @@ import ( "context" "fmt" + "github.com/ODIM-Project/ODIM/lib-utilities/common" eventsproto "github.com/ODIM-Project/ODIM/lib-utilities/proto/events" "github.com/ODIM-Project/ODIM/lib-utilities/services" ) @@ -31,9 +32,10 @@ var ( // DoGetEventService defines the RPC call function for // the GetEventService from events micro service func DoGetEventService(ctx context.Context, req eventsproto.EventSubRequest) (*eventsproto.EventSubResponse, error) { - ctx, conn, err := getConnection(ctx, services.Events) + ctx = common.CreateMetadata(ctx) + conn, err := ClientFunc(services.Events) if err != nil { - return nil, err + return nil, fmt.Errorf("Failed to create client connection: %v", err) } events := NewEventsClientFunc(conn) @@ -49,9 +51,10 @@ func DoGetEventService(ctx context.Context, req eventsproto.EventSubRequest) (*e // DoCreateEventSubscription defines the RPC call function for // the CreateEventSubscription from events micro service func DoCreateEventSubscription(ctx context.Context, req eventsproto.EventSubRequest) (*eventsproto.EventSubResponse, error) { - ctx, conn, err := getConnection(ctx, services.Events) + ctx = common.CreateMetadata(ctx) + conn, err := ClientFunc(services.Events) if err != nil { - return nil, err + return nil, fmt.Errorf("Failed to create client connection: %v", err) } events := NewEventsClientFunc(conn) @@ -67,9 +70,10 @@ func DoCreateEventSubscription(ctx context.Context, req eventsproto.EventSubRequ // DoSubmitTestEvent defines the RPC call function for // the SubmitTestEvent from events micro service func DoSubmitTestEvent(ctx context.Context, req eventsproto.EventSubRequest) (*eventsproto.EventSubResponse, error) { - ctx, conn, err := getConnection(ctx, services.Events) + ctx = common.CreateMetadata(ctx) + conn, err := ClientFunc(services.Events) if err != nil { - return nil, err + return nil, fmt.Errorf("Failed to create client connection: %v", err) } events := NewEventsClientFunc(conn) @@ -85,9 +89,10 @@ func DoSubmitTestEvent(ctx context.Context, req eventsproto.EventSubRequest) (*e // DoGetEventSubscription defines the RPC call function for // the DoGetEventSubscription from events micro service func DoGetEventSubscription(ctx context.Context, req eventsproto.EventRequest) (*eventsproto.EventSubResponse, error) { - ctx, conn, err := getConnection(ctx, services.Events) + ctx = common.CreateMetadata(ctx) + conn, err := ClientFunc(services.Events) if err != nil { - return nil, err + return nil, fmt.Errorf("Failed to create client connection: %v", err) } events := NewEventsClientFunc(conn) @@ -103,9 +108,10 @@ func DoGetEventSubscription(ctx context.Context, req eventsproto.EventRequest) ( // DoDeleteEventSubscription defines the RPC call function for // the DoDeleteEventSubscription from events micro service func DoDeleteEventSubscription(ctx context.Context, req eventsproto.EventRequest) (*eventsproto.EventSubResponse, error) { - ctx, conn, err := getConnection(ctx, services.Events) + ctx = common.CreateMetadata(ctx) + conn, err := ClientFunc(services.Events) if err != nil { - return nil, err + return nil, fmt.Errorf("Failed to create client connection: %v", err) } events := NewEventsClientFunc(conn) @@ -121,9 +127,10 @@ func DoDeleteEventSubscription(ctx context.Context, req eventsproto.EventRequest // DoGetEventSubscriptionsCollection defines the RPC call function for // the DoGetEventSubscription from events micro service func DoGetEventSubscriptionsCollection(ctx context.Context, req eventsproto.EventRequest) (*eventsproto.EventSubResponse, error) { - ctx, conn, err := getConnection(ctx, services.Events) + ctx = common.CreateMetadata(ctx) + conn, err := ClientFunc(services.Events) if err != nil { - return nil, err + return nil, fmt.Errorf("Failed to create client connection: %v", err) } events := NewEventsClientFunc(conn) diff --git a/svc-api/rpc/fabrics.go b/svc-api/rpc/fabrics.go index 0e54497cc..9f899d589 100644 --- a/svc-api/rpc/fabrics.go +++ b/svc-api/rpc/fabrics.go @@ -19,6 +19,7 @@ import ( "context" "fmt" + "github.com/ODIM-Project/ODIM/lib-utilities/common" fabricsproto "github.com/ODIM-Project/ODIM/lib-utilities/proto/fabrics" "github.com/ODIM-Project/ODIM/lib-utilities/services" ) @@ -31,9 +32,10 @@ var ( // GetFabricResource defines the RPC call function for // the GetFabricResource from fabrics micro service func GetFabricResource(ctx context.Context, req fabricsproto.FabricRequest) (*fabricsproto.FabricResponse, error) { - ctx, conn, err := getConnection(ctx, services.Fabrics) + ctx = common.CreateMetadata(ctx) + conn, err := ClientFunc(services.Fabrics) if err != nil { - return nil, err + return nil, fmt.Errorf("Failed to create client connection: %v", err) } fab := NewFabricsClientFunc(conn) @@ -48,9 +50,10 @@ func GetFabricResource(ctx context.Context, req fabricsproto.FabricRequest) (*fa // UpdateFabricResource defines the RPC call function for creating/updating // the Fabric Resource such as Endpoints, Zones from fabrics micro service func UpdateFabricResource(ctx context.Context, req fabricsproto.FabricRequest) (*fabricsproto.FabricResponse, error) { - ctx, conn, err := getConnection(ctx, services.Fabrics) + ctx = common.CreateMetadata(ctx) + conn, err := ClientFunc(services.Fabrics) if err != nil { - return nil, err + return nil, fmt.Errorf("Failed to create client connection: %v", err) } fab := NewFabricsClientFunc(conn) @@ -66,9 +69,10 @@ func UpdateFabricResource(ctx context.Context, req fabricsproto.FabricRequest) ( // DeleteFabricResource defines the RPC call function for // the DeleteFabricResource from fabrics micro service func DeleteFabricResource(ctx context.Context, req fabricsproto.FabricRequest) (*fabricsproto.FabricResponse, error) { - ctx, conn, err := getConnection(ctx, services.Fabrics) + ctx = common.CreateMetadata(ctx) + conn, err := ClientFunc(services.Fabrics) if err != nil { - return nil, err + return nil, fmt.Errorf("Failed to create client connection: %v", err) } fab := NewFabricsClientFunc(conn) diff --git a/svc-api/rpc/licenses.go b/svc-api/rpc/licenses.go index d8682cb96..1aa6f0455 100644 --- a/svc-api/rpc/licenses.go +++ b/svc-api/rpc/licenses.go @@ -18,15 +18,17 @@ import ( "context" "fmt" + "github.com/ODIM-Project/ODIM/lib-utilities/common" licenseproto "github.com/ODIM-Project/ODIM/lib-utilities/proto/licenses" "github.com/ODIM-Project/ODIM/lib-utilities/services" ) // GetLicenseService will do the rpc call to get License Service Information func GetLicenseService(ctx context.Context, req licenseproto.GetLicenseServiceRequest) (*licenseproto.GetLicenseResponse, error) { - ctx, conn, err := getConnection(ctx, services.Licenses) + ctx = common.CreateMetadata(ctx) + conn, err := services.ODIMService.Client(services.Licenses) if err != nil { - return nil, err + return nil, fmt.Errorf("Failed to create client connection: %v", err) } defer conn.Close() licenseService := licenseproto.NewLicensesClient(conn) @@ -39,9 +41,10 @@ func GetLicenseService(ctx context.Context, req licenseproto.GetLicenseServiceRe // GetLicenseCollection will do the rpc call to get License Service Information func GetLicenseCollection(ctx context.Context, req licenseproto.GetLicenseRequest) (*licenseproto.GetLicenseResponse, error) { - ctx, conn, err := getConnection(ctx, services.Licenses) + ctx = common.CreateMetadata(ctx) + conn, err := services.ODIMService.Client(services.Licenses) if err != nil { - return nil, err + return nil, fmt.Errorf("Failed to create client connection: %v", err) } defer conn.Close() licenseService := licenseproto.NewLicensesClient(conn) @@ -54,9 +57,10 @@ func GetLicenseCollection(ctx context.Context, req licenseproto.GetLicenseReques // GetLicenseResource will do the rpc call to get License Service Information func GetLicenseResource(ctx context.Context, req licenseproto.GetLicenseResourceRequest) (*licenseproto.GetLicenseResponse, error) { - ctx, conn, err := getConnection(ctx, services.Licenses) + ctx = common.CreateMetadata(ctx) + conn, err := services.ODIMService.Client(services.Licenses) if err != nil { - return nil, err + return nil, fmt.Errorf("Failed to create client connection: %v", err) } defer conn.Close() licenseService := licenseproto.NewLicensesClient(conn) @@ -69,9 +73,10 @@ func GetLicenseResource(ctx context.Context, req licenseproto.GetLicenseResource // InstallLicenseService will do the rpc call to install License func InstallLicenseService(ctx context.Context, req licenseproto.InstallLicenseRequest) (*licenseproto.GetLicenseResponse, error) { - ctx, conn, err := getConnection(ctx, services.Licenses) + ctx = common.CreateMetadata(ctx) + conn, err := services.ODIMService.Client(services.Licenses) if err != nil { - return nil, err + return nil, fmt.Errorf("Failed to create client connection: %v", err) } defer conn.Close() licenseService := licenseproto.NewLicensesClient(conn) diff --git a/svc-api/rpc/managers.go b/svc-api/rpc/managers.go index 9100d6806..a027773a2 100644 --- a/svc-api/rpc/managers.go +++ b/svc-api/rpc/managers.go @@ -19,6 +19,7 @@ import ( "context" "fmt" + "github.com/ODIM-Project/ODIM/lib-utilities/common" managersproto "github.com/ODIM-Project/ODIM/lib-utilities/proto/managers" "github.com/ODIM-Project/ODIM/lib-utilities/services" ) @@ -30,9 +31,10 @@ var ( // GetManagersCollection will do the rpc call to collect Managers func GetManagersCollection(ctx context.Context, req managersproto.ManagerRequest) (*managersproto.ManagerResponse, error) { - ctx, conn, err := getConnection(ctx, services.Managers) + ctx = common.CreateMetadata(ctx) + conn, err := ClientFunc(services.Managers) if err != nil { - return nil, err + return nil, fmt.Errorf("Failed to create client connection: %v", err) } asService := NewManagersClientFunc(conn) @@ -46,9 +48,10 @@ func GetManagersCollection(ctx context.Context, req managersproto.ManagerRequest // GetManagers will do the rpc calls for the svc-managers func GetManagers(ctx context.Context, req managersproto.ManagerRequest) (*managersproto.ManagerResponse, error) { - ctx, conn, err := getConnection(ctx, services.Managers) + ctx = common.CreateMetadata(ctx) + conn, err := ClientFunc(services.Managers) if err != nil { - return nil, err + return nil, fmt.Errorf("Failed to create client connection: %v", err) } asService := NewManagersClientFunc(conn) @@ -62,9 +65,10 @@ func GetManagers(ctx context.Context, req managersproto.ManagerRequest) (*manage // GetManagersResource will do the rpc calls for the svc-managers func GetManagersResource(ctx context.Context, req managersproto.ManagerRequest) (*managersproto.ManagerResponse, error) { - ctx, conn, err := getConnection(ctx, services.Managers) + ctx = common.CreateMetadata(ctx) + conn, err := ClientFunc(services.Managers) if err != nil { - return nil, err + return nil, fmt.Errorf("Failed to create client connection: %v", err) } asService := NewManagersClientFunc(conn) @@ -78,9 +82,10 @@ func GetManagersResource(ctx context.Context, req managersproto.ManagerRequest) // VirtualMediaInsert will do the rpc calls for the svc-managers func VirtualMediaInsert(ctx context.Context, req managersproto.ManagerRequest) (*managersproto.ManagerResponse, error) { - ctx, conn, err := getConnection(ctx, services.Managers) + ctx = common.CreateMetadata(ctx) + conn, err := ClientFunc(services.Managers) if err != nil { - return nil, err + return nil, fmt.Errorf("Failed to create client connection: %v", err) } asService := NewManagersClientFunc(conn) @@ -94,9 +99,10 @@ func VirtualMediaInsert(ctx context.Context, req managersproto.ManagerRequest) ( // VirtualMediaEject will do the rpc calls for the svc-managers func VirtualMediaEject(ctx context.Context, req managersproto.ManagerRequest) (*managersproto.ManagerResponse, error) { - ctx, conn, err := getConnection(ctx, services.Managers) + ctx = common.CreateMetadata(ctx) + conn, err := ClientFunc(services.Managers) if err != nil { - return nil, err + return nil, fmt.Errorf("Failed to create client connection: %v", err) } asService := NewManagersClientFunc(conn) @@ -110,9 +116,10 @@ func VirtualMediaEject(ctx context.Context, req managersproto.ManagerRequest) (* // GetRemoteAccountService will do the rpc call to collect BMC accounts func GetRemoteAccountService(ctx context.Context, req managersproto.ManagerRequest) (*managersproto.ManagerResponse, error) { - ctx, conn, err := getConnection(ctx, services.Managers) + ctx = common.CreateMetadata(ctx) + conn, err := ClientFunc(services.Managers) if err != nil { - return nil, err + return nil, fmt.Errorf("Failed to create client connection: %v", err) } mService := NewManagersClientFunc(conn) @@ -126,9 +133,10 @@ func GetRemoteAccountService(ctx context.Context, req managersproto.ManagerReque // CreateRemoteAccountService will do the rpc call to create a new BMC account func CreateRemoteAccountService(ctx context.Context, req managersproto.ManagerRequest) (*managersproto.ManagerResponse, error) { - ctx, conn, err := getConnection(ctx, services.Managers) + ctx = common.CreateMetadata(ctx) + conn, err := ClientFunc(services.Managers) if err != nil { - return nil, err + return nil, fmt.Errorf("Failed to create client connection: %v", err) } mService := NewManagersClientFunc(conn) @@ -142,9 +150,10 @@ func CreateRemoteAccountService(ctx context.Context, req managersproto.ManagerRe // UpdateRemoteAccountService will do rpc call to update BMC account func UpdateRemoteAccountService(ctx context.Context, req managersproto.ManagerRequest) (*managersproto.ManagerResponse, error) { - ctx, conn, err := getConnection(ctx, services.Managers) + ctx = common.CreateMetadata(ctx) + conn, err := ClientFunc(services.Managers) if err != nil { - return nil, err + return nil, fmt.Errorf("Failed to create client connection: %v", err) } mService := NewManagersClientFunc(conn) @@ -158,9 +167,10 @@ func UpdateRemoteAccountService(ctx context.Context, req managersproto.ManagerRe // DeleteRemoteAccountService will do the rpc call to delete an existing BMC account func DeleteRemoteAccountService(ctx context.Context, req managersproto.ManagerRequest) (*managersproto.ManagerResponse, error) { - ctx, conn, err := getConnection(ctx, services.Managers) + ctx = common.CreateMetadata(ctx) + conn, err := ClientFunc(services.Managers) if err != nil { - return nil, err + return nil, fmt.Errorf("Failed to create client connection: %v", err) } mService := NewManagersClientFunc(conn) diff --git a/svc-api/rpc/role.go b/svc-api/rpc/role.go index a70c07be5..955e25e54 100644 --- a/svc-api/rpc/role.go +++ b/svc-api/rpc/role.go @@ -19,6 +19,7 @@ import ( "context" "fmt" + "github.com/ODIM-Project/ODIM/lib-utilities/common" roleproto "github.com/ODIM-Project/ODIM/lib-utilities/proto/role" "github.com/ODIM-Project/ODIM/lib-utilities/services" ) @@ -31,9 +32,10 @@ var ( // GetRole defines the RPC call function for // the GetRole from account-session micro service func GetRole(ctx context.Context, req roleproto.GetRoleRequest) (*roleproto.RoleResponse, error) { - ctx, conn, err := getConnection(ctx, services.AccountSession) + ctx = common.CreateMetadata(ctx) + conn, err := ClientFunc(services.AccountSession) if err != nil { - return nil, err + return nil, fmt.Errorf("Failed to create client connection: %v", err) } asService := NewRolesClientFunc(conn) @@ -48,9 +50,10 @@ func GetRole(ctx context.Context, req roleproto.GetRoleRequest) (*roleproto.Role // GetAllRoles defines the RPC call function for // the GetAllRoles from account-session micro service func GetAllRoles(ctx context.Context, req roleproto.GetRoleRequest) (*roleproto.RoleResponse, error) { - ctx, conn, err := getConnection(ctx, services.AccountSession) + ctx = common.CreateMetadata(ctx) + conn, err := ClientFunc(services.AccountSession) if err != nil { - return nil, err + return nil, fmt.Errorf("Failed to create client connection: %v", err) } asService := NewRolesClientFunc(conn) @@ -65,9 +68,10 @@ func GetAllRoles(ctx context.Context, req roleproto.GetRoleRequest) (*roleproto. // UpdateRole defines the RPC call function for // the UpdateRole from account-session micro service func UpdateRole(ctx context.Context, req roleproto.UpdateRoleRequest) (*roleproto.RoleResponse, error) { - ctx, conn, err := getConnection(ctx, services.AccountSession) + ctx = common.CreateMetadata(ctx) + conn, err := ClientFunc(services.AccountSession) if err != nil { - return nil, err + return nil, fmt.Errorf("Failed to create client connection: %v", err) } asService := NewRolesClientFunc(conn) @@ -81,9 +85,10 @@ func UpdateRole(ctx context.Context, req roleproto.UpdateRoleRequest) (*roleprot // DeleteRole defines the RPC call function for the DeleteRole from account-session microservice func DeleteRole(ctx context.Context, req roleproto.DeleteRoleRequest) (*roleproto.RoleResponse, error) { - ctx, conn, err := getConnection(ctx, services.AccountSession) + ctx = common.CreateMetadata(ctx) + conn, err := ClientFunc(services.AccountSession) if err != nil { - return nil, err + return nil, fmt.Errorf("Failed to create client connection: %v", err) } asService := NewRolesClientFunc(conn) diff --git a/svc-api/rpc/sessions.go b/svc-api/rpc/sessions.go index 1f2657da1..d938b4e1d 100644 --- a/svc-api/rpc/sessions.go +++ b/svc-api/rpc/sessions.go @@ -66,9 +66,10 @@ func DoSessionCreationRequest(ctx context.Context, req sessionproto.SessionCreat // DeleteSessionRequest will do the rpc call to delete session func DeleteSessionRequest(ctx context.Context, sessionID, sessionToken string) (*sessionproto.SessionResponse, error) { - ctx, conn, err := getConnection(ctx, services.AccountSession) + ctx = common.CreateMetadata(ctx) + conn, err := ClientFunc(services.AccountSession) if err != nil { - return nil, err + return nil, fmt.Errorf("Failed to create client connection: %v", err) } asService := NewSessionClientFunc(conn) @@ -87,9 +88,10 @@ func DeleteSessionRequest(ctx context.Context, sessionID, sessionToken string) ( // GetSessionRequest will do the rpc call to get session func GetSessionRequest(ctx context.Context, sessionID, sessionToken string) (*sessionproto.SessionResponse, error) { - ctx, conn, err := getConnection(ctx, services.AccountSession) + ctx = common.CreateMetadata(ctx) + conn, err := ClientFunc(services.AccountSession) if err != nil { - return nil, err + return nil, fmt.Errorf("Failed to create client connection: %v", err) } asService := NewSessionClientFunc(conn) @@ -108,9 +110,10 @@ func GetSessionRequest(ctx context.Context, sessionID, sessionToken string) (*se // GetAllActiveSessionRequest will do the rpc call to get session func GetAllActiveSessionRequest(ctx context.Context, sessionID, sessionToken string) (*sessionproto.SessionResponse, error) { - ctx, conn, err := getConnection(ctx, services.AccountSession) + ctx = common.CreateMetadata(ctx) + conn, err := ClientFunc(services.AccountSession) if err != nil { - return nil, err + return nil, fmt.Errorf("Failed to create client connection: %v", err) } asService := NewSessionClientFunc(conn) @@ -129,9 +132,10 @@ func GetAllActiveSessionRequest(ctx context.Context, sessionID, sessionToken str // GetSessionServiceRequest will do the rpc call to check session func GetSessionServiceRequest(ctx context.Context) (*sessionproto.SessionResponse, error) { - ctx, conn, err := getConnection(ctx, services.AccountSession) + ctx = common.CreateMetadata(ctx) + conn, err := ClientFunc(services.AccountSession) if err != nil { - return nil, err + return nil, fmt.Errorf("Failed to create client connection: %v", err) } asService := NewSessionClientFunc(conn) diff --git a/svc-api/rpc/system.go b/svc-api/rpc/system.go index 6add90f7b..f4e170f89 100644 --- a/svc-api/rpc/system.go +++ b/svc-api/rpc/system.go @@ -19,6 +19,7 @@ import ( "context" "fmt" + "github.com/ODIM-Project/ODIM/lib-utilities/common" systemsproto "github.com/ODIM-Project/ODIM/lib-utilities/proto/systems" "github.com/ODIM-Project/ODIM/lib-utilities/services" ) @@ -30,9 +31,10 @@ var ( // GetSystemsCollection will do the rpc call to collect Systems from odimra func GetSystemsCollection(ctx context.Context, req systemsproto.GetSystemsRequest) (*systemsproto.SystemsResponse, error) { - ctx, conn, err := getConnection(ctx, services.Systems) + ctx = common.CreateMetadata(ctx) + conn, err := ClientFunc(services.Systems) if err != nil { - return nil, err + return nil, fmt.Errorf("Failed to create client connection: %v", err) } asService := NewSystemsClientFunc(conn) @@ -46,9 +48,10 @@ func GetSystemsCollection(ctx context.Context, req systemsproto.GetSystemsReques // GetSystemRequestRPC will do the rpc calls for the svc-systems func GetSystemRequestRPC(ctx context.Context, req systemsproto.GetSystemsRequest) (*systemsproto.SystemsResponse, error) { - ctx, conn, err := getConnection(ctx, services.Systems) + ctx = common.CreateMetadata(ctx) + conn, err := ClientFunc(services.Systems) if err != nil { - return nil, err + return nil, fmt.Errorf("Failed to create client connection: %v", err) } asService := NewSystemsClientFunc(conn) @@ -62,9 +65,10 @@ func GetSystemRequestRPC(ctx context.Context, req systemsproto.GetSystemsRequest // GetSystemResource will do the rpc call to collect System Resource func GetSystemResource(ctx context.Context, req systemsproto.GetSystemsRequest) (*systemsproto.SystemsResponse, error) { - ctx, conn, err := getConnection(ctx, services.Systems) + ctx = common.CreateMetadata(ctx) + conn, err := ClientFunc(services.Systems) if err != nil { - return nil, err + return nil, fmt.Errorf("Failed to create client connection: %v", err) } asService := NewSystemsClientFunc(conn) @@ -78,9 +82,10 @@ func GetSystemResource(ctx context.Context, req systemsproto.GetSystemsRequest) // ComputerSystemReset will do the rpc call to reset the computer system func ComputerSystemReset(ctx context.Context, req systemsproto.ComputerSystemResetRequest) (*systemsproto.SystemsResponse, error) { - ctx, conn, err := getConnection(ctx, services.Systems) + ctx = common.CreateMetadata(ctx) + conn, err := ClientFunc(services.Systems) if err != nil { - return nil, err + return nil, fmt.Errorf("Failed to create client connection: %v", err) } asService := NewSystemsClientFunc(conn) @@ -94,9 +99,10 @@ func ComputerSystemReset(ctx context.Context, req systemsproto.ComputerSystemRes // SetDefaultBootOrder will do the rpc call to set the default boot order of computer system func SetDefaultBootOrder(ctx context.Context, req systemsproto.DefaultBootOrderRequest) (*systemsproto.SystemsResponse, error) { - ctx, conn, err := getConnection(ctx, services.Systems) + ctx = common.CreateMetadata(ctx) + conn, err := ClientFunc(services.Systems) if err != nil { - return nil, err + return nil, fmt.Errorf("Failed to create client connection: %v", err) } asService := NewSystemsClientFunc(conn) @@ -110,9 +116,10 @@ func SetDefaultBootOrder(ctx context.Context, req systemsproto.DefaultBootOrderR // ChangeBiosSettings will do the rpc call to change bios settings func ChangeBiosSettings(ctx context.Context, req systemsproto.BiosSettingsRequest) (*systemsproto.SystemsResponse, error) { - ctx, conn, err := getConnection(ctx, services.Systems) + ctx = common.CreateMetadata(ctx) + conn, err := ClientFunc(services.Systems) if err != nil { - return nil, err + return nil, fmt.Errorf("Failed to create client connection: %v", err) } asService := NewSystemsClientFunc(conn) @@ -126,9 +133,10 @@ func ChangeBiosSettings(ctx context.Context, req systemsproto.BiosSettingsReques // ChangeBootOrderSettings will do the rpc call to change Boot Order settings func ChangeBootOrderSettings(ctx context.Context, req systemsproto.BootOrderSettingsRequest) (*systemsproto.SystemsResponse, error) { - ctx, conn, err := getConnection(ctx, services.Systems) + ctx = common.CreateMetadata(ctx) + conn, err := ClientFunc(services.Systems) if err != nil { - return nil, err + return nil, fmt.Errorf("Failed to create client connection: %v", err) } asService := NewSystemsClientFunc(conn) @@ -142,9 +150,10 @@ func ChangeBootOrderSettings(ctx context.Context, req systemsproto.BootOrderSett // CreateVolume will do the rpc call to create a volume under storage func CreateVolume(ctx context.Context, req systemsproto.VolumeRequest) (*systemsproto.SystemsResponse, error) { - ctx, conn, err := getConnection(ctx, services.Systems) + ctx = common.CreateMetadata(ctx) + conn, err := ClientFunc(services.Systems) if err != nil { - return nil, err + return nil, fmt.Errorf("Failed to create client connection: %v", err) } asService := NewSystemsClientFunc(conn) @@ -158,9 +167,10 @@ func CreateVolume(ctx context.Context, req systemsproto.VolumeRequest) (*systems // DeleteVolume will do the rpc call to DeleteVolume a volume under storage func DeleteVolume(ctx context.Context, req systemsproto.VolumeRequest) (*systemsproto.SystemsResponse, error) { - ctx, conn, err := getConnection(ctx, services.Systems) + ctx = common.CreateMetadata(ctx) + conn, err := ClientFunc(services.Systems) if err != nil { - return nil, err + return nil, fmt.Errorf("Failed to create client connection: %v", err) } asService := NewSystemsClientFunc(conn) @@ -174,9 +184,10 @@ func DeleteVolume(ctx context.Context, req systemsproto.VolumeRequest) (*systems // UpdateSecureBoot will do the rpc call to UpdateSecureBoot func UpdateSecureBoot(ctx context.Context, req systemsproto.SecureBootRequest) (*systemsproto.SystemsResponse, error) { - ctx, conn, err := getConnection(ctx, services.Systems) + ctx = common.CreateMetadata(ctx) + conn, err := ClientFunc(services.Systems) if err != nil { - return nil, err + return nil, fmt.Errorf("Failed to create client connection: %v", err) } asService := NewSystemsClientFunc(conn) @@ -190,9 +201,10 @@ func UpdateSecureBoot(ctx context.Context, req systemsproto.SecureBootRequest) ( // ResetSecureBoot will do the rpc call to ResetSecureBoot func ResetSecureBoot(ctx context.Context, req systemsproto.SecureBootRequest) (*systemsproto.SystemsResponse, error) { - ctx, conn, err := getConnection(ctx, services.Systems) + ctx = common.CreateMetadata(ctx) + conn, err := ClientFunc(services.Systems) if err != nil { - return nil, err + return nil, fmt.Errorf("Failed to create client connection: %v", err) } asService := NewSystemsClientFunc(conn) diff --git a/svc-api/rpc/task.go b/svc-api/rpc/task.go index c7ce961fe..4ffa0603c 100644 --- a/svc-api/rpc/task.go +++ b/svc-api/rpc/task.go @@ -34,9 +34,10 @@ var ( // DeleteTaskRequest will do the rpc calls for the svc-task DeleteTask func DeleteTaskRequest(ctx context.Context, req *taskproto.GetTaskRequest) (*taskproto.TaskResponse, error) { - ctx, conn, err := getConnection(ctx, services.Tasks) - if err != nil { - return nil, err + ctx = common.CreateMetadata(ctx) + conn, connErr := ClientFunc(services.Tasks) + if connErr != nil { + return nil, fmt.Errorf("Failed to create client connection: %v", connErr) } asService := NewGetTaskServiceClientFunc(conn) @@ -58,9 +59,10 @@ func DeleteTaskRequest(ctx context.Context, req *taskproto.GetTaskRequest) (*tas // GetTaskRequest will do the rpc calls for the svc-task GetTaskStatus func GetTaskRequest(ctx context.Context, req *taskproto.GetTaskRequest) (*taskproto.TaskResponse, error) { - ctx, conn, err := getConnection(ctx, services.Tasks) - if err != nil { - return nil, err + ctx = common.CreateMetadata(ctx) + conn, connErr := ClientFunc(services.Tasks) + if connErr != nil { + return nil, fmt.Errorf("Failed to create client connection: %v", connErr) } asService := NewGetTaskServiceClientFunc(conn) @@ -82,9 +84,10 @@ func GetTaskRequest(ctx context.Context, req *taskproto.GetTaskRequest) (*taskpr // GetSubTasks will do the rpc calls for the svc-task GetSubTasks func GetSubTasks(ctx context.Context, req *taskproto.GetTaskRequest) (*taskproto.TaskResponse, error) { - ctx, conn, err := getConnection(ctx, services.Tasks) - if err != nil { - return nil, err + ctx = common.CreateMetadata(ctx) + conn, connErr := ClientFunc(services.Tasks) + if connErr != nil { + return nil, fmt.Errorf("Failed to create client connection: %v", connErr) } tService := NewGetTaskServiceClientFunc(conn) @@ -106,9 +109,10 @@ func GetSubTasks(ctx context.Context, req *taskproto.GetTaskRequest) (*taskproto // GetSubTask will do the rpc calls for the svc-task GetSubTask func GetSubTask(ctx context.Context, req *taskproto.GetTaskRequest) (*taskproto.TaskResponse, error) { - ctx, conn, err := getConnection(ctx, services.Tasks) - if err != nil { - return nil, err + ctx = common.CreateMetadata(ctx) + conn, connErr := ClientFunc(services.Tasks) + if connErr != nil { + return nil, fmt.Errorf("Failed to create client connection: %v", connErr) } tService := NewGetTaskServiceClientFunc(conn) @@ -130,9 +134,10 @@ func GetSubTask(ctx context.Context, req *taskproto.GetTaskRequest) (*taskproto. // GetTaskMonitor will do the rpc calls for the svc-task GetTaskMonitor func GetTaskMonitor(ctx context.Context, req *taskproto.GetTaskRequest) (*taskproto.TaskResponse, error) { - ctx, conn, err := getConnection(ctx, services.Tasks) - if err != nil { - return nil, err + ctx = common.CreateMetadata(ctx) + conn, connErr := ClientFunc(services.Tasks) + if connErr != nil { + return nil, fmt.Errorf("Failed to create client connection: %v", connErr) } tService := NewGetTaskServiceClientFunc(conn) @@ -154,9 +159,10 @@ func GetTaskMonitor(ctx context.Context, req *taskproto.GetTaskRequest) (*taskpr // TaskCollection will perform the rpc call to svc-task TaskCollection func TaskCollection(ctx context.Context, req *taskproto.GetTaskRequest) (*taskproto.TaskResponse, error) { - ctx, conn, err := getConnection(ctx, services.Tasks) - if err != nil { - return nil, err + ctx = common.CreateMetadata(ctx) + conn, connErr := ClientFunc(services.Tasks) + if connErr != nil { + return nil, fmt.Errorf("Failed to create client connection: %v", connErr) } tService := NewGetTaskServiceClientFunc(conn) @@ -178,9 +184,10 @@ func TaskCollection(ctx context.Context, req *taskproto.GetTaskRequest) (*taskpr // GetTaskService will perform the rpc call to svc-task GetTaskService func GetTaskService(ctx context.Context, req *taskproto.GetTaskRequest) (*taskproto.TaskResponse, error) { - ctx, conn, err := getConnection(ctx, services.Tasks) - if err != nil { - return nil, err + ctx = common.CreateMetadata(ctx) + conn, connErr := ClientFunc(services.Tasks) + if connErr != nil { + return nil, fmt.Errorf("Failed to create client connection: %v", connErr) } tService := NewGetTaskServiceClientFunc(conn) diff --git a/svc-api/rpc/telemetry.go b/svc-api/rpc/telemetry.go index ab8715231..fa860c201 100644 --- a/svc-api/rpc/telemetry.go +++ b/svc-api/rpc/telemetry.go @@ -19,6 +19,7 @@ import ( "context" "fmt" + "github.com/ODIM-Project/ODIM/lib-utilities/common" teleproto "github.com/ODIM-Project/ODIM/lib-utilities/proto/telemetry" "github.com/ODIM-Project/ODIM/lib-utilities/services" ) @@ -31,9 +32,10 @@ var ( // DoGetTelemetryService defines the RPC call function for // the GetTelemetryService from telemetry micro service func DoGetTelemetryService(ctx context.Context, req teleproto.TelemetryRequest) (*teleproto.TelemetryResponse, error) { - ctx, conn, err := getConnection(ctx, services.Telemetry) + ctx = common.CreateMetadata(ctx) + conn, err := ClientFunc(services.Telemetry) if err != nil { - return nil, err + return nil, fmt.Errorf("Failed to create client connection: %v", err) } telemetry := NewTelemetryClientFunc(conn) @@ -49,9 +51,10 @@ func DoGetTelemetryService(ctx context.Context, req teleproto.TelemetryRequest) // DoGetMetricDefinitionCollection defines the RPC call function for // the GetMetricDefinitionCollection from telemetry micro service func DoGetMetricDefinitionCollection(ctx context.Context, req teleproto.TelemetryRequest) (*teleproto.TelemetryResponse, error) { - ctx, conn, err := getConnection(ctx, services.Telemetry) + ctx = common.CreateMetadata(ctx) + conn, err := ClientFunc(services.Telemetry) if err != nil { - return nil, err + return nil, fmt.Errorf("Failed to create client connection: %v", err) } telemetry := NewTelemetryClientFunc(conn) @@ -66,9 +69,10 @@ func DoGetMetricDefinitionCollection(ctx context.Context, req teleproto.Telemetr // DoGetMetricReportDefinitionCollection defines the RPC call function for // the GetMetricReportDefinitionCollection from telemetry micro service func DoGetMetricReportDefinitionCollection(ctx context.Context, req teleproto.TelemetryRequest) (*teleproto.TelemetryResponse, error) { - ctx, conn, err := getConnection(ctx, services.Telemetry) + ctx = common.CreateMetadata(ctx) + conn, err := ClientFunc(services.Telemetry) if err != nil { - return nil, err + return nil, fmt.Errorf("Failed to create client connection: %v", err) } telemetry := NewTelemetryClientFunc(conn) @@ -83,9 +87,10 @@ func DoGetMetricReportDefinitionCollection(ctx context.Context, req teleproto.Te // DoGetMetricReportCollection defines the RPC call function for // the GetMetricReportCollection from telemetry micro service func DoGetMetricReportCollection(ctx context.Context, req teleproto.TelemetryRequest) (*teleproto.TelemetryResponse, error) { - ctx, conn, err := getConnection(ctx, services.Telemetry) + ctx = common.CreateMetadata(ctx) + conn, err := ClientFunc(services.Telemetry) if err != nil { - return nil, err + return nil, fmt.Errorf("Failed to create client connection: %v", err) } telemetry := NewTelemetryClientFunc(conn) @@ -101,9 +106,10 @@ func DoGetMetricReportCollection(ctx context.Context, req teleproto.TelemetryReq // DoGetTriggerCollection defines the RPC call function for // the GetTriggerCollection from telemetry micro service func DoGetTriggerCollection(ctx context.Context, req teleproto.TelemetryRequest) (*teleproto.TelemetryResponse, error) { - ctx, conn, err := getConnection(ctx, services.Telemetry) + ctx = common.CreateMetadata(ctx) + conn, err := ClientFunc(services.Telemetry) if err != nil { - return nil, err + return nil, fmt.Errorf("Failed to create client connection: %v", err) } telemetry := NewTelemetryClientFunc(conn) @@ -119,9 +125,10 @@ func DoGetTriggerCollection(ctx context.Context, req teleproto.TelemetryRequest) // DoGetMetricDefinition defines the RPC call function for // the GetMetricDefinition from telemetry micro service func DoGetMetricDefinition(ctx context.Context, req teleproto.TelemetryRequest) (*teleproto.TelemetryResponse, error) { - ctx, conn, err := getConnection(ctx, services.Telemetry) + ctx = common.CreateMetadata(ctx) + conn, err := ClientFunc(services.Telemetry) if err != nil { - return nil, err + return nil, fmt.Errorf("Failed to create client connection: %v", err) } telemetry := NewTelemetryClientFunc(conn) @@ -137,9 +144,10 @@ func DoGetMetricDefinition(ctx context.Context, req teleproto.TelemetryRequest) // DoGetMetricReportDefinition defines the RPC call function for // the GetMetricReportDefinition from telemetry micro service func DoGetMetricReportDefinition(ctx context.Context, req teleproto.TelemetryRequest) (*teleproto.TelemetryResponse, error) { - ctx, conn, err := getConnection(ctx, services.Telemetry) + ctx = common.CreateMetadata(ctx) + conn, err := ClientFunc(services.Telemetry) if err != nil { - return nil, err + return nil, fmt.Errorf("Failed to create client connection: %v", err) } telemetry := NewTelemetryClientFunc(conn) @@ -155,9 +163,10 @@ func DoGetMetricReportDefinition(ctx context.Context, req teleproto.TelemetryReq // DoGetMetricReport defines the RPC call function for // the GetMetricReport from telemetry micro service func DoGetMetricReport(ctx context.Context, req teleproto.TelemetryRequest) (*teleproto.TelemetryResponse, error) { - ctx, conn, err := getConnection(ctx, services.Telemetry) + ctx = common.CreateMetadata(ctx) + conn, err := ClientFunc(services.Telemetry) if err != nil { - return nil, err + return nil, fmt.Errorf("Failed to create client connection: %v", err) } telemetry := NewTelemetryClientFunc(conn) @@ -173,9 +182,10 @@ func DoGetMetricReport(ctx context.Context, req teleproto.TelemetryRequest) (*te // DoGetTrigger defines the RPC call function for // the GetTrigger from telemetry micro service func DoGetTrigger(ctx context.Context, req teleproto.TelemetryRequest) (*teleproto.TelemetryResponse, error) { - ctx, conn, err := getConnection(ctx, services.Telemetry) + ctx = common.CreateMetadata(ctx) + conn, err := ClientFunc(services.Telemetry) if err != nil { - return nil, err + return nil, fmt.Errorf("Failed to create client connection: %v", err) } telemetry := NewTelemetryClientFunc(conn) @@ -191,9 +201,10 @@ func DoGetTrigger(ctx context.Context, req teleproto.TelemetryRequest) (*telepro // DoUpdateTrigger defines the RPC call function for // the UpdateTrigger from telemetry micro service func DoUpdateTrigger(ctx context.Context, req teleproto.TelemetryRequest) (*teleproto.TelemetryResponse, error) { - ctx, conn, err := getConnection(ctx, services.Telemetry) + ctx = common.CreateMetadata(ctx) + conn, err := ClientFunc(services.Telemetry) if err != nil { - return nil, err + return nil, fmt.Errorf("Failed to create client connection: %v", err) } telemetry := NewTelemetryClientFunc(conn) From f0eb38a00103f95985c5e5e9a4911dd372510f6b Mon Sep 17 00:00:00 2001 From: Banoshi Date: Mon, 19 Jun 2023 23:20:46 +0530 Subject: [PATCH 12/19] updated response of remote account service endpoint to match the latest schema --- lib-dmtf/model/Chassis.go | 5 +- lib-dmtf/model/accountService.go | 4 +- lib-dmtf/model/common.go | 2 +- lib-dmtf/model/port.go | 12 +- lib-dmtf/model/power.go | 2 +- lib-dmtf/model/task.go | 436 +++++++++++++++--------------- lib-dmtf/model/telemetry.go | 32 +-- lib-dmtf/model/thermal.go | 2 +- lib-utilities/common/constants.go | 2 + svc-managers/managers/managers.go | 1 + 10 files changed, 252 insertions(+), 246 deletions(-) diff --git a/lib-dmtf/model/Chassis.go b/lib-dmtf/model/Chassis.go index 82483acac..84520895a 100644 --- a/lib-dmtf/model/Chassis.go +++ b/lib-dmtf/model/Chassis.go @@ -115,7 +115,7 @@ type SysLog struct { LowestSeverity string `json:"LowestSeverity,omitempty"` } -//Entries redfish structure +// Entries redfish structure type Entries struct { Oid string `json:"@odata.id"` } @@ -164,8 +164,11 @@ type Status struct { // SaveInMemory will create the Chassis in inmemory DB, with key as UUID // Takes: +// // none as function parameter, but takes c of type *Chassis as a pointer receiver implicitly. +// // Returns: +// // err of type error // // On Sucess - returns nil value diff --git a/lib-dmtf/model/accountService.go b/lib-dmtf/model/accountService.go index 784ced1ff..244beebae 100644 --- a/lib-dmtf/model/accountService.go +++ b/lib-dmtf/model/accountService.go @@ -290,8 +290,8 @@ type ExternalAccountProvider struct { LDAPService *LDAPService `json:"LDAPService,omitempty"` OAuth2Service *OAuth2Service `json:"OAuth2Service,omitempty"` PasswordSet bool `json:"PasswordSet,omitempty"` - Priority int `json:"Priority"` - RemoteRoleMapping *RoleMapping `json:"RemoteRoleMapping"` + Priority int `json:"Priority,omitempty"` + RemoteRoleMapping []*RoleMapping `json:"RemoteRoleMapping,omitempty"` ServiceAddresses []string `json:"ServiceAddresses,omitempty"` ServiceEnabled bool `json:"ServiceEnabled,omitempty"` TACACSplusService *TACACSplusService `json:"TACACSplusService,omitempty"` diff --git a/lib-dmtf/model/common.go b/lib-dmtf/model/common.go index 529ff69ab..31a58055c 100644 --- a/lib-dmtf/model/common.go +++ b/lib-dmtf/model/common.go @@ -30,7 +30,7 @@ type Redundancy struct { RedundancySetCount int `json:"RedundancySet@odata.count,omitempty"` } -//Identifier redfish structure +// Identifier redfish structure type Identifier struct { DurableName string `json:"DurableName,omitempty"` DurableNameFormat string `json:"DurableNameFormat,omitempty"` diff --git a/lib-dmtf/model/port.go b/lib-dmtf/model/port.go index fb2497f0a..da9e9460f 100644 --- a/lib-dmtf/model/port.go +++ b/lib-dmtf/model/port.go @@ -14,7 +14,7 @@ package model -//Port is the redfish Port model according to the 2020.3 release +// Port is the redfish Port model according to the 2020.3 release type Port struct { ODataContext string `json:"@odata.context,omitempty"` ODataEtag string `json:"@odata.etag,omitempty"` @@ -76,7 +76,7 @@ type FunctionBandwidth struct { NetworkDeviceFunction *Link `json:"NetworkDeviceFunctions,omitempty"` } -//PortEthernet redfish model +// PortEthernet redfish model type PortEthernet struct { FlowControlConfiguration string `json:"FlowControlConfiguration,omitempty"` FlowControlStatus string `json:"FlowControlStatus,omitempty"` @@ -101,7 +101,7 @@ type LLDP struct { PortIDSubtype string `json:"PortIdSubtype,omitempty"` } -//FibreChannel redfish model +// FibreChannel redfish model type FibreChannel struct { FabricName string `json:"FabricName,omitempty"` NumberDiscoveredRemotePorts int `json:"NumberDiscoveredRemotePorts,omitempty"` @@ -109,7 +109,7 @@ type FibreChannel struct { AssociatedWorldWideNames []string `json:"AssociatedWorldWideNames,omitempty"` } -//LinkConfiguration redfish model +// LinkConfiguration redfish model type LinkConfiguration struct { AutoSpeedNegotiationCapable bool `json:"AutoSpeedNegotiationCapable,omitempty"` AutoSpeedNegotiationEnabled bool `json:"AutoSpeedNegotiationEnabled,omitempty"` @@ -117,13 +117,13 @@ type LinkConfiguration struct { ConfiguredNetworkLinks []CapableLinkSpeedGbps `json:"ConfiguredNetworkLinks,omitempty"` } -//CapableLinkSpeedGbps redfish model +// CapableLinkSpeedGbps redfish model type CapableLinkSpeedGbps struct { ConfiguredLinkSpeedGbps []float64 `json:"ConfiguredLinkSpeedGbps,omitempty"` ConfiguredWidth int `json:"ConfiguredWidth,omitempty"` } -//PortLinks Port link redfish model +// PortLinks Port link redfish model type PortLinks struct { AssociatedEndpoints []Link `json:"AssociatedEndpoints,omitempty"` ConnectedPorts []Link `json:"ConnectedPorts,omitempty"` diff --git a/lib-dmtf/model/power.go b/lib-dmtf/model/power.go index 67dcb9b76..b5a033b97 100644 --- a/lib-dmtf/model/power.go +++ b/lib-dmtf/model/power.go @@ -14,7 +14,7 @@ package model -//Power is the redfish Power model according to the 2020.3 release +// Power is the redfish Power model according to the 2020.3 release type Power struct { ODataContext string `json:"@odata.context,omitempty"` ODataEtag string `json:"@odata.etag,omitempty"` diff --git a/lib-dmtf/model/task.go b/lib-dmtf/model/task.go index 51d8ae531..0d150e197 100644 --- a/lib-dmtf/model/task.go +++ b/lib-dmtf/model/task.go @@ -1,218 +1,218 @@ -//(C) Copyright [2023] Hewlett Packard Enterprise Development LP -// -//Licensed under the Apache License, Version 2.0 (the "License"); you may -//not use this file except in compliance with the License. You may obtain -//a copy of the License at -// -// http://www.apache.org/licenses/LICENSE-2.0 -// -//Unless required by applicable law or agreed to in writing, software -//distributed under the License is distributed on an "AS IS" BASIS, WITHOUT -//WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the -//License for the specific language governing permissions and limitations -// under the License. - -package model - -// TaskState - This property shall indicate the state of the task. -type TaskState string - -// Health - This property shall represent the health state of the resource -// without considering its dependent resources. The values shall conform -// to those defined in the Redfish Specification. -type Health string - -// OverWritePolicy - This property shall contain the overwrite policy for -// completed tasks. This property shall indicate if the task service -// overwrites completed task information. -type OverWritePolicy string - -// State - The known state of the resource, such as, enabled. -// This property shall indicate whether and why this component is available. -type State string - -// The below constants are the states that a task can have -const ( - // This value shall represent that the task is newly created, - // but has not started. - TaskStateNew TaskState = "New" - // This value shall represent that the task is starting. - TaskStateStarting TaskState = "Starting" - // This value shall represent that the task is executing. - TaskStateRunning TaskState = "Running" - // This value shall represent that the task has been suspended - // but is expected to restart and is therefore not complete. - TaskStateSuspended TaskState = "Suspended" - // This value shall represent that the task has been interrupted - // but is expected to restart and is therefore not complete. - TaskStateInterrupted TaskState = "Interrupted" - // This value shall represent that the task is pending some condition - // and has not yet begun to execute. - TaskStatePending TaskState = "Pending" - // This value shall represent that the task is stopping - // but is not yet complete. - TaskStateStopping TaskState = "Stopping" - // This value shall represent that the task completed successfully - // or with warnings. - TaskStateCompleted TaskState = "Completed" - // This value shall represent that the task is complete - // because an operator killed it. - TaskStateKilled TaskState = "Killed" - // This value shall represent that the task completed with errors. - TaskStateException TaskState = "Exception" - // This value shall represent that the task is now running as a service - // and expected to continue operation until stopped or killed. - TaskStateService TaskState = "Service" - // "This value shall represent that the task is in the process of - // being cancelled. - TaskStateCancelling TaskState = "Cancelling" - // This value shall represent that either a DELETE operation - // on a task monitor or Task resource or by an internal process - // cancelled the task. - TaskStateCancelled TaskState = "Cancelled" -) - -// Below constants represents the health conditions that a resource can have -const ( - // Health is Normal. - HealthOK Health = "OK" - // A condition requires attention. - HealthWarning Health = "Warning" - // A critical condition requires immediate attention - HealthCritical Health = "Critical" -) - -// Below constants represents the overwrite policies -const ( - // Completed tasks are not automatically overwritten. - OverWritePolicyManual OverWritePolicy = "Manual" - // Oldest completed tasks are overwritten. - OverWritePolicyOldest OverWritePolicy = "Oldest" -) - -// Below constants represents the states that a resource can have -const ( - // This function or resource is enabled. - StateEnabled State = "Enabled" - // This function or resource is disabled. - StateDisabled State = "Disabled" - // This function or resource is enabled but awaits an external action - // to activate it. - StateStandbyOffline State = "StandbyOffline" - // This function or resource is part of a redundancy set and awaits a - // failover or other external action to activate it. - StateStandbySpare State = "StandbySpare" - // This function or resource is undergoing testing, or is in the process - // of capturing information for debugging. - StateInTest State = "InTest" - //This function or resource is starting. - StateStarting State = "Starting" - // This function or resource is either not present or detected. - StateAbsent State = "Absent" - // This function or resource is present but cannot be used. - StateUnavailableOffline State = "UnavailableOffline" - // The element does not process any commands but queues new requests. - StateDeferring State = "Deferring" - // The element is enabled but only processes a restricted set of commands. - StateQuiesced State = "Quiesced" - // The element is updating and might be unavailable or degraded. - StateUpdating State = "Updating" - //The element quality is within the acceptable range of operation. - StateQualified State = "Qualified" -) - -// Task - The Task schema contains information about a task that the Redfish -// task service schedules or executes. Tasks represent operations that take -// more time than a client typically wants to wait. -// Reference : Task.v1_6_1.json -type Task struct { - ODataContext string `json:"@odata.context,omitempty"` - ODataEtag string `json:"@odata.etag,omitempty"` - ODataID string `json:"@odata.id"` - ODataType string `json:"@odata.type"` - Actions *OemActions `json:"Actions,omitempty"` - Description string `json:"Description,omitempty"` - EndTime string `json:"EndTime,omitempty"` - EstimatedDuration string `json:"EstimatedDuration,omitempty"` - HidePayload bool `json:"HidePayload,omitempty"` - ID string `json:"Id"` - Messages []*Message `json:"Messages,omitempty"` - Name string `json:"Name"` - Payload *Payload `json:"Payload,omitempty"` - PercentComplete int `json:"PercentComplete,omitempty"` - StartTime string `json:"StartTime,omitempty"` - SubTasks *Link `json:"TaskCollection,omitempty"` - TaskMonitor string `json:"TaskMonitor,omitempty"` - TaskState TaskState `json:"TaskState,omitempty"` - TaskStatus Health `json:"TaskStatus,omitempty"` -} - -// Message - This type shall contain a message that the Redfish service returns, -// as described in the Redfish Specification. -type Message struct { - Message string `json:"Message,omitempty"` - MessageArgs []string `json:"MessageArgs,omitempty"` - MessageID string `json:"MessageId"` - Oem Oem `json:"Oem,omitempty"` - RelatedProperties []string `json:"RelatedProperties,omitempty"` - Resolution string `json:"Resolution,omitempty"` - Severity string `json:"Severity,omitempty"` -} - -// Payload - This type shall contain information detailing the HTTP and JSON -// payload information for executing this task. This property shall not be -// included in the response if the HidePayload property is `true`. -type Payload struct { - HTTPHeaders []string `json:"HttpHeaders,omitempty"` - HTTPOperation string `json:"HttpOperation,omitempty"` - JSONBody string `json:"JsonBody,omitempty"` - TargetURI string `json:"TargetUri,omitempty"` -} - -// TaskCollection - This Resource shall represent a Resource Collection of -// Task instances for a Redfish implementation. -// Reference : TTaskCollection.json -type TaskCollection struct { - ODataContext string `json:"@odata.context,omitempty"` - ODataID string `json:"@odata.id"` - ODataType string `json:"@odata.type"` - ODataETag string `json:"@odata.etag"` - Description string `json:"Description,omitempty"` - Members []*Link `json:"Members,omitempty"` - MembersCount int `json:"Members@odata.count"` - MembersNextLink string `json:"Members@odata.nextLink,omitempty"` - Name string `json:"Name"` - Oem Oem `json:"Oem,omitempty"` -} - -// TaskService schema describes a task service that enables management of -// long-duration operations, includes the properties for the task service -// itself, and has links to the resource collection of tasks. -type TaskService struct { - ODataContext string `json:"@odata.context,omitempty"` - ODataEtag string `json:"@odata.etag,omitempty"` - ODataID string `json:"@odata.id"` - ODataType string `json:"@odata.type"` - Actions *OemActions `json:"Actions,omitempty"` - CompletedTaskOverWritePolicy OverWritePolicy `json:"CompletedTaskOverWritePolicy,omitempty"` - DateTime string `json:"DateTime,omitempty"` - Description string `json:"Description,omitempty"` - ID string `json:"Id"` - LifeCycleEventOnTaskStateChange bool `json:"LifeCycleEventOnTaskStateChange,omitempty"` - Name string `json:"Name"` - Oem Oem `json:"Oem,omitempty"` - ServiceEnabled bool `json:"ServiceEnabled,omitempty"` - Status *TaskServiceStatus `json:"Status,omitempty"` - TaskAutoDeleteTimeoutMinutes bool `json:"TaskAutoDeleteTimeoutMinutes,omitempty"` - Tasks *Link `json:"Tasks,omitempty"` -} - -// TaskServiceStatus - This type shall contain any status or health -// properties of Task service -type TaskServiceStatus struct { - Conditions []*Conditions `json:"Conditions,omitempty"` - Health Health `json:"Health,omitempty"` - HealthRollup Health `json:"HealthRollup,omitempty"` - Oem Oem `json:"Oem,omitempty"` - State State `json:"State,omitempty"` -} +//(C) Copyright [2023] Hewlett Packard Enterprise Development LP +// +//Licensed under the Apache License, Version 2.0 (the "License"); you may +//not use this file except in compliance with the License. You may obtain +//a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +//Unless required by applicable law or agreed to in writing, software +//distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +//WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +//License for the specific language governing permissions and limitations +// under the License. + +package model + +// TaskState - This property shall indicate the state of the task. +type TaskState string + +// Health - This property shall represent the health state of the resource +// without considering its dependent resources. The values shall conform +// to those defined in the Redfish Specification. +type Health string + +// OverWritePolicy - This property shall contain the overwrite policy for +// completed tasks. This property shall indicate if the task service +// overwrites completed task information. +type OverWritePolicy string + +// State - The known state of the resource, such as, enabled. +// This property shall indicate whether and why this component is available. +type State string + +// The below constants are the states that a task can have +const ( + // This value shall represent that the task is newly created, + // but has not started. + TaskStateNew TaskState = "New" + // This value shall represent that the task is starting. + TaskStateStarting TaskState = "Starting" + // This value shall represent that the task is executing. + TaskStateRunning TaskState = "Running" + // This value shall represent that the task has been suspended + // but is expected to restart and is therefore not complete. + TaskStateSuspended TaskState = "Suspended" + // This value shall represent that the task has been interrupted + // but is expected to restart and is therefore not complete. + TaskStateInterrupted TaskState = "Interrupted" + // This value shall represent that the task is pending some condition + // and has not yet begun to execute. + TaskStatePending TaskState = "Pending" + // This value shall represent that the task is stopping + // but is not yet complete. + TaskStateStopping TaskState = "Stopping" + // This value shall represent that the task completed successfully + // or with warnings. + TaskStateCompleted TaskState = "Completed" + // This value shall represent that the task is complete + // because an operator killed it. + TaskStateKilled TaskState = "Killed" + // This value shall represent that the task completed with errors. + TaskStateException TaskState = "Exception" + // This value shall represent that the task is now running as a service + // and expected to continue operation until stopped or killed. + TaskStateService TaskState = "Service" + // "This value shall represent that the task is in the process of + // being cancelled. + TaskStateCancelling TaskState = "Cancelling" + // This value shall represent that either a DELETE operation + // on a task monitor or Task resource or by an internal process + // cancelled the task. + TaskStateCancelled TaskState = "Cancelled" +) + +// Below constants represents the health conditions that a resource can have +const ( + // Health is Normal. + HealthOK Health = "OK" + // A condition requires attention. + HealthWarning Health = "Warning" + // A critical condition requires immediate attention + HealthCritical Health = "Critical" +) + +// Below constants represents the overwrite policies +const ( + // Completed tasks are not automatically overwritten. + OverWritePolicyManual OverWritePolicy = "Manual" + // Oldest completed tasks are overwritten. + OverWritePolicyOldest OverWritePolicy = "Oldest" +) + +// Below constants represents the states that a resource can have +const ( + // This function or resource is enabled. + StateEnabled State = "Enabled" + // This function or resource is disabled. + StateDisabled State = "Disabled" + // This function or resource is enabled but awaits an external action + // to activate it. + StateStandbyOffline State = "StandbyOffline" + // This function or resource is part of a redundancy set and awaits a + // failover or other external action to activate it. + StateStandbySpare State = "StandbySpare" + // This function or resource is undergoing testing, or is in the process + // of capturing information for debugging. + StateInTest State = "InTest" + //This function or resource is starting. + StateStarting State = "Starting" + // This function or resource is either not present or detected. + StateAbsent State = "Absent" + // This function or resource is present but cannot be used. + StateUnavailableOffline State = "UnavailableOffline" + // The element does not process any commands but queues new requests. + StateDeferring State = "Deferring" + // The element is enabled but only processes a restricted set of commands. + StateQuiesced State = "Quiesced" + // The element is updating and might be unavailable or degraded. + StateUpdating State = "Updating" + //The element quality is within the acceptable range of operation. + StateQualified State = "Qualified" +) + +// Task - The Task schema contains information about a task that the Redfish +// task service schedules or executes. Tasks represent operations that take +// more time than a client typically wants to wait. +// Reference : Task.v1_6_1.json +type Task struct { + ODataContext string `json:"@odata.context,omitempty"` + ODataEtag string `json:"@odata.etag,omitempty"` + ODataID string `json:"@odata.id"` + ODataType string `json:"@odata.type"` + Actions *OemActions `json:"Actions,omitempty"` + Description string `json:"Description,omitempty"` + EndTime string `json:"EndTime,omitempty"` + EstimatedDuration string `json:"EstimatedDuration,omitempty"` + HidePayload bool `json:"HidePayload,omitempty"` + ID string `json:"Id"` + Messages []*Message `json:"Messages,omitempty"` + Name string `json:"Name"` + Payload *Payload `json:"Payload,omitempty"` + PercentComplete int `json:"PercentComplete,omitempty"` + StartTime string `json:"StartTime,omitempty"` + SubTasks *Link `json:"TaskCollection,omitempty"` + TaskMonitor string `json:"TaskMonitor,omitempty"` + TaskState TaskState `json:"TaskState,omitempty"` + TaskStatus Health `json:"TaskStatus,omitempty"` +} + +// Message - This type shall contain a message that the Redfish service returns, +// as described in the Redfish Specification. +type Message struct { + Message string `json:"Message,omitempty"` + MessageArgs []string `json:"MessageArgs,omitempty"` + MessageID string `json:"MessageId"` + Oem Oem `json:"Oem,omitempty"` + RelatedProperties []string `json:"RelatedProperties,omitempty"` + Resolution string `json:"Resolution,omitempty"` + Severity string `json:"Severity,omitempty"` +} + +// Payload - This type shall contain information detailing the HTTP and JSON +// payload information for executing this task. This property shall not be +// included in the response if the HidePayload property is `true`. +type Payload struct { + HTTPHeaders []string `json:"HttpHeaders,omitempty"` + HTTPOperation string `json:"HttpOperation,omitempty"` + JSONBody string `json:"JsonBody,omitempty"` + TargetURI string `json:"TargetUri,omitempty"` +} + +// TaskCollection - This Resource shall represent a Resource Collection of +// Task instances for a Redfish implementation. +// Reference : TTaskCollection.json +type TaskCollection struct { + ODataContext string `json:"@odata.context,omitempty"` + ODataID string `json:"@odata.id"` + ODataType string `json:"@odata.type"` + ODataETag string `json:"@odata.etag"` + Description string `json:"Description,omitempty"` + Members []*Link `json:"Members,omitempty"` + MembersCount int `json:"Members@odata.count"` + MembersNextLink string `json:"Members@odata.nextLink,omitempty"` + Name string `json:"Name"` + Oem Oem `json:"Oem,omitempty"` +} + +// TaskService schema describes a task service that enables management of +// long-duration operations, includes the properties for the task service +// itself, and has links to the resource collection of tasks. +type TaskService struct { + ODataContext string `json:"@odata.context,omitempty"` + ODataEtag string `json:"@odata.etag,omitempty"` + ODataID string `json:"@odata.id"` + ODataType string `json:"@odata.type"` + Actions *OemActions `json:"Actions,omitempty"` + CompletedTaskOverWritePolicy OverWritePolicy `json:"CompletedTaskOverWritePolicy,omitempty"` + DateTime string `json:"DateTime,omitempty"` + Description string `json:"Description,omitempty"` + ID string `json:"Id"` + LifeCycleEventOnTaskStateChange bool `json:"LifeCycleEventOnTaskStateChange,omitempty"` + Name string `json:"Name"` + Oem Oem `json:"Oem,omitempty"` + ServiceEnabled bool `json:"ServiceEnabled,omitempty"` + Status *TaskServiceStatus `json:"Status,omitempty"` + TaskAutoDeleteTimeoutMinutes bool `json:"TaskAutoDeleteTimeoutMinutes,omitempty"` + Tasks *Link `json:"Tasks,omitempty"` +} + +// TaskServiceStatus - This type shall contain any status or health +// properties of Task service +type TaskServiceStatus struct { + Conditions []*Conditions `json:"Conditions,omitempty"` + Health Health `json:"Health,omitempty"` + HealthRollup Health `json:"HealthRollup,omitempty"` + Oem Oem `json:"Oem,omitempty"` + State State `json:"State,omitempty"` +} diff --git a/lib-dmtf/model/telemetry.go b/lib-dmtf/model/telemetry.go index 160fbfbf2..421a15d57 100644 --- a/lib-dmtf/model/telemetry.go +++ b/lib-dmtf/model/telemetry.go @@ -52,7 +52,7 @@ type CalculationParam struct { SourceMetric string `json:"SourceMetric,omitempty"` } -//MetricReportDefinitions schema describes set of metrics that are collected into a metric report +// MetricReportDefinitions schema describes set of metrics that are collected into a metric report type MetricReportDefinitions struct { ODataID string `json:"@odata.id"` ODataType string `json:"@odata.type"` @@ -77,7 +77,7 @@ type MetricReportDefinitions struct { Oem *Oem `json:"Oem,omitempty"` } -//Schedule defines a series of occurrences +// Schedule defines a series of occurrences type Schedule struct { EnabledDaysOfMonth []string `json:"EnabledDaysOfMonth,omitempty"` EnabledDaysOfWeek []string `json:"EnabledDaysOfWeek,omitempty"` @@ -90,9 +90,9 @@ type Schedule struct { RecurrenceInterval string `json:"RecurrenceInterval,omitempty"` } -//Metric defines the list of metrics to include in the metric report. The -//metrics might include metric properties or calculations -//applied to a metric property +// Metric defines the list of metrics to include in the metric report. The +// metrics might include metric properties or calculations +// applied to a metric property type Metric struct { CollectionDuration string `json:"CollectionDuration,omitempty"` CollectionFunction string `json:"CollectionFunction,omitempty"` @@ -102,19 +102,19 @@ type Metric struct { Oem *Oem `json:"Oem,omitempty"` } -//MetricLink defines the links to other resources that are related to MetricReportDefinition resource +// MetricLink defines the links to other resources that are related to MetricReportDefinition resource type MetricLink struct { Oem *Oem `json:"Oem,omitempty"` Triggers []Oid `json:"Triggers,omitempty"` TriggersCount int `json:"Triggers@odata.count,omitempty"` } -//Oid defines the odata id link +// Oid defines the odata id link type Oid struct { ODataID string `json:"@odata.id"` } -//MetricReports schema represents a set of collected metrics +// MetricReports schema represents a set of collected metrics type MetricReports struct { ODataID string `json:"@odata.id"` ODataType string `json:"@odata.type"` @@ -130,7 +130,7 @@ type MetricReports struct { Actions *OemActions `json:"Actions,omitempty"` } -//MetricValue defines an array of metric values for the metered items of this metric report. +// MetricValue defines an array of metric values for the metered items of this metric report. type MetricValue struct { MetricDefinition Oid `json:"MetricDefinition,omitempty"` MetricID string `json:"MetricId,omitempty"` @@ -140,7 +140,7 @@ type MetricValue struct { Timestamp string `json:"Timestamp,omitempty"` } -//Triggers schema describes a trigger that applies to metrics. +// Triggers schema describes a trigger that applies to metrics. type Triggers struct { ODataID string `json:"@odata.id"` ODataType string `json:"@odata.type"` @@ -161,7 +161,7 @@ type Triggers struct { Oem *Oem `json:"Oem,omitempty"` } -//NumericThresholds defines when a numeric metric triggers +// NumericThresholds defines when a numeric metric triggers type NumericThresholds struct { LowerCritical Threshold `json:"LowerCritical,omitempty"` LowerWarning Threshold `json:"LowerWarning,omitempty"` @@ -169,21 +169,21 @@ type NumericThresholds struct { UpperWarning Threshold `json:"UpperWarning,omitempty"` } -//Threshold schema for numeric threshold +// Threshold schema for numeric threshold type Threshold struct { Activation string `json:"Activation,omitempty"` DwellTime string `json:"DwellTime,omitempty"` Reading int `json:"Reading,omitempty"` } -//TriggerLinks defines links to resources associated with Triggers +// TriggerLinks defines links to resources associated with Triggers type TriggerLinks struct { MetricReportDefinitions []Oid `json:"MetricReportDefinitions,omitempty"` Oem *Oem `json:"Oem,omitempty"` MetricReportDefinitionsCount int `json:"MetricReportDefinitions@odata.count,omitempty"` } -//DiscreteTrigger holds the list of discrete triggers +// DiscreteTrigger holds the list of discrete triggers type DiscreteTrigger struct { DwellTime string `json:"DwellTime,omitempty"` Name string `json:"Name,omitempty"` @@ -191,8 +191,8 @@ type DiscreteTrigger struct { Value string `json:"Value,omitempty"` } -//WildCard defines the wildcards and their substitution values for the entries -//in the MetricProperties array property. +// WildCard defines the wildcards and their substitution values for the entries +// in the MetricProperties array property. type WildCard struct { Name string `json:"Name,omitempty"` Values []string `json:"Values,omitempty"` diff --git a/lib-dmtf/model/thermal.go b/lib-dmtf/model/thermal.go index f51d00b4d..67168f570 100644 --- a/lib-dmtf/model/thermal.go +++ b/lib-dmtf/model/thermal.go @@ -16,7 +16,7 @@ package model //Thermal 1.7.1 (deprecated) -//Thermal is the redfish Power model according to the 2020.3 release +// Thermal is the redfish Power model according to the 2020.3 release type Thermal struct { ODataContext string `json:"@odata.context,omitempty"` ODataEtag string `json:"@odata.etag,omitempty"` diff --git a/lib-utilities/common/constants.go b/lib-utilities/common/constants.go index 955be3fc7..d658159e8 100644 --- a/lib-utilities/common/constants.go +++ b/lib-utilities/common/constants.go @@ -152,6 +152,8 @@ const ( AggregationSourceType = "#AggregationSource.v1_2_0.AggregationSource" //ChassisType has version to be returned with Chassis Service ChassisType = "#Chassis.v1_20_0.Chassis" + //ManagerAccountServiceType has version to be returned with RemoteAccountService response + ManagerAccountServiceType = "#AccountService.v1_13_0.AccountService" // AggregateSubscriptionIndex is a index name which required for indexing // subscription of aggregate AggregateSubscriptionIndex = "AggregateToHost" diff --git a/svc-managers/managers/managers.go b/svc-managers/managers/managers.go index 0f3b0595a..26665341c 100644 --- a/svc-managers/managers/managers.go +++ b/svc-managers/managers/managers.go @@ -625,6 +625,7 @@ func convertToRedfishModel(ctx context.Context, uri, data string) interface{} { if URIRegexRemAcc.MatchString(uri) { var resource dmtf.AccountService json.Unmarshal([]byte(data), &resource) + resource.ODataType = common.ManagerAccountServiceType return resource } else if URIRegexAcc.MatchString(uri) { var resource dmtf.ManagerAccount From 99cb29f57a928b875e0cbb5a9ad881fee443d96c Mon Sep 17 00:00:00 2001 From: Jeevan Kamkar <68366409+jeevan-kamkar@users.noreply.github.com> Date: Mon, 26 Jun 2023 15:07:52 +0530 Subject: [PATCH 13/19] Update docker-images.sh --- docker-images.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docker-images.sh b/docker-images.sh index af1fa5083..c291acb5d 100755 --- a/docker-images.sh +++ b/docker-images.sh @@ -24,7 +24,7 @@ declare -A images_list=(\ ["fabrics"]="4.1" \ ["kafka"]="3.0" \ ["managers"]="6.0" \ - ["redis"]="4.0" \ + ["redis"]="5.0" \ ["systems"]="6.0" \ ["task"]="5.0" \ ["telemetry"]="3.1"\ From 49b4336ee3881bceb316bf1cf67af0ac7f916031 Mon Sep 17 00:00:00 2001 From: Banoshi Date: Tue, 27 Jun 2023 11:40:09 +0530 Subject: [PATCH 14/19] refactor code in svc-account-session --- svc-account-session/account/create.go | 48 +----- svc-account-session/account/create_test.go | 142 +++--------------- svc-account-session/account/delete.go | 24 +-- svc-account-session/account/delete_test.go | 25 +-- svc-account-session/account/getaccounts.go | 56 ++----- .../account/getaccounts_test.go | 37 +---- svc-account-session/account/update.go | 87 +++-------- svc-account-session/account/update_test.go | 99 ++---------- svc-account-session/role/create.go | 73 +-------- svc-account-session/role/create_test.go | 65 ++------ svc-account-session/role/delete.go | 53 +------ svc-account-session/role/delete_test.go | 65 ++------ svc-account-session/role/getroles.go | 37 +---- svc-account-session/role/getroles_test.go | 39 +---- svc-account-session/role/update.go | 85 +---------- svc-account-session/role/update_test.go | 51 +------ svc-account-session/rpc/account.go | 24 +-- svc-account-session/rpc/auth.go | 4 +- svc-account-session/rpc/role.go | 20 +-- svc-account-session/rpc/sessions.go | 62 ++++---- svc-account-session/session/create_test.go | 38 +---- 21 files changed, 183 insertions(+), 951 deletions(-) diff --git a/svc-account-session/account/create.go b/svc-account-session/account/create.go index 41c59ae78..73e0f5465 100644 --- a/svc-account-session/account/create.go +++ b/svc-account-session/account/create.go @@ -93,17 +93,7 @@ func (e *ExternalInterface) Create(ctx context.Context, req *accountproto.Create errorMessage := errorLogPrefix + "User does not have the privilege of creating a new user" resp.StatusCode = http.StatusForbidden resp.StatusMessage = response.InsufficientPrivilege - args := response.Args{ - Code: response.GeneralError, - Message: "", - ErrorArgs: []response.ErrArgs{ - response.ErrArgs{ - StatusMessage: resp.StatusMessage, - ErrorMessage: errorMessage, - MessageArgs: []interface{}{}, - }, - }, - } + args := GetResponseArgs(resp.StatusMessage, errorMessage, []interface{}{}) resp.Body = args.CreateGenericErrorResponse() auth.CustomAuthLog(ctx, session.Token, errorMessage, resp.StatusCode) return resp, fmt.Errorf(errorMessage) @@ -113,17 +103,7 @@ func (e *ExternalInterface) Create(ctx context.Context, req *accountproto.Create errorMessage := errorLogPrefix + "Mandatory fields " + invalidParams + " are empty" resp.StatusCode = http.StatusBadRequest resp.StatusMessage = response.PropertyMissing - args := response.Args{ - Code: response.GeneralError, - Message: "", - ErrorArgs: []response.ErrArgs{ - response.ErrArgs{ - StatusMessage: resp.StatusMessage, - ErrorMessage: errorMessage, - MessageArgs: []interface{}{invalidParams}, - }, - }, - } + args := GetResponseArgs(resp.StatusMessage, errorMessage, []interface{}{invalidParams}) resp.Body = args.CreateGenericErrorResponse() l.LogWithFields(ctx).Error(errorMessage) return resp, fmt.Errorf(errorMessage) @@ -137,17 +117,7 @@ func (e *ExternalInterface) Create(ctx context.Context, req *accountproto.Create errorMessage := err.Error() resp.StatusCode = http.StatusBadRequest resp.StatusMessage = response.PropertyValueFormatError - args := response.Args{ - Code: response.GeneralError, - Message: "", - ErrorArgs: []response.ErrArgs{ - response.ErrArgs{ - StatusMessage: resp.StatusMessage, - ErrorMessage: errorMessage, - MessageArgs: []interface{}{user.Password, "Password"}, - }, - }, - } + args := GetResponseArgs(resp.StatusMessage, errorMessage, []interface{}{user.Password, "Password"}) resp.Body = args.CreateGenericErrorResponse() l.LogWithFields(ctx).Error(errorMessage) return resp, err @@ -164,17 +134,7 @@ func (e *ExternalInterface) Create(ctx context.Context, req *accountproto.Create if errors.DBKeyAlreadyExist == cerr.ErrNo() { resp.StatusCode = http.StatusConflict resp.StatusMessage = response.ResourceAlreadyExists - args := response.Args{ - Code: response.GeneralError, - Message: "", - ErrorArgs: []response.ErrArgs{ - response.ErrArgs{ - StatusMessage: response.ResourceAlreadyExists, - ErrorMessage: errorMessage, - MessageArgs: []interface{}{"ManagerAccount", "Id", user.UserName}, - }, - }, - } + args := GetResponseArgs(response.ResourceAlreadyExists, errorMessage, []interface{}{"ManagerAccount", "Id", user.UserName}) resp.Body = args.CreateGenericErrorResponse() } else { resp.CreateInternalErrorResponse(errorMessage) diff --git a/svc-account-session/account/create_test.go b/svc-account-session/account/create_test.go index 07ddcc9ed..c0d59312f 100644 --- a/svc-account-session/account/create_test.go +++ b/svc-account-session/account/create_test.go @@ -58,127 +58,27 @@ func TestCreate(t *testing.T) { acc := getMockExternalInterface() common.SetUpMockConfig() ctx := mockContext() - errArgs := response.Args{ - Code: response.GeneralError, - Message: "", - ErrorArgs: []response.ErrArgs{ - response.ErrArgs{ - StatusMessage: response.InsufficientPrivilege, - ErrorMessage: "failed to create account for the user testUser3: User does not have the privilege of creating a new user", - MessageArgs: []interface{}{}, - }, - }, - } - errArg := response.Args{ - Code: response.GeneralError, - Message: "", - ErrorArgs: []response.ErrArgs{ - response.ErrArgs{ - StatusMessage: response.PropertyValueFormatError, - ErrorMessage: "error: invalid password, password length is less than the minimum length", - MessageArgs: []interface{}{"Password", "Password"}, - }, - }, - } - errArg2 := response.Args{ - Code: response.GeneralError, - Message: "", - ErrorArgs: []response.ErrArgs{ - response.ErrArgs{ - StatusMessage: response.PropertyValueFormatError, - ErrorMessage: "error: invalid password, username is present inside the password", - MessageArgs: []interface{}{"testUser4", "Password"}, - }, - }, - } - errArg3 := response.Args{ - Code: response.GeneralError, - Message: "", - ErrorArgs: []response.ErrArgs{ - response.ErrArgs{ - StatusMessage: response.PropertyValueFormatError, - ErrorMessage: "error: invalid password, password length is greater than the maximum length", - MessageArgs: []interface{}{"Password1234567890", "Password"}, - }, - }, - } - errArg4 := response.Args{ - Code: response.GeneralError, - Message: "", - ErrorArgs: []response.ErrArgs{ - response.ErrArgs{ - StatusMessage: response.PropertyValueFormatError, - ErrorMessage: "error: invalid password, password should contain minimum One Upper case, One Lower case, One Number and One Special character", - MessageArgs: []interface{}{"password@123", "Password"}, - }, - }, - } - errArg5 := response.Args{ - Code: response.GeneralError, - Message: "", - ErrorArgs: []response.ErrArgs{ - response.ErrArgs{ - StatusMessage: response.PropertyValueFormatError, - ErrorMessage: "error: invalid password, password should contain minimum One Upper case, One Lower case, One Number and One Special character", - MessageArgs: []interface{}{"PASSWORD@123", "Password"}, - }, - }, - } - errArg6 := response.Args{ - Code: response.GeneralError, - Message: "", - ErrorArgs: []response.ErrArgs{ - response.ErrArgs{ - StatusMessage: response.PropertyValueFormatError, - ErrorMessage: "error: invalid password, password should contain minimum One Upper case, One Lower case, One Number and One Special character", - MessageArgs: []interface{}{"Password@ABC", "Password"}, - }, - }, - } - errArg7 := response.Args{ - Code: response.GeneralError, - Message: "", - ErrorArgs: []response.ErrArgs{ - response.ErrArgs{ - StatusMessage: response.PropertyValueFormatError, - ErrorMessage: "error: invalid password, password should contain minimum One Upper case, One Lower case, One Number and One Special character", - MessageArgs: []interface{}{"P\\assword123", "Password"}, - }, - }, - } - errArg1 := response.Args{ - Code: response.GeneralError, - Message: "", - ErrorArgs: []response.ErrArgs{ - response.ErrArgs{ - StatusMessage: response.PropertyMissing, - ErrorMessage: "failed to create account for the user : Mandatory fields UserName Password RoleID are empty", - MessageArgs: []interface{}{"UserName Password RoleID"}, - }, - }, - } - errArgu := response.Args{ - Code: response.GeneralError, - Message: "", - ErrorArgs: []response.ErrArgs{ - response.ErrArgs{ - StatusMessage: response.ResourceAlreadyExists, - ErrorMessage: "failed to create account for the user existingUser: error: data with key existingUser already exists", - MessageArgs: []interface{}{"ManagerAccount", "Id", "existingUser"}, - }, - }, - } - errArgum := response.Args{ - Code: response.GeneralError, - Message: "", - ErrorArgs: []response.ErrArgs{ - response.ErrArgs{ - StatusMessage: response.ResourceNotFound, - ErrorMessage: "failed to create account for the user testUser1: Invalid RoleID present: error while trying to get role details: error: Invalid RoleID xyz present", - MessageArgs: []interface{}{"Role", "xyz"}, - }, - }, - } + errArgs := GetResponseArgs(response.InsufficientPrivilege, "failed to create account for the user testUser3: User does not have the privilege of creating a new user", []interface{}{}) + + errArg := GetResponseArgs(response.PropertyValueFormatError, "error: invalid password, password length is less than the minimum length", []interface{}{"Password", "Password"}) + + errArg2 := GetResponseArgs(response.PropertyValueFormatError, "error: invalid password, username is present inside the password", []interface{}{"testUser4", "Password"}) + + errArg3 := GetResponseArgs(response.PropertyValueFormatError, "error: invalid password, password length is greater than the maximum length", []interface{}{"Password1234567890", "Password"}) + + errArg4 := GetResponseArgs(response.PropertyValueFormatError, "error: invalid password, password should contain minimum One Upper case, One Lower case, One Number and One Special character", []interface{}{"password@123", "Password"}) + + errArg5 := GetResponseArgs(response.PropertyValueFormatError, "error: invalid password, password should contain minimum One Upper case, One Lower case, One Number and One Special character", []interface{}{"PASSWORD@123", "Password"}) + + errArg6 := GetResponseArgs(response.PropertyValueFormatError, "error: invalid password, password should contain minimum One Upper case, One Lower case, One Number and One Special character", []interface{}{"Password@ABC", "Password"}) + + errArg7 := GetResponseArgs(response.PropertyValueFormatError, "error: invalid password, password should contain minimum One Upper case, One Lower case, One Number and One Special character", []interface{}{"P\\assword123", "Password"}) + + errArg1 := GetResponseArgs(response.PropertyMissing, "failed to create account for the user : Mandatory fields UserName Password RoleID are empty", []interface{}{"UserName Password RoleID"}) + + errArgu := GetResponseArgs(response.ResourceAlreadyExists, "failed to create account for the user existingUser: error: data with key existingUser already exists", []interface{}{"ManagerAccount", "Id", "existingUser"}) + + errArgum := GetResponseArgs(response.ResourceNotFound, "failed to create account for the user testUser1: Invalid RoleID present: error while trying to get role details: error: Invalid RoleID xyz present", []interface{}{"Role", "xyz"}) type args struct { req *accountproto.CreateAccountRequest session *asmodel.Session diff --git a/svc-account-session/account/delete.go b/svc-account-session/account/delete.go index f336c5411..425b05c22 100644 --- a/svc-account-session/account/delete.go +++ b/svc-account-session/account/delete.go @@ -68,17 +68,7 @@ func Delete(ctx context.Context, session *asmodel.Session, accountID string) res errorMessage := errorLogPrefix + session.UserName + " does not have the privilege to delete user" resp.StatusCode = http.StatusForbidden resp.StatusMessage = response.InsufficientPrivilege - args := response.Args{ - Code: response.GeneralError, - Message: "", - ErrorArgs: []response.ErrArgs{ - response.ErrArgs{ - StatusMessage: resp.StatusMessage, - ErrorMessage: errorMessage, - MessageArgs: []interface{}{}, - }, - }, - } + args := GetResponseArgs(resp.StatusMessage, errorMessage, []interface{}{}) resp.Body = args.CreateGenericErrorResponse() auth.CustomAuthLog(ctx, session.Token, errorMessage, resp.StatusCode) return resp @@ -90,17 +80,7 @@ func Delete(ctx context.Context, session *asmodel.Session, accountID string) res if errors.DBKeyNotFound == derr.ErrNo() { resp.StatusCode = http.StatusNotFound resp.StatusMessage = response.ResourceNotFound - args := response.Args{ - Code: response.GeneralError, - Message: "", - ErrorArgs: []response.ErrArgs{ - response.ErrArgs{ - StatusMessage: resp.StatusMessage, - ErrorMessage: errorMessage, - MessageArgs: []interface{}{"Account", accountID}, - }, - }, - } + args := GetResponseArgs(resp.StatusMessage, errorMessage, []interface{}{"Account", accountID}) resp.Body = args.CreateGenericErrorResponse() } else { resp.CreateInternalErrorResponse(errorMessage) diff --git a/svc-account-session/account/delete_test.go b/svc-account-session/account/delete_test.go index 933b65e85..7ebfc5ed8 100644 --- a/svc-account-session/account/delete_test.go +++ b/svc-account-session/account/delete_test.go @@ -58,28 +58,9 @@ func TestDelete(t *testing.T) { common.SetUpMockConfig() - errArgs := response.Args{ - Code: response.GeneralError, - Message: "", - ErrorArgs: []response.ErrArgs{ - response.ErrArgs{ - StatusMessage: response.ResourceNotFound, - ErrorMessage: "failed to delete account xyz: no data with the with key xyz found", - MessageArgs: []interface{}{"Account", "xyz"}, - }, - }, - } - errArg := response.Args{ - Code: response.GeneralError, - Message: "", - ErrorArgs: []response.ErrArgs{ - response.ErrArgs{ - StatusMessage: response.InsufficientPrivilege, - ErrorMessage: "failed to delete account 2: SomeOne does not have the privilege to delete user", - MessageArgs: []interface{}{}, - }, - }, - } + errArgs := GetResponseArgs(response.ResourceNotFound, "failed to delete account xyz: no data with the with key xyz found", []interface{}{"Account", "xyz"}) + + errArg := GetResponseArgs(response.InsufficientPrivilege, "failed to delete account 2: SomeOne does not have the privilege to delete user", []interface{}{}) ctx := mockContext() type args struct { session *asmodel.Session diff --git a/svc-account-session/account/getaccounts.go b/svc-account-session/account/getaccounts.go index d0b3026b7..71b837a86 100644 --- a/svc-account-session/account/getaccounts.go +++ b/svc-account-session/account/getaccounts.go @@ -55,17 +55,7 @@ func GetAllAccounts(ctx context.Context, session *asmodel.Session) response.RPC errorMessage := errLogPrefix + "User " + session.UserName + " does not have the privilege to view all users" resp.StatusCode = http.StatusForbidden resp.StatusMessage = response.InsufficientPrivilege - args := response.Args{ - Code: response.GeneralError, - Message: "", - ErrorArgs: []response.ErrArgs{ - response.ErrArgs{ - StatusMessage: resp.StatusMessage, - ErrorMessage: errorMessage, - MessageArgs: []interface{}{}, - }, - }, - } + args := GetResponseArgs(resp.StatusMessage, errorMessage, []interface{}{}) resp.Body = args.CreateGenericErrorResponse() auth.CustomAuthLog(ctx, session.Token, errorMessage, resp.StatusCode) return resp @@ -97,10 +87,8 @@ func GetAllAccounts(ctx context.Context, session *asmodel.Session) response.RPC } commonResponse.CreateGenericResponse(resp.StatusMessage) - commonResponse.Message = "" commonResponse.ID = "" - commonResponse.MessageID = "" - commonResponse.Severity = "" + commonResponse = mapEmptyValuesResponseFields(commonResponse) resp.Body = asresponse.List{ Response: commonResponse, MembersCount: len(users), @@ -136,17 +124,7 @@ func GetAccount(ctx context.Context, session *asmodel.Session, accountID string) errorMessage := errLogPrefix + session.UserName + " does not have the privilege to view other user's details" resp.StatusCode = http.StatusForbidden resp.StatusMessage = response.InsufficientPrivilege - args := response.Args{ - Code: response.GeneralError, - Message: "", - ErrorArgs: []response.ErrArgs{ - response.ErrArgs{ - StatusMessage: resp.StatusMessage, - ErrorMessage: errorMessage, - MessageArgs: []interface{}{}, - }, - }, - } + args := GetResponseArgs(resp.StatusMessage, errorMessage, []interface{}{}) resp.Body = args.CreateGenericErrorResponse() auth.CustomAuthLog(ctx, session.Token, errorMessage, resp.StatusCode) return resp @@ -160,17 +138,7 @@ func GetAccount(ctx context.Context, session *asmodel.Session, accountID string) if errors.DBKeyNotFound == err.ErrNo() { resp.StatusCode = http.StatusNotFound resp.StatusMessage = response.ResourceNotFound - args := response.Args{ - Code: response.GeneralError, - Message: "", - ErrorArgs: []response.ErrArgs{ - response.ErrArgs{ - StatusMessage: resp.StatusMessage, - ErrorMessage: errorMessage, - MessageArgs: []interface{}{"Account", accountID}, - }, - }, - } + args := GetResponseArgs(resp.StatusMessage, errorMessage, []interface{}{"Account", accountID}) resp.Body = args.CreateGenericErrorResponse() } else { resp.CreateInternalErrorResponse(errorMessage) @@ -187,9 +155,7 @@ func GetAccount(ctx context.Context, session *asmodel.Session, accountID string) } commonResponse.CreateGenericResponse(resp.StatusMessage) - commonResponse.Message = "" - commonResponse.MessageID = "" - commonResponse.Severity = "" + commonResponse = mapEmptyValuesResponseFields(commonResponse) resp.Body = asresponse.Account{ Response: commonResponse, UserName: user.UserName, @@ -239,9 +205,7 @@ func GetAccountService(ctx context.Context) response.RPC { } commonResponse.CreateGenericResponse(resp.StatusMessage) - commonResponse.Message = "" - commonResponse.MessageID = "" - commonResponse.Severity = "" + commonResponse = mapEmptyValuesResponseFields(commonResponse) resp.Body = asresponse.AccountService{ Response: commonResponse, //TODO: Yet to implement AccountService state and health @@ -262,3 +226,11 @@ func GetAccountService(ctx context.Context) response.RPC { return resp } + +// mapEmptyValuesResponseFields maps empty string values to Messsage, MessageID and Severity field of Response struct +func mapEmptyValuesResponseFields(commonResponse response.Response) response.Response { + commonResponse.Message = "" + commonResponse.MessageID = "" + commonResponse.Severity = "" + return commonResponse +} diff --git a/svc-account-session/account/getaccounts_test.go b/svc-account-session/account/getaccounts_test.go index 4be1ce290..8804e776a 100644 --- a/svc-account-session/account/getaccounts_test.go +++ b/svc-account-session/account/getaccounts_test.go @@ -56,17 +56,7 @@ func TestGetAllAccounts(t *testing.T) { t.Fatalf("Error in creating mock admin user %v", err) } - errArgs := response.Args{ - Code: response.GeneralError, - Message: "", - ErrorArgs: []response.ErrArgs{ - response.ErrArgs{ - StatusMessage: response.InsufficientPrivilege, - ErrorMessage: "failed to fetch accounts : User SomeOne does not have the privilege to view all users", - MessageArgs: []interface{}{}, - }, - }, - } + errArgs := GetResponseArgs(response.InsufficientPrivilege, "failed to fetch accounts : User SomeOne does not have the privilege to view all users", []interface{}{}) ctx := mockContext() type args struct { session *asmodel.Session @@ -152,28 +142,9 @@ func TestGetAccount(t *testing.T) { accountID string } - errArg := response.Args{ - Code: response.GeneralError, - Message: "", - ErrorArgs: []response.ErrArgs{ - response.ErrArgs{ - StatusMessage: response.InsufficientPrivilege, - ErrorMessage: "failed to fetch the account testUser1: testUser2 does not have the privilege to view other user's details", - MessageArgs: []interface{}{}, - }, - }, - } - errArg1 := response.Args{ - Code: response.GeneralError, - Message: "", - ErrorArgs: []response.ErrArgs{ - response.ErrArgs{ - StatusMessage: response.ResourceNotFound, - ErrorMessage: "failed to fetch the account testUser4: error while trying to get user: no data with the with key testUser4 found", - MessageArgs: []interface{}{"Account", "testUser4"}, - }, - }, - } + errArg := GetResponseArgs(response.InsufficientPrivilege, "failed to fetch the account testUser1: testUser2 does not have the privilege to view other user's details", []interface{}{}) + + errArg1 := GetResponseArgs(response.ResourceNotFound, "failed to fetch the account testUser4: error while trying to get user: no data with the with key testUser4 found", []interface{}{"Account", "testUser4"}) tests := []struct { name string diff --git a/svc-account-session/account/update.go b/svc-account-session/account/update.go index c73a287a8..e07caab18 100644 --- a/svc-account-session/account/update.go +++ b/svc-account-session/account/update.go @@ -118,17 +118,7 @@ func (e *ExternalInterface) Update(ctx context.Context, req *accountproto.Update errorMessage := errorLogPrefix + "Invalid RoleID " + requestUser.RoleID + " present" resp.StatusCode = http.StatusBadRequest resp.StatusMessage = response.PropertyValueNotInList - args := response.Args{ - Code: response.GeneralError, - Message: "", - ErrorArgs: []response.ErrArgs{ - response.ErrArgs{ - StatusMessage: resp.StatusMessage, - ErrorMessage: errorMessage, - MessageArgs: []interface{}{requestUser.RoleID, "RoleID"}, - }, - }, - } + args := GetResponseArgs(resp.StatusMessage, errorMessage, []interface{}{requestUser.RoleID, "RoleID"}) resp.Body = args.CreateGenericErrorResponse() l.LogWithFields(ctx).Error(errorMessage) return resp @@ -146,17 +136,7 @@ func (e *ExternalInterface) Update(ctx context.Context, req *accountproto.Update if errors.DBKeyNotFound == gerr.ErrNo() { resp.StatusCode = http.StatusNotFound resp.StatusMessage = response.ResourceNotFound - args := response.Args{ - Code: response.GeneralError, - Message: "", - ErrorArgs: []response.ErrArgs{ - response.ErrArgs{ - StatusMessage: resp.StatusMessage, - ErrorMessage: errorMessage, - MessageArgs: []interface{}{"Account", id}, - }, - }, - } + args := GetResponseArgs(resp.StatusMessage, errorMessage, []interface{}{"Account", id}) resp.Body = args.CreateGenericErrorResponse() } else { resp.CreateInternalErrorResponse(errorMessage) @@ -170,17 +150,7 @@ func (e *ExternalInterface) Update(ctx context.Context, req *accountproto.Update errorMessage := errorLogPrefix + "User does not have the privilege of updating other accounts" resp.StatusCode = http.StatusForbidden resp.StatusMessage = response.InsufficientPrivilege - args := response.Args{ - Code: response.GeneralError, - Message: "", - ErrorArgs: []response.ErrArgs{ - response.ErrArgs{ - StatusMessage: resp.StatusMessage, - ErrorMessage: errorMessage, - MessageArgs: []interface{}{}, - }, - }, - } + args := GetResponseArgs(resp.StatusMessage, errorMessage, []interface{}{}) resp.Body = args.CreateGenericErrorResponse() auth.CustomAuthLog(ctx, session.Token, errorMessage, resp.StatusCode) return resp @@ -195,17 +165,7 @@ func (e *ExternalInterface) Update(ctx context.Context, req *accountproto.Update errorMessage := errorLogPrefix + "User does not have the privilege of updating any account role, including his own account" resp.StatusCode = http.StatusForbidden resp.StatusMessage = response.InsufficientPrivilege - args := response.Args{ - Code: response.GeneralError, - Message: "", - ErrorArgs: []response.ErrArgs{ - response.ErrArgs{ - StatusMessage: resp.StatusMessage, - ErrorMessage: errorMessage, - MessageArgs: []interface{}{}, - }, - }, - } + args := GetResponseArgs(resp.StatusMessage, errorMessage, []interface{}{}) resp.Body = args.CreateGenericErrorResponse() auth.CustomAuthLog(ctx, session.Token, errorMessage, resp.StatusCode) return resp @@ -218,17 +178,7 @@ func (e *ExternalInterface) Update(ctx context.Context, req *accountproto.Update errorMessage := errorLogPrefix + "Roles, user is associated with, doesn't allow changing own or other users password" resp.StatusCode = http.StatusForbidden resp.StatusMessage = response.InsufficientPrivilege - args := response.Args{ - Code: response.GeneralError, - Message: "", - ErrorArgs: []response.ErrArgs{ - response.ErrArgs{ - StatusMessage: resp.StatusMessage, - ErrorMessage: errorMessage, - MessageArgs: []interface{}{}, - }, - }, - } + args := GetResponseArgs(resp.StatusMessage, errorMessage, []interface{}{}) resp.Body = args.CreateGenericErrorResponse() auth.CustomAuthLog(ctx, session.Token, errorMessage, resp.StatusCode) return resp @@ -239,17 +189,7 @@ func (e *ExternalInterface) Update(ctx context.Context, req *accountproto.Update errorMessage := err.Error() resp.StatusCode = http.StatusBadRequest resp.StatusMessage = response.PropertyValueFormatError - args := response.Args{ - Code: response.GeneralError, - Message: "", - ErrorArgs: []response.ErrArgs{ - response.ErrArgs{ - StatusMessage: resp.StatusMessage, - ErrorMessage: errorMessage, - MessageArgs: []interface{}{requestUser.Password, "Password"}, - }, - }, - } + args := GetResponseArgs(resp.StatusMessage, errorMessage, []interface{}{requestUser.Password, "Password"}) resp.Body = args.CreateGenericErrorResponse() l.LogWithFields(ctx).Error(errorMessage) return resp @@ -303,3 +243,18 @@ func isEmptyRequest(requestBody []byte) bool { } return false } + +// getResponseArgs creates and return Args object with the values provided +func GetResponseArgs(statusMessage string, errorMessage string, messageArgs []interface{}) response.Args { + return response.Args{ + Code: response.GeneralError, + Message: "", + ErrorArgs: []response.ErrArgs{ + response.ErrArgs{ + StatusMessage: statusMessage, + ErrorMessage: errorMessage, + MessageArgs: messageArgs, + }, + }, + } +} diff --git a/svc-account-session/account/update_test.go b/svc-account-session/account/update_test.go index ab3b0e9be..d3be34134 100644 --- a/svc-account-session/account/update_test.go +++ b/svc-account-session/account/update_test.go @@ -59,98 +59,21 @@ func TestUpdate(t *testing.T) { successResponse2.CreateGenericResponse(response.AccountModified) operatorSuccessResponse.CreateGenericResponse(response.AccountModified) - errArg := response.Args{ - Code: response.GeneralError, - Message: "", - ErrorArgs: []response.ErrArgs{ - response.ErrArgs{ - StatusMessage: response.ResourceNotFound, - ErrorMessage: "failed to update the account xyz: Unable to get account: error while trying to get user: no data with the with key xyz found", - MessageArgs: []interface{}{"Account", "xyz"}, - }, - }, - } - errArgs := response.Args{ - Code: response.GeneralError, - Message: "", - ErrorArgs: []response.ErrArgs{ - response.ErrArgs{ - StatusMessage: response.InsufficientPrivilege, - ErrorMessage: "failed to update the account testUser2: User does not have the privilege of updating other accounts", - MessageArgs: []interface{}{}, - }, - }, - } - errArgs5 := response.Args{ - Code: response.GeneralError, - Message: "", - ErrorArgs: []response.ErrArgs{ - response.ErrArgs{ - StatusMessage: response.InsufficientPrivilege, - ErrorMessage: "failed to update the account testUser1: User does not have the privilege of updating other accounts", - MessageArgs: []interface{}{}, - }, - }, - } - errArg4 := response.Args{ - Code: response.GeneralError, - Message: "", - ErrorArgs: []response.ErrArgs{ - response.ErrArgs{ - StatusMessage: response.InsufficientPrivilege, - ErrorMessage: "failed to update the account testUser3: Roles, user is associated with, doesn't allow changing own or other users password", - MessageArgs: []interface{}{}, - }, - }, - } + errArg := GetResponseArgs(response.ResourceNotFound, "failed to update the account xyz: Unable to get account: error while trying to get user: no data with the with key xyz found", []interface{}{"Account", "xyz"}) - errArgs1 := response.Args{ - Code: response.GeneralError, - Message: "", - ErrorArgs: []response.ErrArgs{ - response.ErrArgs{ - StatusMessage: response.InsufficientPrivilege, - ErrorMessage: "failed to update the account testUser3: User does not have the privilege of updating any account role, including his own account", - MessageArgs: []interface{}{}, - }, - }, - } + errArgs := GetResponseArgs(response.InsufficientPrivilege, "failed to update the account testUser2: User does not have the privilege of updating other accounts", []interface{}{}) - errArg2 := response.Args{ - Code: response.GeneralError, - Message: "", - ErrorArgs: []response.ErrArgs{ - response.ErrArgs{ - StatusMessage: response.PropertyValueNotInList, - ErrorMessage: "failed to update the account testUser1: Invalid RoleID xyz present", - MessageArgs: []interface{}{"xyz", "RoleID"}, - }, - }, - } + errArgs5 := GetResponseArgs(response.InsufficientPrivilege, "failed to update the account testUser1: User does not have the privilege of updating other accounts", []interface{}{}) - errArg3 := response.Args{ - Code: response.GeneralError, - Message: "", - ErrorArgs: []response.ErrArgs{ - response.ErrArgs{ - StatusMessage: response.PropertyValueFormatError, - ErrorMessage: "error: invalid password, password length is less than the minimum length", - MessageArgs: []interface{}{"xyz", "Password"}, - }, - }, - } + errArg4 := GetResponseArgs(response.InsufficientPrivilege, "failed to update the account testUser3: Roles, user is associated with, doesn't allow changing own or other users password", []interface{}{}) - errArg5 := response.Args{ - Code: response.GeneralError, - Message: "", - ErrorArgs: []response.ErrArgs{ - response.ErrArgs{ - StatusMessage: response.PropertyMissing, - ErrorMessage: "failed to update the account testUser1: empty request can not be processed", - MessageArgs: []interface{}{"request body"}, - }, - }, - } + errArgs1 := GetResponseArgs(response.InsufficientPrivilege, "failed to update the account testUser3: User does not have the privilege of updating any account role, including his own account", []interface{}{}) + + errArg2 := GetResponseArgs(response.PropertyValueNotInList, "failed to update the account testUser1: Invalid RoleID xyz present", []interface{}{"xyz", "RoleID"}) + + errArg3 := GetResponseArgs(response.PropertyValueFormatError, "error: invalid password, password length is less than the minimum length", []interface{}{"xyz", "Password"}) + + errArg5 := GetResponseArgs(response.PropertyMissing, "failed to update the account testUser1: empty request can not be processed", []interface{}{"request body"}) genArgs := response.Args{ Code: response.GeneralError, diff --git a/svc-account-session/role/create.go b/svc-account-session/role/create.go index bf2d5ed98..3f289bd83 100644 --- a/svc-account-session/role/create.go +++ b/svc-account-session/role/create.go @@ -27,6 +27,7 @@ import ( l "github.com/ODIM-Project/ODIM/lib-utilities/logs" roleproto "github.com/ODIM-Project/ODIM/lib-utilities/proto/role" "github.com/ODIM-Project/ODIM/lib-utilities/response" + "github.com/ODIM-Project/ODIM/svc-account-session/account" "github.com/ODIM-Project/ODIM/svc-account-session/asmodel" "github.com/ODIM-Project/ODIM/svc-account-session/asresponse" "github.com/ODIM-Project/ODIM/svc-account-session/auth" @@ -84,17 +85,7 @@ func Create(ctx context.Context, req *roleproto.RoleRequest, session *asmodel.Se return response } else if err := validate.Var(createRoleReq.ID, "required,is-empty,excludesall=!@#?%&$*"); err != nil { errorMessage := errorLogPrefix + "Invalid create role request" - args := response.Args{ - Code: response.GeneralError, - Message: "", - ErrorArgs: []response.ErrArgs{ - response.ErrArgs{ - StatusMessage: response.PropertyValueNotInList, - ErrorMessage: errorMessage, - MessageArgs: []interface{}{createRoleReq.ID, "RoleId"}, - }, - }, - } + args := account.GetResponseArgs(response.PropertyValueNotInList, errorMessage, []interface{}{createRoleReq.ID, "RoleId"}) resp.StatusCode = http.StatusBadRequest resp.StatusMessage = response.PropertyValueNotInList resp.Body = args.CreateGenericErrorResponse() @@ -108,34 +99,14 @@ func Create(ctx context.Context, req *roleproto.RoleRequest, session *asmodel.Se errorMessage := errorLogPrefix + "User does not have the privilege of creating a new role" resp.StatusCode = int32(status.Code) resp.StatusMessage = status.Message - args := response.Args{ - Code: response.GeneralError, - Message: "", - ErrorArgs: []response.ErrArgs{ - response.ErrArgs{ - StatusMessage: status.Message, - ErrorMessage: errorMessage, - MessageArgs: []interface{}{}, - }, - }, - } + args := account.GetResponseArgs(status.Message, errorMessage, []interface{}{}) resp.Body = args.CreateGenericErrorResponse() auth.CustomAuthLog(ctx, session.Token, errorMessage, resp.StatusCode) return resp } if len(createRoleReq.AssignedPrivileges) == 0 && len(createRoleReq.OEMPrivileges) == 0 { errorMessage := errorLogPrefix + "Both AssignedPrivileges and OemPrivileges cannot be empty." - args := response.Args{ - Code: response.GeneralError, - Message: "", - ErrorArgs: []response.ErrArgs{ - response.ErrArgs{ - StatusMessage: response.PropertyMissing, - ErrorMessage: errorMessage, - MessageArgs: []interface{}{"AssignedPrivileges/OemPrivileges"}, - }, - }, - } + args := account.GetResponseArgs(response.PropertyMissing, errorMessage, []interface{}{"AssignedPrivileges/OemPrivileges"}) resp.StatusCode = http.StatusBadRequest resp.StatusMessage = response.PropertyMissing resp.Body = args.CreateGenericErrorResponse() @@ -149,17 +120,7 @@ func Create(ctx context.Context, req *roleproto.RoleRequest, session *asmodel.Se errorMessage := errorLogPrefix + err.Error() resp.StatusCode = int32(status.Code) resp.StatusMessage = status.Message - args := response.Args{ - Code: response.GeneralError, - Message: "", - ErrorArgs: []response.ErrArgs{ - response.ErrArgs{ - StatusMessage: status.Message, - ErrorMessage: errorMessage, - MessageArgs: messageArgs, - }, - }, - } + args := account.GetResponseArgs(status.Message, errorMessage, messageArgs) resp.Body = args.CreateGenericErrorResponse() l.LogWithFields(ctx).Error(errorMessage) return resp @@ -171,17 +132,7 @@ func Create(ctx context.Context, req *roleproto.RoleRequest, session *asmodel.Se errorMessage := errorLogPrefix + err.Error() resp.StatusCode = int32(status.Code) resp.StatusMessage = status.Message - args := response.Args{ - Code: response.GeneralError, - Message: "", - ErrorArgs: []response.ErrArgs{ - response.ErrArgs{ - StatusMessage: status.Message, - ErrorMessage: errorMessage, - MessageArgs: messageArgs, - }, - }, - } + args := account.GetResponseArgs(status.Message, errorMessage, messageArgs) resp.Body = args.CreateGenericErrorResponse() l.LogWithFields(ctx).Error(errorMessage) return resp @@ -205,17 +156,7 @@ func Create(ctx context.Context, req *roleproto.RoleRequest, session *asmodel.Se } if isPredefined { errorMessage := errorLogPrefix + "Cannot create pre-defined roles" - args := response.Args{ - Code: response.GeneralError, - Message: "", - ErrorArgs: []response.ErrArgs{ - response.ErrArgs{ - StatusMessage: response.InsufficientPrivilege, - ErrorMessage: errorMessage, - MessageArgs: []interface{}{}, - }, - }, - } + args := account.GetResponseArgs(response.InsufficientPrivilege, errorMessage, []interface{}{}) resp.StatusCode = http.StatusForbidden resp.StatusMessage = response.InsufficientPrivilege resp.Body = args.CreateGenericErrorResponse() diff --git a/svc-account-session/role/create_test.go b/svc-account-session/role/create_test.go index c37b04748..f8c54b70a 100644 --- a/svc-account-session/role/create_test.go +++ b/svc-account-session/role/create_test.go @@ -26,6 +26,7 @@ import ( "github.com/ODIM-Project/ODIM/lib-utilities/response" "github.com/ODIM-Project/ODIM/svc-account-session/asmodel" "github.com/ODIM-Project/ODIM/svc-account-session/asresponse" + "github.com/akshata-s-banoshi/Odim-Project/ODIM/svc-account-session/account" ) func mockRedfishRoles() error { @@ -87,61 +88,15 @@ func TestCreate(t *testing.T) { if err != nil { t.Fatalf("Error in creating mock redfish predefined roles %v", err) } - errArgs := response.Args{ - Code: response.GeneralError, - Message: "", - ErrorArgs: []response.ErrArgs{ - response.ErrArgs{ - StatusMessage: response.InsufficientPrivilege, - ErrorMessage: "failed to create role testRole: User does not have the privilege of creating a new role", - MessageArgs: []interface{}{}, - }, - }, - } - errArgsMiss := response.Args{ - Code: response.GeneralError, - Message: "", - ErrorArgs: []response.ErrArgs{ - response.ErrArgs{ - StatusMessage: response.PropertyMissing, - ErrorMessage: "failed to create role testRole: Both AssignedPrivileges and OemPrivileges cannot be empty.", - MessageArgs: []interface{}{"AssignedPrivileges/OemPrivileges"}, - }, - }, - } - errArg := response.Args{ - Code: response.GeneralError, - Message: "", - ErrorArgs: []response.ErrArgs{ - response.ErrArgs{ - StatusMessage: response.PropertyValueNotInList, - ErrorMessage: "failed to create role testRole: Requested Redfish predefined privilege is not correct", - MessageArgs: []interface{}{"Configure", "AssignedPrivileges"}, - }, - }, - } - errArgsInvalid := response.Args{ - Code: response.GeneralError, - Message: "", - ErrorArgs: []response.ErrArgs{ - response.ErrArgs{ - StatusMessage: response.PropertyValueNotInList, - ErrorMessage: "failed to create role @testRole: Invalid create role request", - MessageArgs: []interface{}{"@testRole", "RoleId"}, - }, - }, - } - errArgsInvalidRole := response.Args{ - Code: response.GeneralError, - Message: "", - ErrorArgs: []response.ErrArgs{ - response.ErrArgs{ - StatusMessage: response.InsufficientPrivilege, - ErrorMessage: "failed to create role Administrator: Cannot create pre-defined roles", - MessageArgs: []interface{}{}, - }, - }, - } + errArgs := account.GetResponseArgs(response.InsufficientPrivilege, "failed to create role testRole: User does not have the privilege of creating a new role", []interface{}{}) + + errArgsMiss := account.GetResponseArgs(response.PropertyMissing, "failed to create role testRole: Both AssignedPrivileges and OemPrivileges cannot be empty.", []interface{}{"AssignedPrivileges/OemPrivileges"}) + + errArg := account.GetResponseArgs(response.PropertyValueNotInList, "failed to create role testRole: Requested Redfish predefined privilege is not correct", []interface{}{"Configure", "AssignedPrivileges"}) + + errArgsInvalid := account.GetResponseArgs(response.PropertyValueNotInList, "failed to create role @testRole: Invalid create role request", []interface{}{"@testRole", "RoleId"}) + + errArgsInvalidRole := account.GetResponseArgs(response.InsufficientPrivilege, "failed to create role Administrator: Cannot create pre-defined roles", []interface{}{}) errArgu := response.Args{ Code: response.GeneralError, diff --git a/svc-account-session/role/delete.go b/svc-account-session/role/delete.go index 2533f2175..9b26856b8 100644 --- a/svc-account-session/role/delete.go +++ b/svc-account-session/role/delete.go @@ -19,17 +19,18 @@ import ( "context" "fmt" + "net/http" + "github.com/ODIM-Project/ODIM/lib-utilities/common" "github.com/ODIM-Project/ODIM/lib-utilities/config" "github.com/ODIM-Project/ODIM/lib-utilities/errors" l "github.com/ODIM-Project/ODIM/lib-utilities/logs" roleproto "github.com/ODIM-Project/ODIM/lib-utilities/proto/role" "github.com/ODIM-Project/ODIM/lib-utilities/response" + "github.com/ODIM-Project/ODIM/svc-account-session/account" "github.com/ODIM-Project/ODIM/svc-account-session/asmodel" "github.com/ODIM-Project/ODIM/svc-account-session/auth" "github.com/ODIM-Project/ODIM/svc-account-session/session" - - "net/http" ) func doSessionAuthAndUpdate(ctx context.Context, resp *response.RPC, sessionToken string) (*asmodel.Session, error) { @@ -70,17 +71,7 @@ func Delete(ctx context.Context, req *roleproto.DeleteRoleRequest) *response.RPC errorMessage := errLogPrefix + "The session token doesn't have required privilege" resp.StatusCode = http.StatusForbidden resp.StatusMessage = response.InsufficientPrivilege - args := response.Args{ - Code: response.GeneralError, - Message: "", - ErrorArgs: []response.ErrArgs{ - response.ErrArgs{ - StatusMessage: response.InsufficientPrivilege, - ErrorMessage: errorMessage, - MessageArgs: []interface{}{}, - }, - }, - } + args := account.GetResponseArgs(response.InsufficientPrivilege, errorMessage, []interface{}{}) resp.Body = args.CreateGenericErrorResponse() auth.CustomAuthLog(ctx, req.SessionToken, errorMessage, resp.StatusCode) return &resp @@ -97,17 +88,7 @@ func Delete(ctx context.Context, req *roleproto.DeleteRoleRequest) *response.RPC errorMessage := errLogPrefix + "Role is assigned to a user" resp.StatusCode = http.StatusForbidden resp.StatusMessage = response.ResourceInUse - args := response.Args{ - Code: response.GeneralError, - Message: "", - ErrorArgs: []response.ErrArgs{ - response.ErrArgs{ - StatusMessage: response.ResourceInUse, - ErrorMessage: errorMessage, - MessageArgs: []interface{}{}, - }, - }, - } + args := account.GetResponseArgs(response.ResourceInUse, errorMessage, []interface{}{}) resp.Body = args.CreateGenericErrorResponse() l.LogWithFields(ctx).Error(errorMessage) return &resp @@ -120,17 +101,7 @@ func Delete(ctx context.Context, req *roleproto.DeleteRoleRequest) *response.RPC resp.StatusCode = http.StatusNotFound resp.StatusMessage = response.ResourceNotFound messageArgs := []interface{}{"Role", req.ID} - args := response.Args{ - Code: response.GeneralError, - Message: "", - ErrorArgs: []response.ErrArgs{ - response.ErrArgs{ - StatusMessage: resp.StatusMessage, - ErrorMessage: errorMessage, - MessageArgs: messageArgs, - }, - }, - } + args := account.GetResponseArgs(resp.StatusMessage, errorMessage, messageArgs) resp.Body = args.CreateGenericErrorResponse() } else { resp.CreateInternalErrorResponse(errorMessage) @@ -142,17 +113,7 @@ func Delete(ctx context.Context, req *roleproto.DeleteRoleRequest) *response.RPC errorMessage := errLogPrefix + "A predefined role cannot be deleted." resp.StatusCode = http.StatusForbidden resp.StatusMessage = response.InsufficientPrivilege - args := response.Args{ - Code: response.GeneralError, - Message: "", - ErrorArgs: []response.ErrArgs{ - response.ErrArgs{ - StatusMessage: resp.StatusMessage, - ErrorMessage: errorMessage, - MessageArgs: []interface{}{}, - }, - }, - } + args := account.GetResponseArgs(resp.StatusMessage, errorMessage, []interface{}{}) resp.Body = args.CreateGenericErrorResponse() l.LogWithFields(ctx).Error(errorMessage) return &resp diff --git a/svc-account-session/role/delete_test.go b/svc-account-session/role/delete_test.go index ce5df87ea..ad8714688 100644 --- a/svc-account-session/role/delete_test.go +++ b/svc-account-session/role/delete_test.go @@ -24,6 +24,7 @@ import ( "github.com/ODIM-Project/ODIM/lib-utilities/config" roleproto "github.com/ODIM-Project/ODIM/lib-utilities/proto/role" "github.com/ODIM-Project/ODIM/lib-utilities/response" + "github.com/ODIM-Project/ODIM/svc-account-session/account" "github.com/ODIM-Project/ODIM/svc-account-session/asmodel" "golang.org/x/crypto/sha3" ) @@ -108,61 +109,15 @@ func TestDelete(t *testing.T) { if err != nil { t.Fatalf("Error in creating mock admin user %v", err) } - errArg := response.Args{ - Code: response.GeneralError, - Message: "", - ErrorArgs: []response.ErrArgs{ - response.ErrArgs{ - StatusMessage: response.InsufficientPrivilege, - ErrorMessage: "failed to delete role someRole: The session token doesn't have required privilege", - MessageArgs: []interface{}{}, - }, - }, - } - errArgs := response.Args{ - Code: response.GeneralError, - Message: "", - ErrorArgs: []response.ErrArgs{ - response.ErrArgs{ - StatusMessage: response.ResourceNotFound, - ErrorMessage: "failed to delete role xyz: Unable to get role details: error while trying to get role details: no data with the with key xyz found", - MessageArgs: []interface{}{"Role", "xyz"}, - }, - }, - } - errArgsu := response.Args{ - Code: response.GeneralError, - Message: "", - ErrorArgs: []response.ErrArgs{ - response.ErrArgs{ - StatusMessage: response.NoValidSession, - ErrorMessage: "Unable to authorize session token: error while trying to get session details: error while trying to get the session from DB: no data with the with key invalid-token found", - MessageArgs: []interface{}{}, - }, - }, - } - errArgu := response.Args{ - Code: response.GeneralError, - Message: "", - ErrorArgs: []response.ErrArgs{ - response.ErrArgs{ - StatusMessage: response.InsufficientPrivilege, - ErrorMessage: "failed to delete role someOtherRole: A predefined role cannot be deleted.", - MessageArgs: []interface{}{}, - }, - }, - } - errArgus := response.Args{ - Code: response.GeneralError, - Message: "", - ErrorArgs: []response.ErrArgs{ - response.ErrArgs{ - StatusMessage: response.ResourceInUse, - ErrorMessage: "failed to delete role someUserDefinedRole: Role is assigned to a user", - MessageArgs: []interface{}{}, - }, - }, - } + errArg := account.GetResponseArgs(response.InsufficientPrivilege, "failed to delete role someRole: The session token doesn't have required privilege", []interface{}{}) + + errArgs := account.GetResponseArgs(response.ResourceNotFound, "failed to delete role xyz: Unable to get role details: error while trying to get role details: no data with the with key xyz found", []interface{}{"Role", "xyz"}) + + errArgsu := account.GetResponseArgs(response.NoValidSession, "Unable to authorize session token: error while trying to get session details: error while trying to get the session from DB: no data with the with key invalid-token found", []interface{}{}) + + errArgu := account.GetResponseArgs(response.InsufficientPrivilege, "failed to delete role someOtherRole: A predefined role cannot be deleted.", []interface{}{}) + + errArgus := account.GetResponseArgs(response.ResourceInUse, "failed to delete role someUserDefinedRole: Role is assigned to a user", []interface{}{}) ctx := mockContext() type args struct { req *roleproto.DeleteRoleRequest diff --git a/svc-account-session/role/getroles.go b/svc-account-session/role/getroles.go index d7e2790c8..af0738a47 100644 --- a/svc-account-session/role/getroles.go +++ b/svc-account-session/role/getroles.go @@ -26,6 +26,7 @@ import ( l "github.com/ODIM-Project/ODIM/lib-utilities/logs" roleproto "github.com/ODIM-Project/ODIM/lib-utilities/proto/role" "github.com/ODIM-Project/ODIM/lib-utilities/response" + "github.com/ODIM-Project/ODIM/svc-account-session/account" "github.com/ODIM-Project/ODIM/svc-account-session/asmodel" "github.com/ODIM-Project/ODIM/svc-account-session/asresponse" "github.com/ODIM-Project/ODIM/svc-account-session/auth" @@ -55,17 +56,7 @@ func GetRole(ctx context.Context, req *roleproto.GetRoleRequest, session *asmode errorMessage := errLogPrefix + "User does not have the privilege of viewing the role" resp.StatusCode = int32(status.Code) resp.StatusMessage = status.Message - args := response.Args{ - Code: response.GeneralError, - Message: "", - ErrorArgs: []response.ErrArgs{ - response.ErrArgs{ - StatusMessage: status.Message, - ErrorMessage: errorMessage, - MessageArgs: []interface{}{}, - }, - }, - } + args := account.GetResponseArgs(status.Message, errorMessage, []interface{}{}) resp.Body = args.CreateGenericErrorResponse() auth.CustomAuthLog(ctx, session.Token, errorMessage, resp.StatusCode) return resp @@ -79,17 +70,7 @@ func GetRole(ctx context.Context, req *roleproto.GetRoleRequest, session *asmode resp.StatusCode = http.StatusNotFound resp.StatusMessage = response.ResourceNotFound messageArgs := []interface{}{"Role", req.Id} - args := response.Args{ - Code: response.GeneralError, - Message: "", - ErrorArgs: []response.ErrArgs{ - response.ErrArgs{ - StatusMessage: resp.StatusMessage, - ErrorMessage: errorMessage, - MessageArgs: messageArgs, - }, - }, - } + args := account.GetResponseArgs(resp.StatusMessage, errorMessage, messageArgs) resp.Body = args.CreateGenericErrorResponse() } else { resp.CreateInternalErrorResponse(errorMessage) @@ -137,17 +118,7 @@ func GetAllRoles(ctx context.Context, session *asmodel.Session) response.RPC { errorMessage := errLogPrefix + "User does not have the privilege of viewing the roles" resp.StatusCode = int32(status.Code) resp.StatusMessage = status.Message - args := response.Args{ - Code: response.GeneralError, - Message: "", - ErrorArgs: []response.ErrArgs{ - response.ErrArgs{ - StatusMessage: status.Message, - ErrorMessage: errorMessage, - MessageArgs: []interface{}{}, - }, - }, - } + args := account.GetResponseArgs(status.Message, errorMessage, []interface{}{}) auth.CustomAuthLog(ctx, session.Token, errorMessage, resp.StatusCode) resp.Body = args.CreateGenericErrorResponse() return resp diff --git a/svc-account-session/role/getroles_test.go b/svc-account-session/role/getroles_test.go index 6c147908c..2a4ddf216 100644 --- a/svc-account-session/role/getroles_test.go +++ b/svc-account-session/role/getroles_test.go @@ -25,6 +25,7 @@ import ( "github.com/ODIM-Project/ODIM/svc-account-session/asmodel" "github.com/ODIM-Project/ODIM/svc-account-session/asresponse" "github.com/ODIM-Project/ODIM/svc-account-session/auth" + "github.com/akshata-s-banoshi/Odim-Project/ODIM/svc-account-session/account" ) func createMockRole(roleID string, privileges []string, oemPrivileges []string, predefined bool) error { @@ -69,28 +70,9 @@ func TestGetRole(t *testing.T) { session *asmodel.Session } var errArgs response.Args - errArgs = response.Args{ - Code: response.GeneralError, - Message: "", - ErrorArgs: []response.ErrArgs{ - response.ErrArgs{ - StatusMessage: response.InsufficientPrivilege, - ErrorMessage: "failed to fetch the role Administrator: User does not have the privilege of viewing the role", - MessageArgs: []interface{}{}, - }, - }, - } - errArg := response.Args{ - Code: response.GeneralError, - Message: "", - ErrorArgs: []response.ErrArgs{ - response.ErrArgs{ - StatusMessage: response.ResourceNotFound, - ErrorMessage: "failed to fetch the role ReadOnly: Error while getting the role : error while trying to get role details: no data with the with key " + common.RoleClient + " found", - MessageArgs: []interface{}{"Role", common.RoleClient}, - }, - }, - } + errArgs = account.GetResponseArgs(response.InsufficientPrivilege, "failed to fetch the role Administrator: User does not have the privilege of viewing the role", []interface{}{}) + + errArg := account.GetResponseArgs(response.ResourceNotFound, "failed to fetch the role ReadOnly: Error while getting the role : error while trying to get role details: no data with the with key "+common.RoleClient+" found", []interface{}{"Role", common.RoleClient}) tests := []struct { name string args args @@ -182,17 +164,8 @@ func TestGetAllRoles(t *testing.T) { if err != nil { t.Fatalf("Error in creating mock admin role %v", err) } - errArgs := response.Args{ - Code: response.GeneralError, - Message: "", - ErrorArgs: []response.ErrArgs{ - response.ErrArgs{ - StatusMessage: response.InsufficientPrivilege, - ErrorMessage: "failed to fetch all roles: User does not have the privilege of viewing the roles", - MessageArgs: []interface{}{}, - }, - }, - } + errArgs := account.GetResponseArgs(response.InsufficientPrivilege, "failed to fetch all roles: User does not have the privilege of viewing the roles", []interface{}{}) + ctx := mockContext() type args struct { session *asmodel.Session diff --git a/svc-account-session/role/update.go b/svc-account-session/role/update.go index 03e955292..c48da3682 100644 --- a/svc-account-session/role/update.go +++ b/svc-account-session/role/update.go @@ -26,6 +26,7 @@ import ( l "github.com/ODIM-Project/ODIM/lib-utilities/logs" roleproto "github.com/ODIM-Project/ODIM/lib-utilities/proto/role" "github.com/ODIM-Project/ODIM/lib-utilities/response" + "github.com/ODIM-Project/ODIM/svc-account-session/account" "github.com/ODIM-Project/ODIM/svc-account-session/asmodel" "github.com/ODIM-Project/ODIM/svc-account-session/auth" ) @@ -96,17 +97,7 @@ func Update(ctx context.Context, req *roleproto.UpdateRoleRequest, session *asmo errorMessage := "User does not have the privilege of updating the role" resp.StatusCode = int32(status.Code) resp.StatusMessage = status.Message - args := response.Args{ - Code: response.GeneralError, - Message: "", - ErrorArgs: []response.ErrArgs{ - response.ErrArgs{ - StatusMessage: status.Message, - ErrorMessage: errorMessage, - MessageArgs: []interface{}{}, - }, - }, - } + args := account.GetResponseArgs(status.Message, errorMessage, []interface{}{}) resp.Body = args.CreateGenericErrorResponse() auth.CustomAuthLog(ctx, session.Token, errorMessage, resp.StatusCode) return resp @@ -116,17 +107,7 @@ func Update(ctx context.Context, req *roleproto.UpdateRoleRequest, session *asmo errorMessage := errorLogPrefix + gerr.Error() resp.StatusCode = http.StatusBadRequest resp.StatusMessage = response.ResourceNotFound - args := response.Args{ - Code: response.GeneralError, - Message: "", - ErrorArgs: []response.ErrArgs{ - response.ErrArgs{ - StatusMessage: resp.StatusMessage, - ErrorMessage: errorMessage, - MessageArgs: []interface{}{"Role", req.Id}, - }, - }, - } + args := account.GetResponseArgs(resp.StatusMessage, errorMessage, []interface{}{"Role", req.Id}) resp.Body = args.CreateGenericErrorResponse() l.LogWithFields(ctx).Error(errorMessage) return resp @@ -139,17 +120,7 @@ func Update(ctx context.Context, req *roleproto.UpdateRoleRequest, session *asmo l.LogWithFields(ctx).Error(errorMessage) resp.StatusCode = http.StatusBadRequest resp.StatusMessage = response.PropertyValueConflict - args := response.Args{ - Code: response.GeneralError, - Message: errorMessage, - ErrorArgs: []response.ErrArgs{ - response.ErrArgs{ - StatusMessage: resp.StatusMessage, - ErrorMessage: errorMessage, - MessageArgs: []interface{}{privelege, privelege}, - }, - }, - } + args := account.GetResponseArgs(resp.StatusMessage, errorMessage, []interface{}{privelege, privelege}) resp.Body = args.CreateGenericErrorResponse() return resp } @@ -162,17 +133,7 @@ func Update(ctx context.Context, req *roleproto.UpdateRoleRequest, session *asmo l.LogWithFields(ctx).Error(errorLogPrefix + errorMessage) resp.StatusCode = http.StatusForbidden resp.StatusMessage = response.InsufficientPrivilege - args := response.Args{ - Code: response.GeneralError, - Message: "", - ErrorArgs: []response.ErrArgs{ - response.ErrArgs{ - StatusMessage: resp.StatusMessage, - ErrorMessage: errorMessage, - MessageArgs: []interface{}{}, - }, - }, - } + args := account.GetResponseArgs(resp.StatusMessage, errorMessage, []interface{}{}) resp.Body = args.CreateGenericErrorResponse() return resp } @@ -181,17 +142,7 @@ func Update(ctx context.Context, req *roleproto.UpdateRoleRequest, session *asmo errorMessage := "Assigned privileges or OEM privileges are empty" resp.StatusCode = http.StatusBadRequest resp.StatusMessage = response.PropertyMissing - args := response.Args{ - Code: response.GeneralError, - Message: "", - ErrorArgs: []response.ErrArgs{ - response.ErrArgs{ - StatusMessage: resp.StatusMessage, - ErrorMessage: errorMessage, - MessageArgs: []interface{}{"AssignedPrivileges/OemPrivileges"}, - }, - }, - } + args := account.GetResponseArgs(resp.StatusMessage, errorMessage, []interface{}{"AssignedPrivileges/OemPrivileges"}) resp.Body = args.CreateGenericErrorResponse() return resp } @@ -202,17 +153,7 @@ func Update(ctx context.Context, req *roleproto.UpdateRoleRequest, session *asmo errorMessage := errorLogPrefix + err.Error() resp.StatusCode = int32(status.Code) resp.StatusMessage = status.Message - args := response.Args{ - Code: response.GeneralError, - Message: "", - ErrorArgs: []response.ErrArgs{ - response.ErrArgs{ - StatusMessage: resp.StatusMessage, - ErrorMessage: errorMessage, - MessageArgs: messageArgs, - }, - }, - } + args := account.GetResponseArgs(resp.StatusMessage, errorMessage, messageArgs) resp.Body = args.CreateGenericErrorResponse() l.LogWithFields(ctx).Error(errorMessage) return resp @@ -225,17 +166,7 @@ func Update(ctx context.Context, req *roleproto.UpdateRoleRequest, session *asmo errorMessage := errorLogPrefix + err.Error() resp.StatusCode = int32(status.Code) resp.StatusMessage = status.Message - args := response.Args{ - Code: response.GeneralError, - Message: "", - ErrorArgs: []response.ErrArgs{ - response.ErrArgs{ - StatusMessage: resp.StatusMessage, - ErrorMessage: errorMessage, - MessageArgs: messageArgs, - }, - }, - } + args := account.GetResponseArgs(resp.StatusMessage, errorMessage, messageArgs) resp.Body = args.CreateGenericErrorResponse() l.LogWithFields(ctx).Error(errorMessage) return resp diff --git a/svc-account-session/role/update_test.go b/svc-account-session/role/update_test.go index 3417988cb..3da20e5c9 100644 --- a/svc-account-session/role/update_test.go +++ b/svc-account-session/role/update_test.go @@ -20,6 +20,7 @@ import ( "github.com/ODIM-Project/ODIM/lib-utilities/config" roleproto "github.com/ODIM-Project/ODIM/lib-utilities/proto/role" "github.com/ODIM-Project/ODIM/lib-utilities/response" + "github.com/ODIM-Project/ODIM/svc-account-session/account" "github.com/ODIM-Project/ODIM/svc-account-session/asmodel" "net/http" @@ -58,54 +59,16 @@ func TestUpdate(t *testing.T) { AssignedPrivileges: []string{common.PrivilegeLogin, common.PrivilegeLogin}, OEMPrivileges: []string{}, }) - errArg := response.Args{ - Code: response.GeneralError, - Message: "", - ErrorArgs: []response.ErrArgs{ - response.ErrArgs{ - StatusMessage: response.InsufficientPrivilege, - ErrorMessage: "User does not have the privilege of updating the role", - MessageArgs: []interface{}{}, - }, - }, - } - errArgs := response.Args{ - Code: response.GeneralError, - Message: "", - ErrorArgs: []response.ErrArgs{ - response.ErrArgs{ - StatusMessage: response.PropertyValueNotInList, - ErrorMessage: "failed to update role : Requested Redfish predefined privilege is not correct", - MessageArgs: []interface{}{"Configue", "AssignedPrivileges"}, - }, - }, - } - errArgu := response.Args{ - Code: response.GeneralError, - Message: "", - ErrorArgs: []response.ErrArgs{ - response.ErrArgs{ - StatusMessage: response.ResourceNotFound, - ErrorMessage: "failed to update role : error while trying to get role details: no data with the with key NonExistentRole found", - MessageArgs: []interface{}{"Role", "NonExistentRole"}, - }, - }, - } + errArg := account.GetResponseArgs(response.InsufficientPrivilege, "User does not have the privilege of updating the role", []interface{}{}) + + errArgs := account.GetResponseArgs(response.PropertyValueNotInList, "failed to update role : Requested Redfish predefined privilege is not correct", []interface{}{"Configue", "AssignedPrivileges"}) + + errArgu := account.GetResponseArgs(response.ResourceNotFound, "failed to update role : error while trying to get role details: no data with the with key NonExistentRole found", []interface{}{"Role", "NonExistentRole"}) errArgGen := response.Args{ Code: response.GeneralError, Message: "Updating predefined role is restricted", } - errArgGen1 := response.Args{ - Code: response.GeneralError, - Message: "failed to update role : Duplicate privileges can not be updated", - ErrorArgs: []response.ErrArgs{ - response.ErrArgs{ - StatusMessage: response.PropertyValueConflict, - ErrorMessage: "failed to update role : Duplicate privileges can not be updated", - MessageArgs: []interface{}{common.PrivilegeLogin, common.PrivilegeLogin}, - }, - }, - } + errArgGen1 := account.GetResponseArgs(response.PropertyValueConflict, "failed to update role : Duplicate privileges can not be updated", []interface{}{common.PrivilegeLogin, common.PrivilegeLogin}) ctx := mockContext() type args struct { req *roleproto.UpdateRoleRequest diff --git a/svc-account-session/rpc/account.go b/svc-account-session/rpc/account.go index ccdb18318..8b08f5b09 100644 --- a/svc-account-session/rpc/account.go +++ b/svc-account-session/rpc/account.go @@ -53,9 +53,7 @@ var podName = os.Getenv("POD_NAME") // The function also checks for the session time out of the token // which is present in the request. func (a *Account) Create(ctx context.Context, req *accountproto.CreateAccountRequest) (*accountproto.AccountResponse, error) { - ctx = common.GetContextData(ctx) - ctx = context.WithValue(ctx, common.ThreadName, common.SessionService) - ctx = context.WithValue(ctx, common.ProcessName, podName) + ctx = getContext(ctx, common.SessionService) var resp accountproto.AccountResponse errorArgs := []response.ErrArgs{ response.ErrArgs{ @@ -111,9 +109,7 @@ func (a *Account) Create(ctx context.Context, req *accountproto.CreateAccountReq // The function also checks for the session time out of the token // which is present in the request. func (a *Account) GetAllAccounts(ctx context.Context, req *accountproto.AccountRequest) (*accountproto.AccountResponse, error) { - ctx = common.GetContextData(ctx) - ctx = context.WithValue(ctx, common.ThreadName, common.SessionService) - ctx = context.WithValue(ctx, common.ProcessName, podName) + ctx = getContext(ctx, common.SessionService) var resp accountproto.AccountResponse errorArgs := []response.ErrArgs{ response.ErrArgs{ @@ -167,9 +163,7 @@ func (a *Account) GetAllAccounts(ctx context.Context, req *accountproto.AccountR // The function also checks for the session time out of the token // which is present in the request. func (a *Account) GetAccount(ctx context.Context, req *accountproto.GetAccountRequest) (*accountproto.AccountResponse, error) { - ctx = common.GetContextData(ctx) - ctx = context.WithValue(ctx, common.ThreadName, common.SessionService) - ctx = context.WithValue(ctx, common.ProcessName, podName) + ctx = getContext(ctx, common.SessionService) var resp accountproto.AccountResponse errorArgs := []response.ErrArgs{ response.ErrArgs{ @@ -223,9 +217,7 @@ func (a *Account) GetAccount(ctx context.Context, req *accountproto.GetAccountRe // The function also checks for the session time out of the token // which is present in the request. func (a *Account) GetAccountServices(ctx context.Context, req *accountproto.AccountRequest) (*accountproto.AccountResponse, error) { - ctx = common.GetContextData(ctx) - ctx = context.WithValue(ctx, common.ThreadName, common.SessionService) - ctx = context.WithValue(ctx, common.ProcessName, podName) + ctx = getContext(ctx, common.SessionService) var resp accountproto.AccountResponse errorArgs := []response.ErrArgs{ response.ErrArgs{ @@ -278,9 +270,7 @@ func (a *Account) GetAccountServices(ctx context.Context, req *accountproto.Acco // The function also checks for the session time out of the token // which is present in the request. func (a *Account) Update(ctx context.Context, req *accountproto.UpdateAccountRequest) (*accountproto.AccountResponse, error) { - ctx = common.GetContextData(ctx) - ctx = context.WithValue(ctx, common.ThreadName, common.SessionService) - ctx = context.WithValue(ctx, common.ProcessName, podName) + ctx = getContext(ctx, common.SessionService) var resp accountproto.AccountResponse l.LogWithFields(ctx).Info("Validating session and updating the last used time of the session before updating the account") errorArgs := []response.ErrArgs{ @@ -335,9 +325,7 @@ func (a *Account) Update(ctx context.Context, req *accountproto.UpdateAccountReq // The function also checks for the session time out of the token // which is present in the request. func (a *Account) Delete(ctx context.Context, req *accountproto.DeleteAccountRequest) (*accountproto.AccountResponse, error) { - ctx = common.GetContextData(ctx) - ctx = context.WithValue(ctx, common.ThreadName, common.SessionService) - ctx = context.WithValue(ctx, common.ProcessName, podName) + ctx = getContext(ctx, common.SessionService) var resp accountproto.AccountResponse errorArgs := []response.ErrArgs{ response.ErrArgs{ diff --git a/svc-account-session/rpc/auth.go b/svc-account-session/rpc/auth.go index 7999a0a7f..229024355 100644 --- a/svc-account-session/rpc/auth.go +++ b/svc-account-session/rpc/auth.go @@ -35,9 +35,7 @@ var ( // IsAuthorized will accepts the request and send a request to Auth method // from session package, if its authorized then respond with the status code. func (a *Auth) IsAuthorized(ctx context.Context, req *authproto.AuthRequest) (*authproto.AuthResponse, error) { - ctx = common.GetContextData(ctx) - ctx = context.WithValue(ctx, common.ThreadName, common.SessionService) - ctx = context.WithValue(ctx, common.ProcessName, podName) + ctx = getContext(ctx, common.SessionService) var resp authproto.AuthResponse l.LogWithFields(ctx).Info("Validating if the session is authorized") statusCode, errorMessage := AuthFunc(ctx, req) diff --git a/svc-account-session/rpc/role.go b/svc-account-session/rpc/role.go index f22eac71a..1c3b77a83 100644 --- a/svc-account-session/rpc/role.go +++ b/svc-account-session/rpc/role.go @@ -52,9 +52,7 @@ var ( // The function also checks for the session time out of the token // which is present in the request. func (r *Role) CreateRole(ctx context.Context, req *roleproto.RoleRequest) (*roleproto.RoleResponse, error) { - ctx = common.GetContextData(ctx) - ctx = context.WithValue(ctx, common.ThreadName, common.SessionService) - ctx = context.WithValue(ctx, common.ProcessName, podName) + ctx = getContext(ctx, common.SessionService) var resp roleproto.RoleResponse errorArgs := []response.ErrArgs{ response.ErrArgs{ @@ -112,9 +110,7 @@ func (r *Role) CreateRole(ctx context.Context, req *roleproto.RoleRequest) (*rol // The function also checks for the session time out of the token // which is present in the request. func (r *Role) GetRole(ctx context.Context, req *roleproto.GetRoleRequest) (*roleproto.RoleResponse, error) { - ctx = common.GetContextData(ctx) - ctx = context.WithValue(ctx, common.ThreadName, common.SessionService) - ctx = context.WithValue(ctx, common.ProcessName, podName) + ctx = getContext(ctx, common.SessionService) var resp roleproto.RoleResponse errorArgs := []response.ErrArgs{ response.ErrArgs{ @@ -173,9 +169,7 @@ func (r *Role) GetRole(ctx context.Context, req *roleproto.GetRoleRequest) (*rol // The function also checks for the session time out of the token // which is present in the request. func (r *Role) GetAllRoles(ctx context.Context, req *roleproto.GetRoleRequest) (*roleproto.RoleResponse, error) { - ctx = common.GetContextData(ctx) - ctx = context.WithValue(ctx, common.ThreadName, common.SessionService) - ctx = context.WithValue(ctx, common.ProcessName, podName) + ctx = getContext(ctx, common.SessionService) var resp roleproto.RoleResponse errorArgs := []response.ErrArgs{ response.ErrArgs{ @@ -233,9 +227,7 @@ func (r *Role) GetAllRoles(ctx context.Context, req *roleproto.GetRoleRequest) ( // The function also checks for the session time out of the token // which is present in the request. func (r *Role) UpdateRole(ctx context.Context, req *roleproto.UpdateRoleRequest) (*roleproto.RoleResponse, error) { - ctx = common.GetContextData(ctx) - ctx = context.WithValue(ctx, common.ThreadName, common.SessionService) - ctx = context.WithValue(ctx, common.ProcessName, podName) + ctx = getContext(ctx, common.SessionService) var resp roleproto.RoleResponse errorArgs := []response.ErrArgs{ response.ErrArgs{ @@ -289,9 +281,7 @@ func (r *Role) UpdateRole(ctx context.Context, req *roleproto.UpdateRoleRequest) // DeleteRole handles the RPC call from the client func (r *Role) DeleteRole(ctx context.Context, req *roleproto.DeleteRoleRequest) (*roleproto.RoleResponse, error) { - ctx = common.GetContextData(ctx) - ctx = context.WithValue(ctx, common.ThreadName, common.SessionService) - ctx = context.WithValue(ctx, common.ProcessName, podName) + ctx = getContext(ctx, common.SessionService) var resp roleproto.RoleResponse errorArgs := []response.ErrArgs{ response.ErrArgs{ diff --git a/svc-account-session/rpc/sessions.go b/svc-account-session/rpc/sessions.go index 01761dbd8..bec3c88ea 100644 --- a/svc-account-session/rpc/sessions.go +++ b/svc-account-session/rpc/sessions.go @@ -48,9 +48,7 @@ var ( // and It will check the credentials of user, if user is authorized // then create session for the same func (s *Session) CreateSession(ctx context.Context, req *sessionproto.SessionCreateRequest) (*sessionproto.SessionCreateResponse, error) { - ctx = common.GetContextData(ctx) - ctx = context.WithValue(ctx, common.ThreadName, common.SessionService) - ctx = context.WithValue(ctx, common.ProcessName, podName) + ctx = getContext(ctx, common.SessionService) var err error var resp sessionproto.SessionCreateResponse response, sessionID := CreateNewSessionFunc(ctx, req) @@ -75,9 +73,7 @@ func (s *Session) CreateSession(ctx context.Context, req *sessionproto.SessionCr // It will get all the session tokens from the db and from the session token get the session details // if session id is matched with recieved session id ten delete the session func (s *Session) DeleteSession(ctx context.Context, req *sessionproto.SessionRequest) (*sessionproto.SessionResponse, error) { - ctx = common.GetContextData(ctx) - ctx = context.WithValue(ctx, common.ThreadName, common.SessionService) - ctx = context.WithValue(ctx, common.ProcessName, podName) + ctx = getContext(ctx, common.SessionService) response := DeleteSessionFunc(ctx, req) var resp sessionproto.SessionResponse body, err := MarshalFunc(response.Body) @@ -89,10 +85,7 @@ func (s *Session) DeleteSession(ctx context.Context, req *sessionproto.SessionRe } l.LogWithFields(ctx).Debugf("outgoing response of request to delete the session: %s", string(body)) resp.Body = body - resp.StatusCode = response.StatusCode - resp.StatusMessage = response.StatusMessage - resp.Header = response.Header - resp.Body = body + resp = mapSessionResponse(resp, response, body) return &resp, nil } @@ -100,9 +93,7 @@ func (s *Session) DeleteSession(ctx context.Context, req *sessionproto.SessionRe // It will get all the session tokens from the db and from the session token get the session details // if session id is matched with recieved session id then delete the session func (s *Session) GetSession(ctx context.Context, req *sessionproto.SessionRequest) (*sessionproto.SessionResponse, error) { - ctx = common.GetContextData(ctx) - ctx = context.WithValue(ctx, common.ThreadName, common.SessionService) - ctx = context.WithValue(ctx, common.ProcessName, podName) + ctx = getContext(ctx, common.SessionService) var resp sessionproto.SessionResponse response := GetSessionFunc(ctx, req) body, err := MarshalFunc(response.Body) @@ -112,20 +103,14 @@ func (s *Session) GetSession(ctx context.Context, req *sessionproto.SessionReque return &resp, nil } l.LogWithFields(ctx).Debugf("outgoing response of request to get the session: %s", string(body)) - resp.Body = body - resp.StatusCode = response.StatusCode - resp.StatusMessage = response.StatusMessage - resp.Header = response.Header - resp.Body = body + resp = mapSessionResponse(resp, response, body) return &resp, nil } // GetSessionUserName is a rpc call to get session username // It will get all the session username from the session func (s *Session) GetSessionUserName(ctx context.Context, req *sessionproto.SessionRequest) (*sessionproto.SessionUserName, error) { - ctx = common.GetContextData(ctx) - ctx = context.WithValue(ctx, common.ThreadName, common.SessionService) - ctx = context.WithValue(ctx, common.ProcessName, podName) + ctx = getContext(ctx, common.SessionService) resp, err := GetSessionUserNameFunc(ctx, req) return resp, err } @@ -144,9 +129,7 @@ func (s *Session) GetSessionUserRoleID(ctx context.Context, req *sessionproto.Se // and it will call GetAllActiveSessions from the session package // and respond all the sessionresponse values along with error if there is. func (s *Session) GetAllActiveSessions(ctx context.Context, req *sessionproto.SessionRequest) (*sessionproto.SessionResponse, error) { - ctx = common.GetContextData(ctx) - ctx = context.WithValue(ctx, common.ThreadName, common.SessionService) - ctx = context.WithValue(ctx, common.ProcessName, podName) + ctx = getContext(ctx, common.SessionService) var resp sessionproto.SessionResponse response := GetAllActiveSessionsFunc(ctx, req) body, err := MarshalFunc(response.Body) @@ -158,10 +141,7 @@ func (s *Session) GetAllActiveSessions(ctx context.Context, req *sessionproto.Se } l.LogWithFields(ctx).Debugf("outgoing response of request to get all active sessions: %s", string(body)) resp.Body = body - resp.StatusCode = response.StatusCode - resp.StatusMessage = response.StatusMessage - resp.Header = response.Header - resp.Body = body + resp = mapSessionResponse(resp, response, body) return &resp, nil } @@ -169,9 +149,7 @@ func (s *Session) GetAllActiveSessions(ctx context.Context, req *sessionproto.Se // GetSessionService is a rpc call to get session service // which basically checks if the session service is enabled or not func (s *Session) GetSessionService(ctx context.Context, req *sessionproto.SessionRequest) (*sessionproto.SessionResponse, error) { - ctx = common.GetContextData(ctx) - ctx = context.WithValue(ctx, common.ThreadName, common.SessionService) - ctx = context.WithValue(ctx, common.ProcessName, podName) + ctx = getContext(ctx, common.SessionService) var resp sessionproto.SessionResponse response := GetSessionServiceFunc(ctx, req) body, err := MarshalFunc(response.Body) @@ -181,10 +159,7 @@ func (s *Session) GetSessionService(ctx context.Context, req *sessionproto.Sessi l.LogWithFields(ctx).Printf(response.StatusMessage) return &resp, nil } - resp.StatusCode = response.StatusCode - resp.StatusMessage = response.StatusMessage - resp.Header = response.Header - resp.Body = body + resp = mapSessionResponse(resp, response, body) return &resp, nil } @@ -202,3 +177,20 @@ func getCommonResponse(statusMessage string) asresponse.RedfishSessionResponse { }, } } + +// mapSessionResponse maps the response fields to Sessionresponse object +func mapSessionResponse(resp sessionproto.SessionResponse, response response.RPC, body []byte) sessionproto.SessionResponse { + resp.StatusCode = response.StatusCode + resp.StatusMessage = response.StatusMessage + resp.Header = response.Header + resp.Body = body + + return resp +} + +func getContext(ctx context.Context, service string) context.Context { + ctx = common.GetContextData(ctx) + ctx = context.WithValue(ctx, common.ThreadName, service) + ctx = context.WithValue(ctx, common.ProcessName, podName) + return ctx +} diff --git a/svc-account-session/session/create_test.go b/svc-account-session/session/create_test.go index 1a146ed30..807eae372 100644 --- a/svc-account-session/session/create_test.go +++ b/svc-account-session/session/create_test.go @@ -25,6 +25,7 @@ import ( "github.com/ODIM-Project/ODIM/lib-utilities/config" sessionproto "github.com/ODIM-Project/ODIM/lib-utilities/proto/session" "github.com/ODIM-Project/ODIM/lib-utilities/response" + "github.com/ODIM-Project/ODIM/svc-account-session/account" "github.com/ODIM-Project/ODIM/svc-account-session/asmodel" "github.com/ODIM-Project/ODIM/svc-account-session/asresponse" "github.com/ODIM-Project/ODIM/svc-account-session/auth" @@ -107,40 +108,11 @@ func TestCreateSession(t *testing.T) { ID: "Sessions", Name: "Session Service", } - errArgUnauth := &response.Args{ - Code: response.GeneralError, - Message: "", - ErrorArgs: []response.ErrArgs{ - response.ErrArgs{ - StatusMessage: response.NoValidSession, - ErrorMessage: "failed to create session for user : Unable to authorize session creation credentials: error while checking session credentials: username or password is empty", - MessageArgs: []interface{}{}, - }, - }, - } + errArgUnauth := account.GetResponseArgs(response.NoValidSession, "failed to create session for user : Unable to authorize session creation credentials: error while checking session credentials: username or password is empty", []interface{}{}) - errArgUnauth1 := &response.Args{ - Code: response.GeneralError, - Message: "", - ErrorArgs: []response.ErrArgs{ - response.ErrArgs{ - StatusMessage: response.NoValidSession, - ErrorMessage: "failed to create session for user admin: Unable to authorize session creation credentials: error while checking session credentials: input password is not matching user password", - MessageArgs: []interface{}{}, - }, - }, - } - errArg2 := &response.Args{ - Code: response.GeneralError, - Message: "", - ErrorArgs: []response.ErrArgs{ - response.ErrArgs{ - StatusMessage: response.InsufficientPrivilege, - ErrorMessage: "failed to create session for user sample: User doesn't have required privilege to create a session", - MessageArgs: []interface{}{}, - }, - }, - } + errArgUnauth1 := account.GetResponseArgs(response.NoValidSession, "failed to create session for user admin: Unable to authorize session creation credentials: error while checking session credentials: input password is not matching user password", []interface{}{}) + + errArg2 := account.GetResponseArgs(response.InsufficientPrivilege, "failed to create session for user sample: User doesn't have required privilege to create a session", []interface{}{}) ctx := mockContext() type args struct { req *sessionproto.SessionCreateRequest From 1ed6239bbd118f11ea2cc8a1e8bcc9de313e60f1 Mon Sep 17 00:00:00 2001 From: Banoshi Date: Tue, 27 Jun 2023 13:28:27 +0530 Subject: [PATCH 15/19] refactory accounts.go and role.go --- svc-account-session/rpc/account.go | 140 +++++++---------------------- svc-account-session/rpc/role.go | 123 +++++++------------------ 2 files changed, 62 insertions(+), 201 deletions(-) diff --git a/svc-account-session/rpc/account.go b/svc-account-session/rpc/account.go index 8b08f5b09..15d13350f 100644 --- a/svc-account-session/rpc/account.go +++ b/svc-account-session/rpc/account.go @@ -55,18 +55,7 @@ var podName = os.Getenv("POD_NAME") func (a *Account) Create(ctx context.Context, req *accountproto.CreateAccountRequest) (*accountproto.AccountResponse, error) { ctx = getContext(ctx, common.SessionService) var resp accountproto.AccountResponse - errorArgs := []response.ErrArgs{ - response.ErrArgs{ - StatusMessage: "", - ErrorMessage: "", - MessageArgs: []interface{}{}, - }, - } - args := &response.Args{ - Code: response.GeneralError, - Message: "", - ErrorArgs: errorArgs, - } + args := account.GetResponseArgs("", "", []interface{}{}) l.LogWithFields(ctx).Info("Validating session and updating the last used time of the session before creating the account") sess, errs := CheckSessionTimeOutFunc(ctx, req.SessionToken) @@ -77,8 +66,8 @@ func (a *Account) Create(ctx context.Context, req *accountproto.CreateAccountReq err := UpdateLastUsedTimeFunc(ctx, req.SessionToken) if err != nil { - errorArgs[0].ErrorMessage, resp.StatusCode, resp.StatusMessage = validateUpdateLastUsedTimeError(ctx, err) - errorArgs[0].StatusMessage = resp.StatusMessage + args.ErrorArgs[0].ErrorMessage, resp.StatusCode, resp.StatusMessage = validateUpdateLastUsedTimeError(ctx, err) + args.ErrorArgs[0].StatusMessage = resp.StatusMessage resp.Body, _ = json.Marshal(args.CreateGenericErrorResponse()) return &resp, nil } @@ -94,10 +83,7 @@ func (a *Account) Create(ctx context.Context, req *accountproto.CreateAccountReq return &resp, nil } l.LogWithFields(ctx).Debugf("outgoing response of request to create an account: %s", string(body)) - resp.Body = body - resp.StatusCode = data.StatusCode - resp.StatusMessage = data.StatusMessage - resp.Header = data.Header + resp = mapAccountResponse(resp, body, data) return &resp, nil } @@ -111,18 +97,7 @@ func (a *Account) Create(ctx context.Context, req *accountproto.CreateAccountReq func (a *Account) GetAllAccounts(ctx context.Context, req *accountproto.AccountRequest) (*accountproto.AccountResponse, error) { ctx = getContext(ctx, common.SessionService) var resp accountproto.AccountResponse - errorArgs := []response.ErrArgs{ - response.ErrArgs{ - StatusMessage: "", - ErrorMessage: "", - MessageArgs: []interface{}{}, - }, - } - args := &response.Args{ - Code: response.GeneralError, - Message: "", - ErrorArgs: errorArgs, - } + args := account.GetResponseArgs("", "", []interface{}{}) l.LogWithFields(ctx).Info("Validating session and updating the last used time of the session before fetching all accounts") sess, errs := CheckSessionTimeOutFunc(ctx, req.SessionToken) @@ -133,8 +108,8 @@ func (a *Account) GetAllAccounts(ctx context.Context, req *accountproto.AccountR err := UpdateLastUsedTimeFunc(ctx, req.SessionToken) if err != nil { - errorArgs[0].ErrorMessage, resp.StatusCode, resp.StatusMessage = validateUpdateLastUsedTimeError(ctx, err) - errorArgs[0].StatusMessage = resp.StatusMessage + args.ErrorArgs[0].ErrorMessage, resp.StatusCode, resp.StatusMessage = validateUpdateLastUsedTimeError(ctx, err) + args.ErrorArgs[0].StatusMessage = resp.StatusMessage resp.Body, _ = json.Marshal(args.CreateGenericErrorResponse()) return &resp, nil } @@ -148,10 +123,7 @@ func (a *Account) GetAllAccounts(ctx context.Context, req *accountproto.AccountR return &resp, fmt.Errorf(resp.StatusMessage) } l.LogWithFields(ctx).Debugf("outgoing response of request to view all accounts: %s", string(body)) - resp.Body = body - resp.StatusCode = data.StatusCode - resp.StatusMessage = data.StatusMessage - resp.Header = data.Header + resp = mapAccountResponse(resp, body, data) return &resp, err } @@ -165,18 +137,7 @@ func (a *Account) GetAllAccounts(ctx context.Context, req *accountproto.AccountR func (a *Account) GetAccount(ctx context.Context, req *accountproto.GetAccountRequest) (*accountproto.AccountResponse, error) { ctx = getContext(ctx, common.SessionService) var resp accountproto.AccountResponse - errorArgs := []response.ErrArgs{ - response.ErrArgs{ - StatusMessage: "", - ErrorMessage: "", - MessageArgs: []interface{}{}, - }, - } - args := &response.Args{ - Code: response.GeneralError, - Message: "", - ErrorArgs: errorArgs, - } + args := account.GetResponseArgs("", "", []interface{}{}) l.LogWithFields(ctx).Info("Validating session and updating the last used time of the session before fetching the account") sess, errs := CheckSessionTimeOutFunc(ctx, req.SessionToken) @@ -187,8 +148,8 @@ func (a *Account) GetAccount(ctx context.Context, req *accountproto.GetAccountRe err := UpdateLastUsedTimeFunc(ctx, req.SessionToken) if err != nil { - errorArgs[0].ErrorMessage, resp.StatusCode, resp.StatusMessage = validateUpdateLastUsedTimeError(ctx, err) - errorArgs[0].StatusMessage = resp.StatusMessage + args.ErrorArgs[0].ErrorMessage, resp.StatusCode, resp.StatusMessage = validateUpdateLastUsedTimeError(ctx, err) + args.ErrorArgs[0].StatusMessage = resp.StatusMessage resp.Body, _ = json.Marshal(args.CreateGenericErrorResponse()) return &resp, nil } @@ -202,10 +163,7 @@ func (a *Account) GetAccount(ctx context.Context, req *accountproto.GetAccountRe return &resp, fmt.Errorf(resp.StatusMessage) } l.LogWithFields(ctx).Debugf("outgoing response of request to view the account: %s", string(body)) - resp.Body = body - resp.StatusCode = data.StatusCode - resp.StatusMessage = data.StatusMessage - resp.Header = data.Header + resp = mapAccountResponse(resp, body, data) return &resp, nil } @@ -219,18 +177,7 @@ func (a *Account) GetAccount(ctx context.Context, req *accountproto.GetAccountRe func (a *Account) GetAccountServices(ctx context.Context, req *accountproto.AccountRequest) (*accountproto.AccountResponse, error) { ctx = getContext(ctx, common.SessionService) var resp accountproto.AccountResponse - errorArgs := []response.ErrArgs{ - response.ErrArgs{ - StatusMessage: "", - ErrorMessage: "", - MessageArgs: []interface{}{}, - }, - } - args := &response.Args{ - Code: response.GeneralError, - Message: "", - ErrorArgs: errorArgs, - } + args := account.GetResponseArgs("", "", []interface{}{}) l.LogWithFields(ctx).Info("Validating session and updating the last used time of the session before checking the availability of account session") _, errs := CheckSessionTimeOutFunc(ctx, req.SessionToken) if errs != nil { @@ -240,8 +187,8 @@ func (a *Account) GetAccountServices(ctx context.Context, req *accountproto.Acco err := UpdateLastUsedTimeFunc(ctx, req.SessionToken) if err != nil { - errorArgs[0].ErrorMessage, resp.StatusCode, resp.StatusMessage = validateUpdateLastUsedTimeError(ctx, err) - errorArgs[0].StatusMessage = resp.StatusMessage + args.ErrorArgs[0].ErrorMessage, resp.StatusCode, resp.StatusMessage = validateUpdateLastUsedTimeError(ctx, err) + args.ErrorArgs[0].StatusMessage = resp.StatusMessage resp.Body, _ = json.Marshal(args.CreateGenericErrorResponse()) return &resp, nil } @@ -255,10 +202,7 @@ func (a *Account) GetAccountServices(ctx context.Context, req *accountproto.Acco return &resp, fmt.Errorf(resp.StatusMessage) } l.LogWithFields(ctx).Debugf("outgoing response of request to view the account session: %s", string(body)) - resp.Body = body - resp.StatusCode = data.StatusCode - resp.StatusMessage = data.StatusMessage - resp.Header = data.Header + resp = mapAccountResponse(resp, body, data) return &resp, err } @@ -273,18 +217,7 @@ func (a *Account) Update(ctx context.Context, req *accountproto.UpdateAccountReq ctx = getContext(ctx, common.SessionService) var resp accountproto.AccountResponse l.LogWithFields(ctx).Info("Validating session and updating the last used time of the session before updating the account") - errorArgs := []response.ErrArgs{ - response.ErrArgs{ - StatusMessage: "", - ErrorMessage: "", - MessageArgs: []interface{}{}, - }, - } - args := &response.Args{ - Code: response.GeneralError, - Message: "", - ErrorArgs: errorArgs, - } + args := account.GetResponseArgs("", "", []interface{}{}) sess, errs := CheckSessionTimeOutFunc(ctx, req.SessionToken) if errs != nil { resp.Body, resp.StatusCode, resp.StatusMessage = validateSessionTimeoutError(ctx, req.SessionToken, errs) @@ -293,8 +226,8 @@ func (a *Account) Update(ctx context.Context, req *accountproto.UpdateAccountReq err := UpdateLastUsedTimeFunc(ctx, req.SessionToken) if err != nil { - errorArgs[0].ErrorMessage, resp.StatusCode, resp.StatusMessage = validateUpdateLastUsedTimeError(ctx, err) - errorArgs[0].StatusMessage = resp.StatusMessage + args.ErrorArgs[0].ErrorMessage, resp.StatusCode, resp.StatusMessage = validateUpdateLastUsedTimeError(ctx, err) + args.ErrorArgs[0].StatusMessage = resp.StatusMessage resp.Body, _ = json.Marshal(args.CreateGenericErrorResponse()) return &resp, nil } @@ -310,10 +243,7 @@ func (a *Account) Update(ctx context.Context, req *accountproto.UpdateAccountReq return &resp, nil } l.LogWithFields(ctx).Debugf("outgoing response of request to update the account: %s", string(body)) - resp.Body = body - resp.StatusCode = data.StatusCode - resp.StatusMessage = data.StatusMessage - resp.Header = data.Header + resp = mapAccountResponse(resp, body, data) return &resp, nil } @@ -327,18 +257,7 @@ func (a *Account) Update(ctx context.Context, req *accountproto.UpdateAccountReq func (a *Account) Delete(ctx context.Context, req *accountproto.DeleteAccountRequest) (*accountproto.AccountResponse, error) { ctx = getContext(ctx, common.SessionService) var resp accountproto.AccountResponse - errorArgs := []response.ErrArgs{ - response.ErrArgs{ - StatusMessage: "", - ErrorMessage: "", - MessageArgs: []interface{}{}, - }, - } - args := &response.Args{ - Code: response.GeneralError, - Message: "", - ErrorArgs: errorArgs, - } + args := account.GetResponseArgs("", "", []interface{}{}) l.LogWithFields(ctx).Info("Validating session and updating the last used time of the session before deleting the account") sess, errs := CheckSessionTimeOutFunc(ctx, req.SessionToken) if errs != nil { @@ -348,8 +267,8 @@ func (a *Account) Delete(ctx context.Context, req *accountproto.DeleteAccountReq err := UpdateLastUsedTimeFunc(ctx, req.SessionToken) if err != nil { - errorArgs[0].ErrorMessage, resp.StatusCode, resp.StatusMessage = validateUpdateLastUsedTimeError(ctx, err) - errorArgs[0].StatusMessage = resp.StatusMessage + args.ErrorArgs[0].ErrorMessage, resp.StatusCode, resp.StatusMessage = validateUpdateLastUsedTimeError(ctx, err) + args.ErrorArgs[0].StatusMessage = resp.StatusMessage resp.Body, _ = json.Marshal(args.CreateGenericErrorResponse()) return &resp, nil } @@ -364,10 +283,7 @@ func (a *Account) Delete(ctx context.Context, req *accountproto.DeleteAccountReq return &resp, nil } l.LogWithFields(ctx).Debugf("outgoing response of request to delete the account: %s", string(body)) - resp.Body = body - resp.StatusCode = data.StatusCode - resp.StatusMessage = data.StatusMessage - resp.Header = data.Header + resp = mapAccountResponse(resp, body, data) return &resp, nil } @@ -392,3 +308,11 @@ func validateUpdateLastUsedTimeError(ctx context.Context, err error) (errorMessa l.LogWithFields(ctx).Error(errorMessage) return } + +func mapAccountResponse(resp accountproto.AccountResponse, body []byte, data response.RPC) accountproto.AccountResponse { + resp.Body = body + resp.StatusCode = data.StatusCode + resp.StatusMessage = data.StatusMessage + resp.Header = data.Header + return resp +} diff --git a/svc-account-session/rpc/role.go b/svc-account-session/rpc/role.go index 1c3b77a83..3521bbf25 100644 --- a/svc-account-session/rpc/role.go +++ b/svc-account-session/rpc/role.go @@ -25,6 +25,7 @@ import ( l "github.com/ODIM-Project/ODIM/lib-utilities/logs" roleproto "github.com/ODIM-Project/ODIM/lib-utilities/proto/role" "github.com/ODIM-Project/ODIM/lib-utilities/response" + "github.com/ODIM-Project/ODIM/svc-account-session/account" "github.com/ODIM-Project/ODIM/svc-account-session/auth" "github.com/ODIM-Project/ODIM/svc-account-session/role" "github.com/ODIM-Project/ODIM/svc-account-session/session" @@ -54,18 +55,7 @@ var ( func (r *Role) CreateRole(ctx context.Context, req *roleproto.RoleRequest) (*roleproto.RoleResponse, error) { ctx = getContext(ctx, common.SessionService) var resp roleproto.RoleResponse - errorArgs := []response.ErrArgs{ - response.ErrArgs{ - StatusMessage: "", - ErrorMessage: "", - MessageArgs: []interface{}{}, - }, - } - args := &response.Args{ - Code: response.GeneralError, - Message: "", - ErrorArgs: errorArgs, - } + args := account.GetResponseArgs("", "", []interface{}{}) l.LogWithFields(ctx).Info("Validating session and updating the last used time of the session before creating the role") // Validating the session @@ -77,8 +67,8 @@ func (r *Role) CreateRole(ctx context.Context, req *roleproto.RoleRequest) (*rol err := UpdateLastUsedTimeFunc(ctx, req.SessionToken) if err != nil { - errorArgs[0].ErrorMessage, resp.StatusCode, resp.StatusMessage = validateUpdateLastUsedTimeError(ctx, err) - errorArgs[0].StatusMessage = resp.StatusMessage + args.ErrorArgs[0].ErrorMessage, resp.StatusCode, resp.StatusMessage = validateUpdateLastUsedTimeError(ctx, err) + args.ErrorArgs[0].StatusMessage = resp.StatusMessage resp.Body, _ = json.Marshal(args.CreateGenericErrorResponse()) return &resp, nil } @@ -90,11 +80,7 @@ func (r *Role) CreateRole(ctx context.Context, req *roleproto.RoleRequest) (*rol body, err := MarshalFunc(data.Body) if err != nil { errorMessage := "error while trying to marshal the response body of create role API: " + err.Error() - resp.StatusCode = http.StatusInternalServerError - resp.StatusMessage = response.InternalError - errorArgs[0].ErrorMessage = errorMessage - errorArgs[0].StatusMessage = resp.StatusMessage - resp.Body, _ = json.Marshal(args.CreateGenericErrorResponse()) + resp, args = mapResponseAndError(resp, args, errorMessage) l.LogWithFields(ctx).Error(resp.StatusMessage) return &resp, nil } @@ -112,18 +98,7 @@ func (r *Role) CreateRole(ctx context.Context, req *roleproto.RoleRequest) (*rol func (r *Role) GetRole(ctx context.Context, req *roleproto.GetRoleRequest) (*roleproto.RoleResponse, error) { ctx = getContext(ctx, common.SessionService) var resp roleproto.RoleResponse - errorArgs := []response.ErrArgs{ - response.ErrArgs{ - StatusMessage: "", - ErrorMessage: "", - MessageArgs: []interface{}{}, - }, - } - args := &response.Args{ - Code: response.GeneralError, - Message: "", - ErrorArgs: errorArgs, - } + args := account.GetResponseArgs("", "", []interface{}{}) l.LogWithFields(ctx).Info("Validating session and updating the last used time of the session before fetching the role details") // Validating the session @@ -135,8 +110,8 @@ func (r *Role) GetRole(ctx context.Context, req *roleproto.GetRoleRequest) (*rol err := UpdateLastUsedTimeFunc(ctx, req.SessionToken) if err != nil { - errorArgs[0].ErrorMessage, resp.StatusCode, resp.StatusMessage = validateUpdateLastUsedTimeError(ctx, err) - errorArgs[0].StatusMessage = resp.StatusMessage + args.ErrorArgs[0].ErrorMessage, resp.StatusCode, resp.StatusMessage = validateUpdateLastUsedTimeError(ctx, err) + args.ErrorArgs[0].StatusMessage = resp.StatusMessage resp.Body, _ = json.Marshal(args.CreateGenericErrorResponse()) return &resp, nil } @@ -148,11 +123,8 @@ func (r *Role) GetRole(ctx context.Context, req *roleproto.GetRoleRequest) (*rol body, err := MarshalFunc(data.Body) if err != nil { errorMessage := "error while trying to marshal the response body of get role API: " + err.Error() - resp.StatusCode = http.StatusInternalServerError - resp.StatusMessage = response.InternalError - errorArgs[0].ErrorMessage = errorMessage - errorArgs[0].StatusMessage = resp.StatusMessage - resp.Body, _ = json.Marshal(args.CreateGenericErrorResponse()) + resp, args = mapResponseAndError(resp, args, errorMessage) + l.LogWithFields(ctx).Error(resp.StatusMessage) return &resp, nil } @@ -171,18 +143,7 @@ func (r *Role) GetRole(ctx context.Context, req *roleproto.GetRoleRequest) (*rol func (r *Role) GetAllRoles(ctx context.Context, req *roleproto.GetRoleRequest) (*roleproto.RoleResponse, error) { ctx = getContext(ctx, common.SessionService) var resp roleproto.RoleResponse - errorArgs := []response.ErrArgs{ - response.ErrArgs{ - StatusMessage: "", - ErrorMessage: "", - MessageArgs: []interface{}{}, - }, - } - args := &response.Args{ - Code: response.GeneralError, - Message: "", - ErrorArgs: errorArgs, - } + args := account.GetResponseArgs("", "", []interface{}{}) l.LogWithFields(ctx).Info("Validating session and updating the last used time of the session before fetching all roles") sess, errs := CheckSessionTimeOutFunc(ctx, req.SessionToken) @@ -193,8 +154,8 @@ func (r *Role) GetAllRoles(ctx context.Context, req *roleproto.GetRoleRequest) ( err := UpdateLastUsedTimeFunc(ctx, req.SessionToken) if err != nil { - errorArgs[0].ErrorMessage, resp.StatusCode, resp.StatusMessage = validateUpdateLastUsedTimeError(ctx, err) - errorArgs[0].StatusMessage = resp.StatusMessage + args.ErrorArgs[0].ErrorMessage, resp.StatusCode, resp.StatusMessage = validateUpdateLastUsedTimeError(ctx, err) + args.ErrorArgs[0].StatusMessage = resp.StatusMessage resp.Body, _ = json.Marshal(args.CreateGenericErrorResponse()) return &resp, nil } @@ -206,11 +167,7 @@ func (r *Role) GetAllRoles(ctx context.Context, req *roleproto.GetRoleRequest) ( body, err := MarshalFunc(data.Body) if err != nil { errorMessage := "error while trying to marshal the response body of the get all roles API: " + err.Error() - resp.StatusCode = http.StatusInternalServerError - resp.StatusMessage = response.InternalError - errorArgs[0].ErrorMessage = errorMessage - errorArgs[0].StatusMessage = resp.StatusMessage - resp.Body, _ = json.Marshal(args.CreateGenericErrorResponse()) + resp, args = mapResponseAndError(resp, args, errorMessage) l.LogWithFields(ctx).Error(resp.StatusMessage) return &resp, nil } @@ -229,18 +186,7 @@ func (r *Role) GetAllRoles(ctx context.Context, req *roleproto.GetRoleRequest) ( func (r *Role) UpdateRole(ctx context.Context, req *roleproto.UpdateRoleRequest) (*roleproto.RoleResponse, error) { ctx = getContext(ctx, common.SessionService) var resp roleproto.RoleResponse - errorArgs := []response.ErrArgs{ - response.ErrArgs{ - StatusMessage: "", - ErrorMessage: "", - MessageArgs: []interface{}{}, - }, - } - args := &response.Args{ - Code: response.GeneralError, - Message: "", - ErrorArgs: errorArgs, - } + args := account.GetResponseArgs("", "", []interface{}{}) l.LogWithFields(ctx).Info("Validating session and updating the last used time of the session before updating the role") // Validating the session @@ -252,8 +198,8 @@ func (r *Role) UpdateRole(ctx context.Context, req *roleproto.UpdateRoleRequest) err := UpdateLastUsedTimeFunc(ctx, req.SessionToken) if err != nil { - errorArgs[0].ErrorMessage, resp.StatusCode, resp.StatusMessage = validateUpdateLastUsedTimeError(ctx, err) - errorArgs[0].StatusMessage = resp.StatusMessage + args.ErrorArgs[0].ErrorMessage, resp.StatusCode, resp.StatusMessage = validateUpdateLastUsedTimeError(ctx, err) + args.ErrorArgs[0].StatusMessage = resp.StatusMessage resp.Body, _ = json.Marshal(args.CreateGenericErrorResponse()) return &resp, nil } @@ -265,11 +211,7 @@ func (r *Role) UpdateRole(ctx context.Context, req *roleproto.UpdateRoleRequest) body, err := MarshalFunc(data.Body) if err != nil { errorMessage := "error while trying to marshal the response body of the update role API: " + err.Error() - resp.StatusCode = http.StatusInternalServerError - resp.StatusMessage = response.InternalError - errorArgs[0].ErrorMessage = errorMessage - errorArgs[0].StatusMessage = resp.StatusMessage - resp.Body, _ = json.Marshal(args.CreateGenericErrorResponse()) + resp, args = mapResponseAndError(resp, args, errorMessage) l.LogWithFields(ctx).Error(resp.StatusMessage) return &resp, nil } @@ -283,18 +225,7 @@ func (r *Role) UpdateRole(ctx context.Context, req *roleproto.UpdateRoleRequest) func (r *Role) DeleteRole(ctx context.Context, req *roleproto.DeleteRoleRequest) (*roleproto.RoleResponse, error) { ctx = getContext(ctx, common.SessionService) var resp roleproto.RoleResponse - errorArgs := []response.ErrArgs{ - response.ErrArgs{ - StatusMessage: "", - ErrorMessage: "", - MessageArgs: []interface{}{}, - }, - } - args := &response.Args{ - Code: response.GeneralError, - Message: "", - ErrorArgs: errorArgs, - } + args := account.GetResponseArgs("", "", []interface{}{}) data := DeleteFunc(ctx, req) resp.StatusCode = data.StatusCode resp.StatusMessage = data.StatusMessage @@ -303,11 +234,7 @@ func (r *Role) DeleteRole(ctx context.Context, req *roleproto.DeleteRoleRequest) body, err := MarshalFunc(data.Body) if err != nil { errorMessage := "error while trying to marshal the response body of the delete role API: " + err.Error() - resp.StatusCode = http.StatusInternalServerError - resp.StatusMessage = response.InternalError - errorArgs[0].ErrorMessage = errorMessage - errorArgs[0].StatusMessage = resp.StatusMessage - resp.Body, _ = json.Marshal(args.CreateGenericErrorResponse()) + resp, args = mapResponseAndError(resp, args, errorMessage) l.LogWithFields(ctx).Error(resp.StatusMessage) return &resp, nil } @@ -316,3 +243,13 @@ func (r *Role) DeleteRole(ctx context.Context, req *roleproto.DeleteRoleRequest) return &resp, nil } + +func mapResponseAndError(resp roleproto.RoleResponse, args response.Args, errorMessage string) (roleproto.RoleResponse, response.Args) { + resp.StatusCode = http.StatusInternalServerError + resp.StatusMessage = response.InternalError + args.ErrorArgs[0].ErrorMessage = errorMessage + args.ErrorArgs[0].StatusMessage = resp.StatusMessage + resp.Body, _ = json.Marshal(args.CreateGenericErrorResponse()) + + return resp, args +} From 155da37109ace3a1ed82ed938237ca04aac7ff54 Mon Sep 17 00:00:00 2001 From: Banoshi Date: Tue, 27 Jun 2023 15:34:28 +0530 Subject: [PATCH 16/19] create mapper function for duplicate code block --- svc-account-session/role/create_test.go | 2 +- svc-account-session/role/getroles_test.go | 2 +- svc-account-session/rpc/account.go | 71 +++++++++--------- svc-account-session/rpc/role.go | 87 ++++++++++------------- 4 files changed, 74 insertions(+), 88 deletions(-) diff --git a/svc-account-session/role/create_test.go b/svc-account-session/role/create_test.go index f8c54b70a..296f657a9 100644 --- a/svc-account-session/role/create_test.go +++ b/svc-account-session/role/create_test.go @@ -24,9 +24,9 @@ import ( "github.com/ODIM-Project/ODIM/lib-utilities/config" roleproto "github.com/ODIM-Project/ODIM/lib-utilities/proto/role" "github.com/ODIM-Project/ODIM/lib-utilities/response" + "github.com/ODIM-Project/ODIM/svc-account-session/account" "github.com/ODIM-Project/ODIM/svc-account-session/asmodel" "github.com/ODIM-Project/ODIM/svc-account-session/asresponse" - "github.com/akshata-s-banoshi/Odim-Project/ODIM/svc-account-session/account" ) func mockRedfishRoles() error { diff --git a/svc-account-session/role/getroles_test.go b/svc-account-session/role/getroles_test.go index 2a4ddf216..e9311ab00 100644 --- a/svc-account-session/role/getroles_test.go +++ b/svc-account-session/role/getroles_test.go @@ -22,10 +22,10 @@ import ( "github.com/ODIM-Project/ODIM/lib-utilities/config" roleproto "github.com/ODIM-Project/ODIM/lib-utilities/proto/role" "github.com/ODIM-Project/ODIM/lib-utilities/response" + "github.com/ODIM-Project/ODIM/svc-account-session/account" "github.com/ODIM-Project/ODIM/svc-account-session/asmodel" "github.com/ODIM-Project/ODIM/svc-account-session/asresponse" "github.com/ODIM-Project/ODIM/svc-account-session/auth" - "github.com/akshata-s-banoshi/Odim-Project/ODIM/svc-account-session/account" ) func createMockRole(roleID string, privileges []string, oemPrivileges []string, predefined bool) error { diff --git a/svc-account-session/rpc/account.go b/svc-account-session/rpc/account.go index 15d13350f..165447aa6 100644 --- a/svc-account-session/rpc/account.go +++ b/svc-account-session/rpc/account.go @@ -74,17 +74,13 @@ func (a *Account) Create(ctx context.Context, req *accountproto.CreateAccountReq acc := account.GetExternalInterface() data, err := acc.Create(ctx, req, sess) - var jsonErr error // jsonErr is created to protect the data in err - body, jsonErr := MarshalFunc(data.Body) - if jsonErr != nil { - resp.StatusCode = http.StatusInternalServerError - resp.StatusMessage = "error while trying to marshal the response body of the create account API: " + jsonErr.Error() + errorMessage := "error while trying to marshal the response body of the create account API: " + resp, err = mapAccountResponse(resp, data, errorMessage) + if err != nil { l.LogWithFields(ctx).Error(resp.StatusMessage) return &resp, nil } - l.LogWithFields(ctx).Debugf("outgoing response of request to create an account: %s", string(body)) - resp = mapAccountResponse(resp, body, data) - + l.LogWithFields(ctx).Debugf("outgoing response of request to create an account: %s", string(resp.Body)) return &resp, nil } @@ -115,15 +111,13 @@ func (a *Account) GetAllAccounts(ctx context.Context, req *accountproto.AccountR } data := GetAllAccountsFunc(ctx, sess) - body, err := MarshalFunc(data.Body) + errorMessage := "error while trying to marshal the response body of the get all accounts API: " + resp, err = mapAccountResponse(resp, data, errorMessage) if err != nil { - resp.StatusCode = http.StatusInternalServerError - resp.StatusMessage = "error while trying to marshal the response body of the get all accounts API: " + err.Error() l.LogWithFields(ctx).Error(resp.StatusMessage) return &resp, fmt.Errorf(resp.StatusMessage) } - l.LogWithFields(ctx).Debugf("outgoing response of request to view all accounts: %s", string(body)) - resp = mapAccountResponse(resp, body, data) + l.LogWithFields(ctx).Debugf("outgoing response of request to view all accounts: %s", string(resp.Body)) return &resp, err } @@ -155,15 +149,13 @@ func (a *Account) GetAccount(ctx context.Context, req *accountproto.GetAccountRe } data := GetAccountFunc(ctx, sess, req.AccountID) - body, err := MarshalFunc(data.Body) + errorMessage := "error while trying to marshal the response body of the get account API: " + resp, err = mapAccountResponse(resp, data, errorMessage) if err != nil { - resp.StatusCode = http.StatusInternalServerError - resp.StatusMessage = "error while trying to marshal the response body of the get account API: " + err.Error() l.LogWithFields(ctx).Error(resp.StatusMessage) return &resp, fmt.Errorf(resp.StatusMessage) } - l.LogWithFields(ctx).Debugf("outgoing response of request to view the account: %s", string(body)) - resp = mapAccountResponse(resp, body, data) + l.LogWithFields(ctx).Debugf("outgoing response of request to view the account: %s", string(resp.Body)) return &resp, nil } @@ -194,15 +186,13 @@ func (a *Account) GetAccountServices(ctx context.Context, req *accountproto.Acco } data := GetAccountServiceFunc(ctx) - body, err := MarshalFunc(data.Body) + errorMessage := "error while trying to marshal the response body of the get account service API: " + resp, err = mapAccountResponse(resp, data, errorMessage) if err != nil { - resp.StatusCode = http.StatusInternalServerError - resp.StatusMessage = "error while trying to marshal the response body of the get account service API: " + err.Error() l.LogWithFields(ctx).Printf(resp.StatusMessage) return &resp, fmt.Errorf(resp.StatusMessage) } - l.LogWithFields(ctx).Debugf("outgoing response of request to view the account session: %s", string(body)) - resp = mapAccountResponse(resp, body, data) + l.LogWithFields(ctx).Debugf("outgoing response of request to view the account session: %s", string(resp.Body)) return &resp, err } @@ -235,15 +225,13 @@ func (a *Account) Update(ctx context.Context, req *accountproto.UpdateAccountReq acc := account.GetExternalInterface() data := acc.Update(ctx, req, sess) - body, err := MarshalFunc(data.Body) + errorMessage := "error while to trying to marshal the response body of the update account API: " + resp, err = mapAccountResponse(resp, data, errorMessage) if err != nil { - resp.StatusCode = http.StatusInternalServerError - resp.StatusMessage = "error while to trying to marshal the response body of the update account API: " + err.Error() l.LogWithFields(ctx).Printf(resp.StatusMessage) return &resp, nil } - l.LogWithFields(ctx).Debugf("outgoing response of request to update the account: %s", string(body)) - resp = mapAccountResponse(resp, body, data) + l.LogWithFields(ctx).Debugf("outgoing response of request to update the account: %s", string(resp.Body)) return &resp, nil } @@ -274,16 +262,13 @@ func (a *Account) Delete(ctx context.Context, req *accountproto.DeleteAccountReq } data := AccDeleteFunc(ctx, sess, req.AccountID) - var jsonErr error // jsonErr is created to protect the data in err - body, jsonErr := MarshalFunc(data.Body) - if jsonErr != nil { - resp.StatusCode = http.StatusInternalServerError - resp.StatusMessage = "error while trying to marshal the response body of the delete account API: " + jsonErr.Error() + errorMessage := "error while trying to marshal the response body of the delete account API: " + resp, err = mapAccountResponse(resp, data, errorMessage) + if err != nil { l.LogWithFields(ctx).Error(resp.StatusMessage) return &resp, nil } - l.LogWithFields(ctx).Debugf("outgoing response of request to delete the account: %s", string(body)) - resp = mapAccountResponse(resp, body, data) + l.LogWithFields(ctx).Debugf("outgoing response of request to delete the account: %s", string(resp.Body)) return &resp, nil } @@ -309,10 +294,22 @@ func validateUpdateLastUsedTimeError(ctx context.Context, err error) (errorMessa return } -func mapAccountResponse(resp accountproto.AccountResponse, body []byte, data response.RPC) accountproto.AccountResponse { +func mapAccountResponse(resp accountproto.AccountResponse, data response.RPC, errorMessage string) (accountproto.AccountResponse, error) { + // resp.Body = body + // resp.StatusCode = data.StatusCode + // resp.StatusMessage = data.StatusMessage + // resp.Header = data.Header + // return resp + body, jsonErr := MarshalFunc(data.Body) + if jsonErr != nil { + resp.StatusCode = http.StatusInternalServerError + resp.StatusMessage = errorMessage + jsonErr.Error() + return resp, jsonErr + } resp.Body = body resp.StatusCode = data.StatusCode resp.StatusMessage = data.StatusMessage resp.Header = data.Header - return resp + + return resp, nil } diff --git a/svc-account-session/rpc/role.go b/svc-account-session/rpc/role.go index 3521bbf25..189df3923 100644 --- a/svc-account-session/rpc/role.go +++ b/svc-account-session/rpc/role.go @@ -74,18 +74,14 @@ func (r *Role) CreateRole(ctx context.Context, req *roleproto.RoleRequest) (*rol } data := CreateFunc(ctx, req, sess) - resp.StatusCode = data.StatusCode - resp.StatusMessage = data.StatusMessage - resp.Header = data.Header - body, err := MarshalFunc(data.Body) + errorMessage := "error while trying to marshal the response body of create role API: " + resp, args, err = mapRoleResponse(resp, args, errorMessage, data) + if err != nil { - errorMessage := "error while trying to marshal the response body of create role API: " + err.Error() - resp, args = mapResponseAndError(resp, args, errorMessage) l.LogWithFields(ctx).Error(resp.StatusMessage) return &resp, nil } - l.LogWithFields(ctx).Debugf("outgoing response of request to create a role: %s", string(body)) - resp.Body = body + l.LogWithFields(ctx).Debugf("outgoing response of request to create a role: %s", string(resp.Body)) return &resp, nil } @@ -117,19 +113,16 @@ func (r *Role) GetRole(ctx context.Context, req *roleproto.GetRoleRequest) (*rol } data := GetRoleFunc(ctx, req, sess) - resp.StatusCode = data.StatusCode - resp.StatusMessage = data.StatusMessage - resp.Header = data.Header - body, err := MarshalFunc(data.Body) - if err != nil { - errorMessage := "error while trying to marshal the response body of get role API: " + err.Error() - resp, args = mapResponseAndError(resp, args, errorMessage) + errorMessage := "error while trying to marshal the response body of get role API: " + + resp, args, err = mapRoleResponse(resp, args, errorMessage, data) + + if err != nil { l.LogWithFields(ctx).Error(resp.StatusMessage) return &resp, nil } - l.LogWithFields(ctx).Debugf("outgoing response of request to view role details: %s", string(body)) - resp.Body = body + l.LogWithFields(ctx).Debugf("outgoing response of request to view role details: %s", string(resp.Body)) return &resp, nil } @@ -161,18 +154,14 @@ func (r *Role) GetAllRoles(ctx context.Context, req *roleproto.GetRoleRequest) ( } data := GetAllRolesFunc(ctx, sess) - resp.StatusCode = data.StatusCode - resp.StatusMessage = data.StatusMessage - resp.Header = data.Header - body, err := MarshalFunc(data.Body) + errorMessage := "error while trying to marshal the response body of the get all roles API: " + resp, args, err = mapRoleResponse(resp, args, errorMessage, data) + if err != nil { - errorMessage := "error while trying to marshal the response body of the get all roles API: " + err.Error() - resp, args = mapResponseAndError(resp, args, errorMessage) l.LogWithFields(ctx).Error(resp.StatusMessage) return &resp, nil } - l.LogWithFields(ctx).Debugf("outgoing response of request to view all roles: %s", string(body)) - resp.Body = body + l.LogWithFields(ctx).Debugf("outgoing response of request to view all roles: %s", string(resp.Body)) return &resp, nil } @@ -205,18 +194,14 @@ func (r *Role) UpdateRole(ctx context.Context, req *roleproto.UpdateRoleRequest) } data := UpdateFunc(ctx, req, sess) - resp.StatusCode = data.StatusCode - resp.StatusMessage = data.StatusMessage - resp.Header = data.Header - body, err := MarshalFunc(data.Body) + errorMessage := "error while trying to marshal the response body of the update role API: " + resp, args, err = mapRoleResponse(resp, args, errorMessage, data) + if err != nil { - errorMessage := "error while trying to marshal the response body of the update role API: " + err.Error() - resp, args = mapResponseAndError(resp, args, errorMessage) l.LogWithFields(ctx).Error(resp.StatusMessage) return &resp, nil } - l.LogWithFields(ctx).Debugf("outgoing response of request to update the role: %s", string(body)) - resp.Body = body + l.LogWithFields(ctx).Debugf("outgoing response of request to update the role: %s", string(resp.Body)) return &resp, nil } @@ -227,29 +212,33 @@ func (r *Role) DeleteRole(ctx context.Context, req *roleproto.DeleteRoleRequest) var resp roleproto.RoleResponse args := account.GetResponseArgs("", "", []interface{}{}) data := DeleteFunc(ctx, req) - resp.StatusCode = data.StatusCode - resp.StatusMessage = data.StatusMessage - resp.Header = data.Header var err error - body, err := MarshalFunc(data.Body) + errorMessage := "error while trying to marshal the response body of the delete role API: " + + resp, args, err = mapRoleResponse(resp, args, errorMessage, *data) + if err != nil { - errorMessage := "error while trying to marshal the response body of the delete role API: " + err.Error() - resp, args = mapResponseAndError(resp, args, errorMessage) l.LogWithFields(ctx).Error(resp.StatusMessage) return &resp, nil } - l.LogWithFields(ctx).Debugf("outgoing response of request to delete the role: %s", string(body)) - resp.Body = body + l.LogWithFields(ctx).Debugf("outgoing response of request to delete the role: %s", string(resp.Body)) return &resp, nil } -func mapResponseAndError(resp roleproto.RoleResponse, args response.Args, errorMessage string) (roleproto.RoleResponse, response.Args) { - resp.StatusCode = http.StatusInternalServerError - resp.StatusMessage = response.InternalError - args.ErrorArgs[0].ErrorMessage = errorMessage - args.ErrorArgs[0].StatusMessage = resp.StatusMessage - resp.Body, _ = json.Marshal(args.CreateGenericErrorResponse()) - - return resp, args +func mapRoleResponse(resp roleproto.RoleResponse, args response.Args, errorMessage string, data response.RPC) (roleproto.RoleResponse, response.Args, error) { + resp.StatusCode = data.StatusCode + resp.StatusMessage = data.StatusMessage + resp.Header = data.Header + body, err := MarshalFunc(data.Body) + if err != nil { + resp.StatusCode = http.StatusInternalServerError + resp.StatusMessage = response.InternalError + args.ErrorArgs[0].ErrorMessage = errorMessage + err.Error() + args.ErrorArgs[0].StatusMessage = resp.StatusMessage + resp.Body, _ = json.Marshal(args.CreateGenericErrorResponse()) + return resp, args, err + } + resp.Body = body + return resp, args, nil } From e245365a5008adabf7e5dd24a05791b2f01508cf Mon Sep 17 00:00:00 2001 From: Banoshi Date: Tue, 27 Jun 2023 17:08:55 +0530 Subject: [PATCH 17/19] ran go tools --- svc-account-session/asmodel/privilege.go | 8 +-- svc-account-session/asmodel/redfishroles.go | 4 +- svc-account-session/asmodel/sessions.go | 2 +- svc-account-session/asmodel/userRole.go | 6 +-- svc-account-session/asresponse/accounts.go | 10 ++-- svc-account-session/asresponse/error.go | 6 +-- svc-account-session/asresponse/privilege.go | 2 +- svc-account-session/asresponse/session.go | 6 +-- svc-account-session/rpc/account.go | 37 +++++-------- svc-account-session/session/delete.go | 24 +++------ svc-account-session/session/delete_test.go | 39 +++----------- svc-account-session/session/getsession.go | 54 ++++++++----------- .../session/getsession_test.go | 52 +++--------------- 13 files changed, 79 insertions(+), 171 deletions(-) diff --git a/svc-account-session/asmodel/privilege.go b/svc-account-session/asmodel/privilege.go index 419ddfd8a..e6e69cb67 100644 --- a/svc-account-session/asmodel/privilege.go +++ b/svc-account-session/asmodel/privilege.go @@ -22,12 +22,12 @@ import ( "github.com/ODIM-Project/ODIM/lib-utilities/errors" ) -//Privileges struct definition +// Privileges struct definition type Privileges struct { List []string } -//GetPrivilegeRegistry retrives the privileges from database +// GetPrivilegeRegistry retrives the privileges from database func GetPrivilegeRegistry() (Privileges, *errors.Error) { var privileges Privileges conn, err := GetDBConnectionFunc(common.OnDisk) @@ -57,12 +57,12 @@ func (p *Privileges) Create() *errors.Error { return nil } -//OEMPrivileges struct definition +// OEMPrivileges struct definition type OEMPrivileges struct { List []string } -//GetOEMPrivileges retrives the privileges from database +// GetOEMPrivileges retrives the privileges from database func GetOEMPrivileges() (OEMPrivileges, *errors.Error) { var oemPrivileges OEMPrivileges conn, err := GetDBConnectionFunc(common.OnDisk) diff --git a/svc-account-session/asmodel/redfishroles.go b/svc-account-session/asmodel/redfishroles.go index d03e59e51..424f4063b 100644 --- a/svc-account-session/asmodel/redfishroles.go +++ b/svc-account-session/asmodel/redfishroles.go @@ -22,12 +22,12 @@ import ( "github.com/ODIM-Project/ODIM/lib-utilities/errors" ) -//RedfishRoles struct definition +// RedfishRoles struct definition type RedfishRoles struct { List []string } -//GetRedfishRoles retrives the privileges from database +// GetRedfishRoles retrives the privileges from database func GetRedfishRoles() (RedfishRoles, *errors.Error) { var redfishRoles RedfishRoles conn, err := GetDBConnectionFunc(common.OnDisk) diff --git a/svc-account-session/asmodel/sessions.go b/svc-account-session/asmodel/sessions.go index 77a5b9133..1f91f600c 100644 --- a/svc-account-session/asmodel/sessions.go +++ b/svc-account-session/asmodel/sessions.go @@ -37,7 +37,7 @@ type Session struct { LastUsedTime time.Time } -//CreateSession will hold input request for creating a session +// CreateSession will hold input request for creating a session type CreateSession struct { UserName string `json:"UserName"` Password string `json:"Password"` diff --git a/svc-account-session/asmodel/userRole.go b/svc-account-session/asmodel/userRole.go index 635dbc026..f818a3d52 100644 --- a/svc-account-session/asmodel/userRole.go +++ b/svc-account-session/asmodel/userRole.go @@ -62,7 +62,7 @@ func GetRoleDetailsByID(roleID string) (Role, *errors.Error) { return role, nil } -//UpdateRoleDetails will modify the current details to given changes +// UpdateRoleDetails will modify the current details to given changes func (r *Role) UpdateRoleDetails() *errors.Error { conn, err := GetDBConnectionFunc(common.OnDisk) @@ -75,7 +75,7 @@ func (r *Role) UpdateRoleDetails() *errors.Error { return nil } -//GetAllRoles gets all the roles from the db +// GetAllRoles gets all the roles from the db func GetAllRoles() ([]Role, *errors.Error) { conn, err := GetDBConnectionFunc(common.OnDisk) if err != nil { @@ -102,7 +102,7 @@ func GetAllRoles() ([]Role, *errors.Error) { return roles, nil } -//Delete will delete the role entry from the database based on the uuid +// Delete will delete the role entry from the database based on the uuid func (r *Role) Delete() *errors.Error { conn, err := GetDBConnectionFunc(common.OnDisk) if err != nil { diff --git a/svc-account-session/asresponse/accounts.go b/svc-account-session/asresponse/accounts.go index 3c96b26e1..fb88cccd9 100644 --- a/svc-account-session/asresponse/accounts.go +++ b/svc-account-session/asresponse/accounts.go @@ -31,21 +31,21 @@ type Account struct { OEM *OEM `json:"Oem,omitempty"` } -//OEM struct definition +// OEM struct definition type OEM struct { } -//Links struct definition +// Links struct definition type Links struct { Role Role `json:"Role"` } -//Role struct definition +// Role struct definition type Role struct { OdataID string `json:"@odata.id"` } -//AccountService struct definition +// AccountService struct definition type AccountService struct { response.Response Status Status `json:"Status,omitempty"` @@ -75,7 +75,7 @@ type AccountService struct { TACACSplus *TACACSplus `json:"TACACSplus,omitempty"` } -//Accounts struct definition +// Accounts struct definition type Accounts struct { OdataID string `json:"@odata.id"` } diff --git a/svc-account-session/asresponse/error.go b/svc-account-session/asresponse/error.go index b21c11ee7..0663b09a2 100644 --- a/svc-account-session/asresponse/error.go +++ b/svc-account-session/asresponse/error.go @@ -15,19 +15,19 @@ // Package asresponse ... package asresponse -//CommonError struct definition +// CommonError struct definition type CommonError struct { Error ErrorClass `json:"error"` } -//ErrorClass struct definition +// ErrorClass struct definition type ErrorClass struct { Code string `json:"code"` Message string `json:"message"` MessageExtendedInfo []MsgExtendedInfo `json:"@Message.ExtendedInfo"` } -//MsgExtendedInfo struct definition +// MsgExtendedInfo struct definition type MsgExtendedInfo struct { OdataType string `json:"@odata.type"` MessageID string `json:"MessageId"` diff --git a/svc-account-session/asresponse/privilege.go b/svc-account-session/asresponse/privilege.go index eb6928ad8..6c84dcd87 100644 --- a/svc-account-session/asresponse/privilege.go +++ b/svc-account-session/asresponse/privilege.go @@ -19,7 +19,7 @@ import ( "github.com/ODIM-Project/ODIM/lib-utilities/response" ) -//Privileges strcut definition used to build response +// Privileges strcut definition used to build response type Privileges struct { response.Response PrivilegesUsed []string `json:"PrivilegesUsed"` diff --git a/svc-account-session/asresponse/session.go b/svc-account-session/asresponse/session.go index 60e2cd099..09b0cc513 100644 --- a/svc-account-session/asresponse/session.go +++ b/svc-account-session/asresponse/session.go @@ -43,7 +43,7 @@ type Session struct { CreatedTime string `json:"CreatedTime,omitempty"` } -//SessionService struct definition +// SessionService struct definition type SessionService struct { response.Response Status Status `json:"Status,omitempty"` @@ -52,12 +52,12 @@ type SessionService struct { Sessions Sessions `json:"Sessions,omitempty"` } -//Sessions struct definition +// Sessions struct definition type Sessions struct { OdataID string `json:"@odata.id"` } -//Status struct definition +// Status struct definition type Status struct { State string `json:"State"` Health string `json:"Health"` diff --git a/svc-account-session/rpc/account.go b/svc-account-session/rpc/account.go index 165447aa6..4e15abaf6 100644 --- a/svc-account-session/rpc/account.go +++ b/svc-account-session/rpc/account.go @@ -66,9 +66,7 @@ func (a *Account) Create(ctx context.Context, req *accountproto.CreateAccountReq err := UpdateLastUsedTimeFunc(ctx, req.SessionToken) if err != nil { - args.ErrorArgs[0].ErrorMessage, resp.StatusCode, resp.StatusMessage = validateUpdateLastUsedTimeError(ctx, err) - args.ErrorArgs[0].StatusMessage = resp.StatusMessage - resp.Body, _ = json.Marshal(args.CreateGenericErrorResponse()) + resp = mapErrorResponse(ctx, resp, args, err) return &resp, nil } @@ -104,9 +102,7 @@ func (a *Account) GetAllAccounts(ctx context.Context, req *accountproto.AccountR err := UpdateLastUsedTimeFunc(ctx, req.SessionToken) if err != nil { - args.ErrorArgs[0].ErrorMessage, resp.StatusCode, resp.StatusMessage = validateUpdateLastUsedTimeError(ctx, err) - args.ErrorArgs[0].StatusMessage = resp.StatusMessage - resp.Body, _ = json.Marshal(args.CreateGenericErrorResponse()) + resp = mapErrorResponse(ctx, resp, args, err) return &resp, nil } @@ -142,9 +138,7 @@ func (a *Account) GetAccount(ctx context.Context, req *accountproto.GetAccountRe err := UpdateLastUsedTimeFunc(ctx, req.SessionToken) if err != nil { - args.ErrorArgs[0].ErrorMessage, resp.StatusCode, resp.StatusMessage = validateUpdateLastUsedTimeError(ctx, err) - args.ErrorArgs[0].StatusMessage = resp.StatusMessage - resp.Body, _ = json.Marshal(args.CreateGenericErrorResponse()) + resp = mapErrorResponse(ctx, resp, args, err) return &resp, nil } @@ -179,9 +173,7 @@ func (a *Account) GetAccountServices(ctx context.Context, req *accountproto.Acco err := UpdateLastUsedTimeFunc(ctx, req.SessionToken) if err != nil { - args.ErrorArgs[0].ErrorMessage, resp.StatusCode, resp.StatusMessage = validateUpdateLastUsedTimeError(ctx, err) - args.ErrorArgs[0].StatusMessage = resp.StatusMessage - resp.Body, _ = json.Marshal(args.CreateGenericErrorResponse()) + resp = mapErrorResponse(ctx, resp, args, err) return &resp, nil } @@ -216,9 +208,7 @@ func (a *Account) Update(ctx context.Context, req *accountproto.UpdateAccountReq err := UpdateLastUsedTimeFunc(ctx, req.SessionToken) if err != nil { - args.ErrorArgs[0].ErrorMessage, resp.StatusCode, resp.StatusMessage = validateUpdateLastUsedTimeError(ctx, err) - args.ErrorArgs[0].StatusMessage = resp.StatusMessage - resp.Body, _ = json.Marshal(args.CreateGenericErrorResponse()) + resp = mapErrorResponse(ctx, resp, args, err) return &resp, nil } @@ -255,9 +245,7 @@ func (a *Account) Delete(ctx context.Context, req *accountproto.DeleteAccountReq err := UpdateLastUsedTimeFunc(ctx, req.SessionToken) if err != nil { - args.ErrorArgs[0].ErrorMessage, resp.StatusCode, resp.StatusMessage = validateUpdateLastUsedTimeError(ctx, err) - args.ErrorArgs[0].StatusMessage = resp.StatusMessage - resp.Body, _ = json.Marshal(args.CreateGenericErrorResponse()) + resp = mapErrorResponse(ctx, resp, args, err) return &resp, nil } @@ -295,11 +283,6 @@ func validateUpdateLastUsedTimeError(ctx context.Context, err error) (errorMessa } func mapAccountResponse(resp accountproto.AccountResponse, data response.RPC, errorMessage string) (accountproto.AccountResponse, error) { - // resp.Body = body - // resp.StatusCode = data.StatusCode - // resp.StatusMessage = data.StatusMessage - // resp.Header = data.Header - // return resp body, jsonErr := MarshalFunc(data.Body) if jsonErr != nil { resp.StatusCode = http.StatusInternalServerError @@ -313,3 +296,11 @@ func mapAccountResponse(resp accountproto.AccountResponse, data response.RPC, er return resp, nil } + +func mapErrorResponse(ctx context.Context, resp accountproto.AccountResponse, args response.Args, err error) accountproto.AccountResponse { + args.ErrorArgs[0].ErrorMessage, resp.StatusCode, resp.StatusMessage = validateUpdateLastUsedTimeError(ctx, err) + args.ErrorArgs[0].StatusMessage = resp.StatusMessage + resp.Body, _ = json.Marshal(args.CreateGenericErrorResponse()) + + return resp +} diff --git a/svc-account-session/session/delete.go b/svc-account-session/session/delete.go index bd01d3d7a..7430e02f1 100644 --- a/svc-account-session/session/delete.go +++ b/svc-account-session/session/delete.go @@ -23,6 +23,7 @@ import ( l "github.com/ODIM-Project/ODIM/lib-utilities/logs" sessionproto "github.com/ODIM-Project/ODIM/lib-utilities/proto/session" "github.com/ODIM-Project/ODIM/lib-utilities/response" + "github.com/ODIM-Project/ODIM/svc-account-session/account" "github.com/ODIM-Project/ODIM/svc-account-session/asmodel" "github.com/ODIM-Project/ODIM/svc-account-session/auth" ) @@ -34,18 +35,7 @@ import ( func DeleteSession(ctx context.Context, req *sessionproto.SessionRequest) response.RPC { var resp response.RPC errorLogPrefix := "failed to delete session : " - errorArgs := []response.ErrArgs{ - response.ErrArgs{ - StatusMessage: "", - ErrorMessage: "", - MessageArgs: []interface{}{}, - }, - } - args := &response.Args{ - Code: response.GeneralError, - Message: "", - ErrorArgs: errorArgs, - } + args := account.GetResponseArgs("", "", []interface{}{}) l.LogWithFields(ctx).Info("Validating the request to delete the session") currentSession, serr := asmodel.GetSession(req.SessionToken) if serr != nil { @@ -93,8 +83,8 @@ func DeleteSession(ctx context.Context, req *sessionproto.SessionRequest) respon errorMessage := errorLogPrefix + "Insufficient privileges" resp.StatusCode = http.StatusForbidden resp.StatusMessage = response.InsufficientPrivilege - errorArgs[0].ErrorMessage = errorMessage - errorArgs[0].StatusMessage = resp.StatusMessage + args.ErrorArgs[0].ErrorMessage = errorMessage + args.ErrorArgs[0].StatusMessage = resp.StatusMessage resp.Body = args.CreateGenericErrorResponse() auth.CustomAuthLog(ctx, req.SessionToken, errorMessage, resp.StatusCode) return resp @@ -105,9 +95,9 @@ func DeleteSession(ctx context.Context, req *sessionproto.SessionRequest) respon l.LogWithFields(ctx).Error(errorMessage) resp.StatusCode = http.StatusNotFound resp.StatusMessage = response.ResourceNotFound - errorArgs[0].ErrorMessage = errorMessage - errorArgs[0].StatusMessage = resp.StatusMessage - errorArgs[0].MessageArgs = []interface{}{"Session", req.SessionId} + args.ErrorArgs[0].ErrorMessage = errorMessage + args.ErrorArgs[0].StatusMessage = resp.StatusMessage + args.ErrorArgs[0].MessageArgs = []interface{}{"Session", req.SessionId} resp.Body = args.CreateGenericErrorResponse() return resp } diff --git a/svc-account-session/session/delete_test.go b/svc-account-session/session/delete_test.go index 8b80a18fc..bba5720db 100644 --- a/svc-account-session/session/delete_test.go +++ b/svc-account-session/session/delete_test.go @@ -24,6 +24,7 @@ import ( "github.com/ODIM-Project/ODIM/lib-utilities/config" sessionproto "github.com/ODIM-Project/ODIM/lib-utilities/proto/session" "github.com/ODIM-Project/ODIM/lib-utilities/response" + "github.com/ODIM-Project/ODIM/svc-account-session/account" "github.com/ODIM-Project/ODIM/svc-account-session/asmodel" "github.com/ODIM-Project/ODIM/svc-account-session/auth" ) @@ -75,39 +76,11 @@ func TestDeleteSession(t *testing.T) { req *sessionproto.SessionRequest } - errArgUnauth := &response.Args{ - Code: response.GeneralError, - Message: "", - ErrorArgs: []response.ErrArgs{ - response.ErrArgs{ - StatusMessage: response.NoValidSession, - ErrorMessage: "failed to delete session : error while trying to get the session from DB: no data with the with key found", - MessageArgs: []interface{}{}, - }, - }, - } - eArgs := &response.Args{ - Code: response.GeneralError, - Message: "", - ErrorArgs: []response.ErrArgs{ - response.ErrArgs{ - StatusMessage: response.ResourceNotFound, - ErrorMessage: "failed to delete session : Session ID not found", - MessageArgs: []interface{}{"Session", "invalid-id"}, - }, - }, - } - errArgIns := &response.Args{ - Code: response.GeneralError, - Message: "", - ErrorArgs: []response.ErrArgs{ - response.ErrArgs{ - StatusMessage: response.InsufficientPrivilege, - ErrorMessage: "failed to delete session : Insufficient privileges", - MessageArgs: []interface{}{}, - }, - }, - } + errArgUnauth := account.GetResponseArgs(response.NoValidSession, "failed to delete session : error while trying to get the session from DB: no data with the with key found", []interface{}{}) + + eArgs := account.GetResponseArgs(response.ResourceNotFound, "failed to delete session : Session ID not found", []interface{}{"Session", "invalid-id"}) + + errArgIns := account.GetResponseArgs(response.InsufficientPrivilege, "failed to delete session : Insufficient privileges", []interface{}{}) tests := []struct { name string diff --git a/svc-account-session/session/getsession.go b/svc-account-session/session/getsession.go index f502273e1..7737366e4 100644 --- a/svc-account-session/session/getsession.go +++ b/svc-account-session/session/getsession.go @@ -25,6 +25,7 @@ import ( l "github.com/ODIM-Project/ODIM/lib-utilities/logs" sessionproto "github.com/ODIM-Project/ODIM/lib-utilities/proto/session" "github.com/ODIM-Project/ODIM/lib-utilities/response" + "github.com/ODIM-Project/ODIM/svc-account-session/account" "github.com/ODIM-Project/ODIM/svc-account-session/asmodel" "github.com/ODIM-Project/ODIM/svc-account-session/asresponse" "github.com/ODIM-Project/ODIM/svc-account-session/auth" @@ -83,19 +84,7 @@ func GetSession(ctx context.Context, req *sessionproto.SessionRequest) response. } var resp response.RPC errLogPrefix := "failed to fetch the session : " - - errorArgs := []response.ErrArgs{ - response.ErrArgs{ - StatusMessage: "", - ErrorMessage: "", - MessageArgs: []interface{}{}, - }, - } - args := &response.Args{ - Code: response.GeneralError, - Message: "", - ErrorArgs: errorArgs, - } + args := account.GetResponseArgs("", "", []interface{}{}) l.LogWithFields(ctx).Info("Validating the request to fetch the session") // Validating the session @@ -155,8 +144,8 @@ func GetSession(ctx context.Context, req *sessionproto.SessionRequest) response. errorMessage := errLogPrefix + "The session doesn't have the requisite privileges for the action" resp.StatusCode = http.StatusForbidden resp.StatusMessage = response.InsufficientPrivilege - errorArgs[0].ErrorMessage = errorMessage - errorArgs[0].StatusMessage = resp.StatusMessage + args.ErrorArgs[0].ErrorMessage = errorMessage + args.ErrorArgs[0].StatusMessage = resp.StatusMessage resp.Body = args.CreateGenericErrorResponse() auth.CustomAuthLog(ctx, req.SessionToken, errorMessage, resp.StatusCode) return resp @@ -167,9 +156,9 @@ func GetSession(ctx context.Context, req *sessionproto.SessionRequest) response. l.LogWithFields(ctx).Error(errLogPrefix + errorMessage) resp.StatusCode = http.StatusNotFound resp.StatusMessage = response.ResourceNotFound - errorArgs[0].ErrorMessage = errorMessage - errorArgs[0].StatusMessage = resp.StatusMessage - errorArgs[0].MessageArgs = []interface{}{"Session", req.SessionId} + args.ErrorArgs[0].ErrorMessage = errorMessage + args.ErrorArgs[0].StatusMessage = resp.StatusMessage + args.ErrorArgs[0].MessageArgs = []interface{}{"Session", req.SessionId} resp.Body = args.CreateGenericErrorResponse() return resp } @@ -189,18 +178,19 @@ func GetAllActiveSessions(ctx context.Context, req *sessionproto.SessionRequest) var resp response.RPC errorLogPrefix := "failed to fetch all active sessions : " - errorArgs := []response.ErrArgs{ - response.ErrArgs{ - StatusMessage: "", - ErrorMessage: "", - MessageArgs: []interface{}{}, - }, - } - args := &response.Args{ - Code: response.GeneralError, - Message: "", - ErrorArgs: errorArgs, - } + // errorArgs := []response.ErrArgs{ + // response.ErrArgs{ + // StatusMessage: "", + // ErrorMessage: "", + // MessageArgs: []interface{}{}, + // }, + // } + // args := &response.Args{ + // Code: response.GeneralError, + // Message: "", + // ErrorArgs: errorArgs, + // } + args := account.GetResponseArgs("", "", []interface{}{}) l.LogWithFields(ctx).Info("fetching all active sessions") // Validating the session @@ -230,8 +220,8 @@ func GetAllActiveSessions(ctx context.Context, req *sessionproto.SessionRequest) errorMessage := errorLogPrefix + "Insufficient privileges: " + err.Error() resp.StatusCode = http.StatusForbidden resp.StatusMessage = response.InsufficientPrivilege - errorArgs[0].ErrorMessage = errorMessage - errorArgs[0].StatusMessage = resp.StatusMessage + args.ErrorArgs[0].ErrorMessage = errorMessage + args.ErrorArgs[0].StatusMessage = resp.StatusMessage resp.Body = args.CreateGenericErrorResponse() auth.CustomAuthLog(ctx, req.SessionToken, errorMessage, resp.StatusCode) return resp diff --git a/svc-account-session/session/getsession_test.go b/svc-account-session/session/getsession_test.go index 9c5ee5086..e7886ccbf 100644 --- a/svc-account-session/session/getsession_test.go +++ b/svc-account-session/session/getsession_test.go @@ -25,6 +25,7 @@ import ( "github.com/ODIM-Project/ODIM/lib-utilities/config" sessionproto "github.com/ODIM-Project/ODIM/lib-utilities/proto/session" "github.com/ODIM-Project/ODIM/lib-utilities/response" + "github.com/ODIM-Project/ODIM/svc-account-session/account" "github.com/ODIM-Project/ODIM/svc-account-session/asresponse" "github.com/ODIM-Project/ODIM/svc-account-session/auth" ) @@ -56,28 +57,9 @@ func TestGetSession(t *testing.T) { "X-Auth-Token": sessionToken, } - errArgUnauth := &response.Args{ - Code: response.GeneralError, - Message: "", - ErrorArgs: []response.ErrArgs{ - response.ErrArgs{ - StatusMessage: response.NoValidSession, - ErrorMessage: "failed to fetch the session : Unable to authorize session token: error while trying to get session details: error while trying to get the session from DB: no data with the with key invalid-token found", - MessageArgs: []interface{}{}, - }, - }, - } - eArgs := &response.Args{ - Code: response.GeneralError, - Message: "", - ErrorArgs: []response.ErrArgs{ - response.ErrArgs{ - StatusMessage: response.ResourceNotFound, - ErrorMessage: "No session with id invalid-sessionID found.", - MessageArgs: []interface{}{"Session", "invalid-sessionID"}, - }, - }, - } + errArgUnauth := account.GetResponseArgs(response.NoValidSession, "failed to fetch the session : Unable to authorize session token: error while trying to get session details: error while trying to get the session from DB: no data with the with key invalid-token found", []interface{}{}) + + eArgs := account.GetResponseArgs(response.ResourceNotFound, "No session with id invalid-sessionID found.", []interface{}{"Session", "invalid-sessionID"}) ctx := mockContext() type args struct { req *sessionproto.SessionRequest @@ -168,28 +150,10 @@ func TestGetAllActiveSessions(t *testing.T) { listMembers = append(listMembers, asresponse.ListMember{ OdataID: "/redfish/v1/SessionService/Sessions/" + sessionID, }) - eArgs1 := &response.Args{ - Code: response.GeneralError, - Message: "", - ErrorArgs: []response.ErrArgs{ - response.ErrArgs{ - StatusMessage: response.NoValidSession, - ErrorMessage: "failed to fetch all active sessions : Unable to authorize session token: error: no session token found in header", - MessageArgs: []interface{}{}, - }, - }, - } - errArgUnauth2 := &response.Args{ - Code: response.GeneralError, - Message: "", - ErrorArgs: []response.ErrArgs{ - response.ErrArgs{ - StatusMessage: response.NoValidSession, - ErrorMessage: "failed to fetch all active sessions : Unable to authorize session token: error while trying to get session details: error while trying to get the session from DB: no data with the with key invalidToken found", - MessageArgs: []interface{}{}, - }, - }, - } + + eArgs1 := account.GetResponseArgs(response.NoValidSession, "failed to fetch all active sessions : Unable to authorize session token: error: no session token found in header", []interface{}{}) + + errArgUnauth2 := account.GetResponseArgs(response.NoValidSession, "failed to fetch all active sessions : Unable to authorize session token: error while trying to get session details: error while trying to get the session from DB: no data with the with key invalidToken found", []interface{}{}) ctx := mockContext() type args struct { req *sessionproto.SessionRequest From 66bd3bbc1f9a1446923705dbacb6fa37b86e85de Mon Sep 17 00:00:00 2001 From: Banoshi Date: Tue, 27 Jun 2023 21:59:05 +0530 Subject: [PATCH 18/19] refactor test files --- .../account/getaccounts_test.go | 52 +++++++------------ svc-account-session/account/update_test.go | 40 ++++++-------- svc-account-session/role/create_test.go | 41 ++++++--------- 3 files changed, 50 insertions(+), 83 deletions(-) diff --git a/svc-account-session/account/getaccounts_test.go b/svc-account-session/account/getaccounts_test.go index 8804e776a..138953e17 100644 --- a/svc-account-session/account/getaccounts_test.go +++ b/svc-account-session/account/getaccounts_test.go @@ -38,18 +38,9 @@ func TestGetAllAccounts(t *testing.T) { t.Fatalf("error: %v", err) } }() - successResponse := response.Response{ - OdataType: "#ManagerAccountCollection.ManagerAccountCollection", - OdataID: "/redfish/v1/AccountService/Accounts", - OdataContext: "/redfish/v1/$metadata#ManagerAccountCollection.ManagerAccountCollection", - ID: "Accounts", - Name: "Account Service", - } - successResponse.CreateGenericResponse(response.Success) - successResponse.Message = "" + + successResponse := createMockResponseObject("#ManagerAccountCollection.ManagerAccountCollection", "/redfish/v1/AccountService/Accounts", "/redfish/v1/$metadata#ManagerAccountCollection.ManagerAccountCollection", "Accounts") successResponse.ID = "" - successResponse.MessageID = "" - successResponse.Severity = "" err := createMockUser("testUser1", common.RoleAdmin) if err != nil { @@ -120,17 +111,7 @@ func TestGetAllAccounts(t *testing.T) { } func TestGetAccount(t *testing.T) { - successResponse := response.Response{ - OdataType: common.ManagerAccountType, - OdataID: "/redfish/v1/AccountService/Accounts/testUser1", - OdataContext: "/redfish/v1/$metadata#ManagerAccount.ManagerAccount", - ID: "testUser1", - Name: "Account Service", - } - successResponse.CreateGenericResponse(response.Success) - successResponse.Message = "" - successResponse.MessageID = "" - successResponse.Severity = "" + successResponse := createMockResponseObject(common.ManagerAccountType, "/redfish/v1/AccountService/Accounts/testUser1", "/redfish/v1/$metadata#ManagerAccount.ManagerAccount", "testUser1") config.SetUpMockConfig(t) err := createMockUser("testUser1", common.RoleAdmin) if err != nil { @@ -273,17 +254,7 @@ func TestGetAccount(t *testing.T) { } func TestGetAccountService(t *testing.T) { - successResponse := response.Response{ - OdataType: common.AccountServiceType, - OdataID: "/redfish/v1/AccountService", - OdataContext: "/redfish/v1/$metadata#AccountService.AccountService", - ID: "AccountService", - Name: "Account Service", - } - successResponse.CreateGenericResponse(response.Success) - successResponse.Message = "" - successResponse.MessageID = "" - successResponse.Severity = "" + successResponse := createMockResponseObject(common.AccountServiceType, "/redfish/v1/AccountService", "/redfish/v1/$metadata#AccountService.AccountService", "AccountService") common.SetUpMockConfig() tests := []struct { name string @@ -351,3 +322,18 @@ func TestGetAccountService(t *testing.T) { config.Data.EnabledServices = []string{"XXXX"} } } + +func createMockResponseObject(odataType, odataID, odataContext, ID string) response.Response { + successResponse := response.Response{ + OdataType: odataType, + OdataID: odataID, + OdataContext: odataContext, + ID: ID, + Name: "Account Service", + } + successResponse.CreateGenericResponse(response.Success) + successResponse.Message = "" + successResponse.MessageID = "" + successResponse.Severity = "" + return successResponse +} diff --git a/svc-account-session/account/update_test.go b/svc-account-session/account/update_test.go index d3be34134..7ad561f7c 100644 --- a/svc-account-session/account/update_test.go +++ b/svc-account-session/account/update_test.go @@ -31,33 +31,11 @@ func TestUpdate(t *testing.T) { config.SetUpMockConfig(t) acc := getMockExternalInterface() - successResponse := response.Response{ - OdataType: common.ManagerAccountType, - OdataID: "/redfish/v1/AccountService/Accounts/testUser1", - OdataContext: "/redfish/v1/$metadata#ManagerAccount.ManagerAccount", - ID: "testUser1", - Name: "Account Service", - } + successResponse := createMockUpdateResponseObject(common.ManagerAccountType, "/redfish/v1/AccountService/Accounts/testUser1", "/redfish/v1/$metadata#ManagerAccount.ManagerAccount", "testUser1") - operatorSuccessResponse := response.Response{ - OdataType: common.ManagerAccountType, - OdataID: "/redfish/v1/AccountService/Accounts/operatorUser", - OdataContext: "/redfish/v1/$metadata#ManagerAccount.ManagerAccount", - ID: "operatorUser", - Name: "Account Service", - } + operatorSuccessResponse := createMockUpdateResponseObject(common.ManagerAccountType, "/redfish/v1/AccountService/Accounts/operatorUser", "/redfish/v1/$metadata#ManagerAccount.ManagerAccount", "operatorUser") - successResponse2 := response.Response{ - OdataType: common.ManagerAccountType, - OdataID: "/redfish/v1/AccountService/Accounts/testUser2", - OdataContext: "/redfish/v1/$metadata#ManagerAccount.ManagerAccount", - ID: "testUser2", - Name: "Account Service", - } - - successResponse.CreateGenericResponse(response.AccountModified) - successResponse2.CreateGenericResponse(response.AccountModified) - operatorSuccessResponse.CreateGenericResponse(response.AccountModified) + successResponse2 := createMockUpdateResponseObject(common.ManagerAccountType, "/redfish/v1/AccountService/Accounts/testUser2", "/redfish/v1/$metadata#ManagerAccount.ManagerAccount", "testUser2") errArg := GetResponseArgs(response.ResourceNotFound, "failed to update the account xyz: Unable to get account: error while trying to get user: no data with the with key xyz found", []interface{}{"Account", "xyz"}) @@ -510,3 +488,15 @@ func TestUpdate(t *testing.T) { }) } } + +func createMockUpdateResponseObject(odataType, odataID, odataContext, ID string) response.Response { + successResponse := response.Response{ + OdataType: odataType, + OdataID: odataID, + OdataContext: odataContext, + ID: ID, + Name: "Account Service", + } + successResponse.CreateGenericResponse(response.AccountModified) + return successResponse +} diff --git a/svc-account-session/role/create_test.go b/svc-account-session/role/create_test.go index 296f657a9..6b18ac880 100644 --- a/svc-account-session/role/create_test.go +++ b/svc-account-session/role/create_test.go @@ -102,31 +102,15 @@ func TestCreate(t *testing.T) { Code: response.GeneralError, Message: "Role with name testRole already exists", } - reqBodyCreateRole, _ := json.Marshal(asmodel.Role{ - ID: "testRole", - AssignedPrivileges: []string{common.PrivilegeLogin}, - OEMPrivileges: []string{}, - }) - reqBodyRoleConfigure, _ := json.Marshal(asmodel.Role{ - ID: "testRole", - AssignedPrivileges: []string{"Configure"}, - OEMPrivileges: []string{}, - }) - reqBodyInvalidRole, _ := json.Marshal(asmodel.Role{ - ID: "@testRole", - AssignedPrivileges: []string{common.PrivilegeLogin}, - OEMPrivileges: []string{}, - }) - reqBodyRoleEmpPrivilege, _ := json.Marshal(asmodel.Role{ - ID: "testRole", - AssignedPrivileges: []string{}, - OEMPrivileges: []string{}, - }) - reqBodyCreateAdminRole, _ := json.Marshal(asmodel.Role{ - ID: common.RoleAdmin, - AssignedPrivileges: []string{common.PrivilegeLogin}, - OEMPrivileges: []string{}, - }) + reqBodyCreateRole, _ := marshalRoleRequest("testRole", []string{common.PrivilegeLogin}, []string{}) + + reqBodyRoleConfigure, _ := marshalRoleRequest("testRole", []string{"Configure"}, []string{}) + + reqBodyInvalidRole, _ := marshalRoleRequest("@testRole", []string{common.PrivilegeLogin}, []string{}) + + reqBodyRoleEmpPrivilege, _ := marshalRoleRequest("testRole", []string{}, []string{}) + + reqBodyCreateAdminRole, _ := marshalRoleRequest(common.RoleAdmin, []string{common.PrivilegeLogin}, []string{}) ctx := mockContext() type args struct { req *roleproto.RoleRequest @@ -275,5 +259,12 @@ func TestCreate(t *testing.T) { } }) } +} +func marshalRoleRequest(ID string, assignedPrivileges, oemPrivileges []string) ([]byte, error) { + return json.Marshal(asmodel.Role{ + ID: ID, + AssignedPrivileges: assignedPrivileges, + OEMPrivileges: oemPrivileges, + }) } From c50b18725ddf7f2fa4c018c42998700f061d1fb0 Mon Sep 17 00:00:00 2001 From: Banoshi Date: Wed, 28 Jun 2023 12:37:07 +0530 Subject: [PATCH 19/19] update comment --- svc-account-session/account/update.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/svc-account-session/account/update.go b/svc-account-session/account/update.go index e07caab18..f0eeda768 100644 --- a/svc-account-session/account/update.go +++ b/svc-account-session/account/update.go @@ -244,7 +244,7 @@ func isEmptyRequest(requestBody []byte) bool { return false } -// getResponseArgs creates and return Args object with the values provided +// GetResponseArgs creates and return Args object with the values provided func GetResponseArgs(statusMessage string, errorMessage string, messageArgs []interface{}) response.Args { return response.Args{ Code: response.GeneralError,