summaryrefslogtreecommitdiff
path: root/openstack_dashboard/management/commands/make_web_conf.py
blob: 38d1de887c74d4c514cd07bce39d8b05b803793a (plain)
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
# -*- coding: utf-8 -*-
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.

from __future__ import print_function

from optparse import make_option  # noqa
import os
import socket
import sys
import warnings

from django.conf import settings
from django.core.management.base import BaseCommand  # noqa
from django.template import Context, Template  # noqa

# Suppress DeprecationWarnings which clutter the output to the point of
# rendering it unreadable.
warnings.simplefilter('ignore')

cmd_name = __name__.split('.')[-1]

CURDIR = os.path.realpath(os.path.dirname(__file__))
PROJECT_PATH = os.path.realpath(os.path.join(CURDIR, '../..'))
STATIC_PATH = os.path.realpath(os.path.join(PROJECT_PATH, '../static'))

# Known apache log directory locations
APACHE_LOG_DIRS = (
    '/var/log/httpd',  # RHEL / Red Hat / CentOS / Fedora Linux
    '/var/log/apache2',  # Debian / Ubuntu Linux
)
# Default log directory
DEFAULT_LOG_DIR = '/var/log'


def _getattr(obj, name, default):
    """Like getattr but return `default` if None or False.

    By default, getattr(obj, name, default) returns default only if
    attr does not exist, here, we return `default` even if attr evaluates to
    None or False.
    """
    value = getattr(obj, name, default)
    if value:
        return value
    else:
        return default


context = Context({
    'DJANGO_SETTINGS_MODULE': os.environ['DJANGO_SETTINGS_MODULE'],
    'HOSTNAME': socket.getfqdn(),
    'PROJECT_PATH': os.path.realpath(
        _getattr(settings, 'ROOT_PATH', PROJECT_PATH)),
    'STATIC_PATH': os.path.realpath(
        _getattr(settings, 'STATIC_ROOT', STATIC_PATH)),
    'SSLCERT': '/etc/pki/tls/certs/ca.crt',
    'SSLKEY': '/etc/pki/tls/private/ca.key',
    'CACERT': None,
})

context['PROJECT_ROOT'] = os.path.dirname(context['PROJECT_PATH'])
context['PROJECT_DIR_NAME'] = os.path.basename(
    context['PROJECT_PATH'].split(context['PROJECT_ROOT'])[1])
context['PROJECT_NAME'] = context['PROJECT_DIR_NAME']

context['WSGI_FILE'] = os.path.join(
    context['PROJECT_PATH'], 'wsgi/horizon.wsgi')

VHOSTNAME = context['HOSTNAME'].split('.')
VHOSTNAME[0] = context['PROJECT_NAME']
context['VHOSTNAME'] = '.'.join(VHOSTNAME)

if len(VHOSTNAME) > 1:
    context['DOMAINNAME'] = '.'.join(VHOSTNAME[1:])
else:
    context['DOMAINNAME'] = 'openstack.org'
context['ADMIN'] = 'webmaster@%s' % context['DOMAINNAME']

context['ACTIVATE_THIS'] = None
virtualenv = os.environ.get('VIRTUAL_ENV')
if virtualenv:
    activate_this = os.path.join(
        virtualenv, 'bin/activate_this.py')
    if os.path.exists(activate_this):
        context['ACTIVATE_THIS'] = activate_this


def find_apache_log_dir():
    for log_dir in APACHE_LOG_DIRS:
        if os.path.exists(log_dir) and os.path.isdir(log_dir):
            return log_dir
    return DEFAULT_LOG_DIR
context['LOGDIR'] = find_apache_log_dir()


