Stroika Library 3.0d23
 
Loading...
Searching...
No Matches
Samples/Service/Sources/Main.cpp
Go to the documentation of this file.
1/*
2 * Copyright(c) Sophist Solutions, Inc. 1990-2026. All rights reserved
3 */
4#include "Stroika/Frameworks/StroikaPreComp.h"
5
6#include <cstdlib>
7#include <iostream>
8
10#include "Stroika/Foundation/Debug/Fatal.h"
13#include "Stroika/Foundation/Execution/CommandLine.h"
15#include "Stroika/Foundation/Execution/SignalHandlers.h"
17#if qStroika_Foundation_Common_Platform_Windows
18#include "Stroika/Foundation/Execution/Platform/Windows/Exception.h"
19#include "Stroika/Foundation/Execution/Platform/Windows/StructuredException.h"
20#endif
23#include "Stroika/Frameworks/Service/Main.h"
24
25#include "AppVersion.h"
26
27#include "Service.h"
28
29/**
30 * \file
31 *
32 * SAMPLE CODE
33 *
34 * Sample Simple Service Application
35 *
36 * This sample demonstrates a few Stroika features.
37 *
38 * o Creating a service application (one that can be automatically started/stopped by
39 * the OS, and one where you can query the status, check process ID, etc)
40 *
41 * o Simple example of command line processing
42 *
43 * o Simple example of Logging (to syslog or windows log or other)
44 */
45
46using namespace std;
47
48using namespace Stroika::Foundation;
50using namespace Stroika::Foundation::Execution;
51using namespace Stroika::Frameworks::Service;
52
54using Memory::MakeSharedPtr;
55
56#if qUseLogger
59#endif
60
61namespace {
62 void ShowUsage_ (const Main& m, const InvalidCommandLineArgument& e = {})
63 {
64 if (not e.As<String> ().empty ()) {
65 cerr << "Error: " << e.As<String> () << endl;
66 cerr << endl;
67 }
68 cerr << "Usage: " << m.GetServiceDescription ().fRegistrationName << " [options] where options can be :\n ";
69 if (m.GetServiceIntegrationFeatures ().Contains (Main::ServiceIntegrationFeatures::eInstall)) {
70 cerr << "\t--" << String{Main::CommandNames::kInstall}
71 << " /* Install service (only when debugging - should use real installer like WIX) */" << endl;
72 cerr << "\t--" << String{Main::CommandNames::kUnInstall}
73 << " /* UnInstall service (only when debugging - should use real installer like WIX) */" << endl;
74 }
75 cerr << "\t--" << String{Main::CommandNames::kRunAsService}
76 << " /* Run this process as a service (doesn't exit until the service is done ...) */" << endl;
77 cerr << "\t--" << String{Main::CommandNames::kRunDirectly} << " /* Run this process as a directly (doesn't exit until the service is done or ARGUMENT TIMEOUT seconds elapsed ...) but not using service infrastructure */"
78 << endl;
79 cerr << "\t--" << String{Main::CommandNames::kStart} << " /* Service/Control Function: Start the service */" << endl;
80 cerr << "\t--" << String{Main::CommandNames::kStop} << " /* Service/Control Function: Stop the service */" << endl;
81 cerr << "\t--" << String{Main::CommandNames::kForcedStop}
82 << " /* Service/Control Function: Forced stop the service (after trying to normally stop) */" << endl;
83 cerr << "\t--" << String{Main::CommandNames::kRestart}
84 << " /* Service/Control Function: Stop and then re-start the service (ok if already stopped) */" << endl;
85 cerr << "\t--" << String{Main::CommandNames::kForcedRestart}
86 << " /* Service/Control Function: Stop (force if needed) and then re-start the service (ok if already stopped) */" << endl;
87 cerr << "\t--" << String{Main::CommandNames::kReloadConfiguration} << " /* Reload service configuration */" << endl;
88 cerr << "\t--" << String{Main::CommandNames::kPause} << " /* Service/Control Function: Pause the service */" << endl;
89 cerr << "\t--" << String{Main::CommandNames::kContinue} << " /* Service/Control Function: Continue the paused service */" << endl;
90 cerr << "\t--Status /* Service/Control Function: Print status of running service */ " << endl;
91 cerr << "\t--Version /* print this application version */ " << endl;
92 cerr << "\t--help /* Print this help. */ " << endl;
93 cerr << endl
94 << "\tExtra unrecognized parameters for start/restart, and forced restart operations will be passed along to the actual "
95 "service process"
96 << endl;
97 cerr << endl;
98 }
99}
100
101int main (int argc, const char* argv[])
102{
103 CommandLine cmdLine{argc, argv};
104 Debug::TraceContextBumper ctx{"main", "argv={}"_f, cmdLine};
105
106#if qStroika_Foundation_Execution_Thread_SupportThreadStatistics
107 [[maybe_unused]] auto&& cleanupReport =
108 Finally ([] () { DbgTrace ("Exiting main with thread {} running"_f, Thread::GetStatistics ().fRunningThreads); });
109#endif
110
111 /*
112 * This allows for safe signals to be managed in a threadsafe way
113 */
115
116 /*
117 * Setup basic (optional) error handling.
118 */
119#if qStroika_Foundation_Common_Platform_Windows
122#endif
123 Debug::RegisterDefaultFatalErrorHandlers (DefaultLoggingFatalErrorHandler);
124
125 /*
126 * SetStandardCrashHandlerSignals not really needed, but helpful for many applications so you get a decent log message/debugging on crash.
127 */
129
130 /*
131 * Ignore SIGPIPE is common practice/helpful in POSIX, but not required by the service manager.
132 */
133#if qStroika_Foundation_Common_Platform_POSIX
135#endif
136
137 /*
138 * Setup Logging to the OS logging facility.
139 */
140#if qUseLogger
141 /*
142 * Optional - use buffering feature
143 * Optional - use suppress duplicates in a 15 second window
144 */
145 Logger::Activator loggerActivation{Logger::Options{
146 .fLogBufferingEnabled = true,
147 .fSuppressDuplicatesThreshold = 15s,
148 }};
149 bool dockerContainerFlag = false; // get from command-line???
150 if (dockerContainerFlag) {
151 using namespace IO::FileSystem;
152 Logger::sThe.AddAppender (
153 MakeSharedPtr<Logger::StreamAppender> (FileOutputStream::New (STDOUT_FILENO, FileStream::AdoptFDPolicy::eDisconnectOnDestruction)));
154 }
155 else {
156#if qStroika_HasComponent_syslog
157 Logger::sThe.SetAppenders (MakeSharedPtr<Logger::SysLogAppender> ("Stroika-Sample-Service"sv));
158#elif qStroika_Foundation_Common_Platform_Windows
159 Logger::sThe.SetAppenders (MakeSharedPtr<Logger::WindowsEventLogAppender> ("Stroika-Sample-Service"sv));
160#endif
161 }
162#endif
163
164#if qStroika_Foundation_Debug_TraceToFile
165 Logger::sThe.Log (Logger::eInfo, "Debugging Log2TraceFile: {}"_f, Debug::GetTraceFileName ());
166#endif
167
168 /*
169 * Parse command line arguments, and start looking at options.
170 */
171 shared_ptr<Main::IServiceIntegrationRep> serviceIntegrationRep = Main::mkDefaultServiceIntegrationRep ();
172#if qUseLogger
173 serviceIntegrationRep = MakeSharedPtr<Main::LoggerServiceWrapper> (serviceIntegrationRep);
174#endif
175
176 /*
177 * Create service handler instance.
178 */
179 Main m{MakeSharedPtr<Samples::Service::SampleAppServiceRep> (), serviceIntegrationRep};
180
181 /*
182 * Run request.
183 */
184 try {
185 using StandardCommandLineOptions::kHelp;
186 using StandardCommandLineOptions::kVersion;
187
188 Sequence<CommandLine::Option> allMyOptions =
189 Sequence<CommandLine::Option>{Main::CommandOptions::kAll} + Sequence<CommandLine::Option>{kHelp, kVersion};
190 cmdLine.Validate (allMyOptions);
191
192 if (cmdLine.Has (Main::CommandOptions::kStatus)) {
193 cout << m.GetServiceStatusMessage ().AsUTF8<string> ();
194 return EXIT_SUCCESS;
195 }
196 else if (cmdLine.Has (kHelp)) {
197 ShowUsage_ (m);
198 return EXIT_SUCCESS;
199 }
200 else if (cmdLine.Has (kVersion)) {
201 cout << m.GetServiceDescription ().fPrettyName << ": "sv << Characters::ToString (AppVersion::kVersion) << endl;
202 return EXIT_SUCCESS;
203 }
204 else {
205 /*
206 * Run the commands, and capture/display exceptions
207 */
208 m.Run (cmdLine);
209 }
210 }
211 catch (const InvalidCommandLineArgument& e) {
212 ShowUsage_ (m, e);
213 }
214 catch (...) {
215 String exceptMsg = Characters::ToString (current_exception ());
216#if qUseLogger
217 Logger::sThe.Log (Logger::eError, "{}"_f, exceptMsg);
218#endif
219 cerr << "FAILED: " << exceptMsg << endl;
220 return EXIT_FAILURE;
221 }
222 return EXIT_SUCCESS;
223}
#define DbgTrace
Definition Trace.h:317
String is like std::u32string, except it is much easier to use, often much more space efficient,...
Definition String.h:201
A generalization of a vector: a container whose elements are keyed by the natural numbers.
nonvirtual void SetStandardCrashHandlerSignals(SignalHandler handler=SignalHandler{DefaultCrashSignalHandler, SignalHandler::Type::eDirect}, const Containers::Set< SignalID > &forSignals=GetStandardCrashSignals())
static shared_ptr< IServiceIntegrationRep > mkDefaultServiceIntegrationRep()
nonvirtual Containers::Set< ServiceIntegrationFeatures > GetServiceIntegrationFeatures() const
Definition Main.inl:32
nonvirtual void Run(const CommandArgs &args, const Streams::OutputStream::Ptr< Characters::Character > &out=nullptr)
void DefaultLoggingCrashSignalHandler(Execution::SignalID signal) noexcept
Definition Logger.cpp:604
void DefaultLoggingFatalErrorHandler(const Characters::SDKChar *msg) noexcept
Definition Logger.cpp:588
auto Finally(FUNCTION &&f) -> Private_::FinallySentry< FUNCTION >
Definition Finally.inl:31
STL namespace.