Managing configuration in Erlang application - configuration

I need to distribute some sort of static configuration through my application. What is the best practice to do that?
I see three options:
Call application:get_env directly whenever a module requires to get configuration value.
Plus: simpler than other options.
Minus: how to test such modules without bringing the whole application thing up?
Minus: how to start certain module with different configuration (if required)?
Pass the configuration (retrieved from application:get_env), to application modules during start-up.
Plus: modules are easier to test, you can start them with different configuration.
Minus: lot of boilerplate code. Changing the configuration format requires fixing several places.
Hold the configuration inside separate configuration process.
Plus: more-or-less type-safe approch. Easier to track where certain parameter is used and change those places.
Minus: need to bring up configuration process before running the modules.
Minus: how to start certain module with different configuration (if required)?

Another approach is to transform your configuration data into an Erlang source module that makes the configuration data available through exports. Then you can change the configuration at any time in a running system by simply loading a new version of the configuration module.

For static configuration in my own projects, I like option (1). I'll show you the steps I take to access a configuration parameter called max_widgets in an application called factory.
First, we'll create a module called factory_env which contains the following:
-define(APPLICATION, factory).
get_env(Key, Default) ->
case application:get_env(?APPLICATION, Key) of
{ok, Value} -> Value;
undefined -> Default
end.
set_env(Key, Value) ->
application:set_env(?APPLICATION, Key, Value).
Next, in a module that needs to read max_widgets we'll define a macro like the following:
-define(MAX_WIDGETS, factory_env:get_env(max_widgets, 1000)).
There are a few nice things about this approach:
Because we used application:set_env/3 and application:get_env/2, we don't actually need to start the factory application in order to have our tests pass.
max_widgets gets a default value, so our code will still work even if the parameter isn't defined.
A second module could use a different default value for max_widgets.
Finally, when we are ready to deploy, we'll put a sys.config file in our priv directory and load it with -config priv/sys.config during startup. This allows us to change configuration parameters on a per-node basis if desired. This cleanly separates configuration from code - e.g. we don't need to make another commit in order to change max_widgets to 500.

You could use a process (a gen_server maybe?) to store your configuration parameters in its state. It should expose a get/set interface. If a value hasn't been explicitly set, it should retrieve a default value.
-export([get/1, set/2]).
...
get(Param) ->
gen_server:call(?MODULE, {get, Param}).
...
handle_call({get, Param}, _From, State) ->
case lookup(Param, State#state.params) of
undefined ->
application:get_env(...);
Value ->
{ok, Value}
end.
...
You could then easily mockup this module in your tests. It will also be easy to update the process with some new configuration at run-time.
You could use pattern matching and tuples to associate different configuration parameters to different modules:
set({ModuleName, ParamName}, Value) ->
...
get({ModuleName, ParamName}) ->
...
Put the process under a supervision tree, so it's started before all the other processes which are going to need the configuration.
Oh, I'm glad nobody suggested parametrized modules so far :)

I'd do option 1 for static configuration. You can always test by setting options via application:set_env/3,4. The reason you want to do this is that your tests of the application will need to run the whole application anyway at some time. And the ability to set test-specific configuration at that point is really neat.
The application controller runs by default, so it is not a problem that you need to go the application-way (you need to do that anyway too!)
Finally, if a process needs specific configuration, say so in the configuration data! You can store any Erlang-term, in particular, you can store a term which makes you able to override configuration parameters for a specific node.
For dynamic configuration, you are probably better off by using a gen_server or using the newest gproc features that lets you store such dynamic configuration.

I've also seen people use a .hrl (erlang header file) where all the configuration is defined and include it at the start of any file that needs configuration.
It makes for very concise configuration lookups, and you get configuration of arbitrary complexity.
I believe you can also reload configuration at runtime by performing hot code reloading of the module. The disadvantage is that if you use configuration in several modules and reload only one of them, only that one module will get its configuration updated.
However, I haven't actually checked if it works like that, and I couldn't find definitive documentation on how .hrl and hot code reloading interact, so make sure to double-check this before you actually use it.

Related

How to get the currently loaded configuration in a Symfony application?

I changed the config (config.yml) and want to check, if it worked.
How can I see the actually loaded configurations? Can I access them from a Controller?
When your app first time starts, Sf uses a HttpKernel component to manage the loading of the service container configuration from the application and bundles and also handles the compilation and caching.
After the compilation process has loaded the services from the configuration, extensions and the compiler passes, it is dumped so that the cache can be used next time. The dumped version is then used during subsequent requests as it is more efficient.
More info at: http://symfony.com/doc/current/components/dependency_injection/workflow.html
If you dump $this->container in your controller, you will see all the parameters inside private property parameters, including parameters defined in the parameters.yml file and in the config.yml
Let's say that you want to know what is current value of the parameter locale - you can write this
$this->container->getParameter('locale')
Also, all those parameters are dumped into sf_root/var/cache/your_env/appDevDebugProjectContainer.xml

Make: Redo some targets if configuration changes

I want to reexecute some targets when the configuration changes.
Consider this example:
I have a configuration variable (that is either read from environment variables or a config.local file):
CONF:=...
Based on this variable CONF, I assemble a header file conf.hpp like this:
conf.hpp:
buildConfHeader $(CONF)
Now, of course, I want to rebuild this header if the configuration variable changes, because otherwise the header would not reflect the new configuration. But how can I track this with make? The configuration variable is not tied to a file, as it may be read from environment variables.
Is there any way to achieve this?
I have figured it out. Hopefully this will help anyone having the same problem:
I build a file name from the configuration itself, so if we have
CONF:=a b c d e
then I create a configuration identifier by replacing the spaces with underscores, i.e.,
null:=
space:= $(null) #
CONFID:= $(subst $(space),_,$(strip $(CONF))).conf
which will result in CONFID=a_b_c_d_e.conf
Now, I use this $(CONFID) as dependency for the conf.hpp target. In addition, I add a rule for $(CONFID) to delete old .conf files and create a new one:
$(CONFID):
rm -f *.conf #remove old .conf files, -f so no error when no .conf files are found
touch $(CONFID) #create a new file with the right name
conf.hpp: $(CONFID)
buildConfHeader $(CONF)
Now everything works fine. The file with name $(CONFID) tracks the configuration used to build the current conf.hpp. If the configuration changes, then $(CONFID) will point to a non-existant .conf file. Thus, the first rule will be executed, the old conf will be deleted and a new one will be created. The header will be updated. Exactly what I want :)
There is no way for make to know what to rebuild if the configuration changed via a macro or environment variable.
You can, however, use a target that simply updates the timestamp of conf.hpp, which will force it to always be rebuilt:
conf.hpp: confupdate
buildConfHeader $(CONF)
confupdate:
#touch conf.hpp
However, as I said, conf.hpp will always be built, meaning any targets that depend upon it will need rebuilt as well. A much more friendly solution is to generate the makefile itself. CMake or the GNU Autotools are good for this, except you sacrifice a lot of control over the makefile. You could also use a build script that creates the makefile, but I'd advise against this since there exist tools that will allow you to build one much more easily.

