2 * Copyright 2020 Huawei Technologies Co., Ltd.
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
25 "github.com/apache/servicecomb-service-center/pkg/log"
26 "github.com/apache/servicecomb-service-center/server/core/backend"
27 "github.com/apache/servicecomb-service-center/server/core/proto"
28 "github.com/apache/servicecomb-service-center/server/plugin/pkg/registry"
29 "github.com/satori/go.uuid"
31 "mepserver/mp1/arch/workspace"
32 "mepserver/mp1/models"
35 type SubscribeIst struct {
37 R *http.Request `json:"r,in"`
38 HttpErrInf *proto.Response `json:"httpErrInf,out"`
39 Ctx context.Context `json:"ctx,in"`
40 W http.ResponseWriter `json:"w,in"`
41 RestBody interface{} `json:"restBody,in"`
42 AppInstanceId string `json:"appInstanceId,in"`
43 SubscribeId string `json:"subscribeId,in"`
44 HttpRsp interface{} `json:"httpRsp,out"`
47 func (t *SubscribeIst) OnRequest(data string) workspace.TaskCode {
49 mp1SubscribeInfo, ok := t.RestBody.(*models.SerAvailabilityNotificationSubscription)
51 t.SetFirstErrorCode(SerErrFailBase, "restBody failed")
52 return workspace.TaskFinish
55 appInstanceId := t.AppInstanceId
56 subscribeId := uuid.NewV4().String()
57 t.SubscribeId = subscribeId
58 subscribeJSON, err := json.Marshal(mp1SubscribeInfo)
60 log.Errorf(err, "can not Marshal subscribe info")
61 t.SetFirstErrorCode(ParseInfoErr, "can not marshal subscribe info")
62 return workspace.TaskFinish
64 opts := []registry.PluginOp{
65 registry.OpPut(registry.WithStrKey("/cse-sr/etsi/subscribe/"+appInstanceId+"/"+subscribeId),
66 registry.WithValue(subscribeJSON)),
68 _, resultErr := backend.Registry().TxnWithCmp(context.Background(), opts, nil, nil)
70 log.Errorf(err, "subscription to etcd failed!")
71 t.SetFirstErrorCode(OperateDataWithEtcdErr, "put subscription to etcd failed")
72 return workspace.TaskFinish
75 req := &proto.WatchInstanceRequest{SelfServiceId: appInstanceId[:len(appInstanceId)/2]}
76 t.R.Method = "WATCHLIST"
77 WebsocketListAndWatch(t.Ctx, req, appInstanceId)
78 t.buildResponse(mp1SubscribeInfo)
80 return workspace.TaskFinish
83 func (t *SubscribeIst) buildResponse(sub *models.SerAvailabilityNotificationSubscription) {
84 appInstanceID := t.AppInstanceId
85 subscribeID := t.SubscribeId
88 location := fmt.Sprintf("/mec_service_mgmt/v1/applications/%s/subscriptions/%s/", appInstanceID, subscribeID)
89 t.W.Header().Set("Location", location)