-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprocess.go
More file actions
102 lines (92 loc) · 1.85 KB
/
process.go
File metadata and controls
102 lines (92 loc) · 1.85 KB
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
package subrpc
import (
"encoding/json"
"fmt"
"io/ioutil"
"net"
"os"
"github.com/ethereum/go-ethereum/rpc"
)
// Process type represents an RPC service
type Process struct {
Socket string
Config []byte
Env []string
RPC *rpc.Server
Token string
ServerSocket string
Srv *rpc.Client
}
// NewProcess function
func NewProcess() *Process {
f, err := ioutil.ReadAll(os.Stdin)
if err != nil {
writeLog(err)
panic(err)
}
var opts ProcessInput
err = json.Unmarshal(f, &opts)
if err != nil {
writeLog(err)
panic(err)
}
p := &Process{
Env: os.Environ(),
Socket: opts.Socket,
Config: opts.Config,
RPC: rpc.NewServer(),
Token: opts.Token,
ServerSocket: opts.ServerSocket,
}
srv, err := rpc.Dial(p.ServerSocket)
if err != nil {
writeLog(err)
panic(err)
}
p.Srv = srv
err = p.RPC.RegisterName("ping", new(rpcPing))
if err != nil {
panic(err)
}
return p
}
// Start starts a new process instance
func (p *Process) Start() error {
conn, err := net.Listen("unix", p.Socket)
if err != nil {
writeLog(err)
return err
}
return p.RPC.ServeListener(conn)
}
// AddFunction adds a function to the RPC handler
func (p *Process) AddFunction(name string, f interface{}) error {
return p.RPC.RegisterName(name, f)
}
// Call function
func (p *Process) Call(method string, dst interface{}, args ...interface{}) error {
err := p.Srv.Call(&dst, method, args...)
if err != nil {
writeLog(err)
return err
}
return nil
}
type rpcPing struct{}
func (r *rpcPing) Ping() string {
return "pong"
}
func writeLog(msg ...interface{}) {
f, err := os.OpenFile("./libsubrpc.log", os.O_APPEND, 0600)
if err != nil {
fmt.Println(err)
}
_, err = f.WriteString(fmt.Sprint(msg...))
if err != nil {
fmt.Println(err)
}
err = f.Close()
if err != nil {
fmt.Println(err)
}
}