-
Notifications
You must be signed in to change notification settings - Fork 141
Expand file tree
/
Copy pathEmbeddedPythonRuntimeBootstrap.cs
More file actions
171 lines (140 loc) · 6.39 KB
/
Copy pathEmbeddedPythonRuntimeBootstrap.cs
File metadata and controls
171 lines (140 loc) · 6.39 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
using System;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Reflection;
using System.Threading;
namespace UiPath.Python.Tests
{
public static class EmbeddedPythonRuntimeBootstrap
{
private const string EmbeddedZipFileName = "python-3.14.5-embed-amd64.zip";
public const string PythonVersion = "3.14.5";
private static readonly string RuntimeRoot = Path.Combine(Path.GetTempPath(), "pythons", PythonVersion);
private static readonly string LockFile = Path.Combine(RuntimeRoot, ".setup.lock");
private static readonly string ReadyFile = Path.Combine(RuntimeRoot, ".setup.ready");
private static readonly string InProgressFile = Path.Combine(RuntimeRoot, ".setup.inprogress");
public static string EnsureRuntimePath()
{
Directory.CreateDirectory(RuntimeRoot);
using var lockStream = AcquireSetupLock();
if (IsReady())
return RuntimeRoot;
File.WriteAllText(InProgressFile, $"PID={Environment.ProcessId};UTC={DateTime.UtcNow:O}");
var stagingDir = Path.Combine(Path.GetTempPath(), "pythons", $"staging-{PythonVersion}-{Guid.NewGuid():N}");
try
{
if (Directory.Exists(stagingDir))
Directory.Delete(stagingDir, true);
Directory.CreateDirectory(stagingDir);
using (var zipStream = GetEmbeddedZipStream())
using (var archive = new ZipArchive(zipStream, ZipArchiveMode.Read, leaveOpen: false))
{
archive.ExtractToDirectory(stagingDir, true);
}
CleanRuntimeRoot();
CopyDirectory(stagingDir, RuntimeRoot);
if (!HasExtractedRuntime())
throw new InvalidOperationException($"Extracted embedded Python runtime is invalid in '{RuntimeRoot}'.");
File.WriteAllText(ReadyFile, DateTime.UtcNow.ToString("O"));
}
finally
{
if (File.Exists(InProgressFile))
File.Delete(InProgressFile);
if (Directory.Exists(stagingDir))
Directory.Delete(stagingDir, true);
}
return RuntimeRoot;
}
/// <summary>
/// The folder name Python's own per-user site (e.g. %APPDATA%\Roaming\Python\PythonXY on
/// Windows) resolves to for this embedded runtime's version, derived from
/// <see cref="PythonVersion"/> so it can't drift out of sync when that's bumped.
/// </summary>
public static string UserSiteVersionFolder
{
get
{
var parts = PythonVersion.Split('.');
return $"Python{parts[0]}{parts[1]}";
}
}
public static string GetPythonLibraryPath(string runtimePath)
{
ArgumentNullException.ThrowIfNull(runtimePath);
var specificDll = Directory.EnumerateFiles(runtimePath, "python3*.dll", SearchOption.TopDirectoryOnly)
.Where(file => !string.Equals(Path.GetFileName(file), "python3.dll", StringComparison.OrdinalIgnoreCase))
.OrderBy(file => file)
.LastOrDefault();
var dll = specificDll
?? Directory.EnumerateFiles(runtimePath, "python3*.dll", SearchOption.TopDirectoryOnly)
.OrderBy(file => file)
.FirstOrDefault();
if (string.IsNullOrWhiteSpace(dll))
throw new FileNotFoundException($"No python3*.dll was found in '{runtimePath}'.", runtimePath);
return dll;
}
private static bool IsReady()
{
return File.Exists(Path.Combine(RuntimeRoot, "python.exe")) && File.Exists(ReadyFile);
}
private static bool HasExtractedRuntime()
{
return File.Exists(Path.Combine(RuntimeRoot, "python.exe"));
}
private static FileStream AcquireSetupLock()
{
while (true)
{
try
{
return new FileStream(LockFile, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None);
}
catch (IOException)
{
Thread.Sleep(200);
}
}
}
private static Stream GetEmbeddedZipStream()
{
var assembly = typeof(EmbeddedPythonRuntimeBootstrap).Assembly;
var resourceName = assembly.GetManifestResourceNames()
.FirstOrDefault(name => name.EndsWith(EmbeddedZipFileName, StringComparison.OrdinalIgnoreCase));
if (string.IsNullOrWhiteSpace(resourceName))
throw new FileNotFoundException($"Embedded resource '{EmbeddedZipFileName}' not found in test assembly.");
return assembly.GetManifestResourceStream(resourceName)
?? throw new InvalidOperationException($"Unable to open embedded resource stream '{resourceName}'.");
}
private static void CleanRuntimeRoot()
{
foreach (var file in Directory.EnumerateFiles(RuntimeRoot, "*", SearchOption.TopDirectoryOnly))
{
var name = Path.GetFileName(file);
if (string.Equals(name, Path.GetFileName(LockFile), StringComparison.OrdinalIgnoreCase))
continue;
File.Delete(file);
}
foreach (var dir in Directory.EnumerateDirectories(RuntimeRoot, "*", SearchOption.TopDirectoryOnly))
{
Directory.Delete(dir, true);
}
}
private static void CopyDirectory(string source, string destination)
{
foreach (var directory in Directory.GetDirectories(source, "*", SearchOption.AllDirectories))
{
var relative = Path.GetRelativePath(source, directory);
Directory.CreateDirectory(Path.Combine(destination, relative));
}
foreach (var file in Directory.GetFiles(source, "*", SearchOption.AllDirectories))
{
var relative = Path.GetRelativePath(source, file);
var destFile = Path.Combine(destination, relative);
Directory.CreateDirectory(Path.GetDirectoryName(destFile)!);
File.Copy(file, destFile, true);
}
}
}
}