Repository navigation
Expand file tree
/
Copy pathWindowsInvocationJob.cs
More file actions
489 lines (454 loc) · 19.7 KB
/
Copy pathWindowsInvocationJob.cs
File metadata and controls
489 lines (454 loc) · 19.7 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
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
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
using System.ComponentModel;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Security.Principal;
using Microsoft.Win32.SafeHandles;
#if OPENCLAW_SESSION_HOST
namespace OpenClaw.SessionHost;
#else
namespace OpenClaw.Launcher;
#endif
// Prototype bridge, deliberately separate from the versioned launch JSON.
// An older helper rejects this mode instead of silently ignoring containment.
internal interface IInvocationLifetime : IDisposable
{
string Mode { get; }
/// <summary>The coordinator mode for a state-transfer helper request.</summary>
string StateTransferMode { get; }
void MarkDispatched();
void RequestStop();
void ForegroundExited();
void Stop();
}
internal sealed class WindowsInvocationJob : IInvocationLifetime
{
internal const string ModePrefix = "--request-in-job=";
internal const string CoordinatorModePrefix = "--coordinate-invocation=";
internal const string StateTransferModePrefix = "--state-transfer-in-job=";
internal const string StateTransferCoordinatorModePrefix = "--coordinate-state-transfer=";
private const string NamePrefix = @"Global\OpenClaw.Invocation.";
private readonly SafeFileHandle _job;
private readonly InvocationOwner _owner;
private readonly EventWaitHandle _stopping;
private readonly EventWaitHandle _completed;
private readonly EventWaitHandle _pinned;
private readonly EventWaitHandle _terminated;
private readonly EventWaitHandle _drained;
private readonly EventWaitHandle _foregroundExited = new(false, EventResetMode.ManualReset);
private readonly RegisteredWaitHandle _completion;
private readonly Lock _gate = new();
private Exception? _terminationFailure;
private bool _admissionClosed;
private bool _dispatched;
private bool _drainConfirmed;
private bool _terminationAttempted;
public string Mode { get; }
public string StateTransferMode { get; }
private WindowsInvocationJob(
string id, SafeFileHandle job, EventWaitHandle stopping,
EventWaitHandle completed, EventWaitHandle pinned,
EventWaitHandle terminated, EventWaitHandle drained, InvocationOwner owner)
{
Mode = CoordinatorModePrefix + id;
StateTransferMode = StateTransferCoordinatorModePrefix + id;
_job = job;
_owner = owner;
_stopping = stopping;
_completed = completed;
_pinned = pinned;
_terminated = terminated;
_drained = drained;
_completion = ThreadPool.RegisterWaitForSingleObject(
_completed, (_, _) => RequestStop(), null, Timeout.Infinite, executeOnlyOnce: true);
}
public static WindowsInvocationJob Create(string agentSid)
{
_ = new SecurityIdentifier(agentSid);
using WindowsIdentity identity = WindowsIdentity.GetCurrent();
string owner = identity.User!.Value;
string id = Guid.NewGuid().ToString("N");
string name = NamePrefix + id;
using var jobSecurity = new ObjectSecurity(AccessDescriptor(owner, agentSid, 0x000f));
SafeFileHandle? job = null;
EventWaitHandle? stopping = null;
EventWaitHandle? completed = null;
EventWaitHandle? pinned = null;
EventWaitHandle? terminated = null;
EventWaitHandle? drained = null;
InvocationOwner? invocationOwner = null;
try
{
job = CreateJobObjectW(ref jobSecurity.Attributes, name);
if (job.IsInvalid)
{
throw Failure("create the invocation job");
}
// Match the existing kill-on-close job's layout, without copying
// its CreateProcess path: the helper joins before starting children.
var limits = new ExtendedLimits { LimitFlags = 0x2000 };
if (!SetInformationJobObject(job, 9, ref limits, (uint)Marshal.SizeOf<ExtendedLimits>()))
{
throw Failure("configure the invocation job");
}
stopping = CreateEvent(name + ".stopping", owner, agentSid, 0x00100002);
completed = CreateEvent(name + ".completed", owner, agentSid, 0x00000002);
pinned = CreateEvent(name + ".pinned", owner, agentSid, 0x00000002);
terminated = CreateEvent(name + ".terminated", owner, agentSid, 0x00100000);
drained = CreateEvent(name + ".drained", owner, agentSid, 0x00000002);
invocationOwner = new InvocationOwner(name + ".owner", owner, agentSid);
var result = new WindowsInvocationJob(id, job, stopping, completed, pinned, terminated, drained, invocationOwner);
invocationOwner = null;
job = null;
stopping = null;
completed = null;
pinned = null;
terminated = null;
drained = null;
return result;
}
finally
{
invocationOwner?.Dispose();
stopping?.Dispose();
completed?.Dispose();
pinned?.Dispose();
terminated?.Dispose();
drained?.Dispose();
job?.Dispose();
}
}
internal static bool IsMode(string mode) =>
mode.StartsWith(ModePrefix, StringComparison.Ordinal) &&
Guid.TryParseExact(mode.AsSpan(ModePrefix.Length), "N", out _);
internal static bool IsCoordinatorMode(string mode) =>
mode.StartsWith(CoordinatorModePrefix, StringComparison.Ordinal) &&
Guid.TryParseExact(mode.AsSpan(CoordinatorModePrefix.Length), "N", out _);
internal static bool IsStateTransferMode(string mode) =>
mode.StartsWith(StateTransferModePrefix, StringComparison.Ordinal) &&
Guid.TryParseExact(mode.AsSpan(StateTransferModePrefix.Length), "N", out _);
internal static bool IsStateTransferCoordinatorMode(string mode) =>
mode.StartsWith(StateTransferCoordinatorModePrefix, StringComparison.Ordinal) &&
Guid.TryParseExact(mode.AsSpan(StateTransferCoordinatorModePrefix.Length), "N", out _);
// The invocation identifier a coordinator or worker mode carries.
internal static string InvocationId(string mode) =>
IsCoordinatorMode(mode) ? mode[CoordinatorModePrefix.Length..] :
IsStateTransferCoordinatorMode(mode) ? mode[StateTransferCoordinatorModePrefix.Length..] :
IsMode(mode) ? mode[ModePrefix.Length..] :
IsStateTransferMode(mode) ? mode[StateTransferModePrefix.Length..] :
throw new InvalidOperationException("Invalid invocation job mode.");
public void MarkDispatched()
{
lock (_gate)
{
_dispatched = true;
}
if (_stopping.WaitOne(0) || _completed.WaitOne(0))
{
// Completion/cancellation can precede the native spawn return.
// Resume the latched stop now that a coordinator is owned.
RequestStop();
}
}
public void ForegroundExited()
{
_foregroundExited.Set();
Stop();
}
// The worker opens only ASSIGN_PROCESS and closes it before spawn.
// The outside coordinator can terminate this job only if ownership ends.
internal static void Join(string mode)
{
if (!IsMode(mode) && !IsStateTransferMode(mode))
{
throw new InvalidOperationException("Invalid invocation job mode.");
}
string name = NamePrefix + InvocationId(mode);
using SafeFileHandle job = OpenJobObjectW(0x0001, false, name);
if (job.IsInvalid)
{
throw Failure("open the invocation job");
}
using Process self = Process.GetCurrentProcess();
if (!AssignProcessToJobObject(job, self.Handle))
{
throw Failure("join the invocation job");
}
using SafeWaitHandle handle = OpenEventW(0x00100000, false, name + ".stopping");
if (handle.IsInvalid)
{
throw Failure("open the invocation stop event");
}
using var stopping = new EventWaitHandle(false, EventResetMode.ManualReset) { SafeWaitHandle = handle };
// A cancelled spawn can arrive after an empty job was terminated.
// Joining first, then checking the latched event closes that race.
if (stopping.WaitOne(0))
{
throw new InvalidOperationException("The invocation was stopped before its workload started.");
}
}
public void RequestStop()
{
try
{
Stop();
}
catch (Exception exception) when (exception is Win32Exception or TimeoutException or InvalidOperationException)
{
// Cancellation callbacks must not throw on the caller's thread.
// The execution owner surfaces this failure before releasing state.
}
}
public void Stop()
{
lock (_gate)
{
ThrowRecordedFailure();
try
{
StopCore();
}
catch (Exception exception) when (exception is Win32Exception or TimeoutException or InvalidOperationException)
{
// Preserve the first failed attempt; later cleanup paths must
// not silently retry it or spend another termination budget.
_terminationFailure = exception;
_stopping.Set();
if (!_terminationAttempted && _dispatched)
{
// Admission failure cannot strand the outside coordinator.
// This is the first termination attempt, never a retry.
_terminationAttempted = true;
if (TerminateJobObject(_job, 130))
{
_terminated.Set();
}
else
{
Win32Exception cleanupFailure = Failure("terminate the invocation job");
_terminationFailure = new InvalidOperationException(
"Invocation admission closure and emergency termination both failed.",
new AggregateException(exception, cleanupFailure));
}
}
throw;
}
}
}
private void StopCore()
{
var elapsed = Stopwatch.StartNew();
int Remaining() => (int)Math.Max(0, 30_000 - elapsed.ElapsedMilliseconds);
if (!_admissionClosed)
{
// A finite membership snapshot is safe only after new workload
// admission is closed. Existing members remain alive to pin.
CloseAdmission(_job);
_admissionClosed = true;
}
_stopping.Set();
if (!_dispatched || _drainConfirmed)
{
return;
}
int pinned = WaitHandle.WaitAny([_pinned, _foregroundExited], Remaining());
_terminationAttempted = true;
if (!TerminateJobObject(_job, 130))
{
throw Failure("terminate the invocation job");
}
_terminated.Set();
if (pinned != 0)
{
throw new InvalidOperationException(
"The invocation coordinator did not pin its process handles before exiting or timing out; " +
"termination was requested but exit drain is unconfirmed.");
}
if (WaitHandle.WaitAny([_drained, _foregroundExited], Remaining()) != 0)
{
throw new InvalidOperationException(
"The invocation coordinator did not confirm process exit before exiting or timing out.");
}
_drainConfirmed = true;
}
internal static void CloseAdmission(SafeFileHandle job)
{
var limits = new ExtendedLimits { LimitFlags = 0x2008, ActiveProcessLimit = 1 };
if (!SetInformationJobObject(job, 9, ref limits, (uint)Marshal.SizeOf<ExtendedLimits>()))
{
throw Failure("close invocation process admission");
}
}
private void ThrowRecordedFailure()
{
if (_terminationFailure is { } failure)
{
throw new InvalidOperationException("Invocation cancellation failed.", failure);
}
}
public void Dispose()
{
using var stopped = new EventWaitHandle(false, EventResetMode.ManualReset);
if (_completion.Unregister(stopped))
{
stopped.WaitOne();
}
_owner.Dispose();
_stopping.Dispose();
_completed.Dispose();
_pinned.Dispose();
_terminated.Dispose();
_drained.Dispose();
_foregroundExited.Dispose();
_job.Dispose();
}
private static EventWaitHandle CreateEvent(string name, string owner, string agentSid, uint access)
{
using var security = new ObjectSecurity(AccessDescriptor(owner, agentSid, access));
SafeWaitHandle handle = CreateEventW(ref security.Attributes, true, false, name);
if (handle.IsInvalid)
{
int error = Marshal.GetLastWin32Error();
handle.Dispose();
throw new Win32Exception(error, "Unable to create the invocation lifecycle event.");
}
return new EventWaitHandle(false, EventResetMode.ManualReset) { SafeWaitHandle = handle };
}
// Mutex abandonment is a kernel-confirmed owner death even when another
// process retains a job handle. Keep ownership on one dedicated thread,
// not on an async caller's transient thread-pool thread.
private sealed class InvocationOwner : IDisposable
{
private readonly EventWaitHandle _release = new(false, EventResetMode.ManualReset);
private readonly Thread _thread;
private readonly TaskCompletionSource _ready = new(TaskCreationOptions.RunContinuationsAsynchronously);
private Exception? _failure;
public InvocationOwner(string name, string owner, string agentSid)
{
_thread = new Thread(() => Hold(name, owner, agentSid)) { IsBackground = true };
_thread.Start();
try
{
_ready.Task.GetAwaiter().GetResult();
}
catch
{
_thread.Join();
_release.Dispose();
throw;
}
}
private void Hold(string name, string owner, string agentSid)
{
try
{
using var security = new ObjectSecurity(AccessDescriptor(owner, agentSid, 0x00100001));
SafeWaitHandle handle = CreateMutexW(ref security.Attributes, true, name);
int error = Marshal.GetLastWin32Error();
if (handle.IsInvalid)
{
handle.Dispose();
throw new Win32Exception(error, "Unable to create the invocation owner mutex.");
}
if (error == 183)
{
handle.Dispose();
throw new InvalidOperationException("The invocation owner mutex already exists.");
}
using var mutex = new Mutex(false) { SafeWaitHandle = handle };
_ready.SetResult();
_release.WaitOne();
mutex.ReleaseMutex();
}
catch (Exception exception) when (exception is Win32Exception or InvalidOperationException or
UnauthorizedAccessException)
{
_failure = exception;
_ready.TrySetException(exception);
}
}
public void Dispose()
{
_release.Set();
_thread.Join();
_release.Dispose();
if (_failure is not null)
{
throw new InvalidOperationException("Invocation owner confirmation failed.", _failure);
}
}
}
private static Win32Exception Failure(string operation) =>
new(Marshal.GetLastWin32Error(), $"Unable to {operation}.");
// An unlabeled object takes its creator's integrity level, so an elevated
// launcher would stamp High no-write-up on the job and events and the
// Medium-integrity agent could not assign itself or signal them. The DACL
// already limits access to the owner and the agent; the explicit Medium
// label keeps the integrity check from overriding it. Lowering a label to
// at most the caller's own level needs no privilege.
internal static string AccessDescriptor(string owner, string agentSid, uint agentAccess) =>
$"D:P(A;;GA;;;{owner})(A;;0x{agentAccess:X8};;;{agentSid})S:(ML;;NW;;;ME)";
[StructLayout(LayoutKind.Sequential)]
private struct SecurityAttributes
{
public uint Length;
public IntPtr Descriptor;
public int Inherit;
}
private sealed class ObjectSecurity : IDisposable
{
public SecurityAttributes Attributes;
public ObjectSecurity(string sddl)
{
if (!ConvertStringSecurityDescriptorToSecurityDescriptorW(sddl, 1, out IntPtr descriptor, out _))
{
throw Failure("construct invocation object access");
}
Attributes = new SecurityAttributes
{
Length = (uint)Marshal.SizeOf<SecurityAttributes>(),
Descriptor = descriptor
};
}
public void Dispose() => LocalFree(Attributes.Descriptor);
}
[StructLayout(LayoutKind.Sequential)]
private struct ExtendedLimits
{
public long ProcessTime, JobTime;
public uint LimitFlags;
public nuint MinimumWorkingSet, MaximumWorkingSet;
public uint ActiveProcessLimit;
public nuint Affinity;
public uint PriorityClass, SchedulingClass;
public ulong ReadOperations, WriteOperations, OtherOperations, ReadBytes, WriteBytes, OtherBytes;
public nuint ProcessMemory, JobMemory, PeakProcessMemory, PeakJobMemory;
}
[DllImport("advapi32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool ConvertStringSecurityDescriptorToSecurityDescriptorW(
string sddl, uint revision, out IntPtr descriptor, out uint size);
[DllImport("kernel32.dll")]
private static extern IntPtr LocalFree(IntPtr pointer);
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
private static extern SafeFileHandle CreateJobObjectW(ref SecurityAttributes attributes, string name);
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
private static extern SafeFileHandle OpenJobObjectW(uint access, [MarshalAs(UnmanagedType.Bool)] bool inherit, string name);
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
private static extern SafeWaitHandle CreateEventW(
ref SecurityAttributes attributes, [MarshalAs(UnmanagedType.Bool)] bool manualReset,
[MarshalAs(UnmanagedType.Bool)] bool initialState, string name);
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
private static extern SafeWaitHandle OpenEventW(uint access, [MarshalAs(UnmanagedType.Bool)] bool inherit, string name);
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
private static extern SafeWaitHandle CreateMutexW(
ref SecurityAttributes attributes, [MarshalAs(UnmanagedType.Bool)] bool initialOwner, string name);
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool AssignProcessToJobObject(SafeFileHandle job, IntPtr process);
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool TerminateJobObject(SafeFileHandle job, uint exitCode);
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool SetInformationJobObject(SafeFileHandle job, int kind, ref ExtendedLimits info, uint size);
}