forked from microsoft/winget-cli
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathShutdownMonitoring.cpp
More file actions
405 lines (347 loc) · 12.8 KB
/
Copy pathShutdownMonitoring.cpp
File metadata and controls
405 lines (347 loc) · 12.8 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
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
#include "pch.h"
#include "Public/ShutdownMonitoring.h"
#include <AppInstallerErrors.h>
#include <AppInstallerLogging.h>
#include <AppInstallerRuntime.h>
#include <winget/COMStaticStorage.h>
using namespace std::chrono_literals;
namespace AppInstaller::ShutdownMonitoring
{
static std::atomic_bool s_TerminationSignalHandlerEnabled = true;
std::shared_ptr<TerminationSignalHandler> TerminationSignalHandler::Instance()
{
struct Singleton : public WinRT::COMStaticStorageBase<TerminationSignalHandler>
{
Singleton() : COMStaticStorageBase(L"WindowsPackageManager.TerminationSignalHandler") {}
};
static Singleton s_instance;
return s_instance.Get();
}
void TerminationSignalHandler::AddListener(ICancellable* cancellable)
{
std::lock_guard<std::mutex> lock{ m_listenersLock };
auto itr = std::find(m_listeners.begin(), m_listeners.end(), cancellable);
THROW_HR_IF(E_NOT_VALID_STATE, itr != m_listeners.end());
m_listeners.push_back(cancellable);
}
void TerminationSignalHandler::RemoveListener(ICancellable* cancellable)
{
std::lock_guard<std::mutex> lock{ m_listenersLock };
auto itr = std::find(m_listeners.begin(), m_listeners.end(), cancellable);
if (itr == m_listeners.end())
{
AICLI_LOG(CLI, Warning, << "TerminationSignalHandler::RemoveListener did not find requested object");
}
else
{
m_listeners.erase(itr);
}
}
void TerminationSignalHandler::EnableListener(bool enabled, ICancellable* cancellable)
{
if (enabled)
{
Instance()->AddListener(cancellable);
}
else
{
Instance()->RemoveListener(cancellable);
}
}
bool TerminationSignalHandler::Enabled()
{
return s_TerminationSignalHandlerEnabled;
}
void TerminationSignalHandler::Enabled(bool enabled)
{
s_TerminationSignalHandlerEnabled = enabled;
}
#ifndef AICLI_DISABLE_TEST_HOOKS
HWND TerminationSignalHandler::GetWindowHandle() const
{
return m_windowHandle.get();
}
#endif
TerminationSignalHandler::TerminationSignalHandler()
{
if (!s_TerminationSignalHandlerEnabled)
{
AICLI_LOG(CLI, Info, << "TerminationSignalHandler is disabled, skipping creation of signal listeners");
return;
}
// Create message only window.
m_messageQueueReady.create();
m_windowThread = std::thread(&TerminationSignalHandler::CreateWindowAndStartMessageLoop, this);
if (!m_messageQueueReady.wait(100))
{
AICLI_LOG(CLI, Warning, << "Timeout creating winget window");
}
// Set up ctrl-c handler.
LOG_IF_WIN32_BOOL_FALSE(SetConsoleCtrlHandler(StaticCtrlHandlerFunction, TRUE));
}
TerminationSignalHandler::~TerminationSignalHandler()
{
SetConsoleCtrlHandler(StaticCtrlHandlerFunction, FALSE);
// std::thread requires that any managed thread (joinable) be joined or detached before destructing
if (m_windowThread.joinable())
{
if (m_windowHandle)
{
// Inform the thread that it should stop.
PostMessageW(m_windowHandle.get(), WM_DESTROY, 0, 0);
}
m_windowThread.join();
}
}
void TerminationSignalHandler::StartAppShutdown()
{
AICLI_LOG(CLI, Info, << "Initiating shutdown procedure");
// Lifetime manager sends CTRL-C after the WM_QUERYENDSESSION is processed.
// If we disable the CTRL-C handler, the default handler will kill us.
InformListeners(CancelReason::AppShutdown, true);
}
BOOL WINAPI TerminationSignalHandler::StaticCtrlHandlerFunction(DWORD ctrlType)
{
return Instance()->CtrlHandlerFunction(ctrlType);
}
LRESULT WINAPI TerminationSignalHandler::WindowMessageProcedure(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
switch (uMsg)
{
case WM_QUERYENDSESSION:
AICLI_LOG(CLI, Verbose, << "Received WM_QUERYENDSESSION");
Instance()->StartAppShutdown();
return TRUE;
case WM_ENDSESSION:
case WM_CLOSE:
AICLI_LOG(CLI, Verbose, << "Received window message type: " << uMsg);
// We delay as long as needed during the WM_ENDSESSION as we will be terminated on return.
ServerShutdownSynchronization::WaitForShutdown();
DestroyWindow(hWnd);
break;
case WM_DESTROY:
PostQuitMessage(0);
break;
default:
return DefWindowProc(hWnd, uMsg, wParam, lParam);
}
return FALSE;
}
BOOL TerminationSignalHandler::CtrlHandlerFunction(DWORD ctrlType)
{
// TODO: Move this to be logged per active context when we have thread static globals
AICLI_LOG(CLI, Info, << "Got CTRL type: " << ctrlType);
switch (ctrlType)
{
case CTRL_C_EVENT:
case CTRL_BREAK_EVENT:
return InformListeners(CancelReason::CtrlCSignal, false);
// According to MSDN, we should never receive these due to having gdi32/user32 loaded in our process.
// But handle them as a force terminate anyway.
case CTRL_CLOSE_EVENT:
case CTRL_LOGOFF_EVENT:
case CTRL_SHUTDOWN_EVENT:
return InformListeners(CancelReason::CtrlCSignal, true);
default:
return FALSE;
}
}
// Terminates the currently attached contexts.
// Returns FALSE if no contexts attached; TRUE otherwise.
BOOL TerminationSignalHandler::InformListeners(CancelReason reason, bool force)
{
BOOL result = FALSE;
{
std::lock_guard<std::mutex> lock{ m_listenersLock };
result = m_listeners.empty() ? FALSE : TRUE;
for (auto& listener : m_listeners)
{
listener->Cancel(reason, force);
}
}
// Notify shutdown synchronization as well
ServerShutdownSynchronization::Instance().Signal(reason);
return result;
}
void TerminationSignalHandler::CreateWindowAndStartMessageLoop()
{
PCWSTR windowClass = L"wingetWindow";
HINSTANCE hInstance = GetModuleHandle(NULL);
if (hInstance == NULL)
{
LOG_LAST_ERROR_MSG("Failed getting module handle");
return;
}
WNDCLASSEX wcex = {};
wcex.cbSize = sizeof(wcex);
wcex.style = CS_NOCLOSE;
wcex.lpfnWndProc = TerminationSignalHandler::WindowMessageProcedure;
wcex.cbClsExtra = 0;
wcex.cbWndExtra = 0;
wcex.hInstance = hInstance;
wcex.lpszClassName = windowClass;
if (!RegisterClassEx(&wcex))
{
LOG_LAST_ERROR_MSG("Failed registering window class");
return;
}
// Unregister the window class on exiting the thread
auto classUnregister = wil::scope_exit([&]()
{
UnregisterClassW(windowClass, hInstance);
});
m_windowHandle = wil::unique_hwnd(CreateWindow(
windowClass,
L"WingetMessageOnlyWindow",
WS_OVERLAPPEDWINDOW,
0, /* x */
0, /* y */
0, /* nWidth */
0, /* nHeight */
NULL, /* hWndParent */
NULL, /* hMenu */
hInstance,
NULL)); /* lpParam */
HWND windowHandle = m_windowHandle.get();
if (windowHandle == nullptr)
{
LOG_LAST_ERROR_MSG("Failed creating window");
return;
}
// We must destroy the window first so that the class unregister can succeed
auto destroyWindow = wil::scope_exit([&]()
{
DestroyWindow(windowHandle);
});
ShowWindow(windowHandle, SW_HIDE);
// Force message queue to be created.
MSG msg;
PeekMessage(&msg, NULL, WM_USER, WM_USER, PM_NOREMOVE);
m_messageQueueReady.SetEvent();
// Message loop, we send WM_DESTROY to terminate it
BOOL getMessageResult;
while ((getMessageResult = GetMessage(&msg, windowHandle, 0, 0)) != 0)
{
if (getMessageResult == -1)
{
LOG_LAST_ERROR();
break;
}
else if (msg.message == WM_DESTROY)
{
break;
}
else
{
DispatchMessage(&msg);
}
}
}
void ServerShutdownSynchronization::Initialize(ShutdownCompleteCallback callback, bool createTerminationSignalHandler)
{
Instance().m_callback = callback;
// Force the creation of the TerminationSignalHandler singleton so that the process can listen for termination signals even if
// it never attempts to run anything that explicitly registers for cancellation callbacks.
if (createTerminationSignalHandler)
{
TerminationSignalHandler::Instance();
}
}
void ServerShutdownSynchronization::AddComponent(const ComponentSystem& component)
{
ServerShutdownSynchronization& instance = Instance();
std::lock_guard<std::mutex> lock{ instance.m_componentsLock };
for (const auto& item : instance.m_components)
{
if (item.BlockNewWork == component.BlockNewWork ||
item.BeginShutdown == component.BeginShutdown ||
item.Wait == component.Wait)
{
return;
}
}
instance.m_components.push_back(component);
}
bool ServerShutdownSynchronization::WaitForShutdown(std::optional<DWORD> timeout)
{
ServerShutdownSynchronization& instance = Instance();
if (timeout)
{
return instance.m_shutdownComplete.wait(timeout.value());
}
else
{
{
std::lock_guard<std::mutex> lock{ instance.m_threadLock };
if (!instance.m_shutdownThread.joinable())
{
AICLI_LOG(Core, Warning, << "Attempt to wait for shutdown when shutdown has not been initiated.");
return false;
}
}
return instance.m_shutdownComplete.wait();
}
}
void ServerShutdownSynchronization::Signal(CancelReason reason)
{
std::lock_guard<std::mutex> lock{ m_threadLock };
if (!m_shutdownThread.joinable())
{
m_shutdownThread = std::thread(&ServerShutdownSynchronization::SynchronizeShutdown, this, reason);
}
}
ServerShutdownSynchronization::~ServerShutdownSynchronization()
{
if (m_shutdownThread.joinable())
{
m_shutdownThread.detach();
}
}
ServerShutdownSynchronization& ServerShutdownSynchronization::Instance()
{
static ServerShutdownSynchronization s_instance;
return s_instance;
}
void ServerShutdownSynchronization::SynchronizeShutdown(CancelReason reason) try
{
auto setShutdownComplete = wil::scope_exit([this]() { this->m_shutdownComplete.SetEvent(); });
std::vector<ComponentSystem> components;
{
std::lock_guard<std::mutex> lock{ m_componentsLock };
components = m_components;
}
AICLI_LOG(CLI, Verbose, << "ServerShutdownSynchronization :: BlockNewWork");
for (const auto& component : components)
{
if (component.BlockNewWork)
{
component.BlockNewWork(reason);
}
}
AICLI_LOG(CLI, Verbose, << "ServerShutdownSynchronization :: BeginShutdown");
for (const auto& component : components)
{
if (component.BeginShutdown)
{
component.BeginShutdown(reason);
}
}
AICLI_LOG(CLI, Verbose, << "ServerShutdownSynchronization :: Wait");
for (const auto& component : components)
{
if (component.Wait)
{
component.Wait();
}
}
AICLI_LOG(CLI, Verbose, << "ServerShutdownSynchronization :: ShutdownCompleteCallback");
ShutdownCompleteCallback callback = m_callback;
if (callback)
{
callback();
}
}
CATCH_LOG();
}