Browse Source

Init commit for Distil UI

Some specific Catalyst Cloud stuff are here and there, they will be cleaned
up later after we migrated to Distil v2.

Change-Id: I81df0765cfc876faaa58a43469d87825d30c167e
changes/82/444682/13
Fei Long Wang 2 years ago
parent
commit
502b3eb286
76 changed files with 3863 additions and 0 deletions
  1. 46
    0
      .gitignore
  2. 1
    0
      AUTHORS
  3. 176
    0
      LICENSE
  4. 1
    0
      MANIFEST.in
  5. 64
    0
      README.rst
  6. 5
    0
      babel-django.cfg
  7. 14
    0
      babel-djangojs.cfg
  8. 0
    0
      distil_ui/__init__.py
  9. 0
    0
      distil_ui/api/__init__.py
  10. 316
    0
      distil_ui/api/distil.py
  11. 0
    0
      distil_ui/content/__init__.py
  12. 0
    0
      distil_ui/content/billing/__init__.py
  13. 104
    0
      distil_ui/content/billing/base.py
  14. 22
    0
      distil_ui/content/billing/panel.py
  15. 41
    0
      distil_ui/content/billing/tables.py
  16. 3
    0
      distil_ui/content/billing/templates/billing/billing.csv
  17. 190
    0
      distil_ui/content/billing/templates/billing/index.html
  18. 287
    0
      distil_ui/content/billing/tests.py
  19. 23
    0
      distil_ui/content/billing/urls.py
  20. 116
    0
      distil_ui/content/billing/views.py
  21. 0
    0
      distil_ui/content/default/__init__.py
  22. 24
    0
      distil_ui/content/default/panel.py
  23. 3
    0
      distil_ui/content/default/templates/default/base.html
  24. 38
    0
      distil_ui/dashboard.py
  25. 7
    0
      distil_ui/enabled/_6000_management.py
  26. 20
    0
      distil_ui/enabled/_6010_management_billing.py
  27. 0
    0
      distil_ui/enabled/__init__.py
  28. 155
    0
      distil_ui/karma.conf.js
  29. 5
    0
      distil_ui/static/catalystdashboard/d3.min.js
  30. 1
    0
      distil_ui/static/catalystdashboard/nv.d3.min.css
  31. 6
    0
      distil_ui/static/catalystdashboard/nv.d3.min.js
  32. 44
    0
      distil_ui/static/catalystdashboard/scss/style.css
  33. 0
    0
      distil_ui/test/__init__.py
  34. 0
    0
      distil_ui/test/api_tests/__init__.py
  35. 28
    0
      distil_ui/test/api_tests/rest_api_tests.py
  36. 20
    0
      distil_ui/test/helpers.py
  37. 0
    0
      distil_ui/test/integration_tests/__init__.py
  38. 38
    0
      distil_ui/test/settings.py
  39. 18
    0
      distil_ui/test/test_data.py
  40. 15
    0
      distil_ui/version.py
  41. 153
    0
      doc/Makefile
  42. 441
    0
      doc/source/conf.py
  43. 63
    0
      doc/source/index.rst
  44. 35
    0
      doc/source/sourcecode/autoindex.rst
  45. 8
    0
      doc/source/sourcecode/distil_ui/distil_ui.api.distil.rst
  46. 8
    0
      doc/source/sourcecode/distil_ui/distil_ui.api.rst
  47. 8
    0
      doc/source/sourcecode/distil_ui/distil_ui.content.billing.base.rst
  48. 8
    0
      doc/source/sourcecode/distil_ui/distil_ui.content.billing.panel.rst
  49. 8
    0
      doc/source/sourcecode/distil_ui/distil_ui.content.billing.rst
  50. 8
    0
      doc/source/sourcecode/distil_ui/distil_ui.content.billing.tables.rst
  51. 8
    0
      doc/source/sourcecode/distil_ui/distil_ui.content.billing.urls.rst
  52. 8
    0
      doc/source/sourcecode/distil_ui/distil_ui.content.billing.views.rst
  53. 8
    0
      doc/source/sourcecode/distil_ui/distil_ui.content.rst
  54. 8
    0
      doc/source/sourcecode/distil_ui/distil_ui.enabled._6010_management_billing.rst
  55. 8
    0
      doc/source/sourcecode/distil_ui/distil_ui.enabled.rst
  56. 8
    0
      doc/source/sourcecode/distil_ui/distil_ui.rst
  57. 8
    0
      doc/source/sourcecode/distil_ui/distil_ui.test.api_tests.rest_api_tests.rst
  58. 8
    0
      doc/source/sourcecode/distil_ui/distil_ui.test.api_tests.rst
  59. 8
    0
      doc/source/sourcecode/distil_ui/distil_ui.test.helpers.rst
  60. 8
    0
      doc/source/sourcecode/distil_ui/distil_ui.test.integration_tests.rst
  61. 8
    0
      doc/source/sourcecode/distil_ui/distil_ui.test.rst
  62. 8
    0
      doc/source/sourcecode/distil_ui/distil_ui.test.settings.rst
  63. 8
    0
      doc/source/sourcecode/distil_ui/distil_ui.test.test_data.rst
  64. 8
    0
      doc/source/sourcecode/distil_ui/distil_ui.version.rst
  65. 23
    0
      manage.py
  66. 35
    0
      package.json
  67. 17
    0
      requirements.txt
  68. 583
    0
      run_tests.sh
  69. 30
    0
      setup.cfg
  70. 29
    0
      setup.py
  71. 29
    0
      test-requirements.txt
  72. 97
    0
      test-shim.js
  73. 71
    0
      tools/install_venv.py
  74. 172
    0
      tools/install_venv_common.py
  75. 13
    0
      tools/with_venv.sh
  76. 81
    0
      tox.ini

+ 46
- 0
.gitignore View File

@@ -0,0 +1,46 @@
1
+*.pyc
2
+*.deb
3
+.vagrant
4
+work
5
+*.swp
6
+*~
7
+*.swo
8
+*.sw*
9
+lib/
10
+man/
11
+build/
12
+work-api/
13
+work-client/
14
+env/
15
+dist/
16
+include/
17
+*.egg*/
18
+bin/activate
19
+bin/activate.csh
20
+bin/activate.fish
21
+bin/activate_this.py
22
+bin/ceilometer
23
+bin/easy_install
24
+bin/easy_install-2.7
25
+bin/keystone
26
+bin/netaddr
27
+bin/nosetests
28
+bin/nosetests-2.7
29
+bin/pip
30
+bin/pip-2.7
31
+bin/pybabel
32
+bin/python
33
+bin/python2
34
+bin/python2.7
35
+.project
36
+.pydevproject
37
+.testrepository/
38
+.tox/
39
+.venv/
40
+bin/logs/
41
+bin/waitress-serve
42
+local/
43
+test_vm/
44
+env/
45
+ChangeLog
46
+.idea

+ 1
- 0
AUTHORS View File

@@ -0,0 +1 @@
1
+Fei Long Wang <flwang@catalyst.net.nz>

+ 176
- 0
LICENSE View File

