Fix license headers
[ric-plt/e2mgr.git] / tools / xappmock / sender / jsonSender.go
1 //  This source code is part of the near-RT RIC (RAN Intelligent Controller)
2 //  platform project (RICP).
3
4 // Copyright 2019 Nokia
5 //
6 // Licensed under the Apache License, Version 2.0 (the "License");
7 // you may not use this file except in compliance with the License.
8 // You may obtain a copy of the License at
9 //
10 //      http://www.apache.org/licenses/LICENSE-2.0
11 //
12 // Unless required by applicable law or agreed to in writing, software
13 // distributed under the License is distributed on an "AS IS" BASIS,
14 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 // See the License for the specific language governing permissions and
16 // limitations under the License.
17 //
18
19 //  This source code is part of the near-RT RIC (RAN Intelligent Controller)
20 //  platform project (RICP).
21
22 package sender
23
24 import (
25         "fmt"
26         "github.com/pkg/errors"
27         "os"
28         "reflect"
29         "strconv"
30         "strings"
31         "sync/atomic"
32         "time"
33         "unicode"
34         "xappmock/logger"
35         "xappmock/models"
36         "xappmock/rmr"
37 )
38
39 var counter uint64
40
41 type JsonSender struct {
42         logger *logger.Logger
43 }
44
45 func NewJsonSender(logger *logger.Logger) *JsonSender {
46         return &JsonSender{
47                 logger: logger,
48         }
49 }
50
51 func (s *JsonSender) SendJsonRmrMessage(command models.JsonCommand /*the copy is modified locally*/, xAction *[]byte, r *rmr.Service) error {
52         var payload []byte
53         _, err := fmt.Sscanf(command.PackedPayload, "%x", &payload)
54         if err != nil {
55                 return errors.New(fmt.Sprintf("convert inputPayloadAsStr to payloadAsByte. Error: %v\n", err))
56         }
57         command.PackedPayload = string(payload)
58         command.TransactionId = expandTransactionId(command.TransactionId)
59         if len(command.TransactionId) == 0 {
60                 command.TransactionId = string(*xAction)
61         }
62         command.PayloadHeader = s.expandPayloadHeader(command.PayloadHeader, &command)
63         s.logger.Infof("#JsonSender.SendJsonRmrMessage - command payload header: %s", command.PayloadHeader)
64         rmrMsgId, err := rmr.MessageIdToUint(command.RmrMessageType)
65         if err != nil {
66                 return errors.New(fmt.Sprintf("invalid rmr message id: %s", command.RmrMessageType))
67         }
68
69         msg := append([]byte(command.PayloadHeader), payload...)
70         messageInfo := models.NewMessageInfo(int(rmrMsgId), command.RanName, msg, []byte(command.TransactionId))
71         s.logger.Infof("#JsonSender.SendJsonRmrMessage - going to send message: %s", messageInfo)
72
73         _, err = r.SendMessage(int(rmrMsgId), command.RanName, msg, []byte(command.TransactionId))
74         return err
75 }
76
77 /*
78  * transactionId (xAction): The value may have a fixed value or $ or <prefix>$.
79  * $ is replaced by a value generated at runtime (possibly unique per message sent).
80  * If the tag does not exist, then the mock shall use the value taken from the incoming message.
81  */
82 func expandTransactionId(id string) string {
83         if len(id) == 1 && id[0] == '$' {
84                 return fmt.Sprintf("%d", incAndGetCounter())
85         }
86         if len(id) > 1 && id[len(id)-1] == '$' {
87                 return fmt.Sprintf("%s%d", id[:len(id)-1], incAndGetCounter())
88         }
89         return id
90 }
91
92 /*
93  * payloadHeader: A prefix to combine with the payload that will be the message’s payload. The value may include variables of the format $<name> or #<name> where:
94  *   $<name> expands to the value of <name> if it exists or the empty string if not.
95  *   #<name> expands to the length of the value of <name> if it exists or omitted if not.
96  * The intention is to allow the Mock to construct the payload header required by the setup messages (ranIp|ranPort|ranName|payload len|<payload>).
97  * Example: “payloadHeader”: “$ranIp|$ranPort|$ranName|#packedPayload|”
98  */
99
100 func (s *JsonSender) expandPayloadHeader(header string, command *models.JsonCommand) string {
101         var name strings.Builder
102         var expandedHeader strings.Builder
103
104         r := strings.NewReader(header)
105         ch, err := r.ReadByte()
106         for {
107                 if err != nil {
108                         break
109                 }
110
111                 switch ch {
112                 case '$':
113                         for {
114                                 ch, err = r.ReadByte() //on error ch == 0
115                                 if unicode.IsDigit(rune(ch)) || unicode.IsLetter(rune(ch)) {
116                                         if name.Len() == 0 {
117                                                 name.WriteByte(byte(unicode.ToUpper(rune(ch))))
118                                         } else {
119                                                 name.WriteByte(ch)
120                                         }
121                                 } else {
122                                         if fieldValue := reflect.Indirect(reflect.ValueOf(command)).FieldByName(name.String()); fieldValue.IsValid() {
123                                                 switch fieldValue.Kind() {
124                                                 case reflect.String:
125                                                         expandedHeader.WriteString(fieldValue.String())
126                                                 case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
127                                                         expandedHeader.WriteString(strconv.FormatInt(fieldValue.Int(), 10))
128                                                 case reflect.Bool:
129                                                         expandedHeader.WriteString(strconv.FormatBool(fieldValue.Bool()))
130                                                 case reflect.Float64, reflect.Float32:
131                                                         expandedHeader.WriteString(fmt.Sprintf("%g", fieldValue.Float()))
132                                                 default:
133                                                         s.logger.Errorf("#JsonSender.expandPayloadHeader - invalid type for $%s, value must be a string, an int, a bool or a float", name.String())
134                                                         os.Exit(1)
135                                                 }
136                                         }
137                                         name.Reset()
138                                         break
139                                 }
140                         }
141                 case '#':
142                         for {
143                                 ch, err = r.ReadByte() //on error ch == 0
144                                 if unicode.IsDigit(rune(ch)) || unicode.IsLetter(rune(ch)) {
145                                         if name.Len() == 0 {
146                                                 name.WriteByte(byte(unicode.ToUpper(rune(ch))))
147                                         } else {
148                                                 name.WriteByte(ch)
149                                         }
150                                 } else {
151                                         if fieldValue := reflect.Indirect(reflect.ValueOf(command)).FieldByName(name.String()); fieldValue.IsValid() {
152                                                 if fieldValue.Kind() == reflect.String {
153                                                         expandedHeader.WriteString(strconv.FormatInt(int64(len(fieldValue.String())), 10))
154                                                 } else {
155                                                         s.logger.Errorf("#JsonSender.expandPayloadHeader - invalid type for #%s, value must be a string", name.String())
156                                                         os.Exit(1)
157                                                 }
158                                         }
159                                         name.Reset()
160                                         break
161                                 }
162                         }
163                 default:
164                         if unicode.IsPrint(rune(ch)) {
165                                 expandedHeader.WriteByte(ch)
166                         }
167                         ch, err = r.ReadByte()
168                 }
169         }
170         return expandedHeader.String()
171 }
172
173 func incAndGetCounter() uint64 {
174         return atomic.AddUint64(&counter, 1)
175 }
176
177 func init() {
178         counter = uint64(time.Now().Unix() - 1572000000)
179 }