How do I assign Sublime key mappings for commands in the sidebar context menu?

When browsing files in the Sublime sidebar, I would like to quickly access the commands available in the context menu via shortcuts. E.g. Delete file, rename file/folder, new file/folder.
(FYI: super+N is not an ideal solution for creating new files - it isn't context aware and will usually choose an inappropriate default location).
You can enable command logging by inserting the following into the console sublime.log_commands(True). This will give you the commands and arguments being executed. You can then create a key binding with the appropriate command. My guess is the commands will use some sort of path, so you may need to write a small plugin to inject the correct paths for the various commands.
For new file creation specifically, you may want to take a look at AdvancedNewFile. Disclaimer - I'm the current maintainer of the plugin. I've tried to make it a more flexible than it originally was, with regards to specifying where to create the file. Though if you do decide to use it and have feature request, feel free to create an issue about it.

SSIS Deployment: Dev Stage Live AppSettings

The main problem is: How do i incorporate an appSettings.Config file with a particular build(dev, stage, live)? My appSettings.Config changes the conx strings for data sources based on which server the package is being deployed to. I am able to go through Package configurations and add my appSettings.Config, however, I can only specifically add one file dev, stage, or live. What i need to do is be able to build the solution and based on teh build type incorporate the dev/stage/live appsettings. How could I do this?
You could include all of the configuration files in the install and then just point to the correct one through an environment variable. I know you're wanting to switch the configuration file based on the solution build configuration, but you'll be looking at a complex solution when a simpler alternative exists.
Its quite straight-forward to add registry information during the package install that will set the machine's environment variable under the key:
HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment\MyVariable
...to the path of the .dtsConfig for the current environment.

Monitor changes to settings in app.config

When I use typesafe application settings, I have something like this in my app.exe.config file:
<setting name="IntervalTimeout" serializeAs="String">
<value>10</value>
</setting>
The Settings.Designer.vb does something like this:
<Global.System.Configuration.ApplicationScopedSettingAttribute(), _
Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
Global.System.Configuration.DefaultSettingValueAttribute("10")> _
Public ReadOnly Property IntervalTimeout() As Integer
Get
Return CType(Me("IntervalTimeout"),Integer)
End Get
End Property
And I can access the setting with something like this:
Settings.IntervalTimeout
What is the best practice for monitoring changes to this setting from the outside. I.e. the setting is used by an application that is running as a service and when somebody opens the corresponsing config file and changes the IntervalTimeout to let's say 30, the service application gets notified and does whatever I tell it to do to reconfigure itself.
Usually, I would have used something like this during initialization:
AddHandler Settings.PropertyChanged, New PropertyChangedEventHandler(AddressOf Settings_PropertyChanged)
And then implement an Eventhandler that checks the name of the property that has changed and reacts appropriately.
However, the PropertyChanged event only gets fired when the Set method is called on a property, not when somebody changes the data directly within the file. Of course this would have been heaven, but understandable that this is not the way it works. ;-)
Most probably, I'd implement a filesystemwatcher to monitor changes to the file and then reload the configuration, find out what changed and then do whatever is necessary to reflect those changes.
Does anyone know a better way? Or even a supported one?
ASP.NET monitors the Web.config file for changes. It does this using the System.Web.FileChangesMonitor class (which is marked internal and sealed), which uses another internal class System.Web.FileMonitor. Have a look at them in reflector. It might be too complex for your problem, but I'd certainly look into it if I had a similar requirement.
This looks pretty complex. Bear in mind ASP.NET shuts down the old application and starts a new one once it detects a change. App.config wasn't architectured to detect for changes while the application is running. Perhaps reconsider why you need this?
An easier approach is to restart the service once you've made the change.