-
Notifications
You must be signed in to change notification settings - Fork 0
/
ginsider.go
338 lines (285 loc) · 9.08 KB
/
ginsider.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
/*
* Copyright 2018 Insolar
*
* 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 ginsider
import (
"io/ioutil"
"net/rpc"
"os"
"path/filepath"
"plugin"
"sync"
"github.com/pkg/errors"
"github.com/ugorji/go/codec"
"github.com/insolar/insolar/core"
"github.com/insolar/insolar/log"
"github.com/insolar/insolar/logicrunner/goplugin/foundation"
"github.com/insolar/insolar/logicrunner/goplugin/rpctypes"
"github.com/tylerb/gls"
)
// GoInsider is an RPC interface to run code of plugins
type GoInsider struct {
dir string
UpstreamProtocol string
UpstreamAddress string
UpstreamClient *rpc.Client
plugins map[string]*plugin.Plugin
pluginsMutex sync.Mutex
}
// NewGoInsider creates a new GoInsider instance validating arguments
func NewGoInsider(path, network, address string) *GoInsider {
//TODO: check that path exist, it's a directory and writable
res := GoInsider{dir: path, UpstreamProtocol: network, UpstreamAddress: address}
res.plugins = make(map[string]*plugin.Plugin)
return &res
}
// RPC struct with methods representing RPC interface of this code runner
type RPC struct {
GI *GoInsider
}
// CallMethod is an RPC that runs a method on an object and
// returns a new state of the object and result of the method
func (t *RPC) CallMethod(args rpctypes.DownCallMethodReq, reply *rpctypes.DownCallMethodResp) error {
log.Debugf("Calling method %q on object %q", args.Method, args.Context.Callee)
p, err := t.GI.Plugin(args.Code)
if err != nil {
return errors.Wrapf(err, "Couldn't get plugin by code reference %s", args.Code.String())
}
symbol, err := p.Lookup("INSMETHOD_" + args.Method)
if err != nil {
return errors.Wrapf(
err, "Can't find wrapper for %s (code ref: %s)",
args.Method, args.Code.String(),
)
}
wrapper, ok := symbol.(func(object []byte, data []byte) ([]byte, []byte, error))
if !ok {
return errors.New("Wrapper with wrong signature")
}
gls.Set("ctx", args.Context)
state, result, err := wrapper(args.Data, args.Arguments) // may be entire args???
gls.Cleanup()
if err != nil {
return errors.Wrapf(err, "Method call returned error")
}
reply.Data = state
reply.Ret = result
return nil
}
// CallConstructor is an RPC that runs a method on an object and
// returns a new state of the object and result of the method
func (t *RPC) CallConstructor(args rpctypes.DownCallConstructorReq, reply *rpctypes.DownCallConstructorResp) error {
p, err := t.GI.Plugin(args.Code)
if err != nil {
return err
}
symbol, err := p.Lookup("INSCONSTRUCTOR_" + args.Name)
if err != nil {
return errors.Wrapf(err, "Can't find wrapper for %s", args.Name)
}
f, ok := symbol.(func(data []byte) ([]byte, error))
if !ok {
return errors.New("Wrapper with wrong signature")
}
resValues, err := f(args.Arguments)
if err != nil {
return errors.Wrapf(err, "Can't call constructor %s", args.Name)
}
reply.Ret = resValues
return nil
}
// Upstream returns RPC client connected to upstream server (goplugin)
func (gi *GoInsider) Upstream() (*rpc.Client, error) {
if gi.UpstreamClient != nil {
return gi.UpstreamClient, nil
}
client, err := rpc.Dial(gi.UpstreamProtocol, gi.UpstreamAddress)
if err != nil {
return nil, errors.Wrapf(err, "couldn't dial '%s' over %s", gi.UpstreamAddress, gi.UpstreamProtocol)
}
gi.UpstreamClient = client
return gi.UpstreamClient, nil
}
// ObtainCode returns path on the file system to the plugin, fetches it from a provider
// if it's not in the storage
func (gi *GoInsider) ObtainCode(ref core.RecordRef) (string, error) {
path := filepath.Join(gi.dir, ref.String())
_, err := os.Stat(path)
if err == nil {
return path, nil
} else if !os.IsNotExist(err) {
return "", errors.Wrap(err, "file !notexists()")
}
client, err := gi.Upstream()
if err != nil {
return "", err
}
log.Debugf("obtaining code %q", ref)
res := rpctypes.UpGetCodeResp{}
err = client.Call("RPC.GetCode", rpctypes.UpGetCodeReq{Code: ref, MType: core.MachineTypeGoPlugin}, &res)
if err != nil {
return "", errors.Wrap(err, "on calling main API")
}
err = ioutil.WriteFile(path, res.Code, 0666)
if err != nil {
return "", errors.Wrap(err, "on writing file down")
}
return path, nil
}
// Plugin loads Go plugin by reference and returns `*plugin.Plugin`
// ready to lookup symbols
func (gi *GoInsider) Plugin(ref core.RecordRef) (*plugin.Plugin, error) {
gi.pluginsMutex.Lock()
defer gi.pluginsMutex.Unlock()
key := ref.String()
if gi.plugins[key] != nil {
return gi.plugins[key], nil
}
path, err := gi.ObtainCode(ref)
if err != nil {
return nil, errors.Wrap(err, "couldn't obtain code")
}
log.Debugf("Opening plugin %q from file %q", ref, path)
p, err := plugin.Open(path)
if err != nil {
return nil, errors.Wrap(err, "couldn't open plugin")
}
gi.plugins[key] = p
return p, nil
}
// MakeUpBaseReq makes base of request from current CallContext
func MakeUpBaseReq() rpctypes.UpBaseReq {
if ctx, ok := gls.Get("ctx").(*core.LogicCallContext); ok {
return rpctypes.UpBaseReq{
Me: *ctx.Callee,
}
}
panic("Wrong or unexistent context")
}
// RouteCall ...
func (gi *GoInsider) RouteCall(ref core.RecordRef, wait bool, method string, args []byte) ([]byte, error) {
client, err := gi.Upstream()
if err != nil {
return nil, err
}
req := rpctypes.UpRouteReq{
UpBaseReq: MakeUpBaseReq(),
Wait: wait,
Object: ref,
Method: method,
Arguments: args,
}
res := rpctypes.UpRouteResp{}
err = client.Call("RPC.RouteCall", req, &res)
if err != nil {
return nil, errors.Wrap(err, "on calling main API")
}
return []byte(res.Result), nil
}
// SaveAsChild ...
func (gi *GoInsider) SaveAsChild(parentRef, classRef core.RecordRef, constructorName string, argsSerialized []byte) (core.RecordRef, error) {
client, err := gi.Upstream()
if err != nil {
return core.NewRefFromBase58(""), err
}
req := rpctypes.UpSaveAsChildReq{
UpBaseReq: MakeUpBaseReq(),
Parent: parentRef,
Class: classRef,
ConstructorName: constructorName,
ArgsSerialized: argsSerialized,
}
res := rpctypes.UpSaveAsChildResp{}
err = client.Call("RPC.SaveAsChild", req, &res)
if err != nil {
return core.NewRefFromBase58(""), errors.Wrap(err, "on calling main API")
}
return *res.Reference, nil
}
// GetObjChildren ...
func (gi *GoInsider) GetObjChildren(obj core.RecordRef, class core.RecordRef) ([]core.RecordRef, error) {
client, err := gi.Upstream()
if err != nil {
return nil, err
}
res := rpctypes.UpGetObjChildrenResp{}
req := rpctypes.UpGetObjChildrenReq{
UpBaseReq: MakeUpBaseReq(),
Obj: obj,
Class: class,
}
err = client.Call("RPC.GetObjChildren", req, &res)
if err != nil {
return nil, errors.Wrap(err, "on calling main API RPC.GetObjChildren")
}
return res.Children, nil
}
// SaveAsDelegate ...
func (gi *GoInsider) SaveAsDelegate(intoRef, classRef core.RecordRef, constructorName string, argsSerialized []byte) (core.RecordRef, error) {
client, err := gi.Upstream()
if err != nil {
return core.NewRefFromBase58(""), err
}
req := rpctypes.UpSaveAsDelegateReq{
UpBaseReq: MakeUpBaseReq(),
Into: intoRef,
Class: classRef,
ConstructorName: constructorName,
ArgsSerialized: argsSerialized,
}
res := rpctypes.UpSaveAsDelegateResp{}
err = client.Call("RPC.SaveAsDelegate", req, &res)
if err != nil {
return core.NewRefFromBase58(""), errors.Wrap(err, "on calling main API")
}
return *res.Reference, nil
}
// GetDelegate ...
func (gi *GoInsider) GetDelegate(object, ofType core.RecordRef) (core.RecordRef, error) {
client, err := gi.Upstream()
if err != nil {
return core.NewRefFromBase58(""), err
}
req := rpctypes.UpGetDelegateReq{
UpBaseReq: MakeUpBaseReq(),
Object: object,
OfType: ofType,
}
res := rpctypes.UpGetDelegateResp{}
err = client.Call("RPC.GetDelegate", req, &res)
if err != nil {
return core.NewRefFromBase58(""), errors.Wrap(err, "on calling main API")
}
return res.Object, nil
}
// Serialize - CBOR serializer wrapper: `what` -> `to`
func (gi *GoInsider) Serialize(what interface{}, to *[]byte) error {
ch := new(codec.CborHandle)
log.Debugf("serializing %+v", what)
return codec.NewEncoderBytes(to, ch).Encode(what)
}
// Deserialize - CBOR de-serializer wrapper: `from` -> `into`
func (gi *GoInsider) Deserialize(from []byte, into interface{}) error {
ch := new(codec.CborHandle)
log.Debugf("de-serializing %+v", from)
return codec.NewDecoderBytes(from, ch).Decode(into)
}
// MakeErrorSerializable converts errors satisfying error interface to foundation.Error
func (gi *GoInsider) MakeErrorSerializable(e error) error {
if e == nil {
return nil
}
return &foundation.Error{S: e.Error()}
}