-
Notifications
You must be signed in to change notification settings - Fork 0
/
web.go
182 lines (166 loc) · 5 KB
/
web.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
package harness
import (
"context"
"errors"
"fmt"
"github.com/gin-gonic/gin"
"github.com/panyam/slicer/clients"
"github.com/panyam/slicer/cmd/echosvc"
"github.com/panyam/slicer/protos"
"github.com/panyam/slicer/utils"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"google.golang.org/protobuf/reflect/protoreflect"
"io"
"log"
"net/http"
"os"
// "os/signal"
"sync"
"syscall"
"time"
)
/**
* A simple binary that acts as a shard provider.
* Shard providers are services that are running performing a simple function on its input.
* They append the provider prefix to the input (which is the shard key).
* The providers are only allowed to serve requests
* if they own a particular shard.
*/
type WebClient struct {
Addr string
ControlAddr string
Router *gin.Engine
quitChan chan os.Signal
wg sync.WaitGroup
Logger *log.Logger
}
func NewWebClient(addr string, logfile io.Writer) *WebClient {
out := WebClient{
Addr: addr,
ControlAddr: "localhost:7000",
Router: gin.Default(),
Logger: log.New(logfile, fmt.Sprintf("CLNT[%s] ", addr), log.Ldate|log.Ltime|log.Lshortfile),
}
out.Router.Use(gin.LoggerWithWriter(logfile))
return &out
}
func (w *WebClient) Stop() {
w.quitChan <- syscall.SIGTERM
}
func (w *WebClient) Start() {
// Updating the controller itself
w.Router.GET("/control/:prefix/:shard/:input/", func(ctx *gin.Context) {
/*
shard := ctx.Param("shard")
client := clientmgr.GetClient(shard)
response, err := client.Echo(&Request{
Prefix: ctx.Param("prefix"),
Shard: shard,
Input: ctx.Param("input"),
})
sendResponse(response)
*/
})
// This would be replaced by the discovery service otherwise so that
// every node would have the "latest" client
clientMgr := clients.NewStaticClientMgr(w.ControlAddr, protos.NewControlServiceClient)
ctrlSvcClient, err := clientMgr.GetClient("")
w.Logger.Println("CC, E: ", ctrlSvcClient, err)
if err != nil {
panic(err)
}
clientMap := make(map[string]*clients.RpcClient[echosvc.EchoServiceClient])
w.Router.GET("/:prefix/:shard/:input/", func(ctx *gin.Context) {
shard := ctx.Param("shard")
client, ok := clientMap[shard]
if !ok {
resp, err := ctrlSvcClient.Client.GetShard(
context.Background(),
&protos.GetShardRequest{
Shard: &protos.ShardKey{Key: shard},
},
)
if err != nil {
w.sendResponse(ctx, nil, err)
return
}
// our resp has a bunch of addresses - see if we have those here
// create a client against this shard's address
w.Logger.Println("targets: ", resp)
if len(resp.Targets) == 0 {
ctx.JSON(http.StatusNotFound, gin.H{"error": http.StatusNotFound, "message": "No svc targets found"})
return
} else {
address := resp.Targets[0].Target
newClient, err := clients.NewRpcClient(address, echosvc.NewEchoServiceClient)
if err != nil {
w.sendResponse(ctx, nil, err)
return
}
clientMap[shard] = newClient
client = newClient
}
}
response, err := client.Client.Echo(context.Background(), &echosvc.Request{
Prefix: ctx.Param("prefix"),
Shard: shard,
Input: ctx.Param("input"),
})
w.sendResponse(ctx, response, err)
})
srv := &http.Server{
Addr: w.Addr,
Handler: w.Router,
}
w.wg.Add(2)
go func() {
defer w.wg.Done()
if err := srv.ListenAndServe(); err != nil && errors.Is(err, http.ErrServerClosed) {
w.Logger.Printf("WebClient (%s) Listen: %s\n", w.Addr, err)
}
}()
// Listener for the cancel
w.quitChan = make(chan os.Signal)
go func() {
defer w.wg.Done()
// Wait for interrupt signal to gracefully shutdown the server with
// a timeout of 5 seconds.
// kill (no param) default send syscall.SIGTERM
// kill -2 is syscall.SIGINT
// kill -9 is syscall.SIGKILL but can't be caught, so don't need to add it
// signal.Notify(w.quitChan, syscall.SIGINT, syscall.SIGTERM)
<-w.quitChan
w.Logger.Printf("Shutting down web client: %s", w.Addr)
// The context is used to inform the server it has 5 seconds to finish
// the request it is currently handling
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := srv.Shutdown(ctx); err != nil {
w.Logger.Println(fmt.Sprintf("Server (%s) forced to shutdown: ", w.Addr), err)
}
}()
}
func (w *WebClient) sendResponse(ctx *gin.Context, resp protoreflect.ProtoMessage, err error) {
if err != nil {
if er, ok := status.FromError(err); ok {
code := er.Code()
msg := er.Message()
httpCode := http.StatusInternalServerError
// see if we have a specific client error
if code == codes.PermissionDenied {
httpCode = http.StatusForbidden
} else if code == codes.NotFound {
httpCode = http.StatusNotFound
} else if code == codes.AlreadyExists {
httpCode = http.StatusConflict
} else if code == codes.InvalidArgument {
httpCode = http.StatusBadRequest
}
ctx.JSON(httpCode, gin.H{"error": code, "message": msg})
}
} else {
jsonData := utils.ProtoToJson(resp)
ctx.Data(http.StatusOK, gin.MIMEJSON, jsonData)
}
}