/
grpc.go
339 lines (303 loc) · 8.25 KB
/
grpc.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
// Copyright 2016 OpenConfigd Project.
//
// 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
//
// 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 config
import (
"fmt"
"io"
"net"
"sort"
"strconv"
"strings"
"github.com/coreswitch/cmd"
"github.com/coreswitch/component"
rpc "github.com/coreswitch/openconfigd/proto"
log "github.com/sirupsen/logrus"
"golang.org/x/net/context"
"google.golang.org/grpc"
"google.golang.org/grpc/grpclog"
)
const (
CliSuccess = iota
CliSuccessExec
CliSuccessShow
CliSuccessModule
CliSuccessRedirect
CliSuccessRedirectShow
)
var (
RIBD_SYNCHRONIZED bool
)
var GrpcModuleMap = map[string]string{}
type openconfigServer struct {
cmd *cmd.Cmd
}
type registerServer struct {
cmd *cmd.Cmd
}
type configServer struct {
cmd *cmd.Cmd
}
func execute(Cmd *cmd.Cmd, mode string, args []string, line string, reply *rpc.ExecReply) (ret string) {
result, fn, pargs, _ := Cmd.ParseLine(mode, line, &cmd.Param{Command: args})
fmt.Println(args)
if RIBD_SYNCHRONIZED {
if len(args) >= 4 {
if args[0] == "set" && args[1] == "interfaces" && args[2] == "interface" {
conf := configActive.LookupByPath([]string{"interfaces", "interface", args[3]})
if conf == nil {
ret = "NoMatch\n"
return
}
}
}
}
switch result {
case cmd.ParseSuccess:
cb, ok := fn.(func([]string) (int, string))
if ok {
inst, instStr := cb(cmd.Interface2String(pargs))
switch inst {
case CliSuccess:
ret = "Success"
case CliSuccessExec:
ret = "SuccessExec\n"
ret += instStr
case CliSuccessShow:
reply.Code = rpc.ExecCode_SHOW
//ret = "SuccessShow\n"
ret = instStr
case CliSuccessModule:
ret = "SuccessModule\n"
ret += instStr
case CliSuccessRedirect, CliSuccessRedirectShow:
if inst == CliSuccessRedirectShow {
reply.Code = rpc.ExecCode_REDIRECT_SHOW
} else {
reply.Code = rpc.ExecCode_REDIRECT
}
pair := strings.Split(instStr, ":")
host := pair[0]
port, _ := strconv.ParseUint(pair[1], 10, 32)
reply.Host = host
reply.Port = uint32(port)
ret = "SuccessRedirect\n"
ret += instStr
}
}
case cmd.ParseIncomplete:
ret = "Incomplete\n"
case cmd.ParseNoMatch:
ret = "NoMatch\n"
case cmd.ParseAmbiguous:
ret = "Ambiguous\n"
}
return
}
func complete(Cmd *cmd.Cmd, mode string, args []string, line string, trailing bool) (ret string) {
result, _, _, comps := Cmd.ParseLine(mode, line, &cmd.Param{Command: args, Complete: true, TrailingSpace: trailing})
switch result {
case cmd.ParseSuccess, cmd.ParseIncomplete:
ret = "Success\n"
case cmd.ParseNoMatch:
ret = "NoMatch\n"
case cmd.ParseAmbiguous:
ret = "Ambiguous\n"
}
sort.Sort(comps)
for _, comp := range comps {
var pre string
if !comp.Dir && !comp.Additive {
pre = "--"
} else {
if comp.Additive {
pre = "+"
} else {
pre = " "
}
if comp.Dir {
pre += ">"
} else {
pre += " "
}
}
ret += fmt.Sprintf("%s\t%s\t%s\n", comp.Name, pre, comp.Help)
//ret += comp.Name + "\t" + "" + "\t" + comp.Help + "\n"
}
if result == cmd.ParseSuccess {
ret += "<cr>\t--\t\n"
}
return
}
func unquote(req *rpc.ExecRequest) {
if req.Type == rpc.ExecType_COMPLETE || req.Type == rpc.ExecType_COMPLETE_TRAILING_SPACE {
for pos, arg := range req.Args {
arg, err := strconv.Unquote(arg)
if err == nil {
req.Args[pos] = arg
}
}
}
}
func ExecLine(line string) string {
reply := new(rpc.ExecReply)
args := strings.Split(line, " ")
return execute(TopCmd, "configure", args, line, reply)
}
func (s *openconfigServer) DoExec(_ context.Context, req *rpc.ExecRequest) (*rpc.ExecReply, error) {
reply := new(rpc.ExecReply)
unquote(req)
switch req.Type {
case rpc.ExecType_EXEC:
reply.Lines = execute(s.cmd, req.Mode, req.Args, req.Line, reply)
case rpc.ExecType_COMPLETE:
reply.Lines = complete(s.cmd, req.Mode, req.Args, req.Line, false)
case rpc.ExecType_COMPLETE_TRAILING_SPACE:
reply.Lines = complete(s.cmd, req.Mode, req.Args, req.Line+" ", true)
case rpc.ExecType_COMPLETE_FIRST_COMMANDS:
reply.Lines = s.cmd.FirstCommands(req.Mode, req.Privilege)
case rpc.ExecType_COMPLETE_DYNAMIC:
// Ignore dynamic completion in openconfigd.
}
return reply, nil
}
func (s *registerServer) DoRegister(_ context.Context, req *rpc.RegisterRequest) (*rpc.RegisterReply, error) {
reply := new(rpc.RegisterReply)
host := GrpcModuleMap[req.Module]
inst := CliSuccessRedirect
if req.Code == rpc.ExecCode_REDIRECT_SHOW {
inst = CliSuccessRedirectShow
}
if mode := s.cmd.LookupMode(req.Mode); mode != nil {
mode.InstallLine(req.Line,
func(Args []string) (int, string) {
return inst, host
},
&cmd.Param{Helps: req.Helps, Privilege: req.Privilege, Dynamic: true})
}
return reply, nil
}
func (s *registerServer) DoRegisterModule(_ context.Context, req *rpc.RegisterModuleRequest) (*rpc.RegisterModuleReply, error) {
reply := new(rpc.RegisterModuleReply)
host := req.Host
port := req.Port
if port == "" {
port = "2601"
}
GrpcModuleMap[req.Module] = fmt.Sprintf("%s:%s", host, port)
return reply, nil
}
func (s *configServer) DoConfig(stream rpc.Config_DoConfigServer) error {
loop:
for {
msg, err := stream.Recv()
if err == io.EOF {
fmt.Println("EOF")
break loop
}
if err != nil {
fmt.Println(err)
break loop
}
switch msg.Type {
case rpc.ConfigType_SUBSCRIBE:
go SubscribeRemoteAdd(stream, msg)
case rpc.ConfigType_SUBSCRIBE_MULTI:
go SubscribeRemoteAddMulti(stream, msg)
case rpc.ConfigType_SUBSCRIBE_REQUEST:
go SubscribeAdd(stream, msg)
case rpc.ConfigType_SET:
go YangConfigPush(msg.Path)
case rpc.ConfigType_DELETE:
go YangConfigPull(msg.Path)
case rpc.ConfigType_VALIDATE_SUCCESS:
//fmt.Println("Validate Success")
SubscribeValidateProcess(stream, msg.Type)
case rpc.ConfigType_VALIDATE_FAILED:
//fmt.Println("Validate Failed")
SubscribeValidateProcess(stream, msg.Type)
case rpc.ConfigType_API_CALL_FINISHED:
log.Info("API_SYNC: gRPC message received")
if ApiSyncCh != nil {
close(ApiSyncCh)
}
}
}
if stream != nil {
SubscribeDelete(stream)
}
return nil
}
func DynamicCompletionLocal(commands []string, module string, args []string) []string {
if len(args) > 0 {
switch args[0] {
case "rollback":
return RollbackCompletion(commands)
default:
}
}
return []string{}
}
func DynamicCompletion(commands []string, module string, args []string) []string {
// Local completion check.
// if module == "local" {
// return DynamicCompletionLocal(commands, module, args)
// }
// XXX Need to leverage stream connection. (No need of make a new connection)
host := SubscribeHostLookup(module)
port := SubscribePortLookup(module)
if port == 0 {
port = 2601 // default port
}
url := fmt.Sprintf("%s:%d", host, port)
conn, err := grpc.Dial(url, grpc.WithInsecure())
if err != nil {
fmt.Println("DynamicCompletion: Fail to dial", err)
return []string{}
}
defer conn.Close()
client := rpc.NewExecClient(conn)
req := &rpc.ExecRequest{
Type: rpc.ExecType_COMPLETE_DYNAMIC,
Mode: module,
Commands: commands,
Args: args,
}
reply, err := client.DoExec(context.Background(), req)
if err != nil {
fmt.Println("client DoExec COMPLETE_DYNAMIC failed:", err)
return []string{}
}
return reply.Candidates
}
// RPC component.
type RpcComponent struct {
GrpcEndpoint string
}
// RPC component start method.
func (this *RpcComponent) Start() component.Component {
lis, err := net.Listen("tcp", this.GrpcEndpoint)
if err != nil {
grpclog.Fatalf("failed %v", err)
}
grpcServer := grpc.NewServer()
rpc.RegisterExecServer(grpcServer, &openconfigServer{TopCmd})
rpc.RegisterRegisterServer(grpcServer, ®isterServer{TopCmd})
rpc.RegisterConfigServer(grpcServer, &configServer{TopCmd})
grpcServer.Serve(lis)
return this
}
func (this *RpcComponent) Stop() component.Component {
// fmt.Println("rpc component stop")
return this
}