@@ -0,0 +1,176 @@
1
+
2
+                                 Apache License
3
+                           Version 2.0, January 2004
4
+                        http://www.apache.org/licenses/
5
+
6
+   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+   1. Definitions.
9
+
10
+      "License" shall mean the terms and conditions for use, reproduction,
11
+      and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+      "Licensor" shall mean the copyright owner or entity authorized by
14
+      the copyright owner that is granting the License.
15
+
16
+      "Legal Entity" shall mean the union of the acting entity and all
17
+      other entities that control, are controlled by, or are under common
18
+      control with that entity. For the purposes of this definition,
19
+      "control" means (i) the power, direct or indirect, to cause the
20
+      direction or management of such entity, whether by contract or
21
+      otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+      outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+      "You" (or "Your") shall mean an individual or Legal Entity
25
+      exercising permissions granted by this License.
26
+
27
+      "Source" form shall mean the preferred form for making modifications,
28
+      including but not limited to software source code, documentation
29
+      source, and configuration files.
30
+
31
+      "Object" form shall mean any form resulting from mechanical
32
+      transformation or translation of a Source form, including but
33
+      not limited to compiled object code, generated documentation,
34
+      and conversions to other media types.
35
+
36
+      "Work" shall mean the work of authorship, whether in Source or
37
+      Object form, made available under the License, as indicated by a
38
+      copyright notice that is included in or attached to the work
39
+      (an example is provided in the Appendix below).
40
+
41
+      "Derivative Works" shall mean any work, whether in Source or Object
42
+      form, that is based on (or derived from) the Work and for which the
43
+      editorial revisions, annotations, elaborations, or other modifications
44
+      represent, as a whole, an original work of authorship. For the purposes
45
+      of this License, Derivative Works shall not include works that remain
46
+      separable from, or merely link (or bind by name) to the interfaces of,
47
+      the Work and Derivative Works thereof.
48
+
49
+      "Contribution" shall mean any work of authorship, including
50
+      the original version of the Work and any modifications or additions
51
+      to that Work or Derivative Works thereof, that is intentionally
52
+      submitted to Licensor for inclusion in the Work by the copyright owner
53
+      or by an individual or Legal Entity authorized to submit on behalf of
54
+      the copyright owner. For the purposes of this definition, "submitted"
55
+      means any form of electronic, verbal, or written communication sent
56
+      to the Licensor or its representatives, including but not limited to
57
+      communication on electronic mailing lists, source code control systems,
58
+      and issue tracking systems that are managed by, or on behalf of, the
59
+      Licensor for the purpose of discussing and improving the Work, but
60
+      excluding communication that is conspicuously marked or otherwise
61
+      designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+      "Contributor" shall mean Licensor and any individual or Legal Entity
64
+      on behalf of whom a Contribution has been received by Licensor and
65
+      subsequently incorporated within the Work.
66
+
67
+   2. Grant of Copyright License. Subject to the terms and conditions of
68
+      this License, each Contributor hereby grants to You a perpetual,
69
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+      copyright license to reproduce, prepare Derivative Works of,
71
+      publicly display, publicly perform, sublicense, and distribute the
72
+      Work and such Derivative Works in Source or Object form.
73
+
74
+   3. Grant of Patent License. Subject to the terms and conditions of
75
+      this License, each Contributor hereby grants to You a perpetual,
76
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+      (except as stated in this section) patent license to make, have made,
78
+      use, offer to sell, sell, import, and otherwise transfer the Work,
79
+      where such license applies only to those patent claims licensable
80
+      by such Contributor that are necessarily infringed by their
81
+      Contribution(s) alone or by combination of their Contribution(s)
82
+      with the Work to which such Contribution(s) was submitted. If You
83
+      institute patent litigation against any entity (including a
84
+      cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+      or a Contribution incorporated within the Work constitutes direct
86
+      or contributory patent infringement, then any patent licenses
87
+      granted to You under this License for that Work shall terminate
88
+      as of the date such litigation is filed.
89
+
90
+   4. Redistribution. You may reproduce and distribute copies of the
91
+      Work or Derivative Works thereof in any medium, with or without
92
+      modifications, and in Source or Object form, provided that You
93
+      meet the following conditions:
94
+
95
+      (a) You must give any other recipients of the Work or
96
+          Derivative Works a copy of this License; and
97
+
98
+      (b) You must cause any modified files to carry prominent notices
99
+          stating that You changed the files; and
100
+
101
+      (c) You must retain, in the Source form of any Derivative Works
102
+          that You distribute, all copyright, patent, trademark, and
103
+          attribution notices from the Source form of the Work,
104
+          excluding those notices that do not pertain to any part of
105
+          the Derivative Works; and
106
+
107
+      (d) If the Work includes a "NOTICE" text file as part of its
108
+          distribution, then any Derivative Works that You distribute must
109
+          include a readable copy of the attribution notices contained
110
+          within such NOTICE file, excluding those notices that do not
111
+          pertain to any part of the Derivative Works, in at least one
112
+          of the following places: within a NOTICE text file distributed
113
+          as part of the Derivative Works; within the Source form or
114
+          documentation, if provided along with the Derivative Works; or,
115
+          within a display generated by the Derivative Works, if and
116
+          wherever such third-party notices normally appear. The contents
117
+          of the NOTICE file are for informational purposes only and
118
+          do not modify the License. You may add Your own attribution
119
+          notices within Derivative Works that You distribute, alongside
120
+          or as an addendum to the NOTICE text from the Work, provided
121
+          that such additional attribution notices cannot be construed
122
+          as modifying the License.
123
+
124
+      You may add Your own copyright statement to Your modifications and
125
+      may provide additional or different license terms and conditions
126
+      for use, reproduction, or distribution of Your modifications, or
127
+      for any such Derivative Works as a whole, provided Your use,
128
+      reproduction, and distribution of the Work otherwise complies with
129
+      the conditions stated in this License.
130
+
131
+   5. Submission of Contributions. Unless You explicitly state otherwise,
132
+      any Contribution intentionally submitted for inclusion in the Work
133
+      by You to the Licensor shall be under the terms and conditions of
134
+      this License, without any additional terms or conditions.
135
+      Notwithstanding the above, nothing herein shall supersede or modify
136
+      the terms of any separate license agreement you may have executed
137
+      with Licensor regarding such Contributions.
138
+
139
+   6. Trademarks. This License does not grant permission to use the trade
140
+      names, trademarks, service marks, or product names of the Licensor,
141
+      except as required for reasonable and customary use in describing the
142
+      origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+   7. Disclaimer of Warranty. Unless required by applicable law or
145
+      agreed to in writing, Licensor provides the Work (and each
146
+      Contributor provides its Contributions) on an "AS IS" BASIS,
147
+      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+      implied, including, without limitation, any warranties or conditions
149
+      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+      PARTICULAR PURPOSE. You are solely responsible for determining the
151
+      appropriateness of using or redistributing the Work and assume any
152
+      risks associated with Your exercise of permissions under this License.
153
+
154
+   8. Limitation of Liability. In no event and under no legal theory,
155
+      whether in tort (including negligence), contract, or otherwise,
156
+      unless required by applicable law (such as deliberate and grossly
157
+      negligent acts) or agreed to in writing, shall any Contributor be
158
+      liable to You for damages, including any direct, indirect, special,
159
+      incidental, or consequential damages of any character arising as a
160
+      result of this License or out of the use or inability to use the
161
+      Work (including but not limited to damages for loss of goodwill,
162
+      work stoppage, computer failure or malfunction, or any and all
163
+      other commercial damages or losses), even if such Contributor
164
+      has been advised of the possibility of such damages.
165
+
166
+   9. Accepting Warranty or Additional Liability. While redistributing
167
+      the Work or Derivative Works thereof, You may choose to offer,
168
+      and charge a fee for, acceptance of support, warranty, indemnity,
169
+      or other liability obligations and/or rights consistent with this
170
+      License. However, in accepting such obligations, You may act only
171
+      on Your own behalf and on Your sole responsibility, not on behalf
172
+      of any other Contributor, and only if You agree to indemnify,
173
+      defend, and hold each Contributor harmless for any liability
174
+      incurred by, or claims asserted against, such Contributor by reason
175
+      of your accepting any such warranty or additional liability.
176
+

+ 1
- 0
MANIFEST.in View File

@@ -0,0 +1 @@
1
+include setup.py

+ 64
- 0
README.rst View File

@@ -0,0 +1,64 @@
1
+========================
2
+Team and repository tags
3
+========================
4
+
5
+.. Change things from this point on
6
+
7
+===============================
8
+distil-ui
9
+===============================
10
+
11
+Distil Dashboard
12
+
13
+* Free software: Apache license
14
+* Source: http://git.openstack.org/cgit/openstack/distil-ui
15
+
16
+Enabling in DevStack
17
+--------------------
18
+
19
+Add this repo as an external repository into your ``local.conf`` file::
20
+
21
+    [[local|localrc]]
22
+    enable_plugin distil-ui https://github.com/openstack/distil-ui
23
+
24
+Manual Installation
25
+-------------------
26
+
27
+Begin by cloning the Horizon and Distil UI repositories::
28
+
29
+    git clone https://github.com/openstack/horizon
30
+    git clone https://github.com/openstack/distil-ui
31
+
32
+Create a virtual environment and install Horizon dependencies::
33
+
34
+    cd horizon
35
+    python tools/install_venv.py
36
+
37
+Set up your ``local_settings.py`` file::
38
+
39
+    cp openstack_dashboard/local/local_settings.py.example openstack_dashboard/local/local_settings.py
40
+
41
+Open up the copied ``local_settings.py`` file in your preferred text
42
+editor. You will want to customize several settings:
43
+
44
+-  ``OPENSTACK_HOST`` should be configured with the hostname of your
45
+   OpenStack server. Verify that the ``OPENSTACK_KEYSTONE_URL`` and
46
+   ``OPENSTACK_KEYSTONE_DEFAULT_ROLE`` settings are correct for your
47
+   environment. (They should be correct unless you modified your
48
+   OpenStack server to change them.)
49
+
50
+
51
+Install Distil UI with all dependencies in your virtual environment::
52
+
53
+    tools/with_venv.sh pip install -e ../distil-ui/
54
+
55
+And enable it in Horizon::
56
+
57
+    cp ../distil-ui/enabled/_6010_management_billing.py openstack_dashboard/local/enabled
58
+
59
+To run horizon with the newly enabled Distil UI plugin run::
60
+
61
+    ./run_tests.sh --runserver 0.0.0.0:8080
62
+
63
+to have the application start on port 8080 and the horizon dashboard will be
64
+available in your browser at http://localhost:8080/

+ 5
- 0
babel-django.cfg View File

@@ -0,0 +1,5 @@
1
+[extractors]
2
+django = django_babel.extract:extract_django
3
+
4
+[python: **.py]
5
+[django: templates/**.html]

+ 14
- 0
babel-djangojs.cfg View File

@@ -0,0 +1,14 @@
1
+[extractors]
2
+# We use a custom extractor to find translatable strings in AngularJS
3
+# templates. The extractor is included in horizon.utils for now.
4
+# See http://babel.pocoo.org/docs/messages/#referencing-extraction-methods for
5
+# details on how this works.
6
+angular = horizon.utils.babel_extract_angular:extract_angular
7
+
8
+[javascript: **.js]
9
+
10
+# We need to look into all static folders for HTML files.
11
+# The **/static ensures that we also search within
12
+# /openstack_dashboard/dashboards/XYZ/static which will ensure
13
+# that plugins are also translated.
14
+[angular: **/static/**.html]

+ 0
- 0
distil_ui/__init__.py View File


+ 0
- 0
distil_ui/api/__init__.py View File


+ 316
- 0
distil_ui/api/distil.py View File

@@ -0,0 +1,316 @@
1
+# Copyright (c) 2014 Catalyst IT Ltd.
2
+#
3
+# Licensed under the Apache License, Version 2.0 (the "License");
4
+# you may not use this file except in compliance with the License.
5
+# You may obtain a copy of the License at
6
+#
7
+# http://www.apache.org/licenses/LICENSE-2.0
8
+#
9
+# Unless required by applicable law or agreed to in writing, software
10
+# distributed under the License is distributed on an "AS IS" BASIS,
11
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+# See the License for the specific language governing permissions and
13
+# limitations under the License.
14
+
15
+import collections
16
+import datetime
17
+import logging
18
+import math
19
+import time
20
+
21
+from django.conf import settings
22
+import eventlet
23
+
24
+from openstack_dashboard.api import base
25
+
26
+LOG = logging.getLogger(__name__)
27
+BILLITEM = collections.namedtuple('BillItem',
28
+                                  ['id', 'resource', 'count', 'cost'])
29
+
30
+EMPTY_BREAKDOWN = [BILLITEM(id=1, resource='N/A', count=0, cost=0)]
31
+
32
+RES_NAME_MAPPING = {'Virtual Machine': 'Compute',
33
+                    'Volume': 'Block Storage'}
34
+
35
+KNOWN_RESOURCE_TYPE = ['Compute', 'Block Storage', 'Network', 'Router',
36
+                       'Image', 'Floating IP', 'Object Storage', 'VPN',
37
+                       'Inbound International Traffic',
38
+                       'Outbound International Traffic',
39
+                       'Inbound National Traffic',
40
+                       'Outbound National Traffic']
41
+
42
+SRV_RES_MAPPING = {'m1.tiny': 'Compute',
43
+                   'm1.small': 'Compute',
44
+                   'm1.mini': 'Compute',
45
+                   'm1.medium': 'Compute',
46
+                   'c1.small': 'Compute',
47
+                   'm1.large': 'Compute',
48
+                   'm1.xlarge': 'Compute',
49
+                   'c1.large': 'Compute',
50
+                   'c1.xlarge': 'Compute',
51
+                   'c1.xxlarge': 'Compute',
52
+                   'm1.2xlarge': 'Compute',
53
+                   'c1.c1r1': 'Compute',
54
+                   'c1.c1r2': 'Compute',
55
+                   'c1.c1r4': 'Compute',
56
+                   'c1.c2r1': 'Compute',
57
+                   'c1.c2r2': 'Compute',
58
+                   'c1.c2r4': 'Compute',
59
+                   'c1.c2r8': 'Compute',
60
+                   'c1.c2r16': 'Compute',
61
+                   'c1.c4r2': 'Compute',
62
+                   'c1.c4r4': 'Compute',
63
+                   'c1.c4r8': 'Compute',
64
+                   'c1.c4r16': 'Compute',
65
+                   'c1.c4r32': 'Compute',
66
+                   'c1.c8r4': 'Compute',
67
+                   'c1.c8r8': 'Compute',
68
+                   'c1.c8r16': 'Compute',
69
+                   'c1.c8r32': 'Compute',
70
+                   'b1.standard': 'Block Storage',
71
+                   'o1.standard': 'Object Storage',
72
+                   'n1.ipv4': 'Floating IP',
73
+                   'n1.network': 'Network',
74
+                   'n1.router': 'Router',
75
+                   'n1.vpn': 'VPN',
76
+                   'n1.international-in': 'Inbound International Traffic',
77
+                   'n1.international-out': 'Outbound International Traffic',
78
+                   'n1.national-in': 'Inbound National Traffic',
79
+                   'n1.national-out': 'Outbound National Traffic'}
80
+
81
+TRAFFIC_MAPPING = {'n1.international-in': 'Inbound International Traffic',
82
+                   'n1.international-out': 'Outbound International Traffic',
83
+                   'n1.national-in': 'Inbound National Traffic',
84
+                   'n1.national-out': 'Outbound National Traffic'}
85
+
86
+CACHE = {}
87
+
88
+
89
+def distilclient(request):
90
+    try:
91
+        try:
92
+            from distilclient import client
93
+        except Exception:
94
+            from distil.client import client
95
+        auth_url = base.url_for(request, service_type='identity')
96
+        distil_url = base.url_for(request, service_type='rating')
97
+        insecure = getattr(settings, 'OPENSTACK_SSL_NO_VERIFY', False)
98
+        cacert = getattr(settings, 'OPENSTACK_SSL_CACERT', None)
99
+        distil = client.Client(distil_url=distil_url,
100
+                               os_auth_token=request.user.token.id,
101
+                               os_tenant_id=request.user.tenant_id,
102
+                               os_auth_url=auth_url,
103
+                               os_region_name=request.user.services_region,
104
+                               insecure=insecure,
105
+                               os_cacert=cacert)
106
+        distil.request = request
107
+    except Exception as e:
108
+        LOG.error(e)
109
+        return
110
+    return distil
111
+
112
+
113
+def _get_month_cost(distil_client, tenant_id, start_str, end_str,
114
+                    history_cost, i):
115
+    today = datetime.datetime.today()
116
+    start = datetime.datetime.strptime(start_str, '%Y-%m-%dT%H:%M:%S')
117
+    cache_key = (distil_client.endpoint + '_' + tenant_id + '_' +
118
+                 start_str + '_' + end_str)
119
+    if cache_key in CACHE:
120
+        history_cost[i] = CACHE[cache_key]
121
+        return
122
+
123
+    month_cost = distil_client.get_rated([tenant_id], start_str,
124
+                                         end_str)['usage']
125
+
126
+    resource_cost = collections.OrderedDict()
127
+    prices = {}
128
+    cost_details = collections.defaultdict(list)
129
+    for res in KNOWN_RESOURCE_TYPE:
130
+        cost_details[res] = []
131
+
132
+    for res_id, details in month_cost['resources'].items():
133
+        resource_type = details['type']
134
+        for s in details['services']:
135
+            if resource_type not in prices:
136
+                try:
137
+                    prices[resource_type] = float(s.get('rate', 0))
138
+                except Exception as e:
139
+                    LOG.error('Failed to get rate for %s since %s' % (s, e))
140
+            # Only collect service details for current month, we may support
141
+            # the details for history in the future.
142
+            if ((start.year == today.year and start.month == today.month) or
143
+                    s['name'] in TRAFFIC_MAPPING):
144
+                try:
145
+                    s_copy = s.copy()
146
+                    s_copy['volume'] = round(float(s_copy['volume']), 4)
147
+                    s_copy['resource_id'] = res_id
148
+                    cd_key = ('Image' if resource_type == 'Image' else
149
+                              SRV_RES_MAPPING.get(s['name'], resource_type))
150
+                    if cd_key in ('Image', 'Block Storage', 'Object Storage'):
151
+                        s_copy['unit'] = 'gigabyte * hour'
152
+
153
+                    # NOTE(flwang): Get the related resource info
154
+                    if resource_type == 'Floating IP':
155
+                        s_copy['resource'] = details['ip address']
156
+                    if resource_type in ('Image', 'Object Storage Container',
157
+                                         'Network', 'Virtual Machine',
158
+                                         'Router', 'VPN', 'Volume'):
159
+                        s_copy['resource'] = details['name']
160
+
161
+                    cost_details.get(cd_key).append(s_copy)
162
+                except Exception as e:
163
+                    LOG.error('Failed to save: %s, since %s' % (s, e))
164
+                    continue
165
+
166
+        res_type = (resource_type if resource_type not in
167
+                    RES_NAME_MAPPING else RES_NAME_MAPPING[resource_type])
168
+        count, cost = _calculate_count_cost(list(details['services']),
169
+                                            res_type)
170
+
171
+        if res_type in resource_cost:
172
+            tmp_count_cost = resource_cost[res_type]
173
+            tmp_count_cost = [tmp_count_cost[0] + count,
174
+                              tmp_count_cost[1] + cost]
175
+            resource_cost[res_type] = tmp_count_cost
176
+        else:
177
+            resource_cost[res_type] = [count, cost]
178
+
179
+    # NOTE(flwang): Based on current Distil API design, it's making the
180
+    # traffic data associate with floating ip and router. So we need to
181
+    # get them out and recalculate the cost of floating ip and router.
182
+    if ['admin'] in [r.values() for r in distil_client.request.user.roles]:
183
+        _calculate_traffic_cost(cost_details, resource_cost)
184
+
185
+    breakdown = []
186
+    total_cost = 0
187
+    for resource, count_cost in resource_cost.items():
188
+        rounded_cost = round(count_cost[1], 2)
189
+        breakdown.append(BILLITEM(id=len(breakdown) + 1,
190
+                                  resource=resource,
191
+                                  count=count_cost[0],
192
+                                  cost=rounded_cost))
193
+        total_cost += rounded_cost
194
+
195
+    if breakdown:
196
+        if start.year == today.year and start.month == today.month:
197
+            # Only apply/show the discount for current month
198
+            end_str = today.strftime('%Y-%m-%dT%H:00:00')
199
+            history_cost[i] = _apply_discount((round(total_cost, 2),
200
+                                               breakdown, cost_details),
201
+                                              start_str,
202
+                                              end_str,
203
+                                              prices)
204
+        else:
205
+            month_cost = (round(total_cost, 2), breakdown, [])
206
+            if month_cost:
207
+                CACHE[cache_key] = month_cost
208
+            history_cost[i] = month_cost
209
+
210
+
211
+def _calculate_count_cost(service_details, resource_type):
212
+    count = 0
213
+    cost = 0
214
+    for s in service_details:
215
+        if resource_type == 'Image' and s['name'] == 'b1.standard':
216
+            count += 1
217
+            cost += float(s['cost'])
218
+        if SRV_RES_MAPPING.get(s['name'], '') == resource_type:
219
+            count += 1
220
+            cost += float(s['cost'])
221
+    return count, cost
222
+
223
+
224
+def _calculate_traffic_cost(cost_details, resource_cost):
225
+    for resource_type in TRAFFIC_MAPPING.values():
226
+        if resource_type in cost_details:
227
+            (count, cost) = _calculate_count_cost(cost_details[resource_type],
228
+                                                  resource_type)
229
+            if cost > 0:
230
+                resource_cost[resource_type] = (count, cost)
231
+
232
+
233
+def _apply_discount(cost, start_str, end_str, prices):
234
+    """Appy discount for the usage costs
235
+
236
+    For now we only show the discount info for current month cost, because
237
+    the discount for history month has shown on customer's invoice.
238
+    """
239
+    total_cost, breakdown, cost_details = cost
240
+    start = time.mktime(time.strptime(start_str, '%Y-%m-%dT%H:%M:%S'))
241
+    end = time.mktime(time.strptime(end_str, '%Y-%m-%dT%H:%M:%S'))
242
+    # Get the integer part of the hours
243
+    free_hours = math.floor((end - start) / 3600)
244
+
245
+    free_network_cost = round(prices.get('Network', 0.0164) * free_hours, 2)
246
+    free_router_cost = round(prices.get('Router', 0.0170) * free_hours, 2)
247
+
248
+    for item in breakdown:
249
+        if item.resource == 'Network':
250
+            free_network_cost = (item.cost if item.cost <= free_network_cost
251
+                                 else free_network_cost)
252
+            breakdown[item.id - 1] = item._replace(cost=(item.cost -
253
+                                                         free_network_cost))
254
+            total_cost -= free_network_cost
255
+        if item.resource == 'Router':
256
+            free_router_cost = (item.cost if item.cost <= free_router_cost
257
+                                else free_router_cost)
258
+            breakdown[item.id - 1] = item._replace(cost=(item.cost -
259
+                                                         free_router_cost))
260
+            total_cost -= free_router_cost
261
+
262
+    return (total_cost, breakdown, cost_details)
263
+
264
+
265
+def _calculate_start_date(today):
266
+    last_year = today.year - 1 if today.month < 12 else today.year
267
+    month = ((today.month + 1) % 12 if today.month + 1 > 12
268
+             else today.month + 1)
269
+    return datetime.datetime(last_year, month, 1)
270
+
271
+
272
+def _calculate_end_date(start):
273
+    year = start.year + 1 if start.month + 1 > 12 else start.year
274
+    month = (start.month + 1) % 12 or 12
275
+    return datetime.datetime(year, month, 1)
276
+
277
+
278
+def get_cost(request, distil_client=None, enable_eventlet=True):
279
+    """Get cost for the last 1atest 12 months include current month
280
+
281
+    This function will return the latest 12 months cost and their breakdown
282
+    details, which includes current month.
283
+    """
284
+    if enable_eventlet:
285
+        eventlet.monkey_patch()
286
+    thread_pool = eventlet.GreenPool(size=12)
287
+    history_cost = [(0, EMPTY_BREAKDOWN, []) for _ in range(12)]
288
+
289
+    distil_client = distil_client or distilclient(request)
290
+
291
+    if not distil_client:
292
+        return history_cost
293
+
294
+    today = datetime.date.today()
295
+    start = _calculate_start_date(datetime.date.today())
296
+    end = _calculate_end_date(start)
297
+    final_end = datetime.datetime(today.year, today.month + 1, 1)
298
+
299
+    try:
300
+        for i in range(12):
301
+            start_str = start.strftime("%Y-%m-%dT00:00:00")
302
+            end_str = end.strftime("%Y-%m-%dT00:00:00")
303
+            thread_pool.spawn_n(_get_month_cost,
304
+                                distil_client, request.user.tenant_id,
305
+                                start_str, end_str,
306
+                                history_cost, i)
307
+            start = end
308
+            end = _calculate_end_date(start)
309
+            if end > final_end:
310
+                break
311
+
312
+        thread_pool.waitall()
313
+    except Exception as e:
314
+        LOG.exception('Failed to get the history cost data', e)
315
+
316
+    return history_cost

+ 0
- 0
distil_ui/content/__init__.py View File


+ 0
- 0
distil_ui/content/billing/__init__.py View File


+ 104
- 0
distil_ui/content/billing/base.py View File

@@ -0,0 +1,104 @@
1
+# Licensed under the Apache License, Version 2.0 (the "License"); you may
2
+# not use this file except in compliance with the License. You may obtain
3
+# a copy of the License at
4
+#
5
+#      http://www.apache.org/licenses/LICENSE-2.0
6
+#
7
+# Unless required by applicable law or agreed to in writing, software
8
+# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
9
+# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
10
+# License for the specific language governing permissions and limitations
11
+# under the License.
12
+
13
+from __future__ import division
14
+
15
+import datetime
16
+
17
+from django.utils import timezone
18
+from django.utils.translation import ugettext_lazy as _
19
+
20
+from horizon import forms
21
+from horizon import messages
22
+
23
+
24
+class BaseBilling(object):
25
+
26
+    def __init__(self, request, project_id=None):
27
+        self.project_id = project_id or request.user.tenant_id
28
+        self.request = request
29
+        self.billing_list = []
30
+
31
+    @property
32
+    def today(self):
33
+        return timezone.now()
34
+
35
+    @staticmethod
36
+    def get_start(year, month, day):
37
+        start = datetime.datetime(year, month, day, 0, 0, 0)
38
+        return timezone.make_aware(start, timezone.utc)
39
+
40
+    @staticmethod
41
+    def get_end(year, month, day):
42
+        end = datetime.datetime(year, month, day, 23, 59, 59)
43
+        return timezone.make_aware(end, timezone.utc)
44
+
45
+    def get_date_range(self):
46
+        if not hasattr(self, "start") or not hasattr(self, "end"):
47
+            args_start = (self.today.year, self.today.month, 1)
48
+            args_end = (self.today.year, self.today.month, self.today.day)
49
+            form = self.get_form()
50
+            if form.is_valid():
51
+                start = form.cleaned_data['start']
52
+                end = form.cleaned_data['end']
53
+                args_start = (start.year,
54
+                              start.month,
55
+                              start.day)
56
+                args_end = (end.year,
57
+                            end.month,
58
+                            end.day)
59
+            elif form.is_bound:
60
+                messages.error(self.request,
61
+                               _("Invalid date format: "
62
+                                 "Using today as default."))
63
+        self.start = self.get_start(*args_start)
64
+        self.end = self.get_end(*args_end)
65
+        return self.start, self.end
66
+
67
+    def init_form(self):
68
+        today = datetime.date.today()
69
+        self.start = datetime.date(day=1, month=today.month, year=today.year)
70
+        self.end = today
71
+
72
+        return self.start, self.end
73
+
74
+    def get_form(self):
75
+        if not hasattr(self, 'form'):
76
+            req = self.request
77
+            start = req.GET.get('start', req.session.get('billing_start'))
78
+            end = req.GET.get('end', req.session.get('billing_end'))
79
+            if start and end:
80
+                # bound form
81
+                self.form = forms.DateForm({'start': start, 'end': end})
82
+            else:
83
+                # non-bound form
84
+                init = self.init_form()
85
+                start = init[0].isoformat()
86
+                end = init[1].isoformat()
87
+                self.form = forms.DateForm(initial={'start': start,
88
+                                                    'end': end})
89
+            req.session['billing_start'] = start
90
+            req.session['billing_end'] = end
91
+        return self.form
92
+
93
+    def get_billing_list(self, start, end):
94
+        return []
95
+
96
+    def csv_link(self):
97
+        form = self.get_form()
98
+        data = {}
99
+        if hasattr(form, "cleaned_data"):
100
+            data = form.cleaned_data
101
+        if not ('start' in data and 'end' in data):
102
+            data = {"start": self.today.date(), "end": self.today.date()}
103
+        return "?start=%s&end=%s&format=csv" % (data['start'],
104
+                                                data['end'])

+ 22
- 0
distil_ui/content/billing/panel.py View File

@@ -0,0 +1,22 @@
1
+# Copyright (c) 2014 Catalyst IT Ltd.
2
+#
3
+# Licensed under the Apache License, Version 2.0 (the "License");
4
+# you may not use this file except in compliance with the License.
5
+# You may obtain a copy of the License at
6
+#
7
+# http://www.apache.org/licenses/LICENSE-2.0
8
+#
9
+# Unless required by applicable law or agreed to in writing, software
10
+# distributed under the License is distributed on an "AS IS" BASIS,
11
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+# See the License for the specific language governing permissions and
13
+# limitations under the License.
14
+
15
+from django.utils.translation import ugettext_lazy as _
16
+
17
+import horizon
18
+
19
+
20
+class Billing(horizon.Panel):
21
+    name = _("Usage Costs")
22
+    slug = 'billing'

+ 41
- 0
distil_ui/content/billing/tables.py View File

@@ -0,0 +1,41 @@
1
+# Copyright (c) 2014 Catalyst IT Ltd.
2
+#
3
+# Licensed under the Apache License, Version 2.0 (the "License");
4
+# you may not use this file except in compliance with the License.
5
+# You may obtain a copy of the License at
6
+#
7
+# http://www.apache.org/licenses/LICENSE-2.0
8
+#
9
+# Unless required by applicable law or agreed to in writing, software
10
+# distributed under the License is distributed on an "AS IS" BASIS,
11
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+# See the License for the specific language governing permissions and
13
+# limitations under the License.
14
+
15
+from django.utils.translation import ugettext_lazy as _
16
+
17
+from horizon import tables
18
+
19
+
20
+class CSVSummary(tables.LinkAction):
21
+    name = "csv_summary"
22
+    verbose_name = _("Download CSV Summary")
23
+    icon = "download"
24
+
25
+    def get_link_url(self):
26
+        return self.table.kwargs['billing'].csv_link()
27
+
28
+
29
+class BillingTable(tables.DataTable):
30
+    resource = tables.Column("resource",
31
+                             link=("#"),
32
+                             verbose_name=_("Resource"))
33
+    count = tables.Column("count", verbose_name=_("Count"))
34
+    cost = tables.Column("cost", verbose_name=_("Cost"))
35
+
36
+    class Meta(object):
37
+        name = "billing"
38
+        verbose_name = _("Breakdown")
39
+        columns = ("resource", "count", "cost")
40
+        table_actions = (CSVSummary,)
41
+        multi_select = False

+ 3
- 0
distil_ui/content/billing/templates/billing/billing.csv View File

@@ -0,0 +1,3 @@
1
+{% load i18n %}{% trans "Bill Report For Period" %}:,{{ billing.start|date:"b. d Y" }},{{ billing.end|date:"b. d Y" }}
2
+{% trans "Project ID" %}:,{{ billing.project_id }}
3
+

+ 190
- 0
distil_ui/content/billing/templates/billing/index.html View File

@@ -0,0 +1,190 @@
1
+{% extends 'base.html' %}
2
+{% load compress %}
3
+{% load i18n %}
4
+{% load i18n sizeformat %}
5
+
6
+{% block title %}{% trans "Usage Costs" %}{% endblock %}
7
+
8
+{% block css %}
9
+    {% include "_stylesheets.html" %}
10
+
11
+    <link href="{{ STATIC_URL }}catalystdashboard/nv.d3.min.css" rel="stylesheet" type="text/css">
12
+    <link href='{{ STATIC_URL }}catalystdashboard/scss/style.css' type='text/css' rel='stylesheet'>
13
+{% endblock %}
14
+
15
+{% block page_header %}
16
+  {% include "horizon/common/_page_header.html" with title=_("Usage Costs") %}
17
+{% endblock page_header %}
18
+
19
+{% block main %}
20
+
21
+<p>Disclaimer: This is an estimate for your usage within the current region, not your final invoice. It includes the free router and network discount. All costs are in New Zealand dollars and are exclusive of GST.</p>
22
+
23
+<div class="row-fluid">
24
+    <div class="col-md-4">
25
+        <h3 class="quota-heading dot_line">{% trans "Month to date" %}</h3>
26
+        <div id="pie_chart">
27
+            <svg class="pie"></svg>
28
+        </div>
29
+
30
+        {{table.render}}
31
+    </div>
32
+
33
+    <div class="col-md-8">
34
+      <h3 class="quota-heading dot_line">{% trans "Usage cost history" %}</h3>
35
+      <!-- Remove the date range for now
36
+      <form action="?" method="get" id="date_form" class="form-horizontal">
37
+        <h3>{% trans "Select a period of time to query its cost" %}: </h3>
38
+        <div class="datepicker">
39
+            {% blocktrans with start=form.start %}
40
+            <label>From:</label>{{ start }}{% endblocktrans %}
41
+
42
+            {% blocktrans with end=form.end %}
43
+            <label>To:</label>{{ end }}{% endblocktrans %}
44
+            <button class="btn btn-primary" type="submit">{% trans "Submit" %}</button>
45
+            <small>{% trans "The date should be in YYYY-mm-dd format." %}</small>
46
+        </div>
47
+      </form>
48
+      -->
49
+
50
+      <div id="line_chart">
51
+        <svg class="line"></svg>
52
+      </div>
53
+      <table id="service_details" class="table table-striped datatable  tablesorter tablesorter-default">
54
+         <thead>
55
+           <tr class="table_caption">
56
+             <th data-column="0" class="table_header" colspan="6">
57
+               <h3 class="table_title">Usage Details</h3>
58
+             </th>
59
+           </tr>
60
+           <tr class="tablesorter-headerRow">
61
+            <th tabindex="0" data-column="0" class="sortable normal_column tablesorter-header"><div class="tablesorter-header-inner">Resource ID</div></th>
62
+            <th tabindex="0" data-column="1" class="sortable normal_column tablesorter-header"><div class="tablesorter-header-inner">Resource Name</div></th>
63
+            <th tabindex="0" data-column="2" class="sortable normal_column tablesorter-header"><div class="tablesorter-header-inner">Volume</div></th>
64
+            <th tabindex="0" data-column="3" class="sortable normal_column tablesorter-header"><div class="tablesorter-header-inner">Unit</div></th>
65
+            <th tabindex="0" data-column="4" class="sortable normal_column tablesorter-header"><div class="tablesorter-header-inner">Rate</div></th>
66
+            <th tabindex="0" data-column="5" class="sortable normal_column tablesorter-header"><div class="tablesorter-header-inner">Cost</div></th>
67
+          </tr>
68
+        </thead>
69
+        <tbody>
70
+        </tbody>
71
+      </table>
72
+    </div>
73
+</div>
74
+
75
+<!-- Current d3 version is 3.4.1 -->
76
+<script type="text/javascript" src="{{ STATIC_URL }}catalystdashboard/d3.min.js" charset="utf-8"></script>
77
+<script type="text/javascript" src="{{ STATIC_URL }}catalystdashboard/nv.d3.min.js" charset="utf-8"></script>
78
+<script type="text/javascript">
79
+    var CHART_DATA = {{chart_data | safe}};
80
+    var AMOUNT_COST = {{amount_cost | safe}};
81
+    var COST_DETAILS = {{cost_details | safe}};
82
+
83
+    function draw_pie(where, source){
84
+        nv.addGraph(function() {
85
+            var chart = nv.models.pieChart()
86
+                .x(function(d) { return d.key })
87
+                .y(function(d) { return d.value })
88
+                .showLabels(true)
89
+                .labelType("percent")
90
+                .labelThreshold(.05)
91
+                .donut(true)
92
+                .donutRatio(0.35);
93
+
94
+            chart.tooltipContent(function(k, v, graph) {
95
+                return '<h3>' + k + '</h3>' + '<span style=\'padding:8px\'>$' + v + '</span>'
96
+            });
97
+
98
+            d3.select(where)
99
+                .datum(source)
100
+                .transition().duration(1200)
101
+                .call(chart);
102
+
103
+            nv.utils.windowResize(chart.update);
104
+
105
+            return chart;
106
+        });
107
+    }
108
+
109
+    function draw_line(where, source){
110
+        nv.addGraph(function() {
111
+            var months = {{x_axis_line_chart | safe}};
112
+            var chart = nv.models.lineChart()
113
+                .margin({left: 75})
114
+                .size(70);
115
+
116
+            chart.tooltipContent(function(key, x, y, graph) {
117
+                return '<h3>' + key + '</h3>' + '<span style=\'padding:8px\'>$' + y + ' at ' + x + '</span>'
118
+            });
119
+
120
+            chart.legend
121
+                .radioButtonMode(true);
122
+
123
+            chart.xAxis.axisLabel("Cost per Month")
124
+                .tickValues([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11])
125
+                .tickFormat(function(m){return months[m]});
126
+
127
+            chart.yAxis
128
+                .axisLabel("Cost (NZD) excl. GST")
129
+                .tickFormat(d3.format(',.2f'));
130
+
131
+            d3.select(where)
132
+                .datum(source)
133
+                .call(chart);
134
+
135
+            nv.utils.windowResize(chart.update);
136
+
137
+            return chart;
138
+        });
139
+    }
140
+
141
+    $(document).ready(function(){
142
+        draw_pie("#pie_chart .pie", function(){
143
+            return CHART_DATA['pie'];
144
+        })
145
+
146
+        draw_line("#line_chart .line", function(){
147
+            return CHART_DATA['line'];
148
+        })
149
+
150
+        $('#id_start').attr('disabled', true);
151
+        $('#billing tbody tr').each(function(){
152
+            $(this).find("td").eq(2).html('$' + $(this).find("td").eq(2).html());
153
+        });
154
+        $('#billing tfoot td').attr('colspan', 2);
155
+        $('#billing tfoot>tr').append('<td><span class="total">$'+AMOUNT_COST+'</span></td>');
156
+
157
+        var link_mapping = {"Compute": "/instances/",
158
+                            "Image": "/images/",
159
+                            "Network": "/networks/",
160
+                            "Router": "/routers/",
161
+                            "Block Storage": "/volumes/",
162
+                            "VPN": "/vpn/vpnservice/"}
163
+        $("#billing tbody>tr a")
164
+          .click(function() {
165
+            var resource_type = $(this).html();
166
+            res_cost_details = COST_DETAILS[resource_type]
167
+             $('#service_details .table_title').html(resource_type + ' - Usage Details')
168
+            $('#service_details').show();
169
+            $('#service_details tbody').html('');
170
+            if (res_cost_details.length>0){
171
+                for (i = 0; i < res_cost_details.length; i++) {
172
+                    var row_class = i%2==0? 'odd':'even';
173
+                    var link = "#";
174
+                    if (resource_type in link_mapping){
175
+	                    link = "http://127.0.0.1:9977/project" + link_mapping[resource_type] + res_cost_details[i]['resource_id'];
176
+	                }
177
+	                if (resource_type == 'Network'){
178
+	                    link += '/detail';
179
+	                }
180
+
181
+                    $('#service_details tbody').append('<tr class='+row_class+'><td><a href="' + link +'">' + res_cost_details[i]['resource_id'] + '</a></td><td>'+res_cost_details[i]['resource']+'</td><td>'+res_cost_details[i]['volume']+'</td><td>'+res_cost_details[i]['unit']+'</td><td>'+res_cost_details[i]['rate']+'</td><td>'+res_cost_details[i]['cost']+'</td></tr>');
182
+                }
183
+            }
184
+          })
185
+        $('#service_details').hide();
186
+    });
187
+
188
+</script>
189
+
190
+{% endblock %}

+ 287
- 0
distil_ui/content/billing/tests.py View File

@@ -0,0 +1,287 @@
1
+# Copyright (c) 2014 Catalyst IT Ltd.
2
+#
3
+# Licensed under the Apache License, Version 2.0 (the "License");
4
+# you may not use this file except in compliance with the License.
5
+# You may obtain a copy of the License at
6
+#
7
+# http://www.apache.org/licenses/LICENSE-2.0
8
+#
9
+# Unless required by applicable law or agreed to in writing, software
10
+# distributed under the License is distributed on an "AS IS" BASIS,
11
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+# See the License for the specific language governing permissions and
13
+# limitations under the License.
14
+
15
+import datetime
16
+import math
17
+import time
18
+
19
+from mox3 import mox
20
+
21
+from distil_ui.api import distil
22
+from openstack_dashboard.test import helpers as test
23
+
24
+
25
+class FakeUser(object):
26
+    roles = [{'name': 'admin'}]
27
+
28
+
29
+class FakeRequest(object):
30
+    user = FakeUser()
31
+
32
+
33
+class FakeDistilClient(object):
34
+    """A fake distil client for unit test."""
35
+    endpoint = 'http://localhost:8788'
36
+    request = FakeRequest()
37
+
38
+    def get_rated(self, tenant, start, end):
39
+        raise NotImplemented()
40
+
41
+
42
+class BillingTests(test.TestCase):
43
+    """FIXME(flwang): Move this test to rest_api_tests.py
44
+
45
+    Now we're putting the api test at here, since we don't want to hack
46
+    horizon too much. That means we don't want to put the api.py under /api
47
+    folder, at least for now.
48
+    """
49
+
50
+    def setUp(self):
51
+        super(BillingTests, self).setUp()
52
+        self.mocker = mox.Mox()
53
+
54
+    def test_calculate_end_date(self):
55
+        start = datetime.date(2015, 1, 1)
56
+        end = distil._calculate_end_date(start)
57
+        self.assertEqual((end.year, end.month, end.day), (2015, 2, 1))
58
+
59
+        start = datetime.date(2015, 6, 1)
60
+        end = distil._calculate_end_date(start)
61
+        self.assertEqual((end.year, end.month, end.day), (2015, 7, 1))
62
+
63
+        start = datetime.date(2015, 12, 1)
64
+        end = distil._calculate_end_date(start)
65
+        self.assertEqual((end.year, end.month, end.day), (2016, 1, 1))
66
+
67
+    def test_get_month_cost(self):
68
+        distilclient = self.mocker.CreateMock(FakeDistilClient)
69
+
70
+        resources = {"fake_uuid_1": {"services": [{
71
+                                     "volume": 2100,
72
+                                     "rate": 0.0005,
73
+                                     "cost": 1.05,
74
+                                     "name": "b1.standard",
75
+                                     "unit": "gigabyte"}],
76
+                                     "total_cost": 1.05,
77
+                                     "type": "Image",
78
+                                     "name": "cirros"},
79
+                     "fake_uuid_2": {"services": [{
80
+                                     "volume": 122,
81
+                                     "rate": 0.048,
82
+                                     "cost": 5.86,
83
+                                     "name": "m1.tiny",
84
+                                     "unit": "hour"}],
85
+                                     "total_cost": 5.86,
86
+                                     "type": "Virtual Machine",
87
+                                     "name": "dfgh"},
88
+                     "fake_uuid_3": {"services": [{
89
+                                     "volume": 200,
90
+                                     "rate": 0.048,
91
+                                     "cost": 9.60,
92
+                                     "name": "m1.tiny",
93
+                                     "unit": "hour"}],
94
+                                     "total_cost": 9.60,
95
+                                     "type": "Virtual Machine",
96
+                                     "name": "abcd"},
97
+                     "fake_uuid_4": {"services": [{"volume": 20.00,
98
+                                                   "rate": 0.016,
99
+                                                   "cost": 0.32,
100
+                                                   "name": "n1.network",
101
+                                                   "unit": "hour"},
102
+                                                  {"volume": 10.00,
103
+                                                   "rate": 0.016,
104
+                                                   "cost": 0.16,
105
+                                                   "name": "n1.network",
106
+                                                   "unit": "hour"}],
107
+                                     "total_cost": 0.48,
108
+                                     "type": "Network",
109
+                                     "name": "public"}
110
+                     }
111
+
112
+        result = {'usage': {"end": "2011-03-01 00:00:00", "name": "openstack",
113
+                            "total_cost": 7.23,
114
+                            "tenant_id": "7c3c506ad4b943f5bb12b9fb69478084",
115
+                            "start": "2011-02-01 00:00:00",
116
+                            "resources": resources
117
+                            }
118
+                  }
119
+
120
+        distilclient.get_rated([self.tenant.id],
121
+                               '2011-02-01T00:00:00',
122
+                               '2011-03-01T00:00:00').AndReturn(result)
123
+        self.mocker.ReplayAll()
124
+
125
+        cost = [()]
126
+        distil._get_month_cost(distilclient,
127
+                               self.tenant.id,
128
+                               '2011-02-01T00:00:00',
129
+                               '2011-03-01T00:00:00',
130
+                               cost, 0)
131
+        self.assertEqual(16.99, cost[0][0])
132
+        self.assertEqual(3, len(cost[0][1]))
133
+        bill_items = {}
134
+        for b in cost[0][1]:
135
+            # Convert cost to string make sure the floating number is right
136
+            bill_items[b.resource] = (b.count, str(b.cost))
137
+
138
+        self.assertEqual((2, '0.48'), bill_items['Network'])
139
+        self.assertEqual((2, '15.46'), bill_items['Compute'])
140
+        self.assertEqual((1, '1.05'), bill_items['Image'])
141
+
142
+    def test_calculate_history_date(self):
143
+        """Using the same algorithm to calculate the history date."""
144
+        today = datetime.date(2015, 2, 17)
145
+        start = distil._calculate_start_date(datetime.date(2015, 2, 17))
146
+        end = distil._calculate_end_date(start)
147
+        final_end = datetime.datetime(today.year, today.month + 1, 1)
148
+
149
+        history_date = [None for i in range(12)]
150
+        for i in range(12):
151
+            start_str = start.strftime("%Y-%m-%dT00:00:00")
152
+            end_str = end.strftime("%Y-%m-%dT00:00:00")
153
+            history_date[i] = (start_str, end_str)
154
+            start = end
155
+            end = distil._calculate_end_date(start)
156
+            if end > final_end:
157
+                break
158
+
159
+        self.assertEqual(('2014-03-01T00:00:00', '2014-04-01T00:00:00'),
160
+                         history_date[0])
161
+        self.assertEqual(('2014-04-01T00:00:00', '2014-05-01T00:00:00'),
162
+                         history_date[1])
163
+        self.assertEqual(('2014-05-01T00:00:00', '2014-06-01T00:00:00'),
164
+                         history_date[2])
165
+        self.assertEqual(('2014-06-01T00:00:00', '2014-07-01T00:00:00'),
166
+                         history_date[3])
167
+        self.assertEqual(('2014-07-01T00:00:00', '2014-08-01T00:00:00'),
168
+                         history_date[4])
169
+        self.assertEqual(('2014-08-01T00:00:00', '2014-09-01T00:00:00'),
170
+                         history_date[5])
171
+        self.assertEqual(('2014-09-01T00:00:00', '2014-10-01T00:00:00'),
172
+                         history_date[6])
173
+        self.assertEqual(('2014-10-01T00:00:00', '2014-11-01T00:00:00'),
174
+                         history_date[7])
175
+        self.assertEqual(('2014-11-01T00:00:00', '2014-12-01T00:00:00'),
176
+                         history_date[8])
177
+        self.assertEqual(('2014-12-01T00:00:00', '2015-01-01T00:00:00'),
178
+                         history_date[9])
179
+        self.assertEqual(('2015-01-01T00:00:00', '2015-02-01T00:00:00'),
180
+                         history_date[10])
181
+        self.assertEqual(('2015-02-01T00:00:00', '2015-03-01T00:00:00'),
182
+                         history_date[11])
183
+
184
+    def test_get_cost(self):
185
+        distilclient = self.mocker.CreateMock(FakeDistilClient)
186
+
187
+        today = datetime.date.today()
188
+        start = distil._calculate_start_date(datetime.date.today())
189
+        end = distil._calculate_end_date(start)
190
+        final_end = datetime.datetime(today.year, today.month + 1, 1)
191
+
192
+        for i in range(12):
193
+            result = {'usage': {'total_cost': (i + 1) * 100,
194
+                                'resources': {'uuid': {"services": [{
195
+                                                       "volume": 2100,
196
+                                                       "rate": 0.0005,
197
+                                                       "cost": 1.05,
198
+                                                       "name": "b1.standard",
199
+                                                       "unit": "gigabyte"}],
200
+                                                       "total_cost": 1.05,
201
+                                                       "type": "Image",
202
+                                                       "name": "cirros"}}}}
203
+            start_str = start.strftime("%Y-%m-%dT00:00:00")
204
+            end_str = end.strftime("%Y-%m-%dT00:00:00")
205
+            distilclient.get_rated([self.tenant.id],
206
+                                   start_str,
207
+                                   end_str).AndReturn(result)
208
+
209
+            start = end
210
+            end = distil._calculate_end_date(start)
211
+            if end > final_end:
212
+                break
213
+
214
+        self.mocker.ReplayAll()
215
+        setattr(self.request.user, 'tenant_id', self.tenant.id)
216
+        history_cost = distil.get_cost(self.request,
217
+                                       distil_client=distilclient,
218
+                                       enable_eventlet=False)
219
+        # 2 = math.ceil(1.05)
220
+        self.assertEqual([1.05 for i in range(12)],
221
+                         [c[0] for c in history_cost])
222
+
223
+    def test_apply_discount(self):
224
+        # There are 3 scenarios for current month.
225
+        cost = (47.54,
226
+                [distil.BILLITEM(id=1, resource='Compute', count=9,
227
+                                 cost=31.76),
228
+                 distil.BILLITEM(id=2, resource=u'Network', count=3, cost=1.5),
229
+                 distil.BILLITEM(id=3, resource=u'Image', count=35, cost=3.82),
230
+                 distil.BILLITEM(id=4, resource=u'Router', count=2, cost=0.96),
231
+                 distil.BILLITEM(id=5, resource=u'Floating IP', count=21,
232
+                                 cost=3.57),
233
+                 distil.BILLITEM(id=6, resource='Block Storage', count=22,
234
+                                 cost=6.08)
235
+                 ], [])
236
+        prices = {u'Virtual Machine': 0.044, u'Network': 0.016,
237
+                  u'Image': 0.0005, u'Volume': 0.0005,
238
+                  u'Router': 0.017, u'Floating IP': 0.006}
239
+        start_str = '2015-07-01T00:00:00'
240
+        end_str = '2015-07-02T04:00:00'
241
+
242
+        cost_after_discount = distil._apply_discount(cost, start_str, end_str,
243
+                                                     prices)
244
+        start = time.mktime(time.strptime(start_str, '%Y-%m-%dT%H:%M:%S'))
245
+        end = time.mktime(time.strptime(end_str, '%Y-%m-%dT%H:%M:%S'))
246
+        free_hours = math.floor((end - start) / 3600)
247
+
248
+        free_network_cost = round(0.016 * free_hours, 2)
249
+        free_router_cost = round(0.017 * free_hours, 2)
250
+
251
+        self.assertEqual(cost[0] - free_network_cost - free_router_cost,
252
+                         cost_after_discount[0])
253
+
254
+        self.assertIn(distil.BILLITEM(id=2, resource=u'Network', count=3,
255
+                                      cost=1.05),
256
+                      cost_after_discount[1])
257
+        self.assertIn(distil.BILLITEM(id=4, resource=u'Router', count=2,
258
+                                      cost=0.48),
259
+                      cost_after_discount[1])
260
+
261
+    def test_get_month_cost_with_cache(self):
262
+        distil.CACHE.clear()
263
+        distilclient = self.mocker.CreateMock(FakeDistilClient)
264
+        result = {'usage': {'total_cost': 5.05,
265
+                            'resources': {'uuid':
266
+                                          {"services": [{"volume": 2100,
267
+                                                         "rate": 0.0005,
268
+                                                         "cost": 5.05,
269
+                                                         "name": "b1.standard",
270
+                                                         "unit": "gigabyte"}],
271
+                                           "total_cost": 5.05,
272
+                                           "type": "Image",
273
+                                           "name": "cirros"}}}}
274
+        distilclient.get_rated([self.tenant.id],
275
+                               '2011-02-01T00:00:00',
276
+                               '2011-03-01T00:00:00').AndReturn(result)
277
+        self.mocker.ReplayAll()
278
+
279
+        cost = [()]
280
+        distil._get_month_cost(distilclient,
281
+                               self.tenant.id,
282
+                               '2011-02-01T00:00:00',
283
+                               '2011-03-01T00:00:00',
284
+                               cost, 0)
285
+        key = 'http://localhost:8788_1_2011-02-01T00:00:00_2011-03-01T00:00:00'
286
+        self.assertIn(key, distil.CACHE)
287
+        self.assertEqual(distil.CACHE[key][0], 5.05)

+ 23
- 0
distil_ui/content/billing/urls.py View File

@@ -0,0 +1,23 @@
1
+# Copyright (c) 2014 Catalyst IT Ltd.
2
+#
3
+# Licensed under the Apache License, Version 2.0 (the "License");
4
+# you may not use this file except in compliance with the License.
5
+# You may obtain a copy of the License at
6
+#
7
+# http://www.apache.org/licenses/LICENSE-2.0
8
+#
9
+# Unless required by applicable law or agreed to in writing, software
10
+# distributed under the License is distributed on an "AS IS" BASIS,
11
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+# See the License for the specific language governing permissions and
13
+# limitations under the License.
14
+
15
+from django.conf.urls import patterns  # noqa
16
+from django.conf.urls import url  # noqa
17
+
18
+from distil_ui.content.billing import views
19
+
20
+urlpatterns = patterns(
21
+    '',
22
+    url(r'^$', views.IndexView.as_view(), name='index'),
23
+)

+ 116
- 0
distil_ui/content/billing/views.py View File

@@ -0,0 +1,116 @@
1
+# Copyright (c) 2014 Catalyst IT Ltd.
2
+#
3
+# Licensed under the Apache License, Version 2.0 (the "License");
4
+# you may not use this file except in compliance with the License.
5
+# You may obtain a copy of the License at
6
+#
7
+# http://www.apache.org/licenses/LICENSE-2.0
8
+#
9
+# Unless required by applicable law or agreed to in writing, software
10
+# distributed under the License is distributed on an "AS IS" BASIS,
11
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+# See the License for the specific language governing permissions and
13
+# limitations under the License.
14
+
15
+import datetime
16
+import json
17
+
18
+from django.template import defaultfilters
19
+from django.utils.translation import ugettext_lazy as _
20
+from horizon import exceptions
21
+from horizon import tables as horizon_tables
22
+from horizon.utils import csvbase
23
+
24
+from distil_ui.api import distil
25
+from distil_ui.content.billing import base
26
+from distil_ui.content.billing import tables
27
+
28
+
29
+class IndexCsvRenderer(csvbase.BaseCsvResponse):
30
+    columns = [_("Resource"), _("Count"), _("Cost")]
31
+
32
+    def get_row_data(self):
33
+        for b in self.context['current_month']:
34
+            yield (b.resource,
35
+                   b.count,
36
+                   defaultfilters.floatformat(b.cost, 2))
37
+
38
+
39
+class IndexView(horizon_tables.DataTableView):
40
+    table_class = tables.BillingTable
41
+    show_terminated = True
42
+    csv_template_name = 'management/billing/billing.csv'
43
+    template_name = 'management/billing/index.html'
44
+    csv_response_class = IndexCsvRenderer
45
+
46
+    def __init__(self, *args, **kwargs):
47
+        super(IndexView, self).__init__(*args, **kwargs)
48
+
49
+    def get_template_names(self):
50
+        if self.request.GET.get('format', 'html') == 'csv':
51
+            return (self.csv_template_name or
52
+                    ".".join((self.template_name.rsplit('.', 1)[0], 'csv')))
53
+        return self.template_name
54
+
55
+    def get_content_type(self):
56
+        if self.request.GET.get('format', 'html') == 'csv':
57
+            return "text/csv"
58
+        return "text/html"
59
+
60
+    def get_data(self):
61
+        try:
62
+            project_id = self.kwargs.get('project_id',
63
+                                         self.request.user.tenant_id)
64
+            self.billing = base.BaseBilling(self.request, project_id)
65
+            self.start, self.end = self.billing.get_date_range()
66
+            distil_client = distil.distilclient(self.request)
67
+            self.history = (distil.get_cost(self.request, distil_client))
68
+
69
+            self.kwargs['billing'] = self.billing
70
+            self.kwargs['current_month'] = self.history[-1][1]
71
+            self.kwargs['history'] = self.history
72
+            return self.history[-1][1]
73
+        except Exception:
74
+            exceptions.handle(self.request, _('Unable to get usage cost.'))
75
+            return []
76
+
77
+    def get_context_data(self, **kwargs):
78
+        context = super(IndexView, self).get_context_data(**kwargs)
79
+        context['table'].kwargs['billing'] = self.billing
80
+        context['form'] = self.billing.form
81
+        context['billing'] = self.billing
82
+        context['current_month'] = self.history[-1][1]
83
+        pie_data = [{"value": b.cost, "key": b.resource}
84
+                    for b in self.history[-1][1] if b.cost >= 0]
85
+        line_data = [{"values": [{"y": m[0], "x": i}
86
+                                 for i, m in enumerate(self.history)],
87
+                      "method": "Square Root Choice", "key": "Cost"}]
88
+        chart_data = {'pie': pie_data, 'line': line_data}
89
+        context['chart_data'] = json.dumps(chart_data)
90
+        context['amount_cost'] = self.history[-1][0]
91
+        context['cost_details'] = json.dumps(self.history[-1][2])
92
+        context['x_axis_line_chart'] = self._get_x_axis_for_line_chart()
93
+        return context
94
+
95
+    def _get_x_axis_for_line_chart(self):
96
+        today = datetime.date.today()
97
+        ordered_month = ['Jan ' + str(today.year), 'Feb', 'Mar', "Apr", 'May',
98
+                         'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
99
+
100
+        return ordered_month[today.month:] + ordered_month[:today.month]
101
+
102
+    def render_to_response(self, context, **response_kwargs):
103
+        if self.request.GET.get('format', 'html') == 'csv':
104
+            render_class = self.csv_response_class
105
+            fn_template = "usage_cost_{0}_{1}.csv"
106
+            filename = fn_template.format(self.start.strftime('%Y-%m-%d'),
107
+                                          self.end.strftime('%Y-%m-%d'))
108
+            response_kwargs.setdefault("filename", filename)
109
+        else:
110
+            render_class = self.response_class
111
+        resp = render_class(request=self.request,
112
+                            template=self.get_template_names(),
113
+                            context=context,
114
+                            content_type=self.get_content_type(),
115
+                            **response_kwargs)
116
+        return resp

+ 0
- 0
distil_ui/content/default/__init__.py View File


+ 24
- 0
distil_ui/content/default/panel.py View File

@@ -0,0 +1,24 @@
1
+# Copyright (c) 2014 Catalyst IT Ltd.
2
+#
3
+# Licensed under the Apache License, Version 2.0 (the "License");
4
+# you may not use this file except in compliance with the License.
5
+# You may obtain a copy of the License at
6
+#
7
+# http://www.apache.org/licenses/LICENSE-2.0
8
+#
9
+# Unless required by applicable law or agreed to in writing, software
10
+# distributed under the License is distributed on an "AS IS" BASIS,
11
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+# See the License for the specific language governing permissions and
13
+# limitations under the License.
14
+
15
+from django.utils.translation import ugettext_lazy as _
16
+
17
+import horizon
18
+
19
+
20
+class Default(horizon.Panel):
21
+    name = _("Default")
22
+    slug = 'default'
23
+    urls = 'openstack_dashboard.contrib.management.tickets.urls'
24
+    nav = False

+ 3
- 0
distil_ui/content/default/templates/default/base.html View File

@@ -0,0 +1,3 @@
1
+{% extends 'base.html' %}
2
+
3
+

+ 38
- 0
distil_ui/dashboard.py View File

@@ -0,0 +1,38 @@
1
+# Copyright (c) 2014 Catalyst IT Ltd.
2
+#
3
+# Licensed under the Apache License, Version 2.0 (the "License");
4
+# you may not use this file except in compliance with the License.
5
+# You may obtain a copy of the License at
6
+#
7
+# http://www.apache.org/licenses/LICENSE-2.0
8
+#
9
+# Unless required by applicable law or agreed to in writing, software
10
+# distributed under the License is distributed on an "AS IS" BASIS,
11
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+# See the License for the specific language governing permissions and
13
+# limitations under the License.
14
+
15
+from django.utils.translation import ugettext_lazy as _
16
+
17
+import horizon
18
+
19
+from distil_ui.content.billing import panel as billing_panel
20
+from distil_ui.content.default import panel as default_panel
21
+
22
+
23
+class ManagementDashboard(horizon.Dashboard):
24
+    name = _("Management")
25
+    slug = "management"
26
+    default_panel = 'default'
27
+
28
+try:
29
+    slugs = dict((d.slug, d) for d in horizon.get_dashboards())
30
+except Exception:
31
+    slugs = {}
32
+
33
+if 'management' not in slugs:
34
+    horizon.register(ManagementDashboard)
35
+    ManagementDashboard.register(default_panel.Default)
36
+    ManagementDashboard.register(billing_panel.Billing)
37
+else:
38
+    slugs.get('management').register(billing_panel.Billing)

+ 7
- 0
distil_ui/enabled/_6000_management.py View File

@@ -0,0 +1,7 @@
1
+# The name of the dashboard to be added to HORIZON['dashboards']. Required.
2
+DASHBOARD = 'management'
3
+
4
+# A list of applications to be added to INSTALLED_APPS.
5
+ADD_INSTALLED_APPS = [
6
+    'distil_ui.dashboard'
7
+]

+ 20
- 0
distil_ui/enabled/_6010_management_billing.py View File

@@ -0,0 +1,20 @@
1
+# Copyright 2017 Catalyst IT Ltd.
2
+#
3
+# Licensed under the Apache License, Version 2.0 (the "License");
4
+# you may not use this file except in compliance with the License.
5
+# You may obtain a copy of the License at
6
+#
7
+#    http://www.apache.org/licenses/LICENSE-2.0
8
+#
9
+# Unless required by applicable law or agreed to in writing, software
10
+# distributed under the License is distributed on an "AS IS" BASIS,
11
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+# See the License for the specific language governing permissions and
13
+# limitations under the License.
14
+
15
+PANEL = 'billing'
16
+PANEL_GROUP = 'default'
17
+PANEL_DASHBOARD = 'management'
18
+
19
+ADD_PANEL = ('distil_ui.content.billing.panel.Billing')
20
+ADD_INSTALLED_APPS = ['distil_ui']

+ 0
- 0
distil_ui/enabled/__init__.py View File


+ 155
- 0
distil_ui/karma.conf.js View File

@@ -0,0 +1,155 @@
1
+/*
2
+ * Licensed under the Apache License, Version 2.0 (the 'License');
3
+ * you may not use this file except in compliance with the License.
4
+ * You may obtain a copy of the License at
5
+ *
6
+ *    http://www.apache.org/licenses/LICENSE-2.0
7
+ *
8
+ * Unless required by applicable law or agreed to in writing, software
9
+ * distributed under the License is distributed on an 'AS IS' BASIS,
10
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11
+ * See the License for the specific language governing permissions and
12
+ * limitations under the License.
13
+ */
14
+
15
+'use strict';
16
+
17
+var fs = require('fs');
18
+var path = require('path');
19
+
20
+module.exports = function (config) {
21
+  // This tox venv is setup in the post-install npm step
22
+  var toxPath = '../.tox/py27/lib/python2.7/site-packages/';
23
+
24
+  config.set({
25
+    preprocessors: {
26
+      // Used to collect templates for preprocessing.
27
+      // NOTE: the templates must also be listed in the files section below.
28
+      './static/**/*.html': ['ng-html2js'],
29
+      // Used to indicate files requiring coverage reports.
30
+      './static/**/!(*.spec).js': ['coverage'],
31
+    },
32
+
33
+    // Sets up module to process templates.
34
+    ngHtml2JsPreprocessor: {
35
+      prependPrefix: '/',
36
+      moduleName: 'templates'
37
+    },
38
+
39
+    basePath: './',
40
+
41
+    // Contains both source and test files.
42
+    files: [
43
+      /*
44
+       * shim, partly stolen from /i18n/js/horizon/
45
+       * Contains expected items not provided elsewhere (dynamically by
46
+       * Django or via jasmine template.
47
+       */
48
+      '../test-shim.js',
49
+
50
+      // from jasmine.html
51
+      toxPath + 'xstatic/pkg/jquery/data/jquery.js',
52
+      toxPath + 'xstatic/pkg/angular/data/angular.js',
53
+      toxPath + 'xstatic/pkg/angular/data/angular-route.js',
54
+      toxPath + 'xstatic/pkg/angular/data/angular-mocks.js',
55
+      toxPath + 'xstatic/pkg/angular/data/angular-cookies.js',
56
+      toxPath + 'xstatic/pkg/angular_bootstrap/data/angular-bootstrap.js',
57
+      toxPath + 'xstatic/pkg/angular_gettext/data/angular-gettext.js',
58
+      toxPath + 'xstatic/pkg/angular/data/angular-sanitize.js',
59
+      toxPath + 'xstatic/pkg/d3/data/d3.js',
60
+      toxPath + 'xstatic/pkg/rickshaw/data/rickshaw.js',
61
+      toxPath + 'xstatic/pkg/angular_smart_table/data/smart-table.js',
62
+      toxPath + 'xstatic/pkg/angular_lrdragndrop/data/lrdragndrop.js',
63
+      toxPath + 'xstatic/pkg/spin/data/spin.js',
64
+      toxPath + 'xstatic/pkg/spin/data/spin.jquery.js',
65
+      toxPath + 'xstatic/pkg/tv4/data/tv4.js',
66
+      toxPath + 'xstatic/pkg/objectpath/data/ObjectPath.js',
67
+      toxPath + 'xstatic/pkg/angular_schema_form/data/schema-form.js',
68
+
69
+      // TODO: These should be mocked.
70
+      toxPath + '/horizon/static/horizon/js/horizon.js',
71
+
72
+      /**
73
+       * Include framework source code from horizon that we need.
74
+       * Otherwise, karma will not be able to find them when testing.
75
+       * These files should be mocked in the foreseeable future.
76
+       */
77
+      toxPath + 'horizon/static/framework/**/*.module.js',
78
+      toxPath + 'horizon/static/framework/**/!(*.spec|*.mock).js',
79
+      toxPath + 'openstack_dashboard/static/**/*.module.js',
80
+      toxPath + 'openstack_dashboard/static/**/!(*.spec|*.mock).js',
81
+      toxPath + 'openstack_dashboard/dashboards/**/static/**/*.module.js',
82
+      toxPath + 'openstack_dashboard/dashboards/**/static/**/!(*.spec|*.mock).js',
83
+
84
+      /**
85
+       * First, list all the files that defines application's angular modules.
86
+       * Those files have extension of `.module.js`. The order among them is
87
+       * not significant.
88
+       */
89
+      './static/**/*.module.js',
90
+
91
+      /**
92
+       * Followed by other JavaScript files that defines angular providers
93
+       * on the modules defined in files listed above. And they are not mock
94
+       * files or spec files defined below. The order among them is not
95
+       * significant.
96
+       */
97
+      './static/**/!(*.spec|*.mock).js',
98
+
99
+      /**
100
+       * Then, list files for mocks with `mock.js` extension. The order
101
+       * among them should not be significant.
102
+       */
103
+      toxPath + 'openstack_dashboard/static/**/*.mock.js',
104
+
105
+      /**
106
+       * Finally, list files for spec with `spec.js` extension. The order
107
+       * among them should not be significant.
108
+       */
109
+      './static/**/*.spec.js',
110
+
111
+      /**
112
+       * Angular external templates
113
+       */
114
+      './static/**/*.html'
115
+    ],
116
+
117
+    autoWatch: true,
118
+
119
+    frameworks: ['jasmine'],
120
+
121
+    browsers: ['PhantomJS'],
122
+
123
+    browserNoActivityTimeout: 60000,
124
+
125
+    phantomjsLauncher: {
126
+      // Have phantomjs exit if a ResourceError is encountered
127
+      // (useful if karma exits without killing phantom)
128
+      exitOnResourceError: true
129
+    },
130
+
131
+    reporters: ['progress', 'coverage', 'threshold'],
132
+
133
+    plugins: [
134
+      'karma-phantomjs-launcher',
135
+      'karma-jasmine',
136
+      'karma-ng-html2js-preprocessor',
137
+      'karma-coverage',
138
+      'karma-threshold-reporter'
139
+    ],
140
+
141
+    // Places coverage report in HTML format in the subdirectory below.
142
+    coverageReporter: {
143
+      type: 'html',
144
+      dir: '../cover/karma/'
145
+    },
146
+
147
+    // Coverage threshold values.
148
+    thresholdReporter: {
149
+      statements: 10, // target 100
150
+      branches: 0, // target 100
151
+      functions: 10, // target 100
152
+      lines: 10 // target 100
153
+    }
154
+  });
155
+};

+ 5
- 0
distil_ui/static/catalystdashboard/d3.min.js
File diff suppressed because it is too large
View File


+ 1
- 0
distil_ui/static/catalystdashboard/nv.d3.min.css
File diff suppressed because it is too large
View File


+ 6
- 0
distil_ui/static/catalystdashboard/nv.d3.min.js
File diff suppressed because it is too large
View File


+ 44
- 0
distil_ui/static/catalystdashboard/scss/style.css View File

@@ -0,0 +1,44 @@
1
+#line_chart .nv-lineChart circle.nv-point {
2
+    fill-opacity: 1;
3
+}
4
+
5
+#line_chart .nvd3 .nv-legend .nv-series {
6
+    cursor:default;
7
+}
8
+
9
+.form-horizontal label {
10
+    display: inline;
11
+    margin-bottom: 0;
12
+    margin-right: 5px;
13
+    font-weight: normal;
14
+}
15
+
16
+.pie {
17
+    width:100%;
18
+    height:360px
19
+}
20
+
21
+.line {
22
+    width:100%;
23
+    height:360px;
24
+}
25
+
26
+#billing .total {
27
+    font-size: 14px;
28
+    font-weight:bold;
29
+}
30
+
31
+.dot_line {
32
+    padding-bottom: 6px;
33
+    border-bottom: thin dotted #666;
34
+}
35
+
36
+@media screen and (max-width: 1025px) {
37
+    .row-fluid > [class*="span"] {
38
+        width:100% !important;
39
+    }
40
+
41
+    body {
42
+        min-width: 700px;
43
+    }
44
+}