class Command(BaseCommand):

    args = ''
    help = """Create %(wsgi_file)s
or the contents of an apache %(p_name)s.conf file (on stdout).
The apache configuration is generated on stdout because the place of this
file is distribution dependent.

examples::

    manage.py %(cmd_name)s --wsgi  # creates %(wsgi_file)s
    manage.py %(cmd_name)s --apache  # creates an apache vhost conf file (on \
stdout).
    manage.py %(cmd_name)s --apache --ssl --mail=%(admin)s \
--project=%(p_name)s --hostname=%(hostname)s

To create an acpache configuration file, redirect the output towards the
location you desire, e.g.::

    manage.py %(cmd_name)s --apache > \
/etc/httpd/conf.d/openstack_dashboard.conf

    """ % {
           'cmd_name': cmd_name,
           'p_name': context['PROJECT_NAME'],
           'wsgi_file': context['WSGI_FILE'],
           'admin': context['ADMIN'],
           'hostname': context['VHOSTNAME'], }

    option_list = BaseCommand.option_list + (
        # TODO(ygbo): Add an --nginx option.
        make_option("-a", "--apache",
                    default=False, action="store_true", dest="apache",
                    help="generate an apache vhost configuration"),
        make_option("--cacert",
                    dest="cacert",
                    help=("Use with the --apache and --ssl option to define "
                          "the path to the SSLCACertificateFile"
                          ),
                    metavar="CACERT"),
        make_option("-f", "--force",
                    default=False, action="store_true", dest="force",
                    help="force overwriting of an existing %s file" %
                         context['WSGI_FILE']),
        make_option("-H", "--hostname",
                    dest="hostname",
                    help=("Use with the --apache option to define the server's"
                          " hostname (default : %s)") % context['VHOSTNAME'],
                    metavar="HOSTNAME"),
        make_option("--logdir",
                    dest="logdir",
                    help=("Use with the --apache option to define the path to "
                          "the apache log directory(default : %s)"
                          % context['LOGDIR']),
                    metavar="CACERT"),
        make_option("-m", "--mail",
                    dest="mail",
                    help=("Use with the --apache option to define the web site"
                          " administrator's email (default : %s)") %
                         context['ADMIN'],
                    metavar="MAIL"),
        make_option("-n", "--namedhost",
                    default=False, action="store_true", dest="namedhost",
                    help=("Use with the --apache option. The apache vhost "
                          "configuration will work only when accessed with "
                          "the proper hostname (see --hostname).")),
        make_option("-p", "--project",
                    dest="project",
                    help=("Use with the --apache option to define the project "
                          "name (default : %s)") % context['PROJECT_NAME'],
                    metavar="PROJECT"),
        make_option("-s", "--ssl",
                    default=False, action="store_true", dest="ssl",
                    help=("Use with the --apache option. The apache vhost "
                          "configuration will use an SSL configuration")),
        make_option("--sslcert",
                    dest="sslcert",
                    help=("Use with the --apache and --ssl option to define "
                          "the path to the SSLCertificateFile (default : %s)"
                          ) % context['SSLCERT'],
                    metavar="SSLCERT"),
        make_option("--sslkey",
                    dest="sslkey",
                    help=("Use with the --apache and --ssl option to define "
                          "the path to the SSLCertificateKeyFile "
                          "(default : %s)") % context['SSLKEY'],
                    metavar="SSLKEY"),
        make_option("-w", "--wsgi",
                    default=False, action="store_true", dest="wsgi",
                    help="generate the horizon.wsgi file"),
    )

    def handle(self, *args, **options):
        force = options.get('force')
        context['SSL'] = options.get('ssl')

        if options.get('mail'):
            context['ADMIN'] = options['mail']
        if options.get('cacert'):
            context['CACERT'] = options['cacert']
        if options.get('logdir'):
            context['LOGDIR'] = options['logdir'].rstrip('/')
        if options.get('project'):
            context['PROJECT_NAME'] = options['project']
        if options.get('hostname'):
            context['VHOSTNAME'] = options['hostname']
        if options.get('sslcert'):
            context['SSLCERT'] = options['sslcert']
        if options.get('sslkey'):
            context['SSLKEY'] = options['sslkey']

        if options.get('namedhost'):
            context['NAMEDHOST'] = context['VHOSTNAME']
        else:
            context['NAMEDHOST'] = '*'

        # Generate the WSGI.
        if options.get('wsgi'):
            with open(
                os.path.join(CURDIR, 'horizon.wsgi.template'), 'r'
            ) as fp:
                wsgi_template = Template(fp.read())
            if not os.path.exists(context['WSGI_FILE']) or force:
                with open(context['WSGI_FILE'], 'w') as fp:
                    fp.write(wsgi_template.render(context))
                print('Generated "%s"' % context['WSGI_FILE'])
            else:
                sys.exit('"%s" already exists, use --force to overwrite' %
                         context['WSGI_FILE'])

        # Generate the apache configuration.
        elif options.get('apache'):
            with open(
                os.path.join(CURDIR, 'apache_vhost.conf.template'), 'r'
            ) as fp:
                wsgi_template = Template(fp.read())
            sys.stdout.write(wsgi_template.render(context))
        else:
            self.print_help('manage.py', cmd_name)