ea57cd6c2c6d0ba8032bb97f7ca55678e4368718
[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 // This type represents the general information of a MEC service info for registry/discovery
35 type ServiceInfo struct {
36         SerInstanceId     string        `json:"serInstanceId,omitempty"`
37         SerName           string        `json:"serName"`
38         SerCategory       CategoryRef   `json:"serCategory,omitempty"`
39         Version           string        `json:"version"`
40         State             string        `json:"state"`
41         TransportID       string        `json:"transportId,omitempty"`
42         TransportInfo     TransportInfo `json:"transportInfo"`
43         Serializer        string        `json:"serializer"`
44         ScopeOfLocality   string        `json:"scopeOfLocality,omitempty"`
45         ConsumedLocalOnly bool          `json:"consumedLocalOnly,omitempty"`
46         IsLocal           bool          `json:"isLocal,omitempty"`
47 }
48
49 func (s *ServiceInfo) ToServiceRequest(req *proto.CreateServiceRequest) {
50         if req == nil {
51                 log.Warn("create service request nil")
52         }
53         if req.Service == nil {
54                 req.Service = &proto.MicroService{}
55         }
56         req.Service.AppId = ""
57         req.Service.ServiceName = s.SerName
58         req.Service.Version = s.Version
59         req.Service.Status = "UP"
60         if s.State == "INACTIVE" {
61                 req.Service.Status = "DOWN"
62         }
63 }
64
65 func (s *ServiceInfo) ToRegisterInstance(req *proto.RegisterInstanceRequest) {
66         if req == nil {
67                 log.Warn("register instance request nil")
68         }
69         if req.Instance == nil {
70                 req.Instance = &proto.MicroServiceInstance{}
71         }
72         req.Instance.Properties = make(map[string]string, 5)
73         req.Instance.Properties["serName"] = s.SerName
74         s.serCategoryToProperties(req.Instance.Properties)
75         req.Instance.Version = s.Version
76         req.Instance.Timestamp = strconv.FormatInt(time.Now().Unix(), 10)
77         req.Instance.ModTimestamp = req.Instance.Timestamp
78
79         req.Instance.Status = "UP"
80         if s.State == "INACTIVE" {
81                 req.Instance.Status = "DOWN"
82         }
83         properties := req.Instance.Properties
84         meputil.InfoToProperties(properties, "transportId", s.TransportID)
85         meputil.InfoToProperties(properties, "serializer", s.Serializer)
86         meputil.InfoToProperties(properties, "ScopeOfLocality", s.ScopeOfLocality)
87         meputil.InfoToProperties(properties, "ConsumedLocalOnly", strconv.FormatBool(s.ConsumedLocalOnly))
88         meputil.InfoToProperties(properties, "IsLocal", strconv.FormatBool(s.IsLocal))
89         req.Instance.HostName = "default"
90         var epType string
91         req.Instance.Endpoints, epType = s.toEndpoints()
92         req.Instance.Properties["endPointType"] = epType
93
94         healthCheck := &proto.HealthCheck{
95                 Mode: proto.CHECK_BY_HEARTBEAT,
96                 Port: 0,
97                 Interval: math.MaxInt32 - 1,
98                 Times: 0,
99                 Url: "",
100         }
101         req.Instance.HealthCheck = healthCheck
102         s.transportInfoToProperties(req.Instance.Properties)
103 }
104
105 func (s *ServiceInfo) toEndpoints() ([]string, string) {
106         if len(s.TransportInfo.Endpoint.Addresses) != 0 {
107                 return s.TransportInfo.Endpoint.Uris, "uris"
108         }
109         endPoints := make([]string, 0, 1)
110         if len(s.TransportInfo.Endpoint.Addresses) != 0 {
111
112                 for _, v := range s.TransportInfo.Endpoint.Addresses {
113                         addrDes := fmt.Sprintf("%s:%d", v.Host, v.Port)
114                         endPoints = append(endPoints, addrDes)
115                 }
116                 return endPoints, "addresses"
117         }
118
119         if s.TransportInfo.Endpoint.Alternative != nil {
120                 jsonBytes, err := json.Marshal(s.TransportInfo.Endpoint.Alternative)
121                 if err != nil {
122                         return nil, ""
123                 }
124                 jsonText := util.BytesToStringWithNoCopy(jsonBytes)
125                 endPoints = append(endPoints, jsonText)
126                 return endPoints, "alternative"
127         }
128         return nil, ""
129 }
130
131 func (s *ServiceInfo) transportInfoToProperties(properties map[string]string) {
132         if properties == nil {
133                 return
134         }
135         meputil.InfoToProperties(properties, "transportInfo/id", s.TransportInfo.ID)
136         meputil.InfoToProperties(properties, "transportInfo/name", s.TransportInfo.Name)
137         meputil.InfoToProperties(properties, "transportInfo/description", s.TransportInfo.Description)
138         meputil.InfoToProperties(properties, "transportInfo/type", string(s.TransportInfo.TransType))
139         meputil.InfoToProperties(properties, "transportInfo/protocol", s.TransportInfo.Protocol)
140         meputil.InfoToProperties(properties, "transportInfo/version", s.TransportInfo.Version)
141         grantTypes := strings.Join(s.TransportInfo.Security.OAuth2Info.GrantTypes, ",")
142         meputil.InfoToProperties(properties, "transportInfo/security/oAuth2Info/grantTypes", grantTypes)
143         meputil.InfoToProperties(properties, "transportInfo/security/oAuth2Info/tokenEndpoint", s.TransportInfo.Security.OAuth2Info.TokenEndpoint)
144
145 }
146
147 func (s *ServiceInfo) serCategoryToProperties(properties map[string]string) {
148         if properties == nil {
149                 return
150         }
151         meputil.InfoToProperties(properties, "serCategory/href", s.SerCategory.Href)
152         meputil.InfoToProperties(properties, "serCategory/id", s.SerCategory.ID)
153         meputil.InfoToProperties(properties, "serCategory/name", s.SerCategory.Name)
154         meputil.InfoToProperties(properties, "serCategory/version", s.SerCategory.Version)
155 }
156
157 func (s *ServiceInfo) FromServiceInstance(inst *proto.MicroServiceInstance) {
158         s.SerInstanceId = inst.ServiceId + inst.InstanceId
159         s.serCategoryFromProperties(inst.Properties)
160         s.Version = inst.Version
161         s.State = "ACTIVE"
162         if inst.Status == "DOWN" {
163                 s.State = "INACTIVE"
164         }
165
166         epType := "uris"
167         if inst.Properties != nil {
168                 s.SerName = inst.Properties["serName"]
169                 s.TransportID = inst.Properties["transportId"]
170                 s.Serializer = inst.Properties["serializer"]
171                 epType = inst.Properties["endPointType"]
172                 s.ScopeOfLocality = inst.Properties["ScopeOfLocality"]
173                 var err error
174                 s.ConsumedLocalOnly, err = strconv.ParseBool(inst.Properties["ConsumedLocalOnly"])
175                 if err != nil {
176                         log.Warn("parse bool ConsumedLocalOnly fail")
177                 }
178                 s.IsLocal, err = strconv.ParseBool(inst.Properties["IsLocal"])
179                 if err != nil {
180                         log.Warn("parse bool ConsumedLocalOnly fail")
181                 }
182         }
183         s.fromEndpoints(inst.Endpoints, epType)
184         s.transportInfoFromProperties(inst.Properties)
185 }
186
187 func (s *ServiceInfo) serCategoryFromProperties(properties map[string]string) {
188         if properties == nil {
189                 return
190         }
191         s.SerCategory.Href = properties["serCategory/href"]
192         s.SerCategory.ID = properties["serCategory/id"]
193         s.SerCategory.Name = properties["serCategory/name"]
194         s.SerCategory.Version = properties["serCategory/version"]
195 }
196
197 //Parse service endpoint info
198 func (s *ServiceInfo) fromEndpoints(uris []string, epType string) {
199         if epType == "uris" {
200                 s.TransportInfo.Endpoint.Uris = uris
201                 return
202         }
203         if epType == "address" {
204
205                 s.TransportInfo.Endpoint.Addresses = make([]EndPointInfoAddress, 0, 1)
206                 for _, v := range uris {
207                         host, port := meputil.GetHostPort(v)
208                         tmp := EndPointInfoAddress{
209                                 Host: host,
210                                 Port: uint32(port),
211                         }
212                         s.TransportInfo.Endpoint.Addresses = append(s.TransportInfo.Endpoint.Addresses, tmp)
213                 }
214         }
215         if epType == "alternative" {
216                 jsonObj, err := meputil.JsonTextToObj(uris[0])
217                 if err != nil {
218                         s.TransportInfo.Endpoint.Alternative = jsonObj
219                 }
220                 return
221         }
222 }
223
224 //Parse service transport info
225 func (s *ServiceInfo) transportInfoFromProperties(properties map[string]string) {
226         if properties == nil {
227                 return
228         }
229         s.TransportInfo.ID = properties["transportInfo/id"]
230         s.TransportInfo.Name = properties["transportInfo/name"]
231         s.TransportInfo.Description = properties["transportInfo/description"]
232         s.TransportInfo.TransType = TransportTypes(properties["transportInfo/type"])
233         s.TransportInfo.Protocol = properties["transportInfo/protocol"]
234         s.TransportInfo.Version = properties["transportInfo/version"]
235         grantTypes := properties["transportInfo/security/oAuth2Info/grantTypes"]
236         s.TransportInfo.Security.OAuth2Info.GrantTypes = strings.Split(grantTypes, ",")
237         s.TransportInfo.Security.OAuth2Info.TokenEndpoint = properties["transportInfo/security/oAuth2Info/tokenEndpoint"]
238 }