forked from ava-labs/avalanchego
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfactory.go
103 lines (89 loc) · 2.58 KB
/
factory.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
// Copyright (C) 2019-2022, Ava Labs, Inc. All rights reserved.
// See the file LICENSE for licensing terms.
package rpcchainvm
import (
"errors"
"fmt"
"io"
"log"
"path/filepath"
"github.com/hashicorp/go-hclog"
"github.com/hashicorp/go-plugin"
"github.com/ava-labs/avalanchego/snow"
"github.com/ava-labs/avalanchego/utils/resource"
"github.com/ava-labs/avalanchego/utils/subprocess"
"github.com/ava-labs/avalanchego/vms"
"github.com/ava-labs/avalanchego/vms/rpcchainvm/grpcutils"
)
var (
errWrongVM = errors.New("wrong vm type")
_ vms.Factory = &factory{}
)
type factory struct {
path string
processTracker resource.ProcessTracker
}
func NewFactory(path string, processTracker resource.ProcessTracker) vms.Factory {
return &factory{
path: path,
processTracker: processTracker,
}
}
func (f *factory) New(ctx *snow.Context) (interface{}, error) {
config := &plugin.ClientConfig{
HandshakeConfig: Handshake,
Plugins: PluginMap,
Cmd: subprocess.New(f.path),
AllowedProtocols: []plugin.Protocol{
plugin.ProtocolGRPC,
},
// We kill this client by calling kill() when the chain running this VM
// shuts down. However, there are some cases where the VM's Shutdown
// method is not called. Namely, if:
// 1) The node shuts down after the client is created but before the
// chain is registered with the message router.
// 2) The chain doesn't handle a shutdown message before the node times
// out on the chain's shutdown and dies, leaving the shutdown message
// unhandled.
// We set managed to true so that we can call plugin.CleanupClients on
// node shutdown to ensure every plugin subprocess is killed.
Managed: true,
GRPCDialOptions: grpcutils.DefaultDialOptions,
}
if ctx != nil {
log.SetOutput(ctx.Log)
config.Stderr = ctx.Log
config.Logger = hclog.New(&hclog.LoggerOptions{
Output: ctx.Log,
Level: hclog.Info,
})
} else {
log.SetOutput(io.Discard)
config.Stderr = io.Discard
config.Logger = hclog.New(&hclog.LoggerOptions{
Output: io.Discard,
})
}
client := plugin.NewClient(config)
pluginName := filepath.Base(f.path)
pluginErr := func(err error) error {
return fmt.Errorf("plugin: %q: %w", pluginName, err)
}
rpcClient, err := client.Client()
if err != nil {
client.Kill()
return nil, pluginErr(err)
}
raw, err := rpcClient.Dispense("vm")
if err != nil {
client.Kill()
return nil, pluginErr(err)
}
vm, ok := raw.(*VMClient)
if !ok {
client.Kill()
return nil, pluginErr(errWrongVM)
}
vm.SetProcess(ctx, client, f.processTracker)
return vm, nil
}