+ 0
- 0
distil_ui/test/__init__.py View File


+ 0
- 0
distil_ui/test/api_tests/__init__.py View File


+ 28
- 0
distil_ui/test/api_tests/rest_api_tests.py View File

@@ -0,0 +1,28 @@
1
+# Licensed under the Apache License, Version 2.0 (the "License");
2
+# you may not use this file except in compliance with the License.
3
+# You may obtain a copy of the License at
4
+#
5
+#    http://www.apache.org/licenses/LICENSE-2.0
6
+#
7
+# Unless required by applicable law or agreed to in writing, software
8
+# distributed under the License is distributed on an "AS IS" BASIS,
9
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
10
+# See the License for the specific language governing permissions and
11
+# limitations under the License.
12
+
13
+import mock
14
+
15
+from openstack_dashboard.test.test_data import utils
16
+
17
+from distil_ui.test import test_data
18
+
19
+TEST = utils.TestData(test_data.data)
20
+
21
+
22
+def mock_resource(resource):
23
+    """Utility function to make mocking more DRY"""
24
+
25
+    mocked_data = \
26
+        [mock.Mock(**{'to_dict.return_value': item}) for item in resource]
27
+
28
+    return mocked_data

+ 20
- 0
distil_ui/test/helpers.py View File

@@ -0,0 +1,20 @@
1
+# Licensed under the Apache License, Version 2.0 (the "License");
2
+# you may not use this file except in compliance with the License.
3
+# You may obtain a copy of the License at
4
+#
5
+#    http://www.apache.org/licenses/LICENSE-2.0
6
+#
7
+# Unless required by applicable law or agreed to in writing, software
8
+# distributed under the License is distributed on an "AS IS" BASIS,
9
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
10
+# See the License for the specific language governing permissions and
11
+# limitations under the License.
12
+
13
+from openstack_dashboard.test import helpers
14
+
15
+
16
+class APITestCase(helpers.APITestCase):
17
+    """Extends the base Horizon APITestCase for distilclient"""
18
+
19
+    def setUp(self):
20
+        super(APITestCase, self).setUp()

