forked from microsoft/WSL
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWSLCContainer.cpp
More file actions
1909 lines (1556 loc) · 64 KB
/
WSLCContainer.cpp
File metadata and controls
1909 lines (1556 loc) · 64 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
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*++
Copyright (c) Microsoft. All rights reserved.
Module Name:
WSLCContainer.cpp
Abstract:
Contains the implementation of WSLCContainer.
N.B. This class is designed to allow multiple container operations to run in parallel.
Operations that don't change the state of the container must be const qualified, and acquire a shared lock on m_lock.
Operations that do change the container's state must acquire m_lock exclusively.
Operations that interact with processes inside the container or the init process must acquire m_processesLock.
m_lock must always be acquired before m_processesLock
--*/
#include "precomp.h"
#include "WSLCContainer.h"
#include "WSLCProcess.h"
#include "WSLCProcessIO.h"
using wsl::windows::common::COMServiceExecutionContext;
using wsl::windows::common::docker_schema::ErrorResponse;
using wsl::windows::common::relay::DockerIORelayHandle;
using wsl::windows::common::relay::HandleWrapper;
using wsl::windows::common::relay::HTTPChunkBasedReadHandle;
using wsl::windows::common::relay::OverlappedIOHandle;
using wsl::windows::common::relay::ReadHandle;
using wsl::windows::common::relay::RelayHandle;
using wsl::windows::service::wslc::ContainerPortMapping;
using wsl::windows::service::wslc::RelayedProcessIO;
using wsl::windows::service::wslc::TypedHandle;
using wsl::windows::service::wslc::VMPortMapping;
using wsl::windows::service::wslc::WSLCContainer;
using wsl::windows::service::wslc::WSLCContainerImpl;
using wsl::windows::service::wslc::WSLCContainerMetadata;
using wsl::windows::service::wslc::WSLCContainerMetadataV1;
using wsl::windows::service::wslc::WSLCPortMapping;
using wsl::windows::service::wslc::WSLCSession;
using wsl::windows::service::wslc::WSLCVhdVolumeImpl;
using wsl::windows::service::wslc::WSLCVirtualMachine;
using wsl::windows::service::wslc::WSLCVolumeMount;
using namespace wsl::windows::common::relay;
using namespace wsl::windows::common::docker_schema;
using namespace std::chrono_literals;
using wsl::shared::Localization;
namespace wslc_schema = wsl::windows::common::wslc_schema;
using DockerInspectContainer = wsl::windows::common::docker_schema::InspectContainer;
using WslcInspectContainer = wsl::windows::common::wslc_schema::InspectContainer;
namespace {
std::vector<std::string> StringArrayToVector(const WSLCStringArray& array)
{
if (array.Count == 0)
{
return {};
}
THROW_HR_IF_NULL_MSG(E_INVALIDARG, array.Values, "StringArray.Values is null with Count=%lu", array.Count);
std::vector<std::string> result;
result.reserve(array.Count);
for (ULONG i = 0; i < array.Count; i += 1)
{
THROW_HR_IF_NULL_MSG(E_INVALIDARG, array.Values[i], "StringArray.Values[%lu] is null", i);
result.emplace_back(array.Values[i]);
}
return result;
}
// Builds port mapping list from container options and returns the network mode string.
std::pair<std::vector<ContainerPortMapping>, std::string> ProcessPortMappings(const WSLCContainerOptions& options, WSLCVirtualMachine& virtualMachine)
{
WSLCContainerNetworkType networkType = options.ContainerNetwork.ContainerNetworkType;
// Determine network mode string.
std::string networkMode;
if (networkType == WSLCContainerNetworkTypeBridged)
{
networkMode = "bridge";
}
else if (networkType == WSLCContainerNetworkTypeHost)
{
networkMode = "host";
}
else if (networkType == WSLCContainerNetworkTypeNone)
{
networkMode = "none";
}
else
{
THROW_HR_MSG(E_INVALIDARG, "Invalid networking mode: %i", networkType);
}
// Validate port mappings.
THROW_HR_IF_MSG(
E_INVALIDARG,
options.PortsCount > 0 && networkType == WSLCContainerNetworkTypeNone,
"Port mappings are not supported without networking");
std::vector<ContainerPortMapping> ports;
ports.reserve(options.PortsCount);
for (ULONG i = 0; i < options.PortsCount; i++)
{
auto& entry = ports.emplace_back(VMPortMapping::FromWSLCPortMapping(options.Ports[i]), options.Ports[i].ContainerPort);
// Only allocate port for bridged network. Host mode ports are allocated when the container starts.
if (networkType == WSLCContainerNetworkTypeBridged)
{
entry.VmMapping.AssignVmPort(virtualMachine.AllocatePort(options.Ports[i].Family, options.Ports[i].Protocol));
}
}
return {std::move(ports), std::move(networkMode)};
}
void UnmountVolumes(std::vector<WSLCVolumeMount>& volumes, WSLCVirtualMachine& parentVM)
{
for (auto& volume : volumes)
{
if (volume.Mounted)
{
if (SUCCEEDED(LOG_IF_FAILED(parentVM.UnmountWindowsFolder(volume.ParentVMPath.c_str()))))
{
volume.Mounted = false;
}
}
}
}
auto MountVolumes(std::vector<WSLCVolumeMount>& volumes, WSLCVirtualMachine& parentVM)
{
auto errorCleanup = wil::scope_exit_log(WI_DIAGNOSTICS_INFO, [&volumes, &parentVM]() { UnmountVolumes(volumes, parentVM); });
for (auto& volume : volumes)
{
// Create a new directory if it doesn't exist.
if (!std::filesystem::exists(volume.HostPath))
{
auto result = wil::CreateDirectoryDeepNoThrow(volume.HostPath.c_str());
if (FAILED(result))
{
THROW_HR_WITH_USER_ERROR(
result, Localization::MessageWslcFailedToMountVolume(volume.HostPath, wsl::windows::common::wslutil::GetErrorString(result)));
}
}
auto result = parentVM.MountWindowsFolder(volume.HostPath.c_str(), volume.ParentVMPath.c_str(), volume.ReadOnly);
THROW_IF_FAILED_MSG(result, "Failed to mount %ls -> %hs", volume.HostPath.c_str(), volume.ParentVMPath.c_str());
volume.Mounted = true;
}
return std::move(errorCleanup);
}
WSLCContainerState DockerStateToWSLCState(ContainerState state)
{
// TODO: Handle other states like Paused, Restarting, etc.
switch (state)
{
case ContainerState::Created:
return WSLCContainerState::WslcContainerStateCreated;
case ContainerState::Running:
return WSLCContainerState::WslcContainerStateRunning;
case ContainerState::Exited:
case ContainerState::Dead:
return WSLCContainerState::WslcContainerStateExited;
case ContainerState::Removing:
return WSLCContainerState::WslcContainerStateDeleted;
default:
return WSLCContainerState::WslcContainerStateInvalid;
}
}
WSLCContainerNetworkType DockerNetworkModeToWSLCNetworkType(const std::string& mode)
{
if (mode == "bridge")
{
return WSLCContainerNetworkTypeBridged;
}
else if (mode == "host")
{
return WSLCContainerNetworkTypeHost;
}
else if (mode == "none")
{
return WSLCContainerNetworkTypeNone;
}
THROW_HR_MSG(E_INVALIDARG, "Invalid networking mode: %hs", mode.c_str());
}
std::uint64_t ParseDockerTimestamp(const std::string& timestamp)
{
// Docker timestamps are UTC ISO 8601, e.g. "2026-03-05T10:30:00.123456789Z".
std::chrono::sys_seconds utcSeconds;
std::istringstream stream(timestamp);
stream >> std::chrono::parse("%FT%H:%M:%S%Z", utcSeconds);
THROW_HR_IF_MSG(E_INVALIDARG, stream.fail(), "Failed to parse timestamp '%hs'", timestamp.c_str());
return static_cast<std::uint64_t>(utcSeconds.time_since_epoch().count());
}
std::string CleanContainerName(const std::string& name)
{
// Docker container names have a leading '/', strip it.
if (!name.empty() && name[0] == '/')
{
return name.substr(1);
}
return name;
}
std::string ExtractContainerName(const std::vector<std::string>& names, const std::string& id)
{
if (names.empty())
{
return id;
}
return CleanContainerName(names[0]);
}
std::string FormatPortEndpoint(const ContainerPortMapping& portMapping)
{
auto addr = portMapping.VmMapping.BindingAddressString();
return std::format(
"{}:{}/{}",
(addr.find(':') != std::string::npos) ? std::format("[{}]", addr) : addr,
portMapping.VmMapping.HostPort(),
portMapping.ProtocolString());
}
WSLCContainerMetadataV1 ParseContainerMetadata(const std::string& json)
{
auto wrapper = wsl::shared::FromJson<WSLCContainerMetadata>(json.c_str());
THROW_HR_IF(E_UNEXPECTED, !wrapper.V1.has_value());
return wrapper.V1.value();
}
std::string SerializeContainerMetadata(const WSLCContainerMetadataV1& metadata)
{
WSLCContainerMetadata wrapper;
wrapper.V1 = metadata;
return wsl::shared::ToJson(wrapper);
}
void ProcessNamedVolumes(
const WSLCContainerOptions& containerOptions,
const std::unordered_map<std::string, std::unique_ptr<WSLCVhdVolumeImpl>>& sessionVolumes,
wsl::windows::common::docker_schema::CreateContainer& request)
{
THROW_HR_IF(E_INVALIDARG, containerOptions.NamedVolumesCount > 0 && containerOptions.NamedVolumes == nullptr);
for (ULONG i = 0; i < containerOptions.NamedVolumesCount; i++)
{
const auto& nv = containerOptions.NamedVolumes[i];
THROW_HR_IF_NULL_MSG(E_INVALIDARG, nv.Name, "NamedVolume at index %lu has null Name", i);
THROW_HR_IF_NULL_MSG(E_INVALIDARG, nv.ContainerPath, "NamedVolume at index %lu has null ContainerPath", i);
std::string volumeName = nv.Name;
THROW_HR_WITH_USER_ERROR_IF(
WSLC_E_VOLUME_NOT_FOUND, Localization::MessageWslcVolumeNotFound(nv.Name), !sessionVolumes.contains(volumeName));
wsl::windows::common::docker_schema::Mount mount{};
mount.Source = std::move(volumeName);
mount.Target = std::string(nv.ContainerPath);
mount.Type = "volume";
mount.ReadOnly = static_cast<bool>(nv.ReadOnly);
request.HostConfig.Mounts.emplace_back(mount);
}
}
void ValidateNamedVolumes(
const std::vector<wsl::windows::common::docker_schema::Mount>& mounts,
const std::unordered_map<std::string, std::unique_ptr<WSLCVhdVolumeImpl>>& sessionVolumes,
const std::unordered_set<std::string>& anonymousVolumes)
{
for (const auto& mount : mounts)
{
if (mount.Type == "volume" && !mount.Name.empty())
{
THROW_HR_WITH_USER_ERROR_IF(
WSLC_E_VOLUME_NOT_FOUND,
Localization::MessageWslcVolumeNotFound(mount.Name),
!sessionVolumes.contains(mount.Name) && !anonymousVolumes.contains(mount.Name));
}
}
}
} // namespace
ContainerPortMapping::ContainerPortMapping(VMPortMapping&& VmMapping, uint16_t ContainerPort) :
VmMapping(std::move(VmMapping)), ContainerPort(ContainerPort)
{
}
ContainerPortMapping::ContainerPortMapping(ContainerPortMapping&& Other) :
VmMapping(std::move(Other.VmMapping)), ContainerPort(Other.ContainerPort)
{
}
ContainerPortMapping& ContainerPortMapping::operator=(ContainerPortMapping&& Other)
{
if (this != &Other)
{
VmMapping = std::move(Other.VmMapping);
ContainerPort = Other.ContainerPort;
}
return *this;
}
const char* ContainerPortMapping::ProtocolString() const
{
if (VmMapping.Protocol == IPPROTO_TCP)
{
return "tcp";
}
else
{
WI_ASSERT(VmMapping.Protocol == IPPROTO_UDP);
return "udp";
}
}
WSLCPortMapping ContainerPortMapping::Serialize() const
{
return WSLCPortMapping{
.HostPort = VmMapping.HostPort(),
.VmPort = VmMapping.VmPort ? VmMapping.VmPort->Port() : ContainerPort,
.ContainerPort = ContainerPort,
.Family = VmMapping.BindAddress.si_family,
.Protocol = VmMapping.Protocol,
.BindingAddress = VmMapping.BindingAddressString()};
}
WSLCContainerImpl::WSLCContainerImpl(
WSLCSession& wslcSession,
WSLCVirtualMachine& virtualMachine,
std::string&& Id,
std::string&& Name,
std::string&& Image,
WSLCContainerNetworkType NetworkMode,
std::vector<WSLCVolumeMount>&& volumes,
std::vector<ContainerPortMapping>&& ports,
std::map<std::string, std::string>&& labels,
std::function<void(const WSLCContainerImpl*)>&& onDeleted,
ContainerEventTracker& EventTracker,
DockerHTTPClient& DockerClient,
IORelay& Relay,
WSLCContainerState InitialState,
std::uint64_t CreatedAt,
WSLCProcessFlags InitProcessFlags,
WSLCContainerFlags ContainerFlags) :
m_wslcSession(wslcSession),
m_virtualMachine(virtualMachine),
m_name(std::move(Name)),
m_image(std::move(Image)),
m_networkingMode(NetworkMode),
m_id(std::move(Id)),
m_mountedVolumes(std::move(volumes)),
m_mappedPorts(std::move(ports)),
m_labels(std::move(labels)),
m_comWrapper(wil::MakeOrThrow<WSLCContainer>(this, std::move(onDeleted))),
m_dockerClient(DockerClient),
m_eventTracker(EventTracker),
m_ioRelay(Relay),
m_containerEvents(EventTracker.RegisterContainerStateUpdates(
m_id, std::bind(&WSLCContainerImpl::OnEvent, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3))),
m_state(InitialState),
m_createdAt(CreatedAt),
m_initProcessFlags(InitProcessFlags),
m_containerFlags(ContainerFlags)
{
}
WSLCContainerImpl::~WSLCContainerImpl()
{
WSL_LOG(
"~WSLCContainerImpl",
TraceLoggingValue(m_name.c_str(), "Name"),
TraceLoggingValue(m_id.c_str(), "Id"),
TraceLoggingValue((int)m_state, "State"));
// Snapshot and clear process references under the lock.
// Callbacks are then invoked without holding m_lock.
decltype(m_processes) processes;
decltype(m_initProcessControl) initProcessControl = nullptr;
{
auto lock = m_lock.lock_exclusive();
std::lock_guard processesLock{m_processesLock};
initProcessControl = std::exchange(m_initProcessControl, nullptr);
processes = std::exchange(m_processes, {});
}
if (initProcessControl)
{
initProcessControl->OnContainerReleased();
}
for (auto& process : processes)
{
process->OnContainerReleased();
}
m_containerEvents.Reset();
auto lock = m_lock.lock_exclusive();
ReleaseResources();
}
void WSLCContainerImpl::OnProcessReleased(DockerExecProcessControl* process) noexcept
{
std::lock_guard processesLock{m_processesLock};
auto remove = std::ranges::remove_if(m_processes, [process](const auto* e) { return e == process; });
WI_ASSERT(remove.size() == 1);
m_processes.erase(remove.begin(), remove.end());
}
const std::string& WSLCContainerImpl::Image() const noexcept
{
return m_image;
}
const std::string& WSLCContainerImpl::Name() const noexcept
{
return m_name;
}
std::vector<WSLCPortMapping> WSLCContainerImpl::GetPorts() const
{
auto lock = m_lock.lock_shared();
if (m_state != WslcContainerStateRunning)
{
return {};
}
std::vector<WSLCPortMapping> result;
result.reserve(m_mappedPorts.size());
for (const auto& port : m_mappedPorts)
{
result.push_back(port.Serialize());
}
return result;
}
void WSLCContainerImpl::GetStateChangedAt(ULONGLONG* Result)
{
auto lock = m_lock.lock_shared();
*Result = m_stateChangedAt;
}
void WSLCContainerImpl::GetCreatedAt(ULONGLONG* Result)
{
auto lock = m_lock.lock_shared();
*Result = m_createdAt;
}
void WSLCContainerImpl::CopyTo(IWSLCContainer** Container) const
{
auto lock = m_lock.lock_shared();
THROW_HR_IF_MSG(RPC_E_DISCONNECTED, m_comWrapper == nullptr, "Container '%hs' is being released", m_id.c_str());
THROW_IF_FAILED(m_comWrapper.CopyTo(Container));
}
void WSLCContainerImpl::Attach(LPCSTR DetachKeys, WSLCHandle* Stdin, WSLCHandle* Stdout, WSLCHandle* Stderr) const
{
auto lock = m_lock.lock_shared();
THROW_HR_IF_MSG(
HRESULT_FROM_WIN32(ERROR_INVALID_STATE),
m_state != WslcContainerStateRunning,
"Cannot attach to container '%hs', state: %i",
m_id.c_str(),
m_state);
wil::unique_socket ioHandle;
try
{
ioHandle = m_dockerClient.AttachContainer(m_id, DetachKeys == nullptr ? std::nullopt : std::optional<std::string>(DetachKeys));
}
CATCH_AND_THROW_DOCKER_USER_ERROR("Failed to attach to container '%hs'", m_id.c_str());
// If this is a TTY process, the PTY handle can be returned directly.
if (WI_IsFlagSet(m_initProcessFlags, WSLCProcessFlagsTty))
{
*Stdin = common::wslutil::ToCOMOutputHandle(
reinterpret_cast<HANDLE>(ioHandle.get()), GENERIC_READ | GENERIC_WRITE | SYNCHRONIZE, WSLCHandleTypeSocket);
return;
}
// Otherwise the stream is multiplexed and needs to be relayed.
// TODO: Consider skipping stdin if the stdin flag isn't set.
auto [stdinRead, stdinWrite] = common::wslutil::OpenAnonymousPipe(LX_RELAY_BUFFER_SIZE, true, true);
auto [stdoutRead, stdoutWrite] = common::wslutil::OpenAnonymousPipe(LX_RELAY_BUFFER_SIZE, true, true);
auto [stderrRead, stderrWrite] = common::wslutil::OpenAnonymousPipe(LX_RELAY_BUFFER_SIZE, true, true);
std::vector<std::unique_ptr<OverlappedIOHandle>> handles;
// This is required for docker to know when stdin is closed.
auto onInputComplete = [handle = ioHandle.get()]() { LOG_LAST_ERROR_IF(shutdown(handle, SD_SEND) == SOCKET_ERROR); };
// N.B. Ownership of the io handle is given to the DockerIORelayHandle relay, so it can be closed when docker closes the connection.
handles.emplace_back(
std::make_unique<RelayHandle<ReadHandle>>(HandleWrapper{std::move(stdinRead), std::move(onInputComplete)}, ioHandle.get()));
handles.emplace_back(std::make_unique<DockerIORelayHandle>(
std::move(ioHandle), std::move(stdoutWrite), std::move(stderrWrite), DockerIORelayHandle::Format::Raw));
m_ioRelay.AddHandles(std::move(handles));
*Stdin = common::wslutil::ToCOMOutputHandle(reinterpret_cast<HANDLE>(stdinWrite.get()), GENERIC_WRITE | SYNCHRONIZE, WSLCHandleTypePipe);
*Stdout = common::wslutil::ToCOMOutputHandle(reinterpret_cast<HANDLE>(stdoutRead.get()), GENERIC_READ | SYNCHRONIZE, WSLCHandleTypePipe);
*Stderr = common::wslutil::ToCOMOutputHandle(reinterpret_cast<HANDLE>(stderrRead.get()), GENERIC_READ | SYNCHRONIZE, WSLCHandleTypePipe);
}
void WSLCContainerImpl::Start(WSLCContainerStartFlags Flags, LPCSTR DetachKeys)
{
// Acquire an exclusive lock since this method modifies m_initProcessControl, m_initProcess and m_state.
auto lock = m_lock.lock_exclusive();
THROW_HR_IF_MSG(
HRESULT_FROM_WIN32(ERROR_INVALID_STATE),
m_state != WslcContainerStateCreated && m_state != WslcContainerStateExited,
"Cannot start container '%hs', state: %i",
m_name.c_str(),
m_state);
// Attach to the container's init process so no IO is lost.
std::unique_ptr<WSLCProcessIO> io;
try
{
if (WI_IsFlagSet(Flags, WSLCContainerStartFlagsAttach))
{
auto detachKeys = DetachKeys == nullptr ? std::nullopt : std::optional<std::string>(DetachKeys);
if (WI_IsFlagSet(m_initProcessFlags, WSLCProcessFlagsTty))
{
io = std::make_unique<TTYProcessIO>(TypedHandle{
wil::unique_handle{(HANDLE)m_dockerClient.AttachContainer(m_id, detachKeys).release()}, WSLCHandleTypeSocket});
}
else
{
wil::unique_handle stream{reinterpret_cast<HANDLE>(m_dockerClient.AttachContainer(m_id, detachKeys).release())};
io = CreateRelayedProcessIO(std::move(stream), m_initProcessFlags);
}
}
}
catch (const DockerHTTPException& e)
{
// N.B. This can happen if 'DetachKeys' is invalid.
THROW_DOCKER_USER_ERROR_MSG(e, "Failed to attach to container '%hs' during start", m_id.c_str());
}
auto control = std::make_unique<DockerContainerProcessControl>(*this, m_dockerClient, m_eventTracker);
std::lock_guard processesLock{m_processesLock};
m_initProcessControl = control.get();
m_initProcess = wil::MakeOrThrow<WSLCProcess>(std::move(control), std::move(io), m_initProcessFlags);
auto cleanup = wil::scope_exit_log(WI_DIAGNOSTICS_INFO, [this]() mutable {
m_initProcess.Reset();
m_initProcessControl = nullptr;
});
auto volumeCleanup = MountVolumes(m_mountedVolumes, m_virtualMachine);
auto portCleanup = wil::scope_exit_log(WI_DIAGNOSTICS_INFO, [this]() { UnmapPorts(); });
MapPorts();
try
{
m_dockerClient.StartContainer(m_id, DetachKeys == nullptr ? std::nullopt : std::optional<std::string>(DetachKeys));
}
CATCH_AND_THROW_DOCKER_USER_ERROR("Failed to start container '%hs'", m_id.c_str());
portCleanup.release();
volumeCleanup.release();
Transition(WslcContainerStateRunning);
cleanup.release();
}
void WSLCContainerImpl::OnEvent(ContainerEvent event, std::optional<int> exitCode, std::uint64_t eventTime)
{
if (event == ContainerEvent::Stop)
{
THROW_HR_IF(E_UNEXPECTED, !exitCode.has_value());
// If a Stop() call is in progress, provide the timestamp via the promise
// and let Stop() handle the state transition.
{
std::lock_guard stopLock{m_stopStateLock};
if (m_stopState.has_value())
{
m_stopState->set_value(eventTime);
m_stopState.reset();
return;
}
}
auto lock = m_lock.lock_exclusive();
auto previousState = m_state;
ReleaseProcesses();
// Don't run the deletion logic if the container is already in a stopped / deleted state.
// This can happen if Delete() is called by the user.
if (previousState == WslcContainerStateRunning)
{
Transition(WslcContainerStateExited, eventTime);
ReleaseRuntimeResources();
if (WI_IsFlagSet(m_containerFlags, WSLCContainerFlagsRm))
{
DeleteExclusiveLockHeld(WSLCDeleteFlagsNone);
}
}
}
else if (event == ContainerEvent::Destroy)
{
auto lock = m_lock.lock_exclusive();
if (m_state != WslcContainerStateDeleted)
{
Transition(WslcContainerStateDeleted);
}
}
WSL_LOG(
"ContainerEvent",
TraceLoggingValue(m_name.c_str(), "Name"),
TraceLoggingValue(m_id.c_str(), "Id"),
TraceLoggingValue((int)event, "Event"));
}
void WSLCContainerImpl::Stop(WSLCSignal Signal, LONG TimeoutSeconds, bool Kill)
{
// Acquire an exclusive lock since this method modifies m_state.
auto lock = m_lock.lock_exclusive();
if (m_state == WslcContainerStateExited && !Kill)
{
return;
}
else if (m_state != WslcContainerStateRunning)
{
THROW_HR_IF_MSG(
HRESULT_FROM_WIN32(ERROR_INVALID_STATE),
m_state != WslcContainerStateRunning,
"Cannot stop container '%hs', state: %i",
m_id.c_str(),
m_state);
}
std::optional<WSLCSignal> SignalArg;
if (Signal != WSLCSignalNone)
{
SignalArg = Signal;
}
// Don't wait for the container to stop if we're not sending SIGKILL, since it may not stop the container.
// N.B. If the signal was SIGTERM for instance, we'll receive the stop notification via OnEvent().
bool waitForStop = !Kill || (SignalArg.value_or(WSLCSignalSIGKILL) == WSLCSignalSIGKILL);
// Set up a waitable stop state so OnEvent() can pass the Docker timestamp
// back to Stop() without needing to take m_lock.
std::future<std::uint64_t> stopFuture;
if (waitForStop)
{
std::lock_guard stopLock{m_stopStateLock};
m_stopState.emplace();
stopFuture = m_stopState->get_future();
}
// Ensure m_stopState is cleared on all exit paths so OnEvent() doesn't
// take the promise path after a failed Stop().
auto resetStopState = wil::scope_exit([this, waitForStop]() {
if (waitForStop)
{
std::lock_guard stopLock{m_stopStateLock};
m_stopState.reset();
}
});
try
{
if (Kill)
{
m_dockerClient.SignalContainer(m_id, SignalArg);
if (!waitForStop)
{
return;
}
}
else
{
std::optional<ULONG> TimeoutArg;
if (TimeoutSeconds >= 0)
{
TimeoutArg = static_cast<ULONG>(TimeoutSeconds);
}
m_dockerClient.StopContainer(m_id, SignalArg, TimeoutArg);
}
}
catch (const DockerHTTPException& e)
{
// HTTP 304 is returned when the container is already stopped.
if (Kill || e.StatusCode() != 304)
{
THROW_DOCKER_USER_ERROR_MSG(e, "Failed to %hs container '%hs'", Kill ? "kill" : "stop", m_id.c_str());
}
}
// Wait for the stop event to get the Docker timestamp.
// Safe while holding m_lock since OnEvent() uses m_stopStateLock on this path.
std::optional<std::uint64_t> stopTimestamp;
if (stopFuture.wait_for(60s) == std::future_status::ready)
{
stopTimestamp = stopFuture.get();
}
Transition(WslcContainerStateExited, stopTimestamp);
ReleaseProcesses();
ReleaseRuntimeResources();
if (WI_IsFlagSet(m_containerFlags, WSLCContainerFlagsRm))
{
DeleteExclusiveLockHeld(WSLCDeleteFlagsForce);
}
}
void WSLCContainerImpl::Delete(WSLCDeleteFlags Flags)
{
// Acquire an exclusive lock since this method modifies m_state.
auto lock = m_lock.lock_exclusive();
DeleteExclusiveLockHeld(Flags);
}
__requires_exclusive_lock_held(m_lock) void WSLCContainerImpl::DeleteExclusiveLockHeld(WSLCDeleteFlags Flags)
{
// Validate that the container is not running or already deleted.
THROW_HR_IF_MSG(
HRESULT_FROM_WIN32(ERROR_INVALID_STATE),
(m_state == WslcContainerStateRunning && WI_IsFlagClear(Flags, WSLCDeleteFlagsForce)) || m_state == WslcContainerStateDeleted,
"Cannot delete container '%hs', state: %i",
m_name.c_str(),
m_state);
WI_ASSERT(m_state != WslcContainerStateInvalid);
try
{
m_dockerClient.DeleteContainer(m_id, WI_IsFlagSet(Flags, WSLCDeleteFlagsForce));
}
CATCH_AND_THROW_DOCKER_USER_ERROR("Failed to delete container '%hs'", m_id.c_str());
Transition(WslcContainerStateDeleted);
ReleaseResources();
}
void WSLCContainerImpl::Export(WSLCHandle OutHandle) const
{
auto lock = m_lock.lock_shared();
// Validate that the container is not in the running state.
THROW_HR_IF_MSG(
HRESULT_FROM_WIN32(ERROR_INVALID_STATE),
m_state == WslcContainerStateRunning,
"Cannot export container '%hs', state: %i",
m_name.c_str(),
m_state);
std::pair<uint32_t, wil::unique_socket> SocketCodePair;
SocketCodePair = m_dockerClient.ExportContainer(m_id);
auto userHandle = m_wslcSession.OpenUserHandle(OutHandle);
wsl::windows::common::relay::MultiHandleWait io = m_wslcSession.CreateIOContext();
std::string errorJson;
auto accumulateError = [&](const gsl::span<char>& buffer) {
// If the export failed, accumulate the error message.
errorJson.append(buffer.data(), buffer.size());
};
if (SocketCodePair.first != 200)
{
io.AddHandle(std::make_unique<ReadHandle>(HandleWrapper{std::move(SocketCodePair.second)}, std::move(accumulateError)));
}
else
{
io.AddHandle(
std::make_unique<RelayHandle<HTTPChunkBasedReadHandle>>(HandleWrapper{std::move(SocketCodePair.second)}, userHandle.Get()),
wsl::windows::common::relay::MultiHandleWait::CancelOnCompleted);
}
// Release the lock so the container can still be interacted with while the export is in progress.
// Passed this point, no member variables can be accessed.
lock.reset();
io.Run({});
if (SocketCodePair.first != 200)
{
// Export failed, parse the error message.
auto error = wsl::shared::FromJson<common::docker_schema::ErrorResponse>(errorJson.c_str());
THROW_HR_WITH_USER_ERROR_IF(WSLC_E_CONTAINER_NOT_FOUND, error.message, SocketCodePair.first == 404);
THROW_HR_WITH_USER_ERROR(E_FAIL, error.message);
}
}
void WSLCContainerImpl::GetState(WSLCContainerState* Result)
{
auto lock = m_lock.lock_shared();
*Result = m_state;
}
WSLCContainerState WSLCContainerImpl::State() const noexcept
{
auto lock = m_lock.lock_shared();
return m_state;
}
void WSLCContainerImpl::GetInitProcess(IWSLCProcess** Process) const
{
auto lock = m_lock.lock_shared();
std::lock_guard processesLock{m_processesLock};
THROW_HR_IF(HRESULT_FROM_WIN32(ERROR_INVALID_STATE), !m_initProcess);
THROW_IF_FAILED(m_initProcess.CopyTo(__uuidof(IWSLCProcess), (void**)Process));
}
void WSLCContainerImpl::Exec(const WSLCProcessOptions* Options, LPCSTR DetachKeys, IWSLCProcess** Process)
{
THROW_HR_IF_MSG(E_INVALIDARG, Options->CommandLine.Count == 0, "Exec command line cannot be empty");
auto lock = m_lock.lock_shared();
THROW_HR_IF_MSG(
HRESULT_FROM_WIN32(ERROR_INVALID_STATE),
m_state != WslcContainerStateRunning,
"Container %hs is not running. State: %i",
m_name.c_str(),
m_state);
common::docker_schema::CreateExec request{};
request.AttachStdout = true;
request.AttachStderr = true;
request.Cmd = StringArrayToVector(Options->CommandLine);
request.Env = StringArrayToVector(Options->Environment);
if (Options->CurrentDirectory != nullptr)
{
request.WorkingDir = Options->CurrentDirectory;
}
if (Options->User != nullptr)
{
request.User = Options->User;
}
if (WI_IsFlagSet(Options->Flags, WSLCProcessFlagsTty))
{
request.Tty = true;
}
if (WI_IsFlagSet(Options->Flags, WSLCProcessFlagsStdin))
{
request.AttachStdin = true;
}
if (DetachKeys != nullptr)
{
request.DetachKeys = DetachKeys;
}
try
{
auto result = m_dockerClient.CreateExec(m_id, request);
// N.B. There's no way to delete a created exec instance, it is removed when the container is deleted.
wil::unique_handle stream{
(HANDLE)m_dockerClient
.StartExec(result.Id, common::docker_schema::StartExec{.Tty = request.Tty, .ConsoleSize = request.ConsoleSize})
.release()};
std::unique_ptr<WSLCProcessIO> io;
if (request.Tty)
{
io = std::make_unique<TTYProcessIO>(TypedHandle{std::move(stream), WSLCHandleTypeSocket});
}
else
{
io = CreateRelayedProcessIO(std::move(stream), Options->Flags);
}
auto control = std::make_unique<DockerExecProcessControl>(*this, result.Id, m_dockerClient, m_eventTracker);
{
std::lock_guard processesLock{m_processesLock};
// Store a non owning reference to the process.
m_processes.push_back(control.get());
}
// Poll for the exec'd process to either be running, or failed.
// This is required because StartExec() returns before the process is actually created, and if exec() fails, we'll never
// get an exec_die notification, so this case needs to be caught before returning the process to the caller.
// TODO: Configurable timeout.
auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(30);
do
{
auto state = m_dockerClient.InspectExec(result.Id);
if (state.Running && state.Pid.has_value())
{
control->SetPid(state.Pid.value());
break; // Exec is running, exit.
}
else if (state.ExitCode.has_value())
{
control->SetExitCode(state.ExitCode.value());
break; // Exec has exited, exit.
}
else if (std::chrono::steady_clock::now() > deadline)
{
THROW_HR_MSG(
HRESULT_FROM_WIN32(ERROR_TIMEOUT),
"Timed out waiting for exec state for '%hs'. Last state: %hs",
result.Id.c_str(),
wsl::shared::ToJson(state).c_str());
}
} while (!control->GetExitEvent().wait(100));
auto process = wil::MakeOrThrow<WSLCProcess>(std::move(control), std::move(io), Options->Flags);
THROW_IF_FAILED(process.CopyTo(__uuidof(IWSLCProcess), (void**)Process));
}
CATCH_AND_THROW_DOCKER_USER_ERROR("Failed to exec process in container %hs", m_id.c_str());
}
WslcInspectContainer WSLCContainerImpl::BuildInspectContainer(const DockerInspectContainer& dockerInspect) const
{
WslcInspectContainer wslcInspect{};
wslcInspect.Id = dockerInspect.Id;
wslcInspect.Name = CleanContainerName(dockerInspect.Name);
wslcInspect.Created = dockerInspect.Created;
wslcInspect.Image = m_image;
// Map container state.
wslcInspect.State.Status = dockerInspect.State.Status;
wslcInspect.State.Running = dockerInspect.State.Running;
wslcInspect.State.ExitCode = dockerInspect.State.ExitCode;
wslcInspect.State.StartedAt = dockerInspect.State.StartedAt;
wslcInspect.State.FinishedAt = dockerInspect.State.FinishedAt;
wslcInspect.HostConfig.NetworkMode = dockerInspect.HostConfig.NetworkMode;
// Map WSLC port mappings (Windows host ports only). HostIp is not set here and will use
// the default value ("127.0.0.1") defined in the InspectPortBinding schema.
for (const auto& e : m_mappedPorts)
{
// TODO: ipv6 support.
auto portKey = std::format("{}/{}", e.ContainerPort, e.ProtocolString());