-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathProgram.cs
268 lines (228 loc) · 10.2 KB
/
Program.cs
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
using Containerd.Runhcs.V1;
using Containerd.Services.Containers.V1;
using Containerd.Services.Namespaces.V1;
using Containerd.Services.Tasks.V1;
using Containerd.V1.Types;
using Google.Protobuf;
using Grpc.Core;
using Grpc.Net.Client;
using Microsoft.Win32.SafeHandles;
using System.IO.Pipes;
using System.Net.Sockets;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.Json;
using static Pipes;
const string sockPath = "/run/containerd/containerd.sock";
const string pipeName = @"\\.\pipe\containerd-containerd";
bool isWindows = RuntimeInformation.IsOSPlatform(OSPlatform.Windows);
Console.WriteLine($"Check pipe: {File.Exists(@"\\.\pipe\containerd-containerd")}");
using IConnectionFactory connectionFactory = isWindows ? new NamedPipeConnectionFactory(pipeName) : new UnixDomainSocketConnectionFactory(sockPath);
var socketsHttpHandler = new SocketsHttpHandler
{
ConnectCallback = connectionFactory.ConnectAsync,
UseProxy = false,
};
var channel = GrpcChannel.ForAddress("http://localhost", new GrpcChannelOptions
{
HttpHandler = socketsHttpHandler,
});
var client = new Containers.ContainersClient(channel);
var headers = new Metadata
{
{ "containerd-namespace", "default" }
};
var listNamespaceRequest = new ListNamespacesRequest();
var namespaceClient = new Namespaces.NamespacesClient(channel);
var taskClient = new Tasks.TasksClient(channel);
var namespaces = await namespaceClient.ListAsync(listNamespaceRequest, headers);
foreach (var @namespace in namespaces.Namespaces)
{
headers = new Metadata
{
{ "containerd-namespace", @namespace.Name }
};
var taskRequest = new ListTasksRequest();
var response = await client.ListAsync(new ListContainersRequest(), headers);
var tasks = taskClient.List(taskRequest, headers);
var taskDictionary = tasks.Tasks.ToDictionary(t => t.Id);
byte[] buffer = new byte[8192];
var jsonOptions = new JsonSerializerOptions() { PropertyNameCaseInsensitive = true };
using(MemoryStream memoryStream = new MemoryStream(buffer))
{
foreach (var container in response.Containers)
{
Console.WriteLine(container.Id);
var spec = GetSpec(container, jsonOptions);
memoryStream.Position = 0;
if (spec!.RootElement.TryGetProperty("resources", out JsonElement jsonElement))
{
Console.WriteLine($"resources for {container.Id}");
Console.WriteLine(jsonElement);
}
Console.WriteLine("Processes");
// Tasks indicate that the container is running
if (taskDictionary.ContainsKey(container.Id))
{
ListPidsRequest processRequest = new() { ContainerId = container.Id };
ListPidsResponse pidsResponse = await taskClient.ListPidsAsync(processRequest, headers);
foreach (var item in pidsResponse.Processes)
{
using (MemoryStream memoryStream1 = new MemoryStream())
{
string processInfo = string.Empty;
string processInfo2 = string.Empty;
if (item.Info.Value is not null)
{
Console.Write($"Process Url type: {item.Info.TypeUrl}");
// Windows: https://github.com/microsoft/hcsshim/blob/master/cmd/containerd-shim-runhcs-v1/options/runhcs.proto
// Linux:
if (isWindows)
{
var pd = ProcessDetails.Parser.ParseFrom(item.Info.Value);
// The process name.
processInfo2 = pd.ImageName;
}
else
{
// Get ProcessDetails for Linux.
}
}
Console.WriteLine($"{item.Pid}, {processInfo2}");
}
}
}
Console.WriteLine("------------------------------");
}
}
}
JsonDocument? GetSpec(Container container, JsonSerializerOptions jsonOptions)
{
using (MemoryStream memoryStream = new MemoryStream())
{
// https://github.com/opencontainers/runtime-spec/blob/main/schema/config-linux.json
// https://github.com/opencontainers/runtime-spec/blob/main/schema/config-windows.json
var spec = container.Spec.Value.ToStringUtf8();
container.Spec.Value.WriteTo(memoryStream);
memoryStream.Position = 0;
var specObject = JsonSerializer.Deserialize<JsonDocument>(memoryStream, jsonOptions);
return specObject;
}
}
public sealed class NamedPipeConnectionFactory : IConnectionFactory, IDisposable
{
private SafePipeHandle handle;
private NamedPipeClientStream _pipe;
public NamedPipeConnectionFactory(string pipeName)
{
uint pipeFlags = FILE_FLAG_OVERLAPPED | SECURITY_SQOS_PRESENT | SECURITY_ANONYMOUS;
uint fileAccess = GENERIC_READ | GENERIC_WRITE;
int error;
this.handle = CreateFileW(
pipeName,// the pipe name,
fileAccess, // read access that allows to set ReadMode to message on lines 114 & 172
0, // sharing: none
IntPtr.Zero, // security attributes
FileMode.Open, // open existing
pipeFlags, // impersonation flags
IntPtr.Zero); // template file: null
if (this.handle.IsInvalid)
{
error = Marshal.GetLastWin32Error();
throw new InvalidOperationException($"Failed to create file for pipe. Win error: {error}");
}
_pipe = new NamedPipeClientStream(PipeDirection.InOut, isAsync: true, isConnected: true, safePipeHandle: handle);
}
public async ValueTask<Stream> ConnectAsync(SocketsHttpConnectionContext socketsHttpConnectionContext, CancellationToken cancellationToken)
{ // Reading the first frame that the server sends to unblock the first write that the client will do.
// The Http2Stream will respond with this preface response at first read.
// This is the same behavior that http2_client in go. Line 367 t.reader()
// https://github.com/grpc/grpc-go/blob/master/internal/transport/http2_client.go
// Start the reader goroutine for incoming message. Each transport has
// a dedicated goroutine which reads HTTP2 frame from network. Then it
// dispatches the frame to the corresponding stream entity.
var http2Stream = new Http2Stream(_pipe, InitialReadAsync());
return http2Stream;
}
private async Task<Memory<byte>> InitialReadAsync()
{
var buffer = new byte[32];
var readCount = await _pipe.ReadAsync(buffer);
Console.WriteLine($"Read {readCount} from named pipe to avoid blocking further calls.");
Memory<byte> prefaceResponse = new Memory<byte>(buffer, 0, readCount);
return prefaceResponse;
}
public void Dispose()
{
this._pipe.Dispose();
this.handle.Dispose();
}
}
public interface IConnectionFactory: IDisposable
{
ValueTask<Stream> ConnectAsync(SocketsHttpConnectionContext socketsHttpConnectionContext, CancellationToken cancellationToken);
}
class Http2Stream : Stream
{
private Task<Memory<byte>> initialReadTask;
public Http2Stream(NamedPipeClientStream namedPipeClientStream, Task<Memory<byte>> initialReadTask)
{
namedpipeClientStream = namedPipeClientStream;
this.initialReadTask = initialReadTask;
this.isFirstRead = true;
}
public override bool CanRead => namedpipeClientStream.CanRead;
public override bool CanSeek => namedpipeClientStream.CanSeek;
public override bool CanWrite => namedpipeClientStream.CanWrite;
public override long Length => namedpipeClientStream.Position;
public override long Position { get { return this.namedpipeClientStream.Position; } set { this.namedpipeClientStream.Position = value; } }
private NamedPipeClientStream namedpipeClientStream { get; }
private bool isFirstRead;
public override void Flush()
{
this.namedpipeClientStream.Flush();
}
public override int Read(byte[] buffer, int offset, int count)
{
return this.namedpipeClientStream.Read(buffer, offset, count);
}
public override long Seek(long offset, SeekOrigin origin)
{
return this.namedpipeClientStream.Seek(offset, origin);
}
public override void SetLength(long value)
{
this.namedpipeClientStream.SetLength(value);
}
public override void Write(byte[] buffer, int offset, int count)
{
this.namedpipeClientStream.Write(buffer, offset, count);
}
public override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
return this.namedpipeClientStream.ReadAsync(buffer, offset, count, cancellationToken);
}
public override async ValueTask<int> ReadAsync(Memory<byte> buffer, CancellationToken cancellationToken = default)
{
/// We do the first read at connection time and when the httpclient calls we respond with that same response.
if (isFirstRead)
{
var initialRead = await initialReadTask;
// TODO: What happens if buffer passed to ReadAsync isn't big enough for initial read data.
// Could save the initial read data and keep replaying in ReadAsync calls until empty.
initialRead.CopyTo(buffer);
isFirstRead = false;
return initialRead.Length;
}
var readBytes = await this.namedpipeClientStream.ReadAsync(buffer, cancellationToken);
return readBytes;
}
public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
return this.namedpipeClientStream.WriteAsync(buffer, offset, count, cancellationToken);
}
public override ValueTask WriteAsync(ReadOnlyMemory<byte> buffer, CancellationToken cancellationToken = default)
{
return this.namedpipeClientStream.WriteAsync(buffer, cancellationToken);
}
}