-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclass_USConfigServer.erl
More file actions
1769 lines (1230 loc) · 60.7 KB
/
Copy pathclass_USConfigServer.erl
File metadata and controls
1769 lines (1230 loc) · 60.7 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) 2019-2026 Olivier Boudeville
%
% This file belongs to the US-Common project, a part of the Universal Server
% framework.
%
% This program is free software: you can redistribute it and/or modify it under
% the terms of the GNU Affero General Public License as published by the Free
% Software Foundation, either version 3 of the License, or (at your option) any
% later version.
%
% This program is distributed in the hope that it will be useful, but WITHOUT
% ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
% FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
% details.
%
% You should have received a copy of the GNU Affero General Public License along
% with this program. If not, see <http://www.gnu.org/licenses/>.
%
% Author: Olivier Boudeville [olivier (dot) boudeville (at) esperide (dot) com]
% Creation date: Tuesday, December 24, 2019.
-module(class_USConfigServer).
-moduledoc """
Class defining the singleton server holding the **configuration information** of
the Universal Server, at the level of US-Common.
""".
-define( class_description,
"Singleton server holding the configuration information of the "
"Universal Server, at the level of US-Common." ).
% Determines what are the direct mother classes of this class (if any):
-define( superclasses, [ class_USServer ] ).
-doc "The PID of a US-Config server.".
-type config_server_pid() :: server_pid().
-doc "The origin of an EPMD setting.".
-type epmd_origin() ::
'as_default' % Just the default EPMD port applying for an US application.
| 'explicit_set'. % An EPMD port was explicitly set in the configuration of
% the US application.
-export_type([ config_server_pid/0, epmd_origin/0 ]).
% Design notes:
%
% This overall, singleton server registers itself globally, so that other
% services can interact with it even if running in separate virtual machines
% (e.g. US-Web).
%
% The base directories for configuration information are, by decreasing order of
% priority:
% - $XDG_CONFIG_HOME (default: "$HOME/.config")
% - $XDG_CONFIG_DIRS (default: "/etc/xdg", directories being separated by ':')
%
% See
% https://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html
% and location-of-ini-config-files-in-linux-unix in
% https://stackoverflow.com/questions/1024114 for more information.
%
%
% All base directories shall be absolute directories.
%
% The configuration directory is defined as the ?app_subdir sub-directory of the
% base directory that contains the ?config_filename files, and all other related
% configuration files.
%
% For example "~/.config/universal-server".
% See also: the start/stop scripts and us-common.sh, which apply mostly the same
% look-up logic.
% The class-specific attributes:
%
% (now, for a better robustness, servers are resolved on the fly, their PIDs are
% not to be stored anymore)
%
-define( class_attributes, [
{ config_base_directory, bin_directory_path(),
"the base directory where all US configuration is to be found" },
% No vm_cookie :: net_utils:cookie() stored, as can be read directly from
% the VM.
% If undefined, the Myriad default (rather than Erlang's one) is expected to
% apply.
%
% (note that this information is tracked yet currently not specifically used
% by the servers themselves - it is actually of interest mostly for the
% US-related management scripts in order that they can
% start/monitor/stop/kill instances)
%
{ epmd_port, option( tcp_port() ),
"the EPMD TCP port presumably in use (as read from the configuration; "
"if any; possibly overridden by the US-* application at hand)" },
{ tcp_port_range, option( tcp_port_range() ),
"the range (if any) of TCP ports to use for out-of-band inter-VM "
"communication (not using the Erlang carrier; for example for "
"send_file)" },
{ execution_context, execution_context(),
"tells whether this server is to run in development or production mode" },
{ log_directory, bin_directory_path(),
"the directory where all VM log files and US-specific higher-level "
"traces will be stored" },
{ us_main_config_filename, option( bin_filename() ),
"the name to the configuration file (if any) regarding US-Main (i.e. "
"for sensors and other elements), to be found in the US configuration "
"directory" },
{ us_web_config_filename, option( bin_filename() ),
"the path to the configuration file (if any) regarding US-Web (i.e. "
"webserver, virtual hosting, etc.), to be found in the US configuration "
"directory" },
{ us_username, system_utils:user_name(),
"the user who runs the Universal server application (note that there "
"may be discrepancies between the one of US and the one of other "
"servers such as US-Web)" },
{ us_groupname, system_utils:group_name(),
"the group that shall be common to all US-related users" },
% Cannot easily be obtained otherwise:
{ registration_name, registration_name(),
"the name under which this configuration server is registered" },
{ app_base_directory, bin_directory_path(),
"the base directory where this US application is located (e.g. where "
"the 'priv' directory can be found)" } ] ).
% Used by the trace_categorize/1 macro to use the right emitter:
-define( trace_emitter_categorization, "US.US-Common.Configuration" ).
% For various defines:
-include("class_USConfigServer.hrl").
% The defaut registration name of the overall US configuration server:
-define( default_us_config_reg_name, us_config_server ).
% The default registration scope of the US server (e.g. its configuration one):
%
% (preferred local, to allow multiple US configuration servers to coexist in a
% distributed way)
%
-define( default_registration_scope, local_only ).
% The name of the main Universal Server configuration file:
-define( us_config_filename, "us.config" ).
% Keys possibly read from the US configuration filename:
-define( vm_cookie_key, vm_cookie ).
-define( epmd_port_key, epmd_port ).
-define( tcp_port_range_key, tcp_port_range ).
-define( execution_context_key, execution_context ).
-define( us_username_key, us_username ).
-define( us_groupname_key, us_groupname ).
-define( us_server_registration_name_key, us_server_registration_name ).
-define( us_config_server_registration_name_key,
us_config_server_registration_name ).
-define( us_app_base_dir_key, us_app_base_dir ).
-define( us_log_dir_key, us_log_dir ).
% The settings of the automated actions that shall be supported by a US-Server
% (see the us_action module):
%
-define( us_actions_key, action_settings ).
-define( us_main_config_filename_key, us_main_config_filename ).
-define( us_web_config_filename_key, us_web_config_filename ).
% All known, licit keys for the US configuration file:
-define( known_config_keys, [ ?vm_cookie_key, ?epmd_port_key,
?tcp_port_range_key, ?execution_context_key,
?us_username_key, ?us_groupname_key,
?us_server_registration_name_key,
?us_config_server_registration_name_key,
?us_app_base_dir_key, ?us_log_dir_key, ?us_actions_key,
?us_main_config_filename_key, ?us_web_config_filename_key] ).
% The last-resort environment variable:
-define( us_app_env_variable, "US_APP_BASE_DIR" ).
-define( default_log_base_dir, "/var/log" ).
% Exported helpers:
-export([ get_us_config_server/1, get_us_config_server/2,
get_us_config_registration_info/2, get_execution_target/0 ]).
% Used by tests:
-doc "A table holding US configuration information.".
-type us_config_table() :: table( atom(), term() ).
-export_type([ us_config_table/0 ]).
% Allows to define WOOPER base variables and methods for that class:
-include_lib("wooper/include/wooper.hrl").
% Allows to use macros for trace sending:
-include_lib("traces/include/class_TraceEmitter.hrl").
% To define get_execution_target/0:
-include_lib("myriad/include/utils/basic_utils.hrl").
% Type shorthands:
-type execution_context() :: basic_utils:execution_context().
-type module_name() :: basic_utils:module_name().
-type three_digit_version() :: basic_utils:three_digit_version().
-type ustring() :: text_utils:ustring().
-type file_name() :: file_utils:file_name().
-type file_path() :: file_utils:file_path().
-type bin_file_path() :: file_utils:bin_file_path().
-type directory_path() :: file_utils:directory_path().
-type bin_directory_path() :: file_utils:bin_directory_path().
-type registration_name() :: naming_utils:registration_name().
-type registration_scope() :: naming_utils:registration_scope().
-type lookup_scope() :: naming_utils:lookup_scope().
-type tcp_port() :: net_utils:tcp_port().
%-type tcp_port_range() :: net_utils:tcp_port_range().
-type server_pid() :: class_USServer:server_pid().
-doc """
Constructs the US configuration server, using the default logic to find its
configuration file.
Note: must be kept in line with the next constructor.
""".
-spec construct( wooper:state() ) -> wooper:state().
construct( State ) ->
% Wanting a better control by resisting to exit messages being received:
erlang:process_flag( trap_exit, true ),
% First the direct mother classes, then this class-specific actions:
SrvState = class_USServer:construct( State,
?trace_categorize("Common configuration Server") ),
?send_info_fmt( SrvState, "Creating the overall US configuration server, "
"on node '~ts'.", [ node() ] ),
BinCfgDir = case get_us_config_directory() of
{ undefined, CfgMsg } ->
?send_error_fmt( SrvState, "Unable to determine the US "
"configuration directory; ~ts", [ CfgMsg ] ),
throw( us_configuration_directory_not_found );
{ BinFoundCfgDir, CfgMsg } ->
?send_notice( SrvState, CfgMsg ),
BinFoundCfgDir
end,
% Final trace sent by:
perform_setup( BinCfgDir, SrvState ).
-doc """
Constructs the US configuration server, using the specified configuration
directory.
Useful for example to create auxiliary universal servers or perform tests.
Note: must be kept in line with the previous constructor.
""".
-spec construct( wooper:state(), directory_path() ) -> wooper:state().
construct( State, ConfigDir ) when is_list( ConfigDir ) ->
% Wanting a better control by resisting to exit messages being received:
erlang:process_flag( trap_exit, true ),
ServerName = text_utils:format( "Configuration server from ~ts",
[ file_utils:get_last_path_element( ConfigDir ) ] ),
% First the direct mother classes, then this class-specific actions:
SrvState = class_USServer:construct( State,
?trace_categorize(ServerName) ),
?send_info_fmt( SrvState, "Creating a US configuration server, "
"using the '~ts' configuration directory for that, "
"on node '~ts'.", [ ConfigDir, node() ] ),
BinCfgDir = text_utils:string_to_binary( ConfigDir ),
% Final trace sent by:
perform_setup( BinCfgDir, SrvState ).
-doc "Overridden destructor.".
-spec destruct( wooper:state() ) -> wooper:state().
destruct( State ) ->
% Automatic unregistering.
?info( "Deleted." ),
State.
% Method section.
-doc """
Notifies this server about the specified US-Main configuration server, and
requests related information from it.
""".
-spec getUSMainRuntimeSettings( wooper:state() ) -> const_request_return(
{ bin_directory_path(), execution_context(),
option( bin_file_path() ) } ).
getUSMainRuntimeSettings( State ) ->
% Storing with 'USMainConfigServerPid = ?getSender()' is not desirable.
wooper:const_return_result( { ?getAttr(config_base_directory),
?getAttr(execution_context), ?getAttr(us_main_config_filename) } ).
-doc """
Notifies this server about the specified US-Web configuration server, and
requests web-related information from it.
""".
-spec getUSWebRuntimeSettings( wooper:state() ) -> const_request_return(
{ bin_directory_path(), execution_context(),
option( bin_file_path() ) } ).
getUSWebRuntimeSettings( State ) ->
wooper:const_return_result( { ?getAttr(config_base_directory),
?getAttr(execution_context), ?getAttr(us_web_config_filename) } ).
-doc """
Notifies this US server of a presumably current EPMD port, so that the right
information is known.
Called by `US-*` applications (e.g. `US-{Main,Web}`) whose configuration file
allows to override any US-level setting.
""".
-spec notifyEPMDPort( wooper:state(), tcp_port(), epmd_origin(), module_name(),
server_pid() ) -> oneway_return().
% Sending notice traces rather than info ones, as we do not want them to be
% deactivated (too inconvenient for troubleshooting):
%
notifyEPMDPort( State, EPMDPort, _Origin=as_default, AppModName, AppSrvPid ) ->
NewEPMDPort = case ?getAttr(epmd_port) of
undefined ->
?notice_fmt( "No US-level EPMD port was set, so the default "
"(port #~B) reported by application '~ts' (~w) will apply.",
[ EPMDPort, AppModName, AppSrvPid ] ),
EPMDPort;
OrigPort ->
?notice_fmt( "A US-level EPMD port was already set (port #~B), "
"so the default (port #~B) reported by application '~ts' "
"(~w) will not apply.",
[ OrigPort, EPMDPort, AppModName, AppSrvPid ] ),
OrigPort
end,
NewState = setAttribute( State, epmd_port, NewEPMDPort ),
wooper:return_state( NewState );
notifyEPMDPort( State, EPMDPort, _Origin=explicit_set, AppModName,
AppSrvPid ) ->
% Just different traces:
case ?getAttr(epmd_port) of
undefined ->
?notice_fmt( "No US-level EPMD port was set, so the port #~B, "
"reported by application '~ts' (~w), will apply.",
[ EPMDPort, AppModName, AppSrvPid ] );
OrigPort ->
?notice_fmt( "The port #~B reported by application '~ts' "
"(~w) will override the current US-level EPMD port (#~B).",
[ EPMDPort, AppModName, AppSrvPid, OrigPort ] )
end,
NewState = setAttribute( State, epmd_port, EPMDPort ),
wooper:return_state( NewState ).
% Static section.
-doc """
Returns the PID of the current, supposedly already-launched, **default** US
configuration server, waiting (up to a few seconds, as all US servers are bound
to be launched mostly simultaneously) if needed.
It is better to obtain the PID of a server each time from the naming service
rather than to resolve and store its PID once for all, as, for an increased
robustness, servers may be restarted (hence any stored PID may not reference a
live process anymore).
""".
-spec get_server_pid () -> static_return( config_server_pid() ).
get_server_pid() ->
% Incorrect, as for example the registration name may have been overidden in
% the configuration file:
%
%CfgPid = class_USServer:resolve_server_pid(
% _RegName=?default_us_config_reg_name,
% _RegScope=?default_registration_scope ),
{ _USCfgFilename, _USCfgRegNameKey, USCfgRegSrvName, USCfgRegLookupScope } =
get_default_settings(),
CfgPid = naming_utils:get_registered_pid_for( USCfgRegSrvName,
USCfgRegLookupScope ),
wooper:return_static( CfgPid ).
% Version-related static methods.
-doc "Returns the version of the US-Common library being used.".
-spec get_us_common_version() -> static_return( three_digit_version() ).
get_us_common_version() ->
wooper:return_static(
basic_utils:parse_version( get_us_common_version_string() ) ).
-doc "Returns the version of the US-Common library being used, as a string.".
-spec get_us_common_version_string() -> static_return( ustring() ).
get_us_common_version_string() ->
% As defined (uniquely) in GNUmakevars.inc:
wooper:return_static( ?us_common_version ).
% For a given us_xxx, these two static methods can just be copied verbatim in
% the class_USxxxCentralServer.erl:
% -doc "Returns the version of the US application being used.".
% -spec get_us_app_version() -> static_return( three_digit_version() ).
% get_us_app_version() ->
% wooper:return_static(
% basic_utils:parse_version( get_us_app_version_string() ) ).
% -doc "Returns the version of the US application being used, as a string.".
% -spec get_us_app_version_string() -> static_return( ustring() ).
% get_us_app_version_string() ->
% % As defined (uniquely) in GNUmakevars.inc:
% wooper:return_static( ?us_app_version ).
-doc """
Returns the main default settings regarding the US configuration server, for its
clients.
""".
-spec get_default_settings() -> static_return( { file_name(),
basic_utils:atom_key(), registration_name(),
naming_utils:lookup_scope() } ).
get_default_settings() ->
% Possibly read from any *.config file specified (e.g. refer to the
% INTERNAL_OPTIONS make variable):
% Specifying the application is essential, as this function is to be called
% from any process of any other application:
%
Application = us_common,
USCfgSrvName = case application:get_env( Application,
us_config_server_registration_name ) of
undefined ->
CfgRegName = ?default_us_config_reg_name,
cond_utils:if_defined( us_common_debug_registration,
trace_bridge:debug_fmt( "US-Common configuration server "
"(default) name: '~ts'.", [ CfgRegName ] ) ),
CfgRegName;
{ ok, CfgRegName } when is_atom( CfgRegName ) ->
case naming_utils:vet_registration_name( CfgRegName ) of
true ->
cond_utils:if_defined( us_common_debug_registration,
trace_bridge:debug_fmt( "US-Common configuration "
"server name (as configured): '~ts'.",
[ CfgRegName ] ) ),
CfgRegName;
false ->
trace_utils:error_fmt( "Invalid registration name (type) "
"read for the US-Common configuration server: '~p'.",
[ CfgRegName ] ),
throw( { invalid_us_config_server_registration_name,
CfgRegName } )
end;
{ ok, InvalidRegName } ->
trace_utils:error_fmt( "Invalid registration name read for the "
"US-Common configuration server: '~p'.", [ InvalidRegName ] ),
throw( { invalid_us_config_server_registration_name,
InvalidRegName } )
end,
USCfgSrvScope = case application:get_env( Application,
us_config_server_registration_scope ) of
undefined ->
CfgRegScope = ?default_registration_scope,
cond_utils:if_defined( us_common_debug_registration,
trace_bridge:debug_fmt( "US-Common configuration server "
"(default) scope: '~ts'.", [ CfgRegScope ] ) ),
CfgRegScope;
{ ok, CfgRegScope } when is_atom( CfgRegScope ) ->
case naming_utils:vet_registration_scope( CfgRegScope ) of
true ->
cond_utils:if_defined( us_common_debug_registration,
trace_bridge:debug_fmt( "US-Common configuration "
"server scope (as configured): '~ts'.",
[ CfgRegScope ] ) ),
CfgRegScope;
false ->
trace_utils:error_fmt( "Invalid registration scope (type) "
"read for the US-Common configuration server: '~p'.",
[ CfgRegScope ] ),
throw( { invalid_us_config_server_registration_scope,
CfgRegScope } )
end;
{ ok, InvalidRegScope } ->
trace_utils:error_fmt( "Invalid registration scope read for the "
"US-Common configuration server: '~p'.", [ InvalidRegScope ] ),
throw( { invalid_us_config_server_registration_scope,
InvalidRegScope } )
end,
wooper:return_static( { ?us_config_filename,
?us_config_server_registration_name_key, USCfgSrvName,
naming_utils:registration_to_lookup_scope( USCfgSrvScope ) } ).
-doc """
Returns any found configuration directory and a corresponding trace message.
This is a static method (no state involved), so that both this kind of servers
and others (e.g. web configuration ones), and even tests, can use the same,
factored, logic.
""".
-spec get_us_config_directory() ->
static_return( { option( bin_directory_path() ), ustring() } ).
get_us_config_directory() ->
HomeDir = system_utils:get_user_home_directory(),
% See design notes about directory selection.
FirstEnvVar = "XDG_CONFIG_HOME",
% We prefer devising a single trace message rather than too many:
{ FirstPath, FirstMsg } =
case system_utils:get_environment_variable( FirstEnvVar ) of
false ->
CfgHomeDefaultPath = file_utils:join( HomeDir, ".config" ),
CfgHomeMsg = text_utils:format( "no '~ts' environment variable "
"was defined, defaulting to '~ts'",
[ FirstEnvVar, CfgHomeDefaultPath ] ),
{ CfgHomeDefaultPath, CfgHomeMsg };
Path ->
{ Path, text_utils:format( "path '~ts' was obtained from "
"environment variable '~ts'", [ Path, FirstEnvVar ] ) }
end,
SecondEnvVar = "XDG_CONFIG_DIRS",
{ ListedPathsAsStrings, SecondMsg } =
case system_utils:get_environment_variable( SecondEnvVar ) of
false ->
% A single one here:
DefaultCfgDirs = "/etc/xdg",
CfgDirsMsg = text_utils:format(
"no '~ts' environment variable defined, defaulting to '~ts'",
[ SecondEnvVar, DefaultCfgDirs ] ),
{ DefaultCfgDirs, CfgDirsMsg };
Paths ->
{ Paths, text_utils:format( "paths '~ts' were obtained from "
"environment variable '~ts'", [ Paths, SecondEnvVar ] ) }
end,
ListedPaths = text_utils:split( ListedPathsAsStrings, _Sep=$: ),
AllBasePaths = [ FirstPath | ListedPaths ],
CfgSuffix = file_utils:join( ?app_subdir, ?us_config_filename ),
BaseMsg = text_utils:format( "Searched for the Universal Server "
"configuration directory, based on the '~ts' suffix, "
"knowing that: ~ts~nConfiguration directory ", [ CfgSuffix,
text_utils:strings_to_string( [ FirstMsg, SecondMsg ] ) ] ),
ResPair = find_file_in( AllBasePaths, CfgSuffix, BaseMsg, _Msgs=[] ),
wooper:return_static( ResPair ).
-doc """
Returns the US-Common configuration table, as read from the main US
configuration file, together with the path of this file.
Static method, to be available from external code such as clients or tests.
""".
-spec get_configuration_table( bin_directory_path() ) ->
static_return( diagnosed_fallible( { us_config_table(), file_path() } ) ).
get_configuration_table( BinCfgDir ) ->
CfgFilePath = file_utils:join( BinCfgDir, ?us_config_filename ),
% Should, by design, never fail (already checked):
Res = case file_utils:is_existing_file_or_link( CfgFilePath ) of
true ->
%trace_bridge:info_fmt( "Reading the Universal Server "
% "configuration "from '~ts'.", [ CfgFilePath ] ),
% Ensures as well that all top-level terms are pairs indeed:
try table:new_from_unique_entries(
file_utils:read_etf_file( CfgFilePath ) ) of
ConfigTable ->
{ ok, { ConfigTable, CfgFilePath } }
catch ExClass:ExPattern ->
ErrorMsg = text_utils:format( "The processing of the "
"US-Common configuration file '~ts' failed (~p):~n ~p.",
[ CfgFilePath, ExClass, ExPattern ] ),
{ error, { { us_config_reading_failed, CfgFilePath },
ErrorMsg } }
end;
false ->
ErrorMsg = text_utils:format( "Unable to find the US configuration "
"file from '~ts', searched as '~ts'.",
[ BinCfgDir, CfgFilePath ] ),
{ error, { { us_config_file_not_found, CfgFilePath }, ErrorMsg } }
end,
wooper:return_static( Res ).
-doc """
Returns the name of the expected US-Main configuration file.
Static method, to be available from outside, typically for tests.
""".
-spec get_us_main_configuration_filename( us_config_table() ) ->
static_return( diagnosed_fallible( option( file_name() ) ) ).
get_us_main_configuration_filename( ConfigTable ) ->
CfgKey = ?us_main_config_filename_key,
Res = case table:lookup_entry( CfgKey, ConfigTable ) of
key_not_found ->
{ ok, undefined };
{ value, USMainFilename } when is_list( USMainFilename ) ->
{ ok, USMainFilename };
{ value, InvalidUSMainFilename } ->
ErrorTuploid = { invalid_us_main_config_filename,
InvalidUSMainFilename, CfgKey },
ErrorMsg = text_utils:format( "Obtained invalid user-configured "
"configuration filename for mainservers and virtual hosting: "
" '~p', for key '~ts'.", [ InvalidUSMainFilename, CfgKey ] ),
{ error, { ErrorTuploid, ErrorMsg } }
end,
wooper:return_static( Res ).
-doc """
Returns the name of the expected US-Web configuration file.
Static method, to be available from outside, typically for tests.
""".
-spec get_us_web_configuration_filename( us_config_table() ) ->
static_return( diagnosed_fallible( option( file_name() ) ) ).
get_us_web_configuration_filename( ConfigTable ) ->
CfgKey = ?us_web_config_filename_key,
Res = case table:lookup_entry( CfgKey, ConfigTable ) of
key_not_found ->
{ ok, undefined };
{ value, USWebFilename } when is_list( USWebFilename ) ->
{ ok, USWebFilename };
{ value, InvalidUSWebFilename } ->
ErrorTuploid =
{ invalid_us_web_config_filename, InvalidUSWebFilename,
CfgKey },
ErrorMsg = text_utils:format( "Obtained invalid user-configured "
"configuration filename for webservers and virtual hosting: "
" '~p', for key '~ts'.", [ InvalidUSWebFilename, CfgKey ] ),
{ error, { ErrorTuploid, ErrorMsg } }
end,
wooper:return_static( Res ).
% Helper section.
% (helper)
find_file_in( _AllBasePaths=[], CfgSuffix, BaseMsg, Msgs ) ->
% Configuration directory not found:
FullMsg = BaseMsg ++ text_utils:format( "could not be determined, "
"short of locating a relevant configuration file ('~ts') for that: ",
[ CfgSuffix ] )
++ text_utils:strings_to_enumerated_string( lists:reverse( Msgs ) ),
{ undefined, FullMsg };
find_file_in( _AllBasePaths=[ Path | T ], CfgSuffix, BaseMsg, Msgs ) ->
CfgFilePath =
file_utils:normalise_path( file_utils:join( Path, CfgSuffix ) ),
case file_utils:is_existing_file_or_link( CfgFilePath ) of
true ->
CfgDir = filename:dirname( CfgFilePath ),
FullMsg = text_utils:format( BaseMsg ++
"found as '~ts', as containing '~ts'", [ CfgDir, CfgFilePath ] )
++ case Msgs of
[] ->
"";
_ ->
", after following look-up: "
++ text_utils:strings_to_enumerated_string(
lists:reverse( Msgs ) )
end,
{ text_utils:string_to_binary( CfgDir ), FullMsg };
false ->
NewMsgs = [ text_utils:format( "not found as '~ts'",
[ CfgFilePath ] ) | Msgs ],
find_file_in( T, CfgSuffix, BaseMsg, NewMsgs )
end.
-doc "Performs set-up actions common to all constructors.".
-spec perform_setup( bin_directory_path(), wooper:state() ) ->
wooper:state().
perform_setup( BinCfgDir, State ) ->
LoadState = load_configuration( BinCfgDir, State ),
ReadyState = setAttribute( LoadState, config_base_directory, BinCfgDir ),
% Enforce security in all cases ("chmod 700"); if it fails here, the
% combined path/user configuration must be incorrect; however this server
% may be run from another US application (typically US-Web), possibly
% running as a user of their own, different from the main US user (yet
% supposedly in the same US group).
%
% So:
CurrentUserId = system_utils:get_user_id(),
LogDir = getAttribute( ReadyState, log_directory ),
case file_utils:get_owner_of( LogDir ) of
CurrentUserId ->
file_utils:change_permissions( LogDir,
[ owner_read, owner_write, owner_execute,
group_read, group_write, group_execute ] );
% Not owned, do nothing:
_OtherId ->
ok
end,
?notice_fmt( "Constructed: ~ts.", [ to_string( ReadyState ) ] ),
% We used to rename directly here the trace file; however, as it might be
% updated in turn by the actual US-related framework (e.g. US-Main, US-Web),
% specifying at the US-Common level (in the us.config) an intermediate trace
% file had little interest, so it was done. Yet then the default location
% applied (/var/log/universal-server), which required specific permissions
% (whereas for example tests cannot rely on them). So we disabled this
% intermediate renaming, as anyway US-Common is hardly autonomous.
% Done rather late on purpose, so that the existence of that file can be
% seen as a sign that the initialisation went well (used by
% start-us-web-{native-build,release}.sh).
%
%NewBinTraceFilePath = file_utils:bin_join( LogDir, "us_common.traces" ),
% Already a trace emitter:
%?debug_fmt( "Requesting the renaming of trace file to '~ts'.",
% [ NewBinTraceFilePath ] ),
%?getAttr(trace_aggregator_pid ) ! { renameTraceFile, NewBinTraceFilePath },
ReadyState.
-doc """
Returns the Universal Server configuration table (that is the one of US, not
specifically of any specialised US-*), and directly applies some of the read
settings.
""".
-spec load_configuration( bin_directory_path(), wooper:state() ) ->
wooper:state().
load_configuration( BinCfgDir, State ) ->
{ ConfigTable, ConfigFilePath } =
case get_configuration_table( BinCfgDir ) of
{ ok, P } ->
P;
{ error, P={ { us_config_reading_failed, CfgFileP }, ErrorMsg } } ->
?error_fmt( "The overall US configuration file ('~ts') "
"could not be read: ~p.", [ CfgFileP, ErrorMsg ] ),
throw( P );
{ error, P={ us_config_file_not_found, CfgFileP } } ->
?error_fmt( "The overall US configuration file ('~ts') "
"could not be found.", [ CfgFileP ] ),
% Must have disappeared then:
throw( P )
end,
?info_fmt( "Read US configuration from '~ts': ~ts",
[ ConfigFilePath, table:to_string( ConfigTable ) ] ),
% We follow the usual order in the configuration file:
% Const:
manage_vm_cookie( ConfigTable, State ),
EpmdState = manage_epmd_port( ConfigTable, State ),
TCPState = manage_tcp_port_range( ConfigTable, EpmdState ),
ExecState = manage_execution_context( ConfigTable, TCPState ),
UserState = manage_os_user_group( ConfigTable, ExecState ),
RegState = manage_registration_names( ConfigTable, UserState ),
DirState = manage_app_base_directory( ConfigTable, RegState ),
LogState = manage_log_directory( ConfigTable, DirState ),
MainState = manage_us_main_config( ConfigTable, LogState ),
WebState = manage_us_web_config( ConfigTable, MainState ),
% Detect any extraneous, unexpected entry:
LicitKeys = ?known_config_keys,
case list_utils:difference( table:keys( ConfigTable ), LicitKeys ) of
[] ->
WebState;
UnexpectedKeys ->
?error_fmt( "Unknown key(s) in '~ts': ~ts~nLicit keys: ~ts",
[ ConfigFilePath, text_utils:terms_to_string( UnexpectedKeys ),
text_utils:terms_to_string( LicitKeys ) ] ),
throw( { invalid_configuration_keys, UnexpectedKeys,
ConfigFilePath } )
end.
-doc "Manages any user-configured VM cookie.".
-spec manage_vm_cookie( us_config_table(), wooper:state() ) -> void().
manage_vm_cookie( ConfigTable, State ) ->
case table:lookup_entry( ?vm_cookie_key, ConfigTable ) of
key_not_found ->
CurrentCookie = net_utils:get_cookie(),
?info_fmt( "No user-configured cookie, sticking to original one, "
"'~ts'.", [ CurrentCookie ] );