-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
process.go
340 lines (325 loc) 路 8.27 KB
/
process.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
339
340
package v2ray
import (
"context"
"errors"
"fmt"
"github.com/shirou/gopsutil/v3/mem"
"github.com/v2rayA/v2rayA/conf"
"github.com/v2rayA/v2rayA/core/serverObj"
"github.com/v2rayA/v2rayA/core/v2ray/asset"
"github.com/v2rayA/v2rayA/core/v2ray/where"
"github.com/v2rayA/v2rayA/db/configure"
"github.com/v2rayA/v2rayA/pkg/util/log"
"net"
"os"
"os/exec"
"path/filepath"
"strconv"
"strings"
"sync"
"time"
)
var NoConnectedServerErr = fmt.Errorf("no selected servers")
// Process is a v2ray-core process
type Process struct {
// mutex protect the proc
mutex sync.Mutex
proc *os.Process
procCancel func() // cancel func for proc and pluginManagers
pluginManagers []*os.Process
template *Template
tag2WhichIndex map[string]int
}
func NewProcess(tmpl *Template, prestart func() error, poststart func() error) (process *Process, err error) {
process = &Process{
template: tmpl,
}
if tmpl.MultiObservatory != nil {
// NOTICE: tag2WhichIndex is reliable because once connected servers are changed when v2ray is running,
// the func UpdateV2RayConfig should be invoked and tag2WhichIndex will be regenerated.
tag2WhichIndex := make(map[string]int)
for i, tag := range tmpl.OutboundTags {
tag2WhichIndex[tag] = i
}
process.tag2WhichIndex = tag2WhichIndex
}
err = WriteV2rayConfig(tmpl.ToConfigBytes())
if err != nil {
return nil, err
}
if err = tmpl.CheckInboundPortsOccupied(); err != nil {
return nil, fmt.Errorf("%v", err)
}
go tmpl.ServePlugins()
pCtx, cancel := context.WithCancel(context.Background())
defer func() {
if err != nil {
cancel()
}
}()
// start PluginManagers
if pm := conf.GetEnvironmentConfig().PluginManager; pm != "" {
for _, v := range tmpl.PluginManagerInfoList {
arguments := []string{
pm,
"--stage=run",
fmt.Sprintf("--link=%v", v.Link),
fmt.Sprintf("--port=%v", v.Port),
fmt.Sprintf("--v2raya-confdir=%v", conf.GetEnvironmentConfig().Config),
}
proc, err := RunWithLog(pCtx, pm, arguments, "", os.Environ())
if err != nil {
// clean
for _, pm := range process.pluginManagers {
_ = pm.Kill()
}
process.pluginManagers = nil
return nil, fmt.Errorf("executing PluginManager [state: run, link: %v]: %w", v.Link, err)
}
process.pluginManagers = append(process.pluginManagers, proc)
}
}
defer func() {
if err != nil {
_ = tmpl.Close()
}
}()
if tmpl.API == nil {
log.Fatal("unexpected tmpl.API == nil")
}
process.procCancel = cancel
if err = prestart(); err != nil {
return nil, err
}
proc, err := StartCoreProcess(pCtx)
if err != nil {
return nil, err
}
if err = poststart(); err != nil {
return nil, err
}
process.proc = proc
var unexpectedExiting bool
go func() {
p, e := proc.Wait()
if process.procCancel == nil {
// canceled by v2rayA
return
}
defer ProcessManager.Stop(false)
var t []string
if p != nil {
if p.Success() {
return
}
t = append(t, p.String())
}
if e != nil {
t = append(t, e.Error())
}
log.Warn("v2ray-core: %v", strings.Join(t, ": "))
unexpectedExiting = true
}()
// ports to check
portList := []string{strconv.Itoa(tmpl.ApiPort)}
for _, plu := range tmpl.Plugins {
_, port, err := net.SplitHostPort(plu.ListenAddr())
if err != nil {
return nil, err
}
portList = append(portList, port)
}
startTime := time.Now()
for i := 0; i < len(portList); {
conn, err := net.Dial("tcp", net.JoinHostPort("127.0.0.1", portList[i]))
if err == nil {
conn.Close()
i++
continue
}
if unexpectedExiting {
if log.Log.GetLevel() > log.ParseLevel("info") {
log.Error("some critical information may lost due to your log level")
}
return nil, fmt.Errorf("unexpected exiting: check the log for more information")
}
if time.Since(startTime) > 15*time.Second {
return nil, fmt.Errorf("timeout: check the log for more information")
}
time.Sleep(100 * time.Millisecond)
}
log.Trace("Cost of waiting for v2ray-core: %v", time.Since(startTime).String())
return process, nil
}
type logInfoWriter struct {
}
func (w logInfoWriter) Write(p []byte) (n int, err error) {
s := string(p)
// trim the ending \n
length := len(s)
if s[length-1] == '\n' {
s = s[:length-1]
}
// print each line separately
lines := strings.Split(s, "\n")
for _, line := range lines {
// remove timestamp
fields := strings.SplitN(line, " ", 3)
if len(fields) >= 3 {
if _, err := time.Parse("2006/01/02 15:04:05", fields[0]+" "+fields[1]); err == nil {
log.Info("%v", fields[2])
} else {
log.Info("%v", line)
}
} else {
log.Info("%v", line)
}
}
return len(p), nil
}
var logWriter logInfoWriter
func (p *Process) Close() error {
p.mutex.Lock()
defer p.mutex.Unlock()
if p.procCancel != nil {
p.procCancel()
p.procCancel = nil
err := p.template.Close()
if err != nil {
return err
}
return nil
} else {
_, err := p.proc.Wait()
return err
}
}
func RunWithLog(ctx context.Context, name string, argv []string, dir string, env []string) (*os.Process, error) {
cmd := exec.CommandContext(ctx, name)
cmd.Args = argv
cmd.Dir = dir
cmd.Env = env
cmd.Stdout = logWriter
cmd.Stderr = logWriter
err := cmd.Start()
if err != nil {
return nil, err
}
return cmd.Process, nil
}
func StartCoreProcess(ctx context.Context) (*os.Process, error) {
v2rayBinPath, err := where.GetV2rayBinPath()
if err != nil {
return nil, err
}
dir := filepath.Dir(v2rayBinPath)
var arguments = []string{
v2rayBinPath,
"run",
"--config=" + asset.GetV2rayConfigPath(),
}
if confdir := asset.GetV2rayConfigDirPath(); confdir != "" {
arguments = append(arguments, "--confdir="+confdir)
}
log.Debug(strings.Join(arguments, " "))
assetDir := asset.GetV2rayLocationAssetOverride()
env := append(
os.Environ(),
"V2RAY_LOCATION_ASSET="+assetDir,
)
memstat, err := mem.VirtualMemory()
if err != nil {
log.Warn("cannot get memory info: %v", err)
} else {
if memMiB := memstat.Available / 1024 / 1024; memMiB < 2048 {
env = append(env, "V2RAY_CONF_GEOLOADER=memconservative")
log.Info("low memory: %vMiB, set V2RAY_CONF_GEOLOADER=memconservative", memMiB)
}
}
proc, err := RunWithLog(ctx, v2rayBinPath, arguments, dir, env)
if err != nil {
return nil, err
}
return proc, nil
}
func findAvailablePluginPorts(vms []serverObj.ServerObj) (pluginPortMap map[int]int, err error) {
pluginPortMap = make(map[int]int)
for i, v := range vms {
if !v.NeedPluginPort() {
continue
}
//find a port that not be occupied
var port int
for {
l, err := net.Listen("tcp", "127.0.0.1:0")
if err == nil {
defer l.Close()
port = l.Addr().(*net.TCPAddr).Port
break
}
time.Sleep(30 * time.Millisecond)
}
pluginPortMap[i] = port
}
return pluginPortMap, nil
}
func getConnectedServerObjs() ([]serverObj.ServerObj, []serverInfo, error) {
css := configure.GetConnectedServers()
if css.Len() == 0 { //no connected server. stop v2ray-core.
return nil, nil, nil
}
serverInfos := make([]serverInfo, 0, css.Len())
serverObjs := make([]serverObj.ServerObj, 0, css.Len())
for _, cs := range css.Get() {
sr, err := cs.LocateServerRaw()
if err != nil {
return nil, nil, err
}
serverInfos = append(serverInfos, serverInfo{
Info: sr.ServerObj,
OutboundName: cs.Outbound,
})
serverObjs = append(serverObjs, sr.ServerObj)
}
return serverObjs, serverInfos, nil
}
func NewTemplateFromConnectedServers(setting *configure.Setting) (tmpl *Template, err error) {
//read the database and convert to the v2ray-core template
serverObjs, serverInfos, err := getConnectedServerObjs()
if err != nil {
return nil, err
}
if len(serverObjs) == 0 {
return nil, NoConnectedServerErr
}
var pluginPorts map[int]int
if pluginPorts, err = findAvailablePluginPorts(serverObjs); err != nil {
return nil, err
}
for i := range serverInfos {
if port, ok := pluginPorts[i]; ok {
serverInfos[i].PluginPort = port
}
}
tmpl, err = NewTemplate(serverInfos, setting)
if err != nil {
return nil, err
}
return tmpl, nil
}
func UpdateV2RayConfig() (err error) {
tmpl, err := NewTemplateFromConnectedServers(nil)
if err != nil {
if errors.Is(err, NoConnectedServerErr) {
//no servers are selected, which means to stop the v2ray-core
ProcessManager.Stop(true)
return nil
}
return err
}
err = ProcessManager.Start(tmpl)
if err != nil {
return err
}
return
}