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