Code optimization for Optimization
[ealt-edge.git] / mep / mepserver / mp1 / models / serviceinfo.go
1 /*
2  * Copyright 2020 Huawei Technologies Co., Ltd.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 package models
18
19 import (
20         "encoding/json"
21         "fmt"
22         "math"
23         "strconv"
24         "strings"
25         "time"
26
27         "github.com/apache/servicecomb-service-center/pkg/log"
28         "github.com/apache/servicecomb-service-center/pkg/util"
29         "github.com/apache/servicecomb-service-center/server/core/proto"
30
31         meputil "mepserver/mp1/util"
32 )
33
34 type ServiceInfo struct {
35         SerInstanceId     string        `json:"serInstanceId,omitempty"`
36         SerName           string        `json:"serName"`
37         SerCategory       CategoryRef   `json:"serCategory,omitempty"`
38         Version           string        `json:"version"`
39         State             string        `json:"state"`
40         TransportID       string        `json:"transportId,omitempty"`
41         TransportInfo     TransportInfo `json:"transportInfo"`
42         Serializer        string        `json:"serializer"`
43         ScopeOfLocality   string        `json:"scopeOfLocality,omitempty"`
44         ConsumedLocalOnly bool          `json:"consumedLocalOnly,omitempty"`
45         IsLocal           bool          `json:"isLocal,omitempty"`
46 }
47
48 func (s *ServiceInfo) ToServiceRequest(req *proto.CreateServiceRequest) {
49         if req == nil {
50                 log.Warn("create service request nil")
51         }
52         if req.Service == nil {
53                 req.Service = &proto.MicroService{}
54         }
55         req.Service.AppId = ""
56         req.Service.ServiceName = s.SerName
57         req.Service.Version = s.Version
58         req.Service.Status = "UP"
59         if s.State == "INACTIVE" {
60                 req.Service.Status = "DOWN"
61         }
62 }
63
64 func (s *ServiceInfo) ToRegisterInstance(req *proto.RegisterInstanceRequest) {
65         if req == nil {
66                 log.Warn("register instance request nil")
67         }
68         if req.Instance == nil {
69                 req.Instance = &proto.MicroServiceInstance{}
70         }
71         req.Instance.Properties = make(map[string]string, 5)
72         req.Instance.Properties["serName"] = s.SerName
73         s.serCategoryToProperties(req.Instance.Properties)
74         req.Instance.Version = s.Version
75         req.Instance.Timestamp = strconv.FormatInt(time.Now().Unix(), 10)
76         req.Instance.ModTimestamp = req.Instance.Timestamp
77
78         req.Instance.Status = "UP"
79         if s.State == "INACTIVE" {
80                 req.Instance.Status = "DOWN"
81         }
82         properties := req.Instance.Properties
83         meputil.InfoToProperties(properties, "transportId", s.TransportID)
84         meputil.InfoToProperties(properties, "serializer", s.Serializer)
85         meputil.InfoToProperties(properties, "ScopeOfLocality", s.ScopeOfLocality)
86         meputil.InfoToProperties(properties, "ConsumedLocalOnly", strconv.FormatBool(s.ConsumedLocalOnly))
87         meputil.InfoToProperties(properties, "IsLocal", strconv.FormatBool(s.IsLocal))
88         req.Instance.HostName = "default"
89         var epType string
90         req.Instance.Endpoints, epType = s.toEndpoints()
91         req.Instance.Properties["endPointType"] = epType
92
93         healthCheck := &proto.HealthCheck{
94                 Mode: proto.CHECK_BY_HEARTBEAT,
95                 Port: 0,
96                 Interval: math.MaxInt32 - 1,
97                 Times: 0,
98                 Url: "",
99         }
100         req.Instance.HealthCheck = healthCheck
101         s.transportInfoToProperties(req.Instance.Properties)
102 }
103
104 func (s *ServiceInfo) toEndpoints() ([]string, string) {
105         if len(s.TransportInfo.Endpoint.Addresses) != 0 {
106                 return s.TransportInfo.Endpoint.Uris, "uris"
107         }
108         endPoints := make([]string, 0, 1)
109         if len(s.TransportInfo.Endpoint.Addresses) != 0 {
110
111                 for _, v := range s.TransportInfo.Endpoint.Addresses {
112                         addrDes := fmt.Sprintf("%s:%d", v.Host, v.Port)
113                         endPoints = append(endPoints, addrDes)
114                 }
115                 return endPoints, "addresses"
116         }
117
118         if s.TransportInfo.Endpoint.Alternative != nil {
119                 jsonBytes, err := json.Marshal(s.TransportInfo.Endpoint.Alternative)
120                 if err != nil {
121                         return nil, ""
122                 }
123                 jsonText := util.BytesToStringWithNoCopy(jsonBytes)
124                 endPoints = append(endPoints, jsonText)
125                 return endPoints, "alternative"
126         }
127         return nil, ""
128 }
129
130 func (s *ServiceInfo) transportInfoToProperties(properties map[string]string) {
131         if properties == nil {
132                 return
133         }
134         meputil.InfoToProperties(properties, "transportInfo/id", s.TransportInfo.ID)
135         meputil.InfoToProperties(properties, "transportInfo/name", s.TransportInfo.Name)
136         meputil.InfoToProperties(properties, "transportInfo/description", s.TransportInfo.Description)
137         meputil.InfoToProperties(properties, "transportInfo/type", string(s.TransportInfo.TransType))
138         meputil.InfoToProperties(properties, "transportInfo/protocol", s.TransportInfo.Protocol)
139         meputil.InfoToProperties(properties, "transportInfo/version", s.TransportInfo.Version)
140         grantTypes := strings.Join(s.TransportInfo.Security.OAuth2Info.GrantTypes, ",")
141         meputil.InfoToProperties(properties, "transportInfo/security/oAuth2Info/grantTypes", grantTypes)
142         meputil.InfoToProperties(properties, "transportInfo/security/oAuth2Info/tokenEndpoint", s.TransportInfo.Security.OAuth2Info.TokenEndpoint)
143
144 }
145
146 func (s *ServiceInfo) serCategoryToProperties(properties map[string]string) {
147         if properties == nil {
148                 return
149         }
150         meputil.InfoToProperties(properties, "serCategory/href", s.SerCategory.Href)
151         meputil.InfoToProperties(properties, "serCategory/id", s.SerCategory.ID)
152         meputil.InfoToProperties(properties, "serCategory/name", s.SerCategory.Name)
153         meputil.InfoToProperties(properties, "serCategory/version", s.SerCategory.Version)
154 }
155
156 func (s *ServiceInfo) FromServiceInstance(inst *proto.MicroServiceInstance) {
157         s.SerInstanceId = inst.ServiceId + inst.InstanceId
158         s.serCategoryFromProperties(inst.Properties)
159         s.Version = inst.Version
160         s.State = "ACTIVE"
161         if inst.Status == "DOWN" {
162                 s.State = "INACTIVE"
163         }
164
165         epType := "uris"
166         if inst.Properties != nil {
167                 s.SerName = inst.Properties["serName"]
168                 s.TransportID = inst.Properties["transportId"]
169                 s.Serializer = inst.Properties["serializer"]
170                 epType = inst.Properties["endPointType"]
171                 s.ScopeOfLocality = inst.Properties["ScopeOfLocality"]
172                 var err error
173                 s.ConsumedLocalOnly, err = strconv.ParseBool(inst.Properties["ConsumedLocalOnly"])
174                 if err != nil {
175                         log.Warn("parse bool ConsumedLocalOnly fail")
176                 }
177                 s.IsLocal, err = strconv.ParseBool(inst.Properties["IsLocal"])
178                 if err != nil {
179                         log.Warn("parse bool ConsumedLocalOnly fail")
180                 }
181         }
182         s.fromEndpoints(inst.Endpoints, epType)
183         s.transportInfoFromProperties(inst.Properties)
184 }
185
186 func (s *ServiceInfo) serCategoryFromProperties(properties map[string]string) {
187         if properties == nil {
188                 return
189         }
190         s.SerCategory.Href = properties["serCategory/href"]
191         s.SerCategory.ID = properties["serCategory/id"]
192         s.SerCategory.Name = properties["serCategory/name"]
193         s.SerCategory.Version = properties["serCategory/version"]
194 }
195
196 func (s *ServiceInfo) fromEndpoints(uris []string, epType string) {
197         if epType == "uris" {
198                 s.TransportInfo.Endpoint.Uris = uris
199                 return
200         }
201         if epType == "address" {
202
203                 s.TransportInfo.Endpoint.Addresses = make([]EndPointInfoAddress, 0, 1)
204                 for _, v := range uris {
205                         host, port := meputil.GetHostPort(v)
206                         tmp := EndPointInfoAddress{
207                                 Host: host,
208                                 Port: uint32(port),
209                         }
210                         s.TransportInfo.Endpoint.Addresses = append(s.TransportInfo.Endpoint.Addresses, tmp)
211                 }
212         }
213         if epType == "alternative" {
214                 jsonObj, err := meputil.JsonTextToObj(uris[0])
215                 if err != nil {
216                         s.TransportInfo.Endpoint.Alternative = jsonObj
217                 }
218                 return
219         }
220 }
221
222 func (s *ServiceInfo) transportInfoFromProperties(properties map[string]string) {
223         if properties == nil {
224                 return
225         }
226         s.TransportInfo.ID = properties["transportInfo/id"]
227         s.TransportInfo.Name = properties["transportInfo/name"]
228         s.TransportInfo.Description = properties["transportInfo/description"]
229         s.TransportInfo.TransType = TransportTypes(properties["transportInfo/type"])
230         s.TransportInfo.Protocol = properties["transportInfo/protocol"]
231         s.TransportInfo.Version = properties["transportInfo/version"]
232         grantTypes := properties["transportInfo/security/oAuth2Info/grantTypes"]
233         s.TransportInfo.Security.OAuth2Info.GrantTypes = strings.Split(grantTypes, ",")
234         s.TransportInfo.Security.OAuth2Info.TokenEndpoint = properties["transportInfo/security/oAuth2Info/tokenEndpoint"]
235 }