Change module name to go.fd.io/govpp
[govpp.git] / proxy / proxy.go
1 //  Copyright (c) 2019 Cisco and/or its affiliates.
2 //
3 //  Licensed under the Apache License, Version 2.0 (the "License");
4 //  you may not use this file except in compliance with the License.
5 //  You may obtain a copy of the License at:
6 //
7 //      http://www.apache.org/licenses/LICENSE-2.0
8 //
9 //  Unless required by applicable law or agreed to in writing, software
10 //  distributed under the License is distributed on an "AS IS" BASIS,
11 //  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 //  See the License for the specific language governing permissions and
13 //  limitations under the License.
14
15 package proxy
16
17 import (
18         "fmt"
19         "io"
20         "net"
21         "net/http"
22         "net/rpc"
23
24         "go.fd.io/govpp/adapter"
25 )
26
27 // Server defines a proxy server that serves client requests to stats and binapi.
28 type Server struct {
29         rpc *rpc.Server
30
31         statsRPC  *StatsRPC
32         binapiRPC *BinapiRPC
33 }
34
35 func NewServer() (*Server, error) {
36         srv := &Server{
37                 rpc:       rpc.NewServer(),
38                 statsRPC:  &StatsRPC{},
39                 binapiRPC: &BinapiRPC{},
40         }
41
42         if err := srv.rpc.Register(srv.statsRPC); err != nil {
43                 return nil, err
44         }
45
46         if err := srv.rpc.Register(srv.binapiRPC); err != nil {
47                 return nil, err
48         }
49
50         return srv, nil
51 }
52
53 func (p *Server) ConnectStats(stats adapter.StatsAPI) error {
54         return p.statsRPC.connect(stats)
55 }
56
57 func (p *Server) DisconnectStats() {
58         p.statsRPC.disconnect()
59 }
60
61 func (p *Server) ConnectBinapi(binapi adapter.VppAPI) error {
62         return p.binapiRPC.connect(binapi)
63 }
64
65 func (p *Server) DisconnectBinapi() {
66         p.binapiRPC.disconnect()
67 }
68
69 func (p *Server) ServeHTTP(w http.ResponseWriter, req *http.Request) {
70         p.rpc.ServeHTTP(w, req)
71 }
72
73 func (p *Server) ServeCodec(codec rpc.ServerCodec) {
74         p.rpc.ServeCodec(codec)
75 }
76
77 func (p *Server) ServeConn(conn io.ReadWriteCloser) {
78         p.rpc.ServeConn(conn)
79 }
80
81 func (p *Server) ListenAndServe(addr string) error {
82         p.rpc.HandleHTTP(rpc.DefaultRPCPath, rpc.DefaultDebugPath)
83
84         l, e := net.Listen("tcp", addr)
85         if e != nil {
86                 return fmt.Errorf("listen failed: %v", e)
87         }
88         defer l.Close()
89
90         log.Printf("proxy serving on: %v", addr)
91
92         return http.Serve(l, nil)
93 }