Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add process logs for svc-account-session #1055

Merged
merged 6 commits into from
Dec 20, 2022
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions lib-utilities/common/constants.go
Original file line number Diff line number Diff line change
Expand Up @@ -163,12 +163,17 @@ const (
// Below fields define Service Name
AccountService = "svc-account"
SystemService = "svc-systems"
SessionService = "svc-account-session"
ApiService = "svc-api"
// DefaultThreadID to be used for apis
DefaultThreadID = "0"
// Invalid Action
InvalidActionID = "000"
InvalidActionName = "MethodNotAllowed"
// ThreadName
CheckAuth = "Check-Authentication"
CheckSessionCreation = "CheckSessionCreationCredentials"
CheckSessionTimeout = "CheckSessionTimeOut"
)

// ActionType defines type of action
Expand Down
2 changes: 2 additions & 0 deletions lib-utilities/common/responses.go
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ func GetContextData(ctx context.Context) context.Context {
md, _ := metadata.FromIncomingContext(ctx)
ctx = metadata.NewIncomingContext(ctx, md)
if len(md[TransactionID]) > 0 {
ctx = context.WithValue(ctx, ProcessName, md[ProcessName][0])
ctx = context.WithValue(ctx, TransactionID, md[TransactionID][0])
ctx = context.WithValue(ctx, ActionID, md[ActionID][0])
ctx = context.WithValue(ctx, ActionName, md[ActionName][0])
Expand All @@ -68,6 +69,7 @@ func GetContextData(ctx context.Context) context.Context {
func CreateMetadata(ctx context.Context) context.Context {
if ctx.Value(TransactionID) != nil {
md := metadata.New(map[string]string{
ProcessName: ctx.Value(ProcessName).(string),
TransactionID: ctx.Value(TransactionID).(string),
ActionName: ctx.Value(ActionName).(string),
ActionID: ctx.Value(ActionID).(string),
Expand Down
21 changes: 11 additions & 10 deletions svc-account-session/account/create.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ package account
// IMPORT Section
// ---------------------------------------------------------------------------------------
import (
"context"
"encoding/base64"
"encoding/json"
"fmt"
Expand Down Expand Up @@ -48,13 +49,13 @@ import (
//
// There will be two return values for the fuction. One is the RPC response, which contains the
// status code, status message, headers and body and the second value is error.
func (e *ExternalInterface) Create(req *accountproto.CreateAccountRequest, session *asmodel.Session) (response.RPC, error) {
func (e *ExternalInterface) Create(ctx context.Context, req *accountproto.CreateAccountRequest, session *asmodel.Session) (response.RPC, error) {
// parsing the CreateAccount
var createAccount asmodel.Account
err := json.Unmarshal(req.RequestBody, &createAccount)
if err != nil {
errMsg := "error while trying to marshal the request body of create account API" + err.Error()
l.Log.Error(errMsg)
l.LogWithFields(ctx).Error(errMsg)
return common.GeneralError(http.StatusInternalServerError, response.InternalError, errMsg, nil, nil), fmt.Errorf(errMsg)
}

Expand All @@ -72,11 +73,11 @@ func (e *ExternalInterface) Create(req *accountproto.CreateAccountRequest, sessi
invalidProperties, err := common.RequestParamsCaseValidator(req.RequestBody, createAccount)
if err != nil {
errMsg := errorLogPrefix + "error while validating request parameters: " + err.Error()
l.Log.Error(errMsg)
l.LogWithFields(ctx).Error(errMsg)
return common.GeneralError(http.StatusInternalServerError, response.InternalError, errMsg, nil, nil), fmt.Errorf(errMsg)
} else if invalidProperties != "" {
errorMessage := errorLogPrefix + "One or more properties given in the request body are not valid, ensure properties are listed in upper camel case "
l.Log.Error(errorMessage)
l.LogWithFields(ctx).Error(errorMessage)
resp := common.GeneralError(http.StatusBadRequest, response.PropertyUnknown, errorMessage, []interface{}{invalidProperties}, nil)
return resp, fmt.Errorf(errorMessage)
}
Expand All @@ -87,7 +88,7 @@ func (e *ExternalInterface) Create(req *accountproto.CreateAccountRequest, sessi
RoleID: createAccount.RoleID,
}

l.Log.Infof("Creating account for the user %s", createAccount.UserName)
l.LogWithFields(ctx).Infof("Creating account for the user %s", createAccount.UserName)
if !(session.Privileges[common.PrivilegeConfigureUsers]) {
errorMessage := errorLogPrefix + "User does not have the privilege of creating a new user"
resp.StatusCode = http.StatusForbidden
Expand All @@ -104,7 +105,7 @@ func (e *ExternalInterface) Create(req *accountproto.CreateAccountRequest, sessi
},
}
resp.Body = args.CreateGenericErrorResponse()
auth.CustomAuthLog(session.Token, errorMessage, resp.StatusCode)
auth.CustomAuthLog(ctx, session.Token, errorMessage, resp.StatusCode)
return resp, fmt.Errorf(errorMessage)
}
invalidParams := validateRequest(user)
Expand All @@ -124,12 +125,12 @@ func (e *ExternalInterface) Create(req *accountproto.CreateAccountRequest, sessi
},
}
resp.Body = args.CreateGenericErrorResponse()
l.Log.Error(errorMessage)
l.LogWithFields(ctx).Error(errorMessage)
return resp, fmt.Errorf(errorMessage)
}
if _, gerr := e.GetRoleDetailsByID(user.RoleID); gerr != nil {
errorMessage := errorLogPrefix + "Invalid RoleID present: " + gerr.Error()
l.Log.Error(errorMessage)
l.LogWithFields(ctx).Error(errorMessage)
return common.GeneralError(http.StatusBadRequest, response.ResourceNotFound, errorMessage, []interface{}{"Role", user.RoleID}, nil), fmt.Errorf(errorMessage)
}
if err := validatePassword(user.UserName, user.Password); err != nil {
Expand All @@ -148,7 +149,7 @@ func (e *ExternalInterface) Create(req *accountproto.CreateAccountRequest, sessi
},
}
resp.Body = args.CreateGenericErrorResponse()
l.Log.Error(errorMessage)
l.LogWithFields(ctx).Error(errorMessage)
return resp, err

}
Expand Down Expand Up @@ -178,7 +179,7 @@ func (e *ExternalInterface) Create(req *accountproto.CreateAccountRequest, sessi
} else {
resp.CreateInternalErrorResponse(errorMessage)
}
l.Log.Error(errorMessage)
l.LogWithFields(ctx).Error(errorMessage)
return resp, fmt.Errorf(errorMessage)
}

Expand Down
34 changes: 24 additions & 10 deletions svc-account-session/account/create_test.go
Original file line number Diff line number Diff line change
@@ -1,19 +1,20 @@
//(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 account

import (
"context"
"encoding/json"
"net/http"
"reflect"
Expand All @@ -40,10 +41,23 @@ func createMockRole(roleID string, privileges []string, oemPrivileges []string,
}
return nil
}

func mockContext() context.Context {
ctx := context.Background()
ctx = context.WithValue(ctx, common.TransactionID, "xyz")
ctx = context.WithValue(ctx, common.ActionID, "001")
ctx = context.WithValue(ctx, common.ActionName, "xyz")
ctx = context.WithValue(ctx, common.ThreadID, "0")
ctx = context.WithValue(ctx, common.ThreadName, "xyz")
ctx = context.WithValue(ctx, common.ProcessName, "xyz")
return ctx
}

func TestCreate(t *testing.T) {
config.SetUpMockConfig(t)
acc := getMockExternalInterface()
common.SetUpMockConfig()
ctx := mockContext()
errArgs := response.Args{
Code: response.GeneralError,
Message: "",
Expand Down Expand Up @@ -489,7 +503,7 @@ func TestCreate(t *testing.T) {
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := acc.Create(tt.args.req, tt.args.session)
got, err := acc.Create(ctx, tt.args.req, tt.args.session)
if (err != nil) != tt.wantErr {
t.Errorf("Create() error = %v, wantErr %v", err, tt.wantErr)
}
Expand Down
13 changes: 7 additions & 6 deletions svc-account-session/account/delete.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ package account
// IMPORT Section
// ---------------------------------------------------------------------------------------
import (
"context"
"fmt"
"net/http"

Expand All @@ -38,11 +39,11 @@ import (
//
// As return parameters RPC response, which contains status code, message, headers and data,
// error will be passed back.
func Delete(session *asmodel.Session, accountID string) response.RPC {
func Delete(ctx context.Context, session *asmodel.Session, accountID string) response.RPC {
var resp response.RPC
errorLogPrefix := fmt.Sprintf("failed to delete account %s: ", accountID)

l.Log.Infof("Validating the request to delete the account %s", accountID)
l.LogWithFields(ctx).Infof("Validating the request to delete the account %s", accountID)
// Default admin user account should not be deleted
if accountID == defaultAdminAccount {
errorMessage := errorLogPrefix + "default user account can not be deleted"
Expand All @@ -59,7 +60,7 @@ func Delete(session *asmodel.Session, accountID string) response.RPC {
},
}
resp.Body = args.CreateGenericErrorResponse()
l.Log.Error(errorMessage)
l.LogWithFields(ctx).Error(errorMessage)
return resp
}

Expand All @@ -79,11 +80,11 @@ func Delete(session *asmodel.Session, accountID string) response.RPC {
},
}
resp.Body = args.CreateGenericErrorResponse()
auth.CustomAuthLog(session.Token, errorMessage, resp.StatusCode)
auth.CustomAuthLog(ctx, session.Token, errorMessage, resp.StatusCode)
return resp
}

l.Log.Infof("Deleting the account %s from database", accountID)
l.LogWithFields(ctx).Infof("Deleting the account %s from database", accountID)
if derr := asmodel.DeleteUser(accountID); derr != nil {
errorMessage := errorLogPrefix + derr.Error()
if errors.DBKeyNotFound == derr.ErrNo() {
Expand All @@ -104,7 +105,7 @@ func Delete(session *asmodel.Session, accountID string) response.RPC {
} else {
resp.CreateInternalErrorResponse(errorMessage)
}
l.Log.Error(errorMessage)
l.LogWithFields(ctx).Error(errorMessage)
return resp
}

Expand Down
25 changes: 13 additions & 12 deletions svc-account-session/account/delete_test.go
Original file line number Diff line number Diff line change
@@ -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 account

Expand Down Expand Up @@ -80,7 +80,7 @@ func TestDelete(t *testing.T) {
},
},
}

ctx := mockContext()
type args struct {
session *asmodel.Session
accountID string
Expand Down Expand Up @@ -145,7 +145,7 @@ func TestDelete(t *testing.T) {
t.Fatalf("Error in creating mock admin user %v", err)
}
t.Run(tt.name, func(t *testing.T) {
got := Delete(tt.args.session, tt.args.accountID)
got := Delete(ctx, tt.args.session, tt.args.accountID)
if !reflect.DeepEqual(got, tt.want) {
t.Errorf("Delete() = %v, want %v", got, tt.want)
}
Expand Down Expand Up @@ -177,6 +177,7 @@ func TestDeleteDefaultAdminAccount(t *testing.T) {
if err != nil {
t.Fatalf("Error in creating mock admin user %v", err)
}
ctx := mockContext()
type args struct {
session *asmodel.Session
accountID string
Expand Down Expand Up @@ -206,7 +207,7 @@ func TestDeleteDefaultAdminAccount(t *testing.T) {
for _, tt := range tests {

t.Run(tt.name, func(t *testing.T) {
got := Delete(tt.args.session, tt.args.accountID)
got := Delete(ctx, tt.args.session, tt.args.accountID)
if !reflect.DeepEqual(got, tt.want) {
t.Errorf("Delete() = %v, want %v", got, tt.want)
}
Expand Down
19 changes: 10 additions & 9 deletions svc-account-session/account/getaccounts.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ package account
// IMPORT Section
// ---------------------------------------------------------------------------------------
import (
"context"
"fmt"
"net/http"

Expand All @@ -39,7 +40,7 @@ import (
//
// As return parameters RPC response, which contains status code, message, headers and data,
// error will be passed back.
func GetAllAccounts(session *asmodel.Session) response.RPC {
func GetAllAccounts(ctx context.Context, session *asmodel.Session) response.RPC {
commonResponse := response.Response{
OdataType: "#ManagerAccountCollection.ManagerAccountCollection",
OdataID: "/redfish/v1/AccountService/Accounts",
Expand All @@ -66,17 +67,17 @@ func GetAllAccounts(session *asmodel.Session) response.RPC {
},
}
resp.Body = args.CreateGenericErrorResponse()
auth.CustomAuthLog(session.Token, errorMessage, resp.StatusCode)
auth.CustomAuthLog(ctx, session.Token, errorMessage, resp.StatusCode)
return resp
}

l.Log.Info("Retrieving all users from the database")
l.LogWithFields(ctx).Info("Retrieving all users from the database")
//Get all user keys
users, err := asmodel.GetAllUsers()
if err != nil {
errorMessage := errLogPrefix + err.Error()
resp.CreateInternalErrorResponse(errorMessage)
l.Log.Error(errorMessage)
l.LogWithFields(ctx).Error(errorMessage)
return resp
}
//Build response body and headers
Expand Down Expand Up @@ -118,7 +119,7 @@ func GetAllAccounts(session *asmodel.Session) response.RPC {
//
// As return parameters RPC response, which contains status code, message, headers and data,
// error will be passed back.
func GetAccount(session *asmodel.Session, accountID string) response.RPC {
func GetAccount(ctx context.Context, session *asmodel.Session, accountID string) response.RPC {
commonResponse := response.Response{
OdataType: common.ManagerAccountType,
OdataID: "/redfish/v1/AccountService/Accounts/" + accountID,
Expand Down Expand Up @@ -147,12 +148,12 @@ func GetAccount(session *asmodel.Session, accountID string) response.RPC {
},
}
resp.Body = args.CreateGenericErrorResponse()
auth.CustomAuthLog(session.Token, errorMessage, resp.StatusCode)
auth.CustomAuthLog(ctx, session.Token, errorMessage, resp.StatusCode)
return resp
}
}

l.Log.Infof("Retrieving the user details from the database for the account %s", accountID)
l.LogWithFields(ctx).Infof("Retrieving the user details from the database for the account %s", accountID)
user, err := asmodel.GetUserDetails(accountID)
if err != nil {
errorMessage := errLogPrefix + err.Error()
Expand All @@ -174,7 +175,7 @@ func GetAccount(session *asmodel.Session, accountID string) response.RPC {
} else {
resp.CreateInternalErrorResponse(errorMessage)
}
l.Log.Error(errorMessage)
l.LogWithFields(ctx).Error(errorMessage)
return resp
}

Expand Down Expand Up @@ -210,7 +211,7 @@ func GetAccount(session *asmodel.Session, accountID string) response.RPC {
//
// As return parameters RPC response, which contains status code, message, headers and data,
// error will be passed back.
func GetAccountService() response.RPC {
func GetAccountService(ctx context.Context) response.RPC {
commonResponse := response.Response{
OdataType: common.AccountServiceType,
OdataID: "/redfish/v1/AccountService",
Expand Down
Loading