Skip to content

add ability to pass in all config values as environment variables. - #1385

Merged
berkerpeksag merged 4 commits into
benoitc:masterfrom
hramezani:issues_1360
Jan 8, 2017
Merged

berkerpeksag merged 4 commits into
benoitc:masterfrom
hramezani:issues_1360

Conversation

@hramezani

Copy link
Copy Markdown
Contributor

add environment variables that starts with GUNICORN_ like GUNICORN_WORKERS as settings.
skip variables that does not start with GUNICORN_, and also skip variable that not in settings like GUNICORN_FOO

@tilgovi tilgovi left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Overall, I like the idea, but interested to hear others' thoughts.

Comment thread gunicorn/config.py Outdated
for k,v in self.env_orig.items():
if k.startswith('GUNICORN_'):
try:
name = k.split('GUNICORN_', 1)[1].lower()

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't think this can ever fail if k.startswith('GUNICORN_').

Comment thread gunicorn/app/base.py Outdated

# Load up environment configuration
env_vars = self.cfg.parse_env_vars()
for k,v in env_vars.items():

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

small linting nit here, space between ,v.

Comment thread gunicorn/config.py Outdated

def parse_env_vars(self):
env_vars = {}
for k,v in self.env_orig.items():

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same nitpick here about spacing.

Comment thread gunicorn/config.py Outdated
name = k.split('GUNICORN_', 1)[1].lower()
except:
continue
if not name or name not in self.settings:

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

name not in self.settings should be sufficient, no?

@hramezani

Copy link
Copy Markdown
Contributor Author

@tilgovi thanks, i fix problems.

@berkerpeksag

Copy link
Copy Markdown
Collaborator

I also like the idea, thanks! I haven't reviewed the code yet, but we should document all GUNICORN_ env variables before merging this.

Comment thread tests/test_config.py Outdated
os.environ["GUNICORN_FOO"] = "BAR"
with AltArgs():
app = NoConfigApp()
try:

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This can be written as:

with pytest.raises(AttributeError):
    app.cfg.too

Comment thread tests/test_config.py Outdated
assert c.logger_class == MyLogger

def test_load_enviroment_variables_config():
os.environ["GUNICORN_WORKERS"] = "4"

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We need to unset these environment variables. I don't know what's the best practice to do this in pytest though (I'd suggest writing a context manager if we were using unittest -- perhaps you need a fixture?)

@hramezani

hramezani commented Dec 22, 2016 •

Copy link
Copy Markdown
Contributor Author

@berkerpeksag Thanks,
this PR accept KNOWN_SETTINGS in this format GUNICORN_setting_name. known setting names are in Settings. for example GUNICORN_bind, GUNICORN_worker_class, ...
Is this a good idea that a write a paragraph in settings page and mention that we can change all of settings in this page by setting environment variables with abov format?

@benoitc

benoitc commented Dec 22, 2016

Copy link
Copy Markdown
Owner

What is the use case for this change? Can you elaborate about it?

@hramezani

hramezani commented Dec 23, 2016 •

Copy link
Copy Markdown
Contributor Author

@benoitc i saw Ability to pass in all config values as environment variables in issue list and @tilgovi commented:

I don't see any reason not to support it. Pull requests welcome.

finally i decide to do this.

with this change we can change gunicorn settings with environment variables.

@tilgovi

tilgovi commented Dec 23, 2016

Copy link
Copy Markdown
Collaborator

There are times, especially in these days of containerization, where it is much easier to change an environment variable than to change the command line invocation or a configuration file.

@tilgovi

tilgovi commented Dec 23, 2016

Copy link
Copy Markdown
Collaborator

We can do this in a separate PR, but I'm wondering if there is any reason to clear these keys from the environment when we spawn workers. I'm just wondering if any settings might contain information that we should try to prevent from leaking to workers and possibly then into a response.

@hramezani

Copy link
Copy Markdown
Contributor Author

@benoitc @tilgovi
Is there anything that I do?

@berkerpeksag

Copy link
Copy Markdown
Collaborator

Is this a good idea that a write a paragraph in settings page and mention that we can change all of settings in this page by setting environment variables with abov format?

It would be nice to add something like "Environment variable: GUNICORN_FOO" (or just plain GUNICORN_FOO) to every setting. For example, let's take a look at bind: http://docs.gunicorn.org/en/stable/settings.html#bind With "-b ADDRESS, --bind ADDRESS", we know that we can pass -b or --bind to gunicorn. We can document the env variable in the same way:

bind

* -b ADDRESS, --bind ADDRESS (CLI)
* GUNICORN_BIND (env variable)
* ['127.0.0.1:8000'] (default value)

@hramezani

Copy link
Copy Markdown
Contributor Author

@berkerpeksag thanks for reply, I add documents.

@berkerpeksag

Copy link
Copy Markdown
Collaborator

Thanks, docs/source/settings.rst is automatically generated. I prefer modifying https://github.com/benoitc/gunicorn/blob/master/docs/gunicorn_ext.py#L39 instead of manually adding these names. You can then run make -C docs html to update settings.rst (note that make html will make some unrelated changes in settings.rst -- please discard them before committing your changes)

Comment thread docs/source/settings.rst Outdated
~~~~~~

* ``-c CONFIG, --config CONFIG``
* ``GUNICORN_CONFIG (env variable)``

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

"(env variable)" can be removed. I used it as an annotation in my example :)

