Repository navigation
Expand file tree
/
Copy pathScriptInstance.cs
More file actions
759 lines (671 loc) · 31 KB
/
Copy pathScriptInstance.cs
File metadata and controls
759 lines (671 loc) · 31 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
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace SharpTagManager
{
class ScriptInstance
{
public string Name;
public string ExecutablePath { private set; get; }
public string ErrorMessage { private set; get; }
public Process ProcessObj { private set; get; }
public object CurrentlyProcessing = null;
// SemaphoreSlim, not Mutex: Mutex ownership is thread-affine (only the thread that called
// WaitOne may call ReleaseMutex), but venv prep acquires this in Start() on the calling
// thread and releases it later from a background Task — a different thread.
public SemaphoreSlim AccessMutex = new SemaphoreSlim(1, 1);
public JsonRpc Rpc = null;
// Set when the script was loaded from a .json descriptor file.
public ScriptDescriptor Descriptor { get; set; }
// Holds the user's current option values; initialised from defaults when the descriptor is loaded.
public ScriptOptionsBag OptionsBag { get; set; }
public FormScriptOutput FormOutput;
public delegate void StdioReceiveEvent(DataReceivedEventArgs e, bool isError=false);
public StdioReceiveEvent StdioReceiveCallback;
private string lastArguments = null;
// Guards against double-starting (or blocking the caller) while venv prep is in flight —
// see Start(). Plain bool is fine here: it's only ever read/written on relatively rare,
// non-overlapping-in-practice call patterns, and a stale read just means one extra no-op.
private bool isStarting = false;
// True while venv prep is in flight, so there is no process yet even though the script is alive.
public bool IsStarting => isStarting;
public ScriptInstance(string name, string path)
{
Name = name;
ExecutablePath = path;
}
private void Process_OutputDataReceived(object sender, DataReceivedEventArgs e)
{
bool isJson = (e.Data?.StartsWith("{")) == true;
Rpc?.StdioReceive(e);
if (StdioReceiveCallback != null)
StdioReceiveCallback(e, false);
if (isJson == false)
{
if (AppSettings.Instance.Scripting_ShowOnMessage && (e.Data != null))
FormScriptOutput.Show(this);
FormOutput?.Process_StdioReceive(e);
}
}
private void Process_OutputErrorReceived(object sender, DataReceivedEventArgs e)
{
if ((e.Data != null) && AppSettings.Instance.Scripting_ShowOnError)
FormScriptOutput.Show(this);
Rpc?.StdioReceive(e, isError:true);
FormOutput?.Process_StdioReceive(e, isError: true);
if (StdioReceiveCallback != null)
StdioReceiveCallback(e, true);
}
private void Process_Exited(object sender, EventArgs e)
{
// BeginInvoke (not a direct/blocking Show()) - this can fire while the UI thread is
// still inside Stop()'s Kill()/Dispose(), and a blocking Invoke there would deadlock.
if ((AppSettings.Instance.Scripting_ShowOnError) && (ProcessObj?.ExitCode != 0))
FormMain.Instance.BeginInvoke((MethodInvoker)(() => FormScriptOutput.Show(this)));
Rpc?.Abort(); // unblock any RPC call still waiting on this now-dead process
FormOutput?.Process_Exited(sender, e);
}
public int Start(string arguments=null)
{
// Venv prep (see StartWithVenv) can take a while on first use (uv download, Python
// install, pip install) and runs on a background thread. If it's already in flight,
// don't double-start and don't block the caller (often the UI thread) waiting on it.
if (isStarting)
return 0;
// Make sure the any previous ones are stopped
if (ProcessObj != null)
Stop();
lastArguments = arguments;
if (Descriptor?.venv != null)
{
isStarting = true;
// Hold the semaphore for the whole prep+launch window so a concurrent RPC call
// (which also waits on this same semaphore — see ScriptRpc.img2tag/tag2tag/img2img)
// blocks until the real process is ready, instead of writing to a stdin that
// doesn't exist yet.
AccessMutex.Wait();
Task.Run(() => StartWithVenv(arguments));
return 0;
}
return LaunchProcess(arguments);
}
private void StartWithVenv(string arguments)
{
try
{
string scriptDir = Path.GetDirectoryName(Path.GetFullPath(ExecutablePath));
FormScriptOutput.Show(this); // First-time setup can be slow; always show its progress.
string venvPython = ScriptVenvManager.PrepareEnvironment(this, Descriptor.venv, scriptDir);
LaunchProcess(arguments, venvPython);
}
catch (Exception err)
{
ErrorMessage = err.Message;
FormOutput?.Process_Error(null, err.Message);
}
finally
{
isStarting = false;
AccessMutex.Release();
}
}
// Does the actual process spawn. interpreterOverride, when set, is used as the launch
// executable instead of the descriptor's own "run" (used to point at a prepared venv's
// python.exe instead of whatever "python" resolves to on PATH).
private int LaunchProcess(string arguments, string interpreterOverride = null)
{
// Build the process locally and only publish it to ProcessObj once it has actually
// started. Otherwise code that reads ProcessObj concurrently (e.g. FormScriptOutput's
// status timer, which ticks independently on the UI thread while venv prep runs this
// method on a background thread) could observe a Process that exists but has no
// associated OS process yet — Process.HasExited throws in that state.
Process proc = new Process();
proc.StartInfo.FileName = ExecutablePath;
if (arguments != null)
proc.StartInfo.Arguments = arguments;
proc.StartInfo.RedirectStandardInput = true;
proc.StartInfo.RedirectStandardOutput = true;
proc.StartInfo.RedirectStandardError = true;
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.CreateNoWindow = true;
proc.EnableRaisingEvents = true;
// Force UTF-8 on all three pipes instead of the machine's OEM/ANSI code page. The
// JSON-RPC requests we write to stdin can contain non-ASCII (e.g. accented image paths,
// Unicode tags); without this they'd be corrupted on any non-ASCII-Western locale.
// BOM-less so scripts don't see a stray U+FEFF at the start of stdin.
var utf8 = new UTF8Encoding(false);
proc.StartInfo.StandardInputEncoding = utf8;
proc.StartInfo.StandardOutputEncoding = utf8;
proc.StartInfo.StandardErrorEncoding = utf8;
// Make Python honor UTF-8 for its stdio and filesystem encoding to match the pipes
// above (ignored by non-Python interpreters, so harmless to set unconditionally).
proc.StartInfo.EnvironmentVariables["PYTHONUTF8"] = "1";
proc.StartInfo.EnvironmentVariables["PYTHONIOENCODING"] = "utf-8";
// Hook stdout, stderr
proc.OutputDataReceived += new DataReceivedEventHandler(Process_OutputDataReceived);
proc.ErrorDataReceived += new DataReceivedEventHandler(Process_OutputErrorReceived);
proc.Exited += Process_Exited;
// Tweak the process according to what is being run
TweakProcess(proc, interpreterOverride);
// Start the process
ErrorMessage = null;
try
{
// Let's goooooo
proc.Start();
// Start pumping data from stdio
proc.BeginOutputReadLine();
proc.BeginErrorReadLine();
}
catch (Exception err)
{
if (AppSettings.Instance.Scripting_ShowOnError)
FormScriptOutput.Show(this);
FormOutput?.Process_Error(null, err.Message);
ErrorMessage = err.Message;
return -1;
}
// Only now is it safe to publish this as the script's active process.
ProcessObj = proc;
// Set up RPC
Rpc = new JsonRpc(this);
// Inform the output form
if (AppSettings.Instance.Scripting_AlwaysShowConsole)
FormScriptOutput.Show(this);
FormOutput?.Process_Started(proc, new EventArgs());
// Add to JobObject (Makes sure this process is cleaned up if this app terminates unexpectedly)
WindowsJobObjectUtility.BindProcess(proc);
return proc.Id;
}
public void Stop()
{
if (ProcessObj != null)
{
try
{
if (ProcessObj.HasExited == false)
{
FormOutput?.Process_Error(ProcessObj, "Ended process");
// entireProcessTree: true — a script can spawn its own subprocesses (e.g.
// florence2.py's "pip install" for torch); killing just the top process
// would leave those running orphaned.
ProcessObj.Kill(entireProcessTree: true);
}
}
catch (Exception) { }
ProcessObj.Dispose();
ProcessObj = null;
}
Rpc?.Abort(); // don't rely on Process_Exited's own Abort() timing
}
public void Restart()
{
Stop();
Start(lastArguments);
}
public bool IsRunning()
{
try
{
if (ProcessObj != null)
{
if((ProcessObj.HasExited == false) && (ProcessObj.Id != 0))
return true;
}
}
catch (Exception) { }
return false;
}
private void TweakProcess(Process process, string interpreterOverride = null)
{
// Descriptor-based launch: run/args come from the .json file, not from the .json itself.
if (Descriptor != null)
{
string scriptDir = Path.GetDirectoryName(Path.GetFullPath(ExecutablePath));
string run;
if (interpreterOverride != null)
{
// A venv was prepared for this script — use its python.exe instead of
// whatever the descriptor's own "run" / PATH would otherwise resolve to.
run = interpreterOverride;
}
else
{
// Resolve the executable: if it looks like a relative path and the file exists,
// use the full path; otherwise pass it as a bare command name (resolved from PATH).
run = Descriptor.run ?? "";
if (!Path.IsPathRooted(run))
{
string candidate = Path.GetFullPath(Path.Combine(scriptDir, run));
if (File.Exists(candidate)) run = candidate;
}
}
process.StartInfo.FileName = run;
// Working directory: a relative path resolves against this descriptor's own folder.
if (!string.IsNullOrEmpty(Descriptor.workingDirectory))
{
string wd = Descriptor.workingDirectory;
process.StartInfo.WorkingDirectory = Path.IsPathRooted(wd)
? wd : Path.GetFullPath(Path.Combine(scriptDir, wd));
}
// Extra environment variables declared by the descriptor.
if (Descriptor.env != null)
foreach (var kvp in Descriptor.env)
process.StartInfo.EnvironmentVariables[kvp.Key] = kvp.Value;
// Build argument list.
var parts = new List<string>();
// 1. Base args from the descriptor (resolve relative paths where the file exists).
foreach (string arg in Descriptor.args ?? new string[0])
{
if (!arg.StartsWith("-"))
{
string abs = Path.IsPathRooted(arg) ? arg : Path.GetFullPath(Path.Combine(scriptDir, arg));
if (File.Exists(abs) || Directory.Exists(abs))
{
parts.Add($"\"{abs}\"");
continue;
}
}
parts.Add(arg.Contains(' ') ? $"\"{arg}\"" : arg);
}
// 2. User-configured option args (e.g. "--device cuda", "--verbose").
if (OptionsBag != null)
foreach (string s in OptionsBag.BuildArgStrings())
parts.Add(s);
// 3. Mode flag already placed in Arguments by Start() (e.g. "-img2tag").
string modeFlag = process.StartInfo.Arguments?.Trim();
if (!string.IsNullOrEmpty(modeFlag))
parts.Add(modeFlag);
process.StartInfo.Arguments = string.Join(" ", parts);
return;
}
string extension = Path.GetExtension(process.StartInfo.FileName).ToLower();
string scriptPath = process.StartInfo.FileName;
// Determine action needed to run this kind of executable
switch (extension)
{
case ".py":
process.StartInfo.FileName = "python";
process.StartInfo.Arguments = $"-u \"{Path.GetFullPath(scriptPath)}\" {process.StartInfo.Arguments}";
break;
case ".bat":
case ".cmd":
process.StartInfo.FileName = "cmd.exe";
process.StartInfo.Arguments = $"/c \"{Path.GetFullPath(scriptPath)}\" {process.StartInfo.Arguments}";
break;
case ".ps1":
process.StartInfo.FileName = "powershell.exe";
process.StartInfo.Arguments = $"-ExecutionPolicy Bypass -File \"{Path.GetFullPath(scriptPath)}\" {process.StartInfo.Arguments}";
break;
case ".sh":
process.StartInfo.FileName = "bash";
process.StartInfo.Arguments = $"\"{scriptPath}\" {process.StartInfo.Arguments}";
break;
case ".vbs":
case ".vbe":
case ".js":
process.StartInfo.FileName = "cscript.exe";
process.StartInfo.Arguments = $"//B //Nologo \"{Path.GetFullPath(scriptPath)}\" {process.StartInfo.Arguments}";
break;
case ".wsf":
process.StartInfo.FileName = "wscript.exe";
process.StartInfo.Arguments = $"\"{Path.GetFullPath(scriptPath)}\" {process.StartInfo.Arguments}";
break;
default:
// Handle other executables directly, including .exe
break;
}
}
}
static class ScriptRunner
{
public class TaskItem
{
public string Name;
public ScriptInstance Script;
public object Target;
public string Arguments;
public object Tag;
public object Results;
public string Errors;
public enum StateE { Unknown, New, Running, Completed, Failed, Canceled }
public StateE State;
public delegate void TaskComplete(TaskItem task);
public TaskComplete TaskCallback;
public delegate void TaskWork(TaskItem task);
public TaskWork TaskToExecute;
internal Task Task;
internal CancellationTokenSource TaskCancelToken;
}
static Queue<TaskItem> TaskQueue = new Queue<TaskItem>();
public static int TotalCount { get; private set; }
public static int CompletedCount { get; private set; }
public static int QueueCount { get => TaskQueue.Count; }
public static TaskItem CurrentTask { get; private set; }
public static void Enqueue(TaskItem task)
{
if ((TaskQueue.Count == 0) && (CurrentTask == null))
{
TotalCount = 0;
CompletedCount = 0;
}
TotalCount++;
TaskQueue.Enqueue(task);
}
public static void CancelAll()
{
TaskQueue.Clear();
if (CurrentTask != null)
Cancel(CurrentTask);
TotalCount = 0;
CompletedCount = 0;
}
public static void Cancel(TaskItem task)
{
// Remove the item from the queue (a bit tricky as Queue doesn't have a .Remove feature)
Queue<TaskItem> tempQueue = new Queue<TaskItem>();
foreach (var item in TaskQueue)
if (item != task)
tempQueue.Enqueue(item);
TaskQueue.Clear();
foreach (var item in tempQueue)
TaskQueue.Enqueue(item);
if (CurrentTask == task)
{
CurrentTask.TaskCancelToken?.Cancel();
CurrentTask.State = TaskItem.StateE.Canceled;
if (CurrentTask.TaskCallback != null)
CurrentTask.TaskCallback(CurrentTask);
}
}
// Used to launch a script with no actual work queued (e.g. the top "Scripting" menu with
// nothing selected). "-startup" tells the script no request is coming, so non-persistent
// scripts (single blocking stdin read, no timeout) know to exit immediately instead of
// hanging forever waiting for a request that never arrives.
public static TaskItem TaskFromScript(ScriptInstance script)
{
TaskItem task = new TaskItem();
task.Name = "Script " + script.Name;
task.Script = script;
task.Arguments = "-startup";
return task;
}
public static void ExecuteTick()
{
// Check up on currently running tasks
if (CurrentTask != null)
{
// IsCompleted, not Status != Running: a freshly started task briefly sits in
// WaitingToRun, which Status != Running would wrongly treat as already done.
if ((CurrentTask.Task == null) || CurrentTask.Task.IsCompleted || (CurrentTask.State != TaskItem.StateE.Running))
{
if (CurrentTask.Task?.IsFaulted == true)
{
//CurrentTask.Errors = ((CurrentTask.Errors == null) ? "" : CurrentTask.Errors) + CurrentTask.Task.Exception.Message;
string error = "";
Exception err = CurrentTask.Task.Exception;
while (err != null)
{
error += "\n\n" + err.Message;
if(err.StackTrace != null)
error += "\n\n" + err.StackTrace;
err = err.InnerException;
}
MessageBox.Show(error);
}
else
{
// Fire off callback and clean up the task
if (CurrentTask.TaskCallback != null)
CurrentTask.TaskCallback(CurrentTask);
}
CompletedCount++;
CurrentTask = null;
}
else
{
ScriptInstance script = CurrentTask.Script;
if ((script != null) && !script.IsRunning() && !script.IsStarting)
{
// Script process must have exited unexpectedly
CurrentTask.Errors = $"Process '{CurrentTask.Script.ExecutablePath}' ended unexpectedly";
CurrentTask.TaskCancelToken?.Cancel();
CompletedCount++;
CurrentTask = null;
}
}
}
// Make sure no task is currently running
if (CurrentTask == null)
{
// Start up the next task
if (TaskQueue.Count > 0)
{
// Pull a new task off the queue
TaskItem task = TaskQueue.Dequeue();
CurrentTask = task;
// If there is a script specified, make sure that script is running
if (task.Script != null)
{
if (task.Script.IsRunning() == false)
{
task.Script.Start(task.Arguments);
if (task.Script.ErrorMessage != null)
{
CurrentTask.Errors = task.Script.ErrorMessage;
CurrentTask.State = TaskItem.StateE.Failed;
return;
}
}
}
// Start the task
if (task.TaskToExecute != null)
{
task.TaskCancelToken = new CancellationTokenSource();
Action taskLambda = () => task.TaskToExecute(task);
task.Task = Task.Run(taskLambda, task.TaskCancelToken.Token);
task.State = TaskItem.StateE.Running;
}
else
{
task.State = TaskItem.StateE.Completed;
}
}
else
{
TotalCount = 0;
CompletedCount = 0;
}
}
}
}
/// <summary>
/// Builds "one menu item per script" dropdowns, shared by the main "Scripting" menu and the
/// Active Scripts window's own "Run" submenu (they only differ in what a click does).
/// </summary>
static class ScriptMenuHelper
{
public static void PopulateScriptMenu(ToolStripMenuItem button, Dictionary<string, ScriptInstance> scripts, EventHandler onScriptClick)
{
if (scripts.Count > 0)
{
foreach (ScriptInstance script in scripts.Values)
{
ToolStripMenuItem scriptMenuItem = new ToolStripMenuItem(script.Name);
scriptMenuItem.Tag = script;
scriptMenuItem.Click += onScriptClick;
button.DropDownItems.Add(scriptMenuItem);
}
button.Enabled = true;
}
else
{
button.Enabled = false;
}
}
}
// Persisted contents of one of the Scripting menu's 10 profile slots (see FormMain's
// scriptSlots/ScriptSlot_Persist) - which script is assigned and that script's option values.
class ScriptProfile
{
public string ScriptName { get; set; }
public string DisplayName { get; set; }
public Dictionary<string, object> OptionValues { get; set; } = new Dictionary<string, object>();
}
/// <summary>
/// Windows API that makes sure all child processes (script processes, uv.exe, and anything
/// those spawn in turn — e.g. a script's own "pip install" subprocess) also terminate if this
/// app terminates, including on a crash or a forceful kill where no .NET cleanup code runs at
/// all. CreateJobObject alone does NOT do this — the job needs the KILL_ON_JOB_CLOSE limit set
/// via SetInformationJobObject, at which point the OS itself (not our code) terminates every
/// process still assigned to the job the moment its last handle closes, which happens
/// automatically when this process's handle table is torn down, for any reason.
/// </summary>
static class WindowsJobObjectUtility
{
// P/Invoke to use Windows JobObject APIs
[DllImport("kernel32.dll", SetLastError = true)]
public static extern IntPtr CreateJobObject(IntPtr lpJobAttributes, string lpName);
[DllImport("kernel32.dll", SetLastError = true)]
public static extern bool AssignProcessToJobObject(IntPtr hJob, IntPtr hProcess);
[DllImport("kernel32.dll", SetLastError = true)]
public static extern bool TerminateJobObject(IntPtr hJob, uint uExitCode);
[DllImport("kernel32.dll", SetLastError = true)]
static extern bool SetInformationJobObject(IntPtr hJob, int JobObjectInfoClass,
ref JOBOBJECT_EXTENDED_LIMIT_INFORMATION lpJobObjectInfo, uint cbJobObjectInfoLength);
private const int JobObjectExtendedLimitInformation = 9;
private const uint JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE = 0x2000;
[StructLayout(LayoutKind.Sequential)]
struct JOBOBJECT_BASIC_LIMIT_INFORMATION
{
public long PerProcessUserTimeLimit;
public long PerJobUserTimeLimit;
public uint LimitFlags;
public UIntPtr MinimumWorkingSetSize;
public UIntPtr MaximumWorkingSetSize;
public uint ActiveProcessLimit;
public UIntPtr Affinity;
public uint PriorityClass;
public uint SchedulingClass;
}
[StructLayout(LayoutKind.Sequential)]
struct IO_COUNTERS
{
public ulong ReadOperationCount;
public ulong WriteOperationCount;
public ulong OtherOperationCount;
public ulong ReadTransferCount;
public ulong WriteTransferCount;
public ulong OtherTransferCount;
}
[StructLayout(LayoutKind.Sequential)]
struct JOBOBJECT_EXTENDED_LIMIT_INFORMATION
{
public JOBOBJECT_BASIC_LIMIT_INFORMATION BasicLimitInformation;
public IO_COUNTERS IoInfo;
public UIntPtr ProcessMemoryLimit;
public UIntPtr JobMemoryLimit;
public UIntPtr PeakProcessMemoryUsed;
public UIntPtr PeakJobMemoryUsed;
}
static IntPtr jobHandle;
public static IntPtr BindProcess(Process process)
{
if (jobHandle == default)
{
jobHandle = CreateJobObject(IntPtr.Zero, null);
if (jobHandle == IntPtr.Zero)
{
throw new Exception("Failed to create JobObject");
}
var info = new JOBOBJECT_EXTENDED_LIMIT_INFORMATION
{
BasicLimitInformation = new JOBOBJECT_BASIC_LIMIT_INFORMATION
{
LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE
}
};
int size = Marshal.SizeOf<JOBOBJECT_EXTENDED_LIMIT_INFORMATION>();
if (!SetInformationJobObject(jobHandle, JobObjectExtendedLimitInformation, ref info, (uint)size))
{
throw new Exception("Failed to configure JobObject for kill-on-close");
}
}
AssignProcessToJobObject(jobHandle, process.Handle);
return jobHandle;
}
}
static class CpuUsageTracker
{
// Dictionary to store the previous CPU times and timestamps for each process
private static Dictionary<int, CpuUsageState> processCpuStates = new Dictionary<int, CpuUsageState>();
// Method to get CPU usage of a process
public static double GetCpuUsage(Process process, bool usagePerCore=true)
{
int processId = process.Id;
// Get current CPU time and timestamp
TimeSpan currentCpuTime = process.TotalProcessorTime;
DateTime currentTime = DateTime.UtcNow;
// Prune entries not seen in a while so the dictionary doesn't grow forever
foreach (int stalePid in processCpuStates
.Where(kv => (currentTime - kv.Value.Timestamp).TotalMinutes > 1)
.Select(kv => kv.Key).ToList())
{
processCpuStates.Remove(stalePid);
}
// Check if we have previous data for this process
if (processCpuStates.ContainsKey(processId))
{
// Retrieve previous state
CpuUsageState previousState = processCpuStates[processId];
// Calculate the CPU usage difference
TimeSpan cpuUsed = currentCpuTime - previousState.CpuTime;
double elapsedSeconds = (currentTime - previousState.Timestamp).TotalSeconds;
// Update the state with current CPU time and timestamp
processCpuStates[processId] = new CpuUsageState
{
CpuTime = currentCpuTime,
Timestamp = currentTime
};
// Guard against division errors and a reused PID producing a negative delta
if (elapsedSeconds <= 0 || cpuUsed < TimeSpan.Zero) return 0;
// Calculate CPU usage as a percentage
double cpuUsagePercent = 0;
if (usagePerCore)
{
cpuUsagePercent = (cpuUsed.TotalSeconds / elapsedSeconds) * 100;
}
else
{
int cpuCores = Environment.ProcessorCount;
cpuUsagePercent = (cpuUsed.TotalSeconds / elapsedSeconds) * 100 / cpuCores;
}
return cpuUsagePercent;
}
else
{
// If there's no previous data, store the current state and return 0
processCpuStates[processId] = new CpuUsageState
{
CpuTime = currentCpuTime,
Timestamp = currentTime
};
return 0;
}
}
// Nested class to store CPU time and timestamp for each process
private class CpuUsageState
{
public TimeSpan CpuTime { get; set; }
public DateTime Timestamp { get; set; }
}
}
}