+ 0
- 0
distil_ui/test/integration_tests/__init__.py View File


+ 38
- 0
distil_ui/test/settings.py View File

@@ -0,0 +1,38 @@
1
+# Licensed under the Apache License, Version 2.0 (the "License");
2
+# you may not use this file except in compliance with the License.
3
+# You may obtain a copy of the License at
4
+#
5
+#    http://www.apache.org/licenses/LICENSE-2.0
6
+#
7
+# Unless required by applicable law or agreed to in writing, software
8
+# distributed under the License is distributed on an "AS IS" BASIS,
9
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
10
+# See the License for the specific language governing permissions and
11
+# limitations under the License.
12
+
13
+# Default to Horizons test settings to avoid any missing keys
14
+from horizon.test.settings import *  # noqa
15
+from openstack_dashboard.test.settings import *  # noqa
16
+
17
+# Update the dashboards with distil_ui
18
+import openstack_dashboard.enabled
19
+from openstack_dashboard.utils import settings
20
+
21
+import distil_ui.enabled
22
+
23
+# pop these keys to avoid log warnings about deprecation
24
+# update_dashboards will populate them anyway
25
+HORIZON_CONFIG.pop('dashboards', None)
26
+HORIZON_CONFIG.pop('default_dashboard', None)
27
+
28
+settings.update_dashboards(
29
+    [
30
+        distil_ui.enabled,
31
+        openstack_dashboard.enabled,
32
+    ],
33
+    HORIZON_CONFIG,
34
+    INSTALLED_APPS
35
+)
36
+
37
+# Ensure any duplicate apps are removed after the update_dashboards call
38
+INSTALLED_APPS = list(set(INSTALLED_APPS))