@hramezani

hramezani commented Dec 26, 2016 •

Copy link
Copy Markdown
Contributor Author

@berkerpeksag Thanks, whta is your opinion about adding a property like cli with name env_var and type boolean to Setting class? this can be used for following purpose:

  1. add variables to config if this propery = True.
  2. disable this functionality for some setting.
  3. generate document based on this property.

@benoitc

benoitc commented Dec 27, 2016

Copy link
Copy Markdown
Owner

I'm not sure i'm comfortable with this change, it introduces an extra level of complexity in the configuration, having to document the variables to use is a sign. What about instead having a simple GUNICORN_CMD_ARGS (or whatever its name) where you pass the command line arguments that could be parsed like usual? Ie:

GUNICORN_CMD_ARGS ="--bind=127.0.0.1 --workers=3" ...

So we wouldn't have to document each changes and could reuse the current code to handle it. Thoughts?

@hramezani
hramezani force-pushed the issues_1360 branch 2 times, most recently from 45fc933 to e6bab60 Compare December 27, 2016 23:35
@hramezani

Copy link
Copy Markdown
Contributor Author

@benoitc Thanks, I change PR as your previous comment.

@decal

decal commented Jan 6, 2017

Copy link
Copy Markdown

Looks even better than the Apache 2.4 envvars support..

@benoitc
benoitc self-requested a review January 8, 2017 00:43

@berkerpeksag berkerpeksag left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The PR looks pretty good to me, thanks! Just left some trivial comments.

We also need to document the new env variable.

Comment thread gunicorn/config.py Outdated
self.settings[name].set(value)

def get_gunicorn_env_var(self):
env_vars = []

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Unless I'm missing something obvious, env_vars is not needed here:

if 'GUNICORN_CMD_ARGS' in self.env_orig:
    return self.env_orig['GUNICORN_CMD_ARGS'].split()
return []

Comment thread gunicorn/config.py Outdated
def get_gunicorn_env_var(self):
env_vars = []
if 'GUNICORN_CMD_ARGS' in self.env_orig:
env_vars = self.env_orig['GUNICORN_CMD_ARGS'].split()

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Did you consider using shlex.split() here?

Comment thread gunicorn/config.py Outdated
raise AttributeError("No configuration setting for: %s" % name)
self.settings[name].set(value)

def get_gunicorn_env_var(self):

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not a native English speaker, but perhaps we can rename it to something like get_cmd_args_from_env? get_gunicorn_env_var sounds too generic to me. Ping @tilgovi :)

Comment thread gunicorn/app/base.py Outdated
env_vars = self.cfg.get_gunicorn_env_var()
if env_vars:
env_args = parser.parse_args(env_vars)
for k, v in env_args.__dict__.items():

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Wouldn't vars(env_args).items() be better?

Comment thread tests/test_config.py Outdated
app = NoConfigApp()
assert app.cfg.workers == 4

def test_cli_overrides_enviroment_variables_module():

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Tests are look great, thank you! :) Could you also add a test that passes an invalid config option (e.g os.environ["GUNICORN_CMD_ARGS"] = "--monty-python"?

@hramezani

Copy link
Copy Markdown
Contributor Author

@berkerpeksag Thanks, i fix all your comments.

@berkerpeksag

Copy link
Copy Markdown
Collaborator

Looks great, thanks! I think you forgot to address two of my previous comments:

  • We need to cleanup the env variables we set in tests. We can do this in the following way:

    def test_cli_overrides_enviroment_variables_module(monkeypatch):
        monkeypatch.setenv("GUNICORN_CMD_ARGS", "--workers=4")
        # test code
  • GUNICORN_CMD_ARGS needs to be documented. We can mention it in docs/source/run.rst and docs/gunicorn_ext.py. We can leave this to a separate PR if you want.

Comment thread tests/test_config.py Outdated
os.environ["GUNICORN_CMD_ARGS"] = "--foo=bar"
with AltArgs():
with pytest.raises(SystemExit):
app = NoConfigApp()

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Style nit: No need to set NoConfigApp() to app. Just call NoConfigApp().

Comment thread tests/test_config.py
c.set('statsd_host', 'localhost:12345')
# still uses custom logger over statsd
assert c.logger_class == MyLogger

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Style nit: Please add two empty lines after each tests.

@hramezani

hramezani commented Jan 8, 2017 •

Copy link
Copy Markdown
Contributor Author

@berkerpeksag thanks!, comments fixed.
can you help me for documentation? is this ok to add a note or paragraph in Settings and Running Gunicorn page, and describe that we can use all command line config in env vars in bellow format?
GUNICORN_CMD_ARGS ="--bind=127.0.0.1 --workers=3" ...

@berkerpeksag
berkerpeksag merged commit 3f9eace into benoitc:master Jan 8, 2017
@berkerpeksag

Copy link
Copy Markdown
Collaborator

Thanks for the PR, @hramezani! :)

is this ok to add a note or paragraph in Settings and Running Gunicorn page, and describe that we can use all command line config in env vars in bellow format?
GUNICORN_CMD_ARGS ="--bind=127.0.0.1 --workers=3"

Yes, that sounds good to me. Let's open another pull request for documentation.

@hramezani

Copy link
Copy Markdown
Contributor Author

@berkerpeksag thanks very much for your help. i open another pull request for documentation soon.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants