forked from 86Box/86BoxManager
-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathUnixExecutor.cs
More file actions
98 lines (82 loc) · 2.65 KB
/
Copy pathUnixExecutor.cs
File metadata and controls
98 lines (82 loc) · 2.65 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
using System;
using System.IO;
using System.Collections.Generic;
using System.Diagnostics;
using System.Net.Sockets;
using _86BoxManager.API;
using _86BoxManager.Common;
namespace _86BoxManager.Unix
{
public sealed class UnixExecutor : CommonExecutor, IDisposable
{
private readonly string _tempDir;
private readonly IDictionary<string, SocketInfo> _runningVm;
public UnixExecutor(string tempDir)
{
_tempDir = tempDir;
_runningVm = new Dictionary<string, SocketInfo>();
}
public void Dispose()
{
foreach (var info in _runningVm.Values)
info.Dispose();
_runningVm.Clear();
}
~UnixExecutor()
{
Dispose();
}
public override ProcessStartInfo BuildStartInfo(IExecVars args)
{
var info = base.BuildStartInfo(args);
var name = args.Vm.Name;
var socketName = name + Environment.ProcessId;
var server = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.Unspecified);
var socketPath = Path.Combine(_tempDir, socketName);
server.Bind(new UnixDomainSocketEndPoint(socketPath));
server.Listen();
_runningVm[name] = new SocketInfo { Server = server };
args.Vm.OnExit = OnVmExit;
var opEnv = info.Environment;
opEnv["86BOX_MANAGER_SOCKET"] = socketName;
if (server.IsBound)
server.BeginAccept(OnSocketConnect, (server, name));
return info;
}
private void OnSocketConnect(IAsyncResult result)
{
var (server, name) = (ValueTuple<Socket, string>)result.AsyncState!;
try
{
var client = server.EndAccept(result);
_runningVm[name].Client = client;
}
catch
{
// Simply ignore!
}
}
private void OnVmExit(IVm vm)
{
var name = vm.Name;
if (!_runningVm.TryGetValue(name, out var info))
return;
info.Dispose();
_runningVm.Remove(name);
}
private sealed class SocketInfo : IDisposable
{
public Socket Server { get; set; }
public Socket Client { get; set; }
public void Dispose()
{
Server?.Dispose();
Client?.Dispose();
}
}
internal Socket GetClient(string name)
{
return _runningVm.TryGetValue(name, out var info) ? info.Client : null;
}
}
}