+ 18
- 0
distil_ui/test/test_data.py View File

@@ -0,0 +1,18 @@
1
+# Licensed under the Apache License, Version 2.0 (the "License");
2
+# you may not use this file except in compliance with the License.
3
+# You may obtain a copy of the License at
4
+#
5
+#    http://www.apache.org/licenses/LICENSE-2.0
6
+#
7
+# Unless required by applicable law or agreed to in writing, software
8
+# distributed under the License is distributed on an "AS IS" BASIS,
9
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
10
+# See the License for the specific language governing permissions and
11
+# limitations under the License.
12
+
13
+from openstack_dashboard.test.test_data import utils
14
+
15
+
16
+def data(TEST):
17
+    # Test Data Container in Horizon
18
+    TEST.queues = utils.TestDataContainer()

+ 15
- 0
distil_ui/version.py View File

@@ -0,0 +1,15 @@
1
+#  Licensed under the Apache License, Version 2.0 (the "License"); you may
2
+#  not use this file except in compliance with the License. You may obtain
3
+#  a copy of the License at
4
+#
5
+#       http://www.apache.org/licenses/LICENSE-2.0
6
+#
7
+#  Unless required by applicable law or agreed to in writing, software
8
+#  distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
9
+#  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
10
+#  License for the specific language governing permissions and limitations
11
+#  under the License.
12
+
13
+import pbr.version
14
+
15
+version_info = pbr.version.VersionInfo('distil-ui')

+ 153
- 0
doc/Makefile View File

@@ -0,0 +1,153 @@
1
+# Makefile for Sphinx documentation
2
+#
3
+
4
+# You can set these variables from the command line.
5
+SPHINXOPTS    =
6
+SPHINXBUILD   = sphinx-build
7
+PAPER         =
8
+BUILDDIR      = build
9
+
10
+# Internal variables.
11
+PAPEROPT_a4     = -D latex_paper_size=a4
12
+PAPEROPT_letter = -D latex_paper_size=letter
13
+ALLSPHINXOPTS   = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) source
14
+# the i18n builder cannot share the environment and doctrees with the others
15
+I18NSPHINXOPTS  = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) source
16
+
17
+.PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext
18
+
19
+help:
20
+	@echo "Please use \`make <target>' where <target> is one of"
21
+	@echo "  html       to make standalone HTML files"
22
+	@echo "  dirhtml    to make HTML files named index.html in directories"
23
+	@echo "  singlehtml to make a single large HTML file"
24
+	@echo "  pickle     to make pickle files"
25
+	@echo "  json       to make JSON files"
26
+	@echo "  htmlhelp   to make HTML files and a HTML help project"
27
+	@echo "  qthelp     to make HTML files and a qthelp project"
28
+	@echo "  devhelp    to make HTML files and a Devhelp project"
29
+	@echo "  epub       to make an epub"
30
+	@echo "  latex      to make LaTeX files, you can set PAPER=a4 or PAPER=letter"
31
+	@echo "  latexpdf   to make LaTeX files and run them through pdflatex"
32
+	@echo "  text       to make text files"
33
+	@echo "  man        to make manual pages"
34
+	@echo "  texinfo    to make Texinfo files"
35
+	@echo "  info       to make Texinfo files and run them through makeinfo"
36
+	@echo "  gettext    to make PO message catalogs"
37
+	@echo "  changes    to make an overview of all changed/added/deprecated items"
38
+	@echo "  linkcheck  to check all external links for integrity"
39
+	@echo "  doctest    to run all doctests embedded in the documentation (if enabled)"
40
+
41
+clean:
42
+	-rm -rf $(BUILDDIR)/*
43
+
44
+html:
45
+	$(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html
46
+	@echo
47
+	@echo "Build finished. The HTML pages are in $(BUILDDIR)/html."
48
+
49
+dirhtml:
50
+	$(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml
51
+	@echo
52
+	@echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml."
53
+
54
+singlehtml:
55
+	$(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml
56
+	@echo
57
+	@echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml."
58
+
59
+pickle:
60
+	$(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle
61
+	@echo
62
+	@echo "Build finished; now you can process the pickle files."
63
+
64
+json:
65
+	$(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json
66
+	@echo
67
+	@echo "Build finished; now you can process the JSON files."
68
+
69
+htmlhelp:
70
+	$(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp
71
+	@echo
72
+	@echo "Build finished; now you can run HTML Help Workshop with the" \
73
+	      ".hhp project file in $(BUILDDIR)/htmlhelp."
74
+
75
+qthelp:
76
+	$(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp
77
+	@echo
78
+	@echo "Build finished; now you can run "qcollectiongenerator" with the" \
79
+	      ".qhcp project file in $(BUILDDIR)/qthelp, like this:"
80
+	@echo "# qcollectiongenerator $(BUILDDIR)/qthelp/Cisco.qhcp"
81
+	@echo "To view the help file:"
82
+	@echo "# assistant -collectionFile $(BUILDDIR)/qthelp/Cisco.qhc"
83
+
84
+devhelp:
85
+	$(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp
86
+	@echo
87
+	@echo "Build finished."
88
+	@echo "To view the help file:"
89
+	@echo "# mkdir -p $$HOME/.local/share/devhelp/Cisco"
90
+	@echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/Cisco"
91
+	@echo "# devhelp"
92
+
93
+epub:
94
+	$(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub
95
+	@echo
96
+	@echo "Build finished. The epub file is in $(BUILDDIR)/epub."
97
+
98
+latex:
99
+	$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
100
+	@echo
101
+	@echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex."
102
+	@echo "Run \`make' in that directory to run these through (pdf)latex" \
103
+	      "(use \`make latexpdf' here to do that automatically)."
104
+
105
+latexpdf:
106
+	$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
107
+	@echo "Running LaTeX files through pdflatex..."
108
+	$(MAKE) -C $(BUILDDIR)/latex all-pdf
109
+	@echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex."
110
+
111
+text:
112
+	$(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text
113
+	@echo
114
+	@echo "Build finished. The text files are in $(BUILDDIR)/text."
115
+
116
+man:
117
+	$(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man
118
+	@echo
119
+	@echo "Build finished. The manual pages are in $(BUILDDIR)/man."
120
+
121
+texinfo:
122
+	$(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
123
+	@echo
124
+	@echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo."
125
+	@echo "Run \`make' in that directory to run these through makeinfo" \
126
+	      "(use \`make info' here to do that automatically)."
127
+
128
+info:
129
+	$(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
130
+	@echo "Running Texinfo files through makeinfo..."
131
+	make -C $(BUILDDIR)/texinfo info
132
+	@echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo."
133
+
134
+gettext:
135
+	$(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale
136
+	@echo
137
+	@echo "Build finished. The message catalogs are in $(BUILDDIR)/locale."
138
+
139
+changes:
140
+	$(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes
141
+	@echo
142
+	@echo "The overview file is in $(BUILDDIR)/changes."
143
+
144
+linkcheck:
145
+	$(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck
146
+	@echo
147
+	@echo "Link check complete; look for any errors in the above output " \
148
+	      "or in $(BUILDDIR)/linkcheck/output.txt."
149
+
150
+doctest:
151
+	$(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest
152
+	@echo "Testing of doctests in the sources finished, look at the " \
153
+	      "results in $(BUILDDIR)/doctest/output.txt."

+ 441
- 0
doc/source/conf.py View File

@@ -0,0 +1,441 @@
1
+# Licensed under the Apache License, Version 2.0 (the "License"); you may
2
+# not use this file except in compliance with the License. You may obtain
3
+# a copy of the License at
4
+#
5
+#      http://www.apache.org/licenses/LICENSE-2.0
6
+#
7
+# Unless required by applicable law or agreed to in writing, software
8
+# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
9
+# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
10
+# License for the specific language governing permissions and limitations
11
+# under the License.
12
+#
13
+# Horizon documentation build configuration file, created by
14
+# sphinx-quickstart on Thu Oct 27 11:38:59 2011.
15
+#
16
+# This file is execfile()d with the current directory set to its
17
+# containing dir.
18
+#
19
+# Note that not all possible configuration values are present in this
20
+# autogenerated file.
21
+#
22
+# All configuration values have a default; values that are commented out
23
+# serve to show the default.
24
+
25
+from __future__ import print_function
26
+
27
+import os
28
+import subprocess
29
+import sys
30
+
31
+BASE_DIR = os.path.dirname(os.path.abspath(__file__))
32
+ROOT = os.path.abspath(os.path.join(BASE_DIR, "..", ".."))
33
+
34
+sys.path.insert(0, ROOT)
35
+
36
+# This is required for ReadTheDocs.org, but isn't a bad idea anyway.
37
+os.environ.setdefault('DJANGO_SETTINGS_MODULE',
38
+                      'openstack_dashboard.test.settings')
39
+
40
+from distil_ui \
41
+    import version as distilui_ver
42
+
43
+
44
+def write_autodoc_index():
45
+
46
+    def find_autodoc_modules(module_name, sourcedir):
47
+        """returns a list of modules in the SOURCE directory."""
48
+        modlist = []
49
+        os.chdir(os.path.join(sourcedir, module_name))
50
+        print("SEARCHING %s" % sourcedir)
51
+        for root, dirs, files in os.walk("."):
52
+            for filename in files:
53
+                if filename == 'tests.py':
54
+                    continue
55
+                if filename.endswith(".py"):
56
+                    # remove the pieces of the root
57
+                    elements = root.split(os.path.sep)
58
+                    # replace the leading "." with the module name
59
+                    elements[0] = module_name
60
+                    # and get the base module name
61
+                    base, extension = os.path.splitext(filename)
62
+                    if not (base == "__init__"):
63
+                        elements.append(base)
64
+                    result = ".".join(elements)
65
+                    # print result
66
+                    modlist.append(result)
67
+        return modlist
68
+
69
+    RSTDIR = os.path.abspath(os.path.join(BASE_DIR, "sourcecode"))
70
+    SRCS = [('distil_ui', ROOT), ]
71
+
72
+    EXCLUDED_MODULES = ()
73
+    CURRENT_SOURCES = {}
74
+
75
+    if not(os.path.exists(RSTDIR)):
76
+        os.mkdir(RSTDIR)
77
+    CURRENT_SOURCES[RSTDIR] = ['autoindex.rst']
78
+
79
+    INDEXOUT = open(os.path.join(RSTDIR, "autoindex.rst"), "w")
80
+    INDEXOUT.write("""
81
+=================
82
+Source Code Index
83
+=================
84
+
85
+.. contents::
86
+   :depth: 1
87
+   :local:
88
+
89
+""")
90
+
91
+    for modulename, path in SRCS:
92
+        sys.stdout.write("Generating source documentation for %s\n" %
93
+                         modulename)
94
+        INDEXOUT.write("\n%s\n" % modulename.capitalize())
95
+        INDEXOUT.write("%s\n" % ("=" * len(modulename),))
96
+        INDEXOUT.write(".. toctree::\n")
97
+        INDEXOUT.write("   :maxdepth: 1\n")
98
+        INDEXOUT.write("\n")
99
+
100
+        MOD_DIR = os.path.join(RSTDIR, modulename)
101
+        CURRENT_SOURCES[MOD_DIR] = []
102
+        if not(os.path.exists(MOD_DIR)):
103
+            os.mkdir(MOD_DIR)
104
+        for module in find_autodoc_modules(modulename, path):
105
+            if any([module.startswith(exclude) for exclude
106
+                   in EXCLUDED_MODULES]):
107
+                print("Excluded module %s." % module)
108
+                continue
109
+            mod_path = os.path.join(path, *module.split("."))
110
+            generated_file = os.path.join(MOD_DIR, "%s.rst" % module)
111
+
112
+            INDEXOUT.write("   %s/%s\n" % (modulename, module))
113
+
114
+            # Find the __init__.py module if this is a directory
115
+            if os.path.isdir(mod_path):
116
+                source_file = ".".join((os.path.join(mod_path, "__init__"),
117
+                                        "py",))
118
+            else:
119
+                source_file = ".".join((os.path.join(mod_path), "py"))
120
+
121
+            CURRENT_SOURCES[MOD_DIR].append("%s.rst" % module)
122
+            # Only generate a new file if the source has changed or we don't
123
+            # have a doc file to begin with.
124
+            if not os.access(generated_file, os.F_OK) or (
125
+                    os.stat(generated_file).st_mtime <
126
+                    os.stat(source_file).st_mtime):
127
+                print("Module %s updated, generating new documentation."
128
+                      % module)
129
+                FILEOUT = open(generated_file, "w")
130
+                header = "The :mod:`%s` Module" % module
131
+                FILEOUT.write("%s\n" % ("=" * len(header),))
132
+                FILEOUT.write("%s\n" % header)
133
+                FILEOUT.write("%s\n" % ("=" * len(header),))
134
+                FILEOUT.write(".. automodule:: %s\n" % module)
135
+                FILEOUT.write("  :members:\n")
136
+                FILEOUT.write("  :undoc-members:\n")
137
+                FILEOUT.write("  :show-inheritance:\n")
138
+                FILEOUT.write("  :noindex:\n")
139
+                FILEOUT.close()
140
+
141
+    INDEXOUT.close()
142
+
143
+    # Delete auto-generated .rst files for sources which no longer exist
144
+    for directory, subdirs, files in list(os.walk(RSTDIR)):
145
+        for old_file in files:
146
+            if old_file not in CURRENT_SOURCES.get(directory, []):
147
+                print("Removing outdated file for %s" % old_file)
148
+                os.remove(os.path.join(directory, old_file))
149
+
150
+
151
+write_autodoc_index()
152
+
153
+# If extensions (or modules to document with autodoc) are in another directory,
154
+# add these directories to sys.path here. If the directory is relative to the
155
+# documentation root, use os.path.abspath to make it absolute, like shown here.
156
+# sys.path.insert(0, os.path.abspath('.'))
157
+
158
+# -- General configuration ----------------------------------------------------
159
+
160
+# If your documentation needs a minimal Sphinx version, state it here.
161
+# needs_sphinx = '1.0'
162
+
163
+# Add any Sphinx extension module names here, as strings.
164
+# They can be extensions coming with Sphinx (named 'sphinx.ext.*')
165
+# or your custom ones.
166
+extensions = ['sphinx.ext.autodoc',
167
+              'sphinx.ext.todo',
168
+              'sphinx.ext.coverage',
169
+              'sphinx.ext.viewcode',
170
+              'oslosphinx',
171
+              ]
172
+
173
+# Add any paths that contain templates here, relative to this directory.
174
+templates_path = ['_templates']
175
+
176
+# The suffix of source filenames.
177
+source_suffix = '.rst'
178
+
179
+# The encoding of source files.
180
+# source_encoding = 'utf-8-sig'
181
+
182
+# The master toctree document.
183
+master_doc = 'index'
184
+
185
+# General information about the project.
186
+project = u'Distil UI'
187
+copyright = u'2017, Catalyst IT Ltd'
188
+
189
+# The version info for the project you're documenting, acts as replacement for
190
+# |version| and |release|, also used in various other places throughout the
191
+# built documents.
192
+#
193
+# The short X.Y version.
194
+version = distilui_ver.version_info.version_string()
195
+# The full version, including alpha/beta/rc tags.
196
+release = distilui_ver.version_info.release_string()
197
+
198
+# The language for content autogenerated by Sphinx. Refer to documentation
199
+# for a list of supported languages.
200
+# language = None
201
+
202
+# There are two options for replacing |today|: either, you set today to some
203
+# non-false value, then it is used:
204
+# today = ''
205
+# Else, today_fmt is used as the format for a strftime call.
206
+# today_fmt = '%B %d, %Y'
207
+
208
+# List of patterns, relative to source directory, that match files and
209
+# directories to ignore when looking for source files.
210
+exclude_patterns = ['**/#*', '**~', '**/#*#']
211
+
212
+# The reST default role (used for this markup: `text`)
213
+# to use for all documents.
214
+# default_role = None
215
+
216
+# If true, '()' will be appended to :func: etc. cross-reference text.
217
+# add_function_parentheses = True
218
+
219
+# If true, the current module name will be prepended to all description
220
+# unit titles (such as .. function::).
221
+# add_module_names = True
222
+
223
+# If true, sectionauthor and moduleauthor directives will be shown in the
224
+# output. They are ignored by default.
225
+show_authors = False
226
+
227
+# The name of the Pygments (syntax highlighting) style to use.
228
+pygments_style = 'sphinx'
229
+
230
+# A list of ignored prefixes for module index sorting.
231
+# modindex_common_prefix = []
232
+
233
+primary_domain = 'py'
234
+nitpicky = False
235
+
236
+
237
+# -- Options for HTML output --------------------------------------------------
238
+
239
+# The theme to use for HTML and HTML Help pages.  See the documentation for
240
+# a list of builtin themes.
241
+# html_theme_path = ['.']
242
+# html_theme = '_theme'
243
+
244
+# Theme options are theme-specific and customize the look and feel of a theme
245
+# further.  For a list of options available for each theme, see the
246
+# documentation.
247
+html_theme_options = {
248
+    "nosidebar": "false"
249
+}
250
+
251
+# Add any paths that contain custom themes here, relative to this directory.
252
+# html_theme_path = []
253
+
254
+# The name for this set of Sphinx documents.  If None, it defaults to
255
+# "<project> v<release> documentation".
256
+# html_title = None
257
+
258
+# A shorter title for the navigation bar.  Default is the same as html_title.
259
+# html_short_title = None
260
+
261
+# The name of an image file (relative to this directory) to place at the top
262
+# of the sidebar.
263
+# html_logo = None
264
+
265
+# The name of an image file (within the static path) to use as favicon of the
266
+# docs.  This file should be a Windows icon file (.ico) being 16x16 or 32x32
267
+# pixels large.
268
+# html_favicon = None
269
+
270
+# Add any paths that contain custom static files (such as style sheets) here,
271
+# relative to this directory. They are copied after the builtin static files,
272
+# so a file named "default.css" will overwrite the builtin "default.css".
273
+html_static_path = ['_static']
274
+
275
+# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
276
+# using the given strftime format.
277
+# html_last_updated_fmt = '%b %d, %Y'
278
+git_cmd = ["git", "log", "--pretty=format:'%ad, commit %h'", "--date=local",
279
+           "-n1"]
280
+html_last_updated_fmt = subprocess.check_output(git_cmd,
281
+                                                stdin=subprocess.PIPE)
282
+
283
+# If true, SmartyPants will be used to convert quotes and dashes to
284
+# typographically correct entities.
285
+# html_use_smartypants = True
286
+
287
+# Custom sidebar templates, maps document names to template names.
288
+# html_sidebars = {}
289
+
290
+# Additional templates that should be rendered to pages, maps page names to
291
+# template names.
292
+# html_additional_pages = {}
293
+
294
+# If false, no module index is generated.
295
+# html_domain_indices = True
296
+
297
+# If false, no index is generated.
298
+# html_use_index = True
299
+
300
+# If true, the index is split into individual pages for each letter.
301
+# html_split_index = False
302
+
303
+# If true, links to the reST sources are added to the pages.
304
+# html_show_sourcelink = True
305
+
306
+# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
307
+# html_show_sphinx = True
308
+
309
+# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
310
+# html_show_copyright = True
311
+
312
+# If true, an OpenSearch description file will be output, and all pages will
313
+# contain a <link> tag referring to it.  The value of this option must be the
314
+# base URL from which the finished HTML is served.
315
+# html_use_opensearch = ''
316
+
317
+# This is the file name suffix for HTML files (e.g. ".xhtml").
318
+# html_file_suffix = None
319
+
320
+# Output file base name for HTML help builder.
321
+htmlhelp_basename = 'Horizondoc'
322
+
323
+
324
+# -- Options for LaTeX output -------------------------------------------------
325
+
326
+latex_elements = {
327
+    # The paper size ('letterpaper' or 'a4paper').
328
+    # 'papersize': 'letterpaper',
329
+
330
+    # The font size ('10pt', '11pt' or '12pt').
331
+    # 'pointsize': '10pt',
332
+
333
+    # Additional stuff for the LaTeX preamble.
334
+    # 'preamble': '',
335
+}
336
+
337
+# Grouping the document tree into LaTeX files. List of tuples
338
+# (source start file, target name, title, author, documentclass
339
+# [howto/manual]).
340
+latex_documents = [
341
+    ('index', 'Horizon.tex', u'Horizon Documentation',
342
+     u'OpenStack Foundation', 'manual'),
343
+]
344
+
345
+# The name of an image file (relative to this directory) to place at the top of
346
+# the title page.
347
+# latex_logo = None
348
+
349
+# For "manual" documents, if this is true, then toplevel headings are parts,
350
+# not chapters.
351
+# latex_use_parts = False
352
+
353
+# If true, show page references after internal links.
354
+# latex_show_pagerefs = False
355
+
356
+# If true, show URL addresses after external links.
357
+# latex_show_urls = False
358
+
359
+# Documents to append as an appendix to all manuals.
360
+# latex_appendices = []
361
+
362
+# If false, no module index is generated.
363
+# latex_domain_indices = True
364
+
365
+
366
+# -- Options for manual page output -------------------------------------------
367
+
368
+# One entry per manual page. List of tuples
369
+# (source start file, name, description, authors, manual section).
370
+man_pages = [
371
+    ('index', u'Distil UI Documentation',
372
+     'Documentation for the Distil UI plugin to the OpenStack\
373
+      Dashboard (Horizon)',
374
+     [u'OpenStack'], 1)
375
+]
376
+
377
+# If true, show URL addresses after external links.
378
+# man_show_urls = False
379
+
380
+
381
+# -- Options for Texinfo output -----------------------------------------------
382
+
383
+# Grouping the document tree into Texinfo files. List of tuples
384
+# (source start file, target name, title, author,
385
+#  dir menu entry, description, category)
386
+texinfo_documents = [
387
+    ('index', 'Horizon', u'Horizon Documentation', u'OpenStack',
388
+     'Horizon', 'One line description of project.', 'Miscellaneous'),
389
+]
390
+
391
+# Documents to append as an appendix to all manuals.
392
+# texinfo_appendices = []
393
+
394
+# If false, no module index is generated.
395
+# texinfo_domain_indices = True
396
+
397
+# How to display URL addresses: 'footnote', 'no', or 'inline'.
398
+# texinfo_show_urls = 'footnote'
399
+
400
+
401
+# -- Options for Epub output --------------------------------------------------
402
+
403
+# Bibliographic Dublin Core info.
404
+epub_title = u'Horizon'
405
+epub_author = u'OpenStack'
406
+epub_publisher = u'OpenStack'
407
+epub_copyright = u'2012, OpenStack'
408
+
409
+# The language of the text. It defaults to the language option
410
+# or en if the language is not set.
411
+# epub_language = ''
412
+
413
+# The scheme of the identifier. Typical schemes are ISBN or URL.
414
+# epub_scheme = ''
415
+
416
+# The unique identifier of the text. This can be an ISBN number
417
+# or the project homepage.
418
+# epub_identifier = ''
419
+
420
+# A unique identification for the text.
421
+# epub_uid = ''
422
+
423
+# A tuple containing the cover image and cover page html template filenames.
424
+# epub_cover = ()
425
+
426
+# HTML files that should be inserted before the pages created by sphinx.
427
+# The format is a list of tuples containing the path and title.
428
+# epub_pre_files = []
429
+
430
+# HTML files shat should be inserted after the pages created by sphinx.
431
+# The format is a list of tuples containing the path and title.
432
+# epub_post_files = []
433
+
434
+# A list of files that should not be packed into the epub file.
435
+# epub_exclude_files = []
436
+