102 | {%- endblock %}
103 |
104 | {%- block footer %}
105 |
125 | {%- endblock %}
126 |
127 |
--------------------------------------------------------------------------------
/tests/test_heart_rest.py:
--------------------------------------------------------------------------------
1 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
2 |
3 | # Nova Billing
4 | # Copyright (C) GridDynamics Openstack Core Team, GridDynamics
5 | #
6 | # This program is free software: you can redistribute it and/or modify
7 | # it under the terms of the GNU General Public License as published by
8 | # the Free Software Foundation, either version 3 of the License, or
9 | # (at your option) any later version.
10 | #
11 | # This program is distributed in the hope that it will be useful,
12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 | # GNU General Public License for more details.
15 | #
16 | # You should have received a copy of the GNU General Public License
17 | # along with this program. If not, see .
18 |
19 | """
20 | Tests for nova_billing.rest
21 | """
22 |
23 | import os
24 | import sys
25 | import json
26 | import datetime
27 | import unittest
28 | import stubout
29 | import tempfile
30 |
31 | import routes
32 | import webob
33 |
34 | sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
35 | import tests
36 |
37 |
38 | from nova_billing import utils
39 |
40 | from nova_billing.heart import app
41 | from nova_billing.heart.database import db
42 |
43 |
44 | class TestCase(tests.TestCase):
45 |
46 | def setUp(self):
47 | super(TestCase, self).setUp()
48 | self.db_fd, self.db_filename = tempfile.mkstemp()
49 | app.config['SQLALCHEMY_DATABASE_URI'] = "sqlite:////" + self.db_filename
50 | app.config['TESTING'] = True
51 | self.app_client = app.test_client()
52 | db.create_all()
53 |
54 | def tearDown(self):
55 | os.close(self.db_fd)
56 | os.unlink(self.db_filename)
57 | super(TestCase, self).tearDown()
58 |
59 | def assertSuccess(self, res):
60 | self.assertEqual(res.status_code / 100, 2)
61 |
62 | def populate_db(self):
63 | res = self.app_client.post(
64 | "/tariff",
65 | data=json.dumps(self.json_load_from_file("rest.tariff.in.json")),
66 | content_type=utils.ContentType.JSON)
67 | self.assertSuccess(res)
68 | for filename in ("os_amqp.instances.out.json",
69 | "os_amqp.local_volumes.out.json"):
70 | json_out = self.json_load_from_file(filename)
71 | for event in json_out:
72 | res = self.app_client.post(
73 | "/event",
74 | data=json.dumps(event),
75 | content_type=utils.ContentType.JSON)
76 | self.assertSuccess(res)
77 |
78 | def fake_now(self):
79 | return datetime.datetime(2011, 1, 1)
80 |
81 | def test_version(self):
82 | res = self.app_client.get("/version")
83 | self.assertSuccess(res)
84 |
85 | def test_tariff(self):
86 | res = self.app_client.post(
87 | "/tariff",
88 | data=json.dumps(self.json_load_from_file("rest.tariff.in.json")),
89 | content_type=utils.ContentType.JSON)
90 | self.assertSuccess(res)
91 | self.json_check_with_file(json.loads(res.data),
92 | "rest.tariff.out.json")
93 |
94 | def test_account(self):
95 | self.populate_db()
96 | res = self.app_client.get("/account")
97 | self.assertSuccess(res)
98 | self.json_check_with_file(json.loads(res.data),
99 | "rest.account.out.json")
100 |
101 | def test_resource(self):
102 | self.populate_db()
103 | res = self.app_client.get("/resource")
104 | self.assertSuccess(res)
105 | self.json_check_with_file(json.loads(res.data),
106 | "rest.resource.out.json")
107 |
108 | def test_resource_filter(self):
109 | self.populate_db()
110 | res = self.app_client.get("/resource?rtype=nova/instance")
111 | self.assertSuccess(res)
112 | self.json_check_with_file(json.loads(res.data),
113 | "rest.resource_filter.out.json")
114 |
115 | def test_bill(self):
116 | self.stubs.Set(utils, "now", self.fake_now)
117 | self.populate_db()
118 | res = self.app_client.get("/bill")
119 | self.assertSuccess(res)
120 | self.json_check_with_file(json.loads(res.data),
121 | "rest.bill.out.json")
122 | self.stubs.UnsetAll()
123 |
--------------------------------------------------------------------------------
/tests/os_amqp.instances.in.json:
--------------------------------------------------------------------------------
1 | {
2 | "run": {
3 | "_context_roles": [
4 | "projectmanager"
5 | ],
6 | "_context_request_id": "29615116-ddd0-4a20-8018-ef5f90f8bdf3",
7 | "args": {
8 | "request_spec": {
9 | "num_instances": 1,
10 | "image": {
11 | "status": "active",
12 | "deleted": false,
13 | "container_format": "ami",
14 | "updated_at": "2011-12-05 12:15:26.659439",
15 | "is_public": true,
16 | "deleted_at": null,
17 | "properties": {
18 | "kernel_id": "2",
19 | "owner": null,
20 | "min_ram": "0",
21 | "ramdisk_id": "1",
22 | "min_disk": "0"
23 | },
24 | "size": 216858624,
25 | "name": "SL61",
26 | "checksum": "ecd1d23a8039b72812db4fee5a11a547",
27 | "created_at": "2011-12-05 12:15:25.541042",
28 | "disk_format": "ami",
29 | "id": 4,
30 | "location": "file:///var/lib/glance/images/4"
31 | },
32 | "filter": null,
33 | "instance_type": {
34 | "rxtx_quota": 0,
35 | "deleted": false,
36 | "updated_at": null,
37 | "extra_specs": {},
38 | "local_gb": 20,
39 | "id": 5,
40 | "deleted_at": null,
41 | "name": "m1.small",
42 | "flavorid": 2,
43 | "created_at": null,
44 | "memory_mb": 2048,
45 | "vcpus": 1,
46 | "rxtx_cap": 0,
47 | "swap": 0
48 | },
49 | "blob": null,
50 | "instance_properties": {
51 | "vm_state": "building",
52 | "availability_zone": null,
53 | "ramdisk_id": "1",
54 | "instance_type_id": 5,
55 | "user_data": "",
56 | "vm_mode": null,
57 | "reservation_id": "r-851pambx",
58 | "user_id": "admin",
59 | "display_description": null,
60 | "key_data": null,
61 | "power_state": 0,
62 | "project_id": "systenant",
63 | "metadata": {},
64 | "access_ip_v6": null,
65 | "access_ip_v4": null,
66 | "kernel_id": "2",
67 | "key_name": null,
68 | "display_name": null,
69 | "config_drive_id": "",
70 | "local_gb": 20,
71 | "architecture": null,
72 | "locked": false,
73 | "launch_time": "2011-12-06T19:12:57Z",
74 | "memory_mb": 2048,
75 | "vcpus": 1,
76 | "image_ref": 4,
77 | "root_device_name": null,
78 | "os_type": null,
79 | "config_drive": ""
80 | }
81 | },
82 | "requested_networks": null,
83 | "availability_zone": null,
84 | "instance_id": 16,
85 | "admin_password": null,
86 | "injected_files": null
87 | },
88 | "_context_auth_token": null,
89 | "_context_user_id": "admin",
90 | "_context_read_deleted": false,
91 | "_context_strategy": "noauth",
92 | "_context_is_admin": true,
93 | "_context_project_id": "systenant",
94 | "_context_timestamp": "2011-12-06T19:12:57.805503",
95 | "method": "run_instance",
96 | "_context_remote_address": "128.107.79.131"
97 | },
98 | "any": {
99 | "_context_auth_token": null,
100 | "_context_strategy": "noauth",
101 | "_context_is_admin": true,
102 | "_context_read_deleted": false,
103 | "_context_project_id": "systenant",
104 | "_context_timestamp": "2011-12-06T19:12:57.805503",
105 | "_context_user_id": "admin",
106 | "args": {
107 | "instance_id": 16
108 | },
109 | "method": "start_instance",
110 | "_context_remote_address": "128.107.79.131"
111 | }
112 | }
--------------------------------------------------------------------------------
/nova_billing/os_amqp/instances.py:
--------------------------------------------------------------------------------
1 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
2 |
3 | # Nova Billing
4 | # Copyright (C) GridDynamics Openstack Core Team, GridDynamics
5 | #
6 | # This program is free software: you can redistribute it and/or modify
7 | # it under the terms of the GNU General Public License as published by
8 | # the Free Software Foundation, either version 3 of the License, or
9 | # (at your option) any later version.
10 | #
11 | # This program is distributed in the hope that it will be useful,
12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 | # GNU General Public License for more details.
15 | #
16 | # You should have received a copy of the GNU General Public License
17 | # along with this program. If not, see .
18 |
19 | import logging
20 | from nova_billing import utils
21 | from nova_billing.utils import global_conf
22 |
23 |
24 | LOG = logging.getLogger(__name__)
25 |
26 |
27 | class vm_states(object):
28 | ACTIVE = 0
29 | BUILDING = 1
30 | REBUILDING = 2
31 |
32 | PAUSED = 3
33 | SUSPENDED = 4
34 | RESCUED = 5
35 | DELETED = 6
36 | STOPPED = 7
37 |
38 | MIGRATING = 8
39 | RESIZING = 9
40 |
41 | ERROR = 10
42 |
43 |
44 | used_resources = {
45 | vm_states.ACTIVE: ("memory_mb", "vcpus", "local_gb"),
46 | vm_states.SUSPENDED: ("memory_mb", "local_gb"),
47 | vm_states.PAUSED: ("memory_mb", "local_gb"),
48 | vm_states.STOPPED: ("local_gb", ),
49 | }
50 |
51 |
52 | target_state = {
53 | "run_instance": vm_states.ACTIVE,
54 | "terminate_instance": vm_states.DELETED,
55 | "start_instance": vm_states.ACTIVE,
56 | "stop_instance": vm_states.STOPPED,
57 | "unpause_instance": vm_states.ACTIVE,
58 | "pause_instance": vm_states.PAUSED,
59 | "resume_instance": vm_states.ACTIVE,
60 | "suspend_instance": vm_states.SUSPENDED,
61 | }
62 |
63 |
64 | nova_client = utils.get_nova_client()
65 |
66 | # Cache flavors here
67 | flavors = {}
68 | no_flavor = {
69 | "name": "",
70 | "local_gb": 0,
71 | "memory_mb": 0,
72 | "vcpus": 0,
73 | }
74 |
75 | def get_flavor(flavor_id):
76 | try:
77 | return flavors[flavor_id]
78 | except KeyError:
79 | pass
80 | try:
81 | flav = nova_client.flavors.get(flavor_id)
82 | except:
83 | return no_flavor
84 | flav = {
85 | "name": flav.name,
86 | "local_gb": flav.disk,
87 | "memory_mb": flav.ram,
88 | "vcpus": flav.vcpus,
89 | }
90 | flavors[flavor_id] = flav
91 | return flav
92 |
93 |
94 | def get_instance_flavor(instance_id):
95 | try:
96 | return get_flavor(
97 | nova_client.servers.get(instance_id).flavor["id"])
98 | except:
99 | return no_flavor
100 |
101 |
102 | def create_heart_request(method, body):
103 | try:
104 | state = target_state[method]
105 | except KeyError:
106 | return None
107 |
108 | heart_request = {"rtype": "nova/instance"}
109 |
110 | release = getattr(global_conf, "os_release", None)
111 | checked_keys = {"diablo": ("instance_id", ),
112 | "essex": ("instance_uuid", )}
113 | checked_keys = checked_keys.get(release, ("instance_uuid", "instance_id"))
114 | for key in checked_keys:
115 | try:
116 | heart_request["name"] = body["args"][key]
117 | break
118 | except KeyError:
119 | pass
120 | if "name" not in heart_request:
121 | LOG.error("cannot find keys %s (maybe incorrect OpenStack release)" %
122 | (checked_keys, ))
123 | return None
124 |
125 | child_keys = ("local_gb", "memory_mb", "vcpus")
126 | if method == "terminate_instance":
127 | heart_request["fixed"] = None
128 | heart_request["children"] = [
129 | {"rtype": key, "fixed": None}
130 | for key in child_keys]
131 | else:
132 | used = used_resources[state]
133 | try:
134 | flav = body["args"]["request_spec"]["instance_type"]
135 | except KeyError:
136 | flav = get_instance_flavor(heart_request["name"])
137 | if method == "run_instance":
138 | heart_request["fixed"] = 0
139 | heart_request["attrs"] = {"instance_type": flav["name"]}
140 | else:
141 | child_keys = child_keys[1:]
142 | heart_request["children"] = [
143 | {"rtype": key, "linear": flav[key] if key in used else 0}
144 | for key in child_keys
145 | ]
146 | return heart_request
147 |
--------------------------------------------------------------------------------
/doc/Makefile:
--------------------------------------------------------------------------------
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 |
15 | .PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest
16 |
17 | help:
18 | @echo "Please use \`make ' where is one of"
19 | @echo " html to make standalone HTML files"
20 | @echo " dirhtml to make HTML files named index.html in directories"
21 | @echo " singlehtml to make a single large HTML file"
22 | @echo " pickle to make pickle files"
23 | @echo " json to make JSON files"
24 | @echo " htmlhelp to make HTML files and a HTML help project"
25 | @echo " qthelp to make HTML files and a qthelp project"
26 | @echo " devhelp to make HTML files and a Devhelp project"
27 | @echo " epub to make an epub"
28 | @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter"
29 | @echo " latexpdf to make LaTeX files and run them through pdflatex"
30 | @echo " text to make text files"
31 | @echo " man to make manual pages"
32 | @echo " changes to make an overview of all changed/added/deprecated items"
33 | @echo " linkcheck to check all external links for integrity"
34 | @echo " doctest to run all doctests embedded in the documentation (if enabled)"
35 |
36 | clean:
37 | -rm -rf $(BUILDDIR)/*
38 |
39 | html:
40 | $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html
41 | @echo
42 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/html."
43 |
44 | dirhtml:
45 | $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml
46 | @echo
47 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml."
48 |
49 | singlehtml:
50 | $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml
51 | @echo
52 | @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml."
53 |
54 | pickle:
55 | $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle
56 | @echo
57 | @echo "Build finished; now you can process the pickle files."
58 |
59 | json:
60 | $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json
61 | @echo
62 | @echo "Build finished; now you can process the JSON files."
63 |
64 | htmlhelp:
65 | $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp
66 | @echo
67 | @echo "Build finished; now you can run HTML Help Workshop with the" \
68 | ".hhp project file in $(BUILDDIR)/htmlhelp."
69 |
70 | qthelp:
71 | $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp
72 | @echo
73 | @echo "Build finished; now you can run "qcollectiongenerator" with the" \
74 | ".qhcp project file in $(BUILDDIR)/qthelp, like this:"
75 | @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/nova-billing.qhcp"
76 | @echo "To view the help file:"
77 | @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/nova-billing.qhc"
78 |
79 | devhelp:
80 | $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp
81 | @echo
82 | @echo "Build finished."
83 | @echo "To view the help file:"
84 | @echo "# mkdir -p $$HOME/.local/share/devhelp/nova-billing"
85 | @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/nova-billing"
86 | @echo "# devhelp"
87 |
88 | epub:
89 | $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub
90 | @echo
91 | @echo "Build finished. The epub file is in $(BUILDDIR)/epub."
92 |
93 | latex:
94 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
95 | @echo
96 | @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex."
97 | @echo "Run \`make' in that directory to run these through (pdf)latex" \
98 | "(use \`make latexpdf' here to do that automatically)."
99 |
100 | latexpdf:
101 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
102 | @echo "Running LaTeX files through pdflatex..."
103 | make -C $(BUILDDIR)/latex all-pdf
104 | @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex."
105 |
106 | text:
107 | $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text
108 | @echo
109 | @echo "Build finished. The text files are in $(BUILDDIR)/text."
110 |
111 | man:
112 | $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man
113 | @echo
114 | @echo "Build finished. The manual pages are in $(BUILDDIR)/man."
115 |
116 | changes:
117 | $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes
118 | @echo
119 | @echo "The overview file is in $(BUILDDIR)/changes."
120 |
121 | linkcheck:
122 | $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck
123 | @echo
124 | @echo "Link check complete; look for any errors in the above output " \
125 | "or in $(BUILDDIR)/linkcheck/output.txt."
126 |
127 | doctest:
128 | $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest
129 | @echo "Testing of doctests in the sources finished, look at the " \
130 | "results in $(BUILDDIR)/doctest/output.txt."
131 |
--------------------------------------------------------------------------------
/tests/os_amqp.instances.out.json:
--------------------------------------------------------------------------------
1 | [
2 | {
3 | "account": "systenant",
4 | "name": 16,
5 | "datetime": "2011-01-02T00:00:00Z",
6 | "attrs": {
7 | "instance_type": "m1.small"
8 | },
9 | "fixed": 0,
10 | "rtype": "nova/instance",
11 | "children": [
12 | {
13 | "rtype": "local_gb",
14 | "linear": 20
15 | },
16 | {
17 | "rtype": "memory_mb",
18 | "linear": 2048
19 | },
20 | {
21 | "rtype": "vcpus",
22 | "linear": 1
23 | }
24 | ]
25 | },
26 | {
27 | "account": "systenant",
28 | "datetime": "2011-01-03T00:00:00Z",
29 | "rtype": "nova/instance",
30 | "name": 16,
31 | "children": [
32 | {
33 | "rtype": "memory_mb",
34 | "linear": 0
35 | },
36 | {
37 | "rtype": "vcpus",
38 | "linear": 0
39 | }
40 | ]
41 | },
42 | {
43 | "account": "systenant",
44 | "datetime": "2011-01-04T00:00:00Z",
45 | "rtype": "nova/instance",
46 | "name": 16,
47 | "children": [
48 | {
49 | "rtype": "memory_mb",
50 | "linear": 2048
51 | },
52 | {
53 | "rtype": "vcpus",
54 | "linear": 1
55 | }
56 | ]
57 | },
58 | {
59 | "account": "systenant",
60 | "datetime": "2011-01-05T00:00:00Z",
61 | "rtype": "nova/instance",
62 | "name": 16,
63 | "children": [
64 | {
65 | "rtype": "memory_mb",
66 | "linear": 2048
67 | },
68 | {
69 | "rtype": "vcpus",
70 | "linear": 0
71 | }
72 | ]
73 | },
74 | {
75 | "account": "systenant",
76 | "datetime": "2011-01-06T00:00:00Z",
77 | "rtype": "nova/instance",
78 | "name": 16,
79 | "children": [
80 | {
81 | "rtype": "memory_mb",
82 | "linear": 2048
83 | },
84 | {
85 | "rtype": "vcpus",
86 | "linear": 1
87 | }
88 | ]
89 | },
90 | {
91 | "account": "systenant",
92 | "datetime": "2011-01-07T00:00:00Z",
93 | "rtype": "nova/instance",
94 | "name": 16,
95 | "children": [
96 | {
97 | "rtype": "memory_mb",
98 | "linear": 2048
99 | },
100 | {
101 | "rtype": "vcpus",
102 | "linear": 0
103 | }
104 | ]
105 | },
106 | {
107 | "account": "systenant",
108 | "datetime": "2011-01-08T00:00:00Z",
109 | "rtype": "nova/instance",
110 | "name": 16,
111 | "children": [
112 | {
113 | "rtype": "memory_mb",
114 | "linear": 2048
115 | },
116 | {
117 | "rtype": "vcpus",
118 | "linear": 1
119 | }
120 | ]
121 | },
122 | {
123 | "account": "systenant",
124 | "name": 16,
125 | "datetime": "2011-01-09T00:00:00Z",
126 | "fixed": null,
127 | "rtype": "nova/instance",
128 | "children": [
129 | {
130 | "fixed": null,
131 | "rtype": "local_gb"
132 | },
133 | {
134 | "fixed": null,
135 | "rtype": "memory_mb"
136 | },
137 | {
138 | "fixed": null,
139 | "rtype": "vcpus"
140 | }
141 | ]
142 | },
143 | {
144 | "account": "systenant",
145 | "name": 16,
146 | "datetime": "2011-01-10T00:00:00Z",
147 | "attrs": {
148 | "instance_type": "m1.small"
149 | },
150 | "fixed": 0,
151 | "rtype": "nova/instance",
152 | "children": [
153 | {
154 | "rtype": "local_gb",
155 | "linear": 20
156 | },
157 | {
158 | "rtype": "memory_mb",
159 | "linear": 2048
160 | },
161 | {
162 | "rtype": "vcpus",
163 | "linear": 1
164 | }
165 | ]
166 | },
167 | {
168 | "account": "systenant",
169 | "datetime": "2011-01-11T00:00:00Z",
170 | "rtype": "nova/instance",
171 | "name": 16,
172 | "children": [
173 | {
174 | "rtype": "memory_mb",
175 | "linear": 0
176 | },
177 | {
178 | "rtype": "vcpus",
179 | "linear": 0
180 | }
181 | ]
182 | },
183 | {
184 | "account": "systenant",
185 | "datetime": "2011-01-12T00:00:00Z",
186 | "rtype": "nova/instance",
187 | "name": 16,
188 | "children": [
189 | {
190 | "rtype": "memory_mb",
191 | "linear": 2048
192 | },
193 | {
194 | "rtype": "vcpus",
195 | "linear": 1
196 | }
197 | ]
198 | }
199 | ]
--------------------------------------------------------------------------------
/nova_billing/os_amqp/amqp.py:
--------------------------------------------------------------------------------
1 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
2 |
3 | # Nova Billing
4 | # Copyright (C) GridDynamics Openstack Core Team, GridDynamics
5 | #
6 | # This program is free software: you can redistribute it and/or modify
7 | # it under the terms of the GNU General Public License as published by
8 | # the Free Software Foundation, either version 3 of the License, or
9 | # (at your option) any later version.
10 | #
11 | # This program is distributed in the hope that it will be useful,
12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 | # GNU General Public License for more details.
15 | #
16 | # You should have received a copy of the GNU General Public License
17 | # along with this program. If not, see .
18 |
19 | """
20 | OpenStack AMQP listener
21 | """
22 |
23 | import time
24 | import socket
25 | import logging
26 |
27 | import eventlet
28 |
29 | import kombu.entity
30 | import kombu.messaging
31 | import kombu.connection
32 |
33 | from nova_billing import utils
34 | from nova_billing.utils import global_conf
35 |
36 | from . import instances
37 | from . import volumes
38 |
39 |
40 | LOG = logging.getLogger(__name__)
41 |
42 |
43 | class Service(object):
44 | billing_heart = utils.get_heart_client()
45 | heart_request_interceptors = (
46 | instances.create_heart_request,
47 | volumes.create_heart_request,
48 | )
49 | """
50 | Class of AMQP listening service.
51 | Usually this service starts at the beginning of the billing daemon
52 | and starts listening immediately. In case of connection errors
53 | reconnection attempts will be made periodically.
54 |
55 | The service listens for ``compute.#`` routing keys.
56 | """
57 | def __init__(self):
58 | self.params = dict(hostname=global_conf.rabbit_host,
59 | port=global_conf.rabbit_port,
60 | userid=global_conf.rabbit_userid,
61 | password=global_conf.rabbit_password,
62 | virtual_host=global_conf.rabbit_virtual_host)
63 | self.connection = None
64 |
65 | def reconnect(self):
66 | if self.connection:
67 | try:
68 | self.connection.close()
69 | except self.connection.connection_errors:
70 | pass
71 | time.sleep(1)
72 |
73 | self.connection = kombu.connection.BrokerConnection(**self.params)
74 |
75 | options = {
76 | "durable": global_conf.rabbit_durable_queues,
77 | "auto_delete": False,
78 | "exclusive": False
79 | }
80 |
81 | exchange = kombu.entity.Exchange(
82 | name=global_conf.control_exchange,
83 | type="topic",
84 | durable=options["durable"],
85 | auto_delete=options["auto_delete"])
86 | self.channel = self.connection.channel()
87 |
88 | self.queue = kombu.entity.Queue(
89 | name="nova_billing",
90 | exchange=exchange,
91 | routing_key="compute.#",
92 | channel=self.channel,
93 | **options)
94 | LOG.debug("Created kombu connection: %s" % self.params)
95 |
96 | def process_message(self, body, message):
97 | try:
98 | self.process_event(body, message)
99 | except:
100 | LOG.exception("Cannot handle message")
101 | message.ack()
102 |
103 | def process_event(self, body, message):
104 | """
105 | This function analyzes ``body`` and calls
106 | heart_request_interceptors.
107 | """
108 | method = body.get("method", None)
109 | heart_request = None
110 | for interceptor in self.heart_request_interceptors:
111 | heart_request = interceptor(method, body)
112 | if heart_request is not None:
113 | heart_request.setdefault("datetime", utils.datetime_to_str(
114 | self.get_event_datetime(body)))
115 | heart_request.setdefault("account", body["_context_project_id"])
116 | try:
117 | self.billing_heart.event(heart_request)
118 | except socket.error as ex:
119 | LOG.error("cannot post event to the Heart: %s" % str(ex))
120 | except:
121 | LOG.exception("cannot post event to the Heart")
122 | break
123 | try:
124 | routing_key = message.delivery_info["routing_key"]
125 | except AttributeError, KeyError:
126 | routing_key = ""
127 | LOG.debug("routing_key=%s method=%s" % (routing_key, method))
128 |
129 | def get_event_datetime(self, body):
130 | return utils.now()
131 |
132 | def consume(self):
133 | """
134 | Get messages in an infinite loop. This is the main function of service's green thread.
135 | """
136 | while True:
137 | try:
138 | self.reconnect()
139 | with kombu.messaging.Consumer(
140 | channel=self.channel,
141 | queues=self.queue,
142 | callbacks=[self.process_message]) as consumer:
143 | while True:
144 | self.connection.drain_events()
145 | except socket.error:
146 | pass
147 | except Exception, e:
148 | LOG.exception('Failed to consume message from queue: %s' % str(e))
149 |
150 | def start(self):
151 | self.server = eventlet.spawn(self.consume)
152 |
153 | def stop(self):
154 | self.server.stop()
155 |
156 | def wait(self):
157 | self.server.wait()
158 |
--------------------------------------------------------------------------------
/nova_billing/utils.py:
--------------------------------------------------------------------------------
1 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
2 |
3 | # Nova Billing
4 | # Copyright (C) GridDynamics Openstack Core Team, GridDynamics
5 | #
6 | # This program is free software: you can redistribute it and/or modify
7 | # it under the terms of the GNU General Public License as published by
8 | # the Free Software Foundation, either version 3 of the License, or
9 | # (at your option) any later version.
10 | #
11 | # This program is distributed in the hope that it will be useful,
12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 | # GNU General Public License for more details.
15 | #
16 | # You should have received a copy of the GNU General Public License
17 | # along with this program. If not, see .
18 | """
19 | Miscellaneous utility functions:
20 |
21 | - usage calculations for different VM states;
22 | - datetime manipulations;
23 | - other.
24 | """
25 |
26 | import json
27 | import logging
28 | import sys
29 | import os
30 | from datetime import datetime
31 |
32 | from nova_billing.client import BillingHeartClient
33 |
34 |
35 | LOG = logging.getLogger(__name__)
36 |
37 |
38 | class ContentType(object):
39 | JSON = "application/json"
40 |
41 |
42 | def total_seconds(td):
43 | """This function is added for portability
44 | because timedelta.total_seconds()
45 | was introduced only in python 2.7."""
46 | return (td.microseconds + (td.seconds + td.days * 24 * 3600) * 10**6) / 10**6
47 |
48 |
49 | def now():
50 | """
51 | Return current time in UTC.
52 | """
53 | return datetime.utcnow()
54 |
55 |
56 | def str_to_datetime(dtstr):
57 | """
58 | Convert string to datetime.datetime. String should be in ISO 8601 format.
59 | The function returns ``None`` for invalid date string.
60 | """
61 | if not dtstr:
62 | return None
63 | if dtstr.endswith("Z"):
64 | dtstr = dtstr[:-1]
65 | for fmt in ("%Y-%m-%dT%H:%M:%S",
66 | "%Y-%m-%dT%H:%M:%S.%f",
67 | "%Y-%m-%d %H:%M:%S",
68 | "%Y-%m-%d %H:%M:%S.%f"):
69 | try:
70 | return datetime.strptime(dtstr, fmt)
71 | except ValueError:
72 | pass
73 | return None
74 |
75 |
76 | def datetime_to_str(dt):
77 | """
78 | Convert datetime.datetime instance to string.
79 | Used for JSONization.
80 | """
81 | return ("%sZ" % dt.isoformat()) if isinstance(dt, datetime) else None
82 |
83 |
84 | def usage_to_hours(usage):
85 | """
86 | Convert usage measured for seconds to hours.
87 | """
88 | return dict([(key + "_h", usage[key] / 3600.0) for key in usage])
89 |
90 |
91 | def dict_add(a, b):
92 | """
93 | Increment all keys in ``a`` on keys in ``b``.
94 | """
95 | for key in b:
96 | a[key] = a.get(key, 0) + b[key]
97 |
98 |
99 | def cost_add(cost, begin_at, end_at):
100 | # 31556952 seconds - an average Gregorian year
101 | return cost if cost < 0 else cost * total_seconds(end_at - begin_at) / 31556952.0
102 |
103 |
104 | class GlobalConf(object):
105 | _FLAGS = object()
106 | _conf = {
107 | "host": "127.0.0.1",
108 | "port": 8787,
109 | "log_dir": "/var/log/nova-billing",
110 | "log_format": "%(asctime)-15s:nova-billing:%(levelname)s:%(name)s:%(message)s",
111 | "log_level": "DEBUG",
112 | "nova_conf": "nova.conf",
113 | }
114 |
115 | def load_from_file(self, filename):
116 | try:
117 | with open(filename, "r") as file:
118 | self._conf.update(json.loads(file.read()))
119 | except:
120 | pass
121 |
122 | def load_nova_conf(self):
123 | try:
124 | from nova import flags
125 | from nova import utils
126 | utils.default_flagfile(self.nova_conf)
127 | flags.FLAGS(sys.argv)
128 | self._FLAGS = flags.FLAGS
129 | except Exception:
130 | LOG.exception("cannot load nova flags")
131 |
132 | def __getattr__(self, name):
133 | try:
134 | return self._conf[name]
135 | except KeyError:
136 | pass
137 | try:
138 | return getattr(self._FLAGS, name)
139 | except AttributeError:
140 | pass
141 | raise AttributeError(name)
142 |
143 | def logging(self):
144 | try:
145 | log_file = self.log_file
146 | except AttributeError:
147 | log_name = os.path.basename(sys.argv[0])
148 | if not log_name:
149 | log_name = "unknown"
150 | log_file = "%s/%s.log" % (self.log_dir, log_name)
151 |
152 | def get_logging_level(name):
153 | if name in ("DEBUG", "INFO", "WARN", "ERROR"):
154 | return getattr(logging, name)
155 | return logging.DEBUG
156 |
157 | level = get_logging_level(self.log_level)
158 | handler = logging.FileHandler(log_file)
159 | handler.setFormatter(logging.Formatter(self.log_format))
160 | LOG = logging.getLogger()
161 | LOG.addHandler(handler)
162 | LOG.setLevel(level)
163 |
164 |
165 | global_conf = GlobalConf()
166 | global_conf.load_from_file("/etc/nova-billing/settings.json")
167 |
168 |
169 | def get_heart_client():
170 | return BillingHeartClient(
171 | management_url=global_conf.billing_heart_url)
172 |
173 |
174 | def get_nova_client():
175 | from novaclient.v1_1 import Client
176 | client = Client("", "", "", "")
177 | client.client.auth_token = global_conf.admin_token
178 | client.client.management_url = global_conf.nova_url
179 | return client
180 |
181 |
182 | def get_keystone_client():
183 | from keystoneclient.v2_0 import client as keystone_client
184 | client = keystone_client.Client(
185 | endpoint=global_conf.keystone_url,
186 | token=global_conf.admin_token)
187 | return client
188 |
189 |
--------------------------------------------------------------------------------
/nova_billing/migrate.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python2
2 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
3 |
4 | # Nova Billing
5 | # Copyright (C) GridDynamics Openstack Core Team, GridDynamics
6 | #
7 | # This program is free software: you can redistribute it and/or modify
8 | # it under the terms of the GNU General Public License as published by
9 | # the Free Software Foundation, either version 3 of the License, or
10 | # (at your option) any later version.
11 | #
12 | # This program is distributed in the hope that it will be useful,
13 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 | # GNU General Public License for more details.
16 | #
17 | # You should have received a copy of the GNU General Public License
18 | # along with this program. If not, see .
19 |
20 | import sys
21 | import json
22 |
23 | from sqlalchemy import create_engine
24 | from flask import _request_ctx_stack
25 |
26 | from nova_billing import utils
27 | from nova_billing.utils import global_conf
28 | from nova_billing import client
29 | from nova_billing.heart.database import db
30 | from nova_billing.heart.database import api as db_api
31 | from nova_billing.heart.database.models import Segment
32 |
33 |
34 | class ResourceTypes(object):
35 | Instance = "nova/instance"
36 | Image = "glance/image"
37 |
38 |
39 | usage = "usage: python2 -m nova_billing.migrate [images|instances] URL"
40 |
41 |
42 | def complain_usage():
43 | print >>sys.stderr, usage
44 | sys.exit(1)
45 |
46 |
47 | def main():
48 | if len(sys.argv) < 3:
49 | complain_usage()
50 |
51 | _request_ctx_stack.push(1)
52 | db.create_all()
53 | if sys.argv[1] == "images":
54 | migrate_images(sys.argv[2])
55 | elif sys.argv[1] == "instances":
56 | migrate_instances(sys.argv[2])
57 | else:
58 | complain_usage()
59 |
60 |
61 | def migrate_images(glance_url):
62 | glance_client = client.RestClient()
63 | glance_client.auth_headers = {"x-auth-token": global_conf.admin_token}
64 | glance_client.management_url = glance_url
65 |
66 | tariffs = db_api.tariff_map()
67 | accounts = {}
68 | images = json.loads(glance_client.get("/images/detail"))["images"]
69 | for project_id in (img1["owner"] for img1 in images if img1["owner"]):
70 | accounts[project_id] = \
71 | db_api.account_get_or_create(project_id).id
72 |
73 | for img1 in images:
74 | if not img1["owner"]:
75 | continue
76 | account_id = accounts[img1["owner"]]
77 | img2 = db_api.resource_get_or_create(
78 | account_id, None,
79 | ResourceTypes.Image,
80 | img1["id"]
81 | )
82 | seg = Segment(
83 | resource_id=img2.id,
84 | cost=img1["size"] * tariffs.get(ResourceTypes.Image, 1) / (1024.0 ** 3),
85 | begin_at=utils.str_to_datetime(img1["created_at"]),
86 | end_at=utils.str_to_datetime(img1["deleted_at"]))
87 | db.session.add(seg)
88 |
89 | db.session.commit()
90 |
91 |
92 | def migrate_instances(old_db_url):
93 | engine1 = create_engine(old_db_url)
94 |
95 | tariffs = db_api.tariff_map()
96 | instance_resources = ("local_gb", "memory_mb", "vcpus")
97 | instance_info_attrs = (
98 | "id", "instance_id", "project_id",
99 | "local_gb", "memory_mb", "vcpus")
100 | instance_segment_attrs = (
101 | "id", "instance_info_id",
102 | "segment_type", "begin_at",
103 | "end_at")
104 | instance_infos = {}
105 | accounts = {}
106 | for inst1 in engine1.execute(
107 | "select distinct project_id from billing_instance_info"):
108 | accounts[inst1.project_id] = \
109 | db_api.account_get_or_create(inst1.project_id).id
110 |
111 | for inst1 in engine1.execute(
112 | "select %s from billing_instance_info" %
113 | ", ".join(instance_info_attrs)):
114 | account_id = accounts[inst1.project_id]
115 | inst2 = db_api.resource_get_or_create(
116 | account_id, None,
117 | ResourceTypes.Instance,
118 | inst1.instance_id
119 | )
120 | inst_dict = {
121 | "inst1": inst1,
122 | "inst2": inst2,
123 | }
124 | for rtype in instance_resources:
125 | inst_dict[rtype + "_id"] = db_api.resource_get_or_create(
126 | account_id, inst2.id,
127 | rtype,
128 | None
129 | )
130 | instance_infos[inst1.id] = inst_dict
131 |
132 | for iseg in engine1.execute(
133 | "select %s from billing_instance_segment" %
134 | ", ".join(instance_segment_attrs)):
135 | inst_dict = instance_infos[iseg.instance_info_id]
136 | inst1 = inst_dict["inst1"]
137 | begin_at = utils.str_to_datetime(iseg.begin_at)
138 | end_at = utils.str_to_datetime(iseg.end_at)
139 | inst_dict["begin_at"] = (min(inst_dict["begin_at"], begin_at)
140 | if "begin_at" in inst_dict else begin_at)
141 | try:
142 | prev = inst_dict["end_at"]
143 | except KeyError:
144 | inst_dict["end_at"] = end_at
145 | else:
146 | inst_dict["end_at"] = (
147 | max(prev, end_at) if prev
148 | else None)
149 | for rtype in instance_resources:
150 | seg = Segment(
151 | resource_id=inst_dict[rtype + "_id"].id,
152 | cost=getattr(inst1, rtype) * tariffs.get(rtype, 1),
153 | begin_at=begin_at,
154 | end_at=end_at)
155 | db.session.add(seg)
156 |
157 | for inst_dict in instance_infos.values():
158 | seg = Segment(
159 | resource_id=inst_dict["inst2"].id,
160 | cost=tariffs.get("nova/instance", 0),
161 | begin_at=inst_dict.get("begin_at", None),
162 | end_at=inst_dict.get("end_at", None))
163 | db.session.add(seg)
164 |
165 | db.session.commit()
166 |
167 |
168 | if __name__ == "__main__":
169 | main()
170 |
--------------------------------------------------------------------------------
/doc/source/conf.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | #
3 | # nova-billing documentation build configuration file, created by
4 | # sphinx-quickstart on Tue Dec 20 11:51:46 2011.
5 | #
6 | # This file is execfile()d with the current directory set to its containing dir.
7 | #
8 | # Note that not all possible configuration values are present in this
9 | # autogenerated file.
10 | #
11 | # All configuration values have a default; values that are commented out
12 | # serve to show the default.
13 |
14 | import sys, os
15 |
16 | # If extensions (or modules to document with autodoc) are in another directory,
17 | # add these directories to sys.path here. If the directory is relative to the
18 | # documentation root, use os.path.abspath to make it absolute, like shown here.
19 | #sys.path.insert(0, os.path.abspath('.'))
20 |
21 | # -- General configuration -----------------------------------------------------
22 |
23 | # If your documentation needs a minimal Sphinx version, state it here.
24 | #needs_sphinx = '1.0'
25 |
26 | # Add any Sphinx extension module names here, as strings. They can be extensions
27 | # coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
28 | extensions = ['sphinx.ext.autodoc']
29 |
30 | # Add any paths that contain templates here, relative to this directory.
31 | templates_path = ['_templates']
32 |
33 | # The suffix of source filenames.
34 | source_suffix = '.rst'
35 |
36 | # The encoding of source files.
37 | #source_encoding = 'utf-8-sig'
38 |
39 | # The master toctree document.
40 | master_doc = 'index'
41 |
42 | # General information about the project.
43 | project = u'nova-billing'
44 | copyright = u'2012, Alessio Ababilov (Grid Dynamics Openstack Core Team)'
45 |
46 | # The version info for the project you're documenting, acts as replacement for
47 | # |version| and |release|, also used in various other places throughout the
48 | # built documents.
49 | #
50 | # The short X.Y version.
51 | version = '2.0.0'
52 | # The full version, including alpha/beta/rc tags.
53 | release = '2.0.0'
54 |
55 | # The language for content autogenerated by Sphinx. Refer to documentation
56 | # for a list of supported languages.
57 | #language = None
58 |
59 | # There are two options for replacing |today|: either, you set today to some
60 | # non-false value, then it is used:
61 | #today = ''
62 | # Else, today_fmt is used as the format for a strftime call.
63 | #today_fmt = '%B %d, %Y'
64 |
65 | # List of patterns, relative to source directory, that match files and
66 | # directories to ignore when looking for source files.
67 | exclude_patterns = []
68 |
69 | # The reST default role (used for this markup: `text`) to use for all documents.
70 | #default_role = None
71 |
72 | # If true, '()' will be appended to :func: etc. cross-reference text.
73 | #add_function_parentheses = True
74 |
75 | # If true, the current module name will be prepended to all description
76 | # unit titles (such as .. function::).
77 | #add_module_names = True
78 |
79 | # If true, sectionauthor and moduleauthor directives will be shown in the
80 | # output. They are ignored by default.
81 | #show_authors = False
82 |
83 | # The name of the Pygments (syntax highlighting) style to use.
84 | pygments_style = 'sphinx'
85 |
86 | # A list of ignored prefixes for module index sorting.
87 | #modindex_common_prefix = []
88 |
89 |
90 | # -- Options for HTML output ---------------------------------------------------
91 |
92 | # The theme to use for HTML and HTML Help pages. See the documentation for
93 | # a list of builtin themes.
94 | html_theme = 'default'
95 |
96 | # Theme options are theme-specific and customize the look and feel of a theme
97 | # further. For a list of options available for each theme, see the
98 | # documentation.
99 | #html_theme_options = {}
100 |
101 | # Add any paths that contain custom themes here, relative to this directory.
102 | #html_theme_path = []
103 |
104 | # The name for this set of Sphinx documents. If None, it defaults to
105 | # " v documentation".
106 | #html_title = None
107 |
108 | # A shorter title for the navigation bar. Default is the same as html_title.
109 | #html_short_title = None
110 |
111 | # The name of an image file (relative to this directory) to place at the top
112 | # of the sidebar.
113 | #html_logo = None
114 |
115 | # The name of an image file (within the static path) to use as favicon of the
116 | # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
117 | # pixels large.
118 | #html_favicon = None
119 |
120 | # Add any paths that contain custom static files (such as style sheets) here,
121 | # relative to this directory. They are copied after the builtin static files,
122 | # so a file named "default.css" will overwrite the builtin "default.css".
123 | html_static_path = ['_static']
124 |
125 | # If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
126 | # using the given strftime format.
127 | #html_last_updated_fmt = '%b %d, %Y'
128 |
129 | # If true, SmartyPants will be used to convert quotes and dashes to
130 | # typographically correct entities.
131 | #html_use_smartypants = True
132 |
133 | # Custom sidebar templates, maps document names to template names.
134 | #html_sidebars = {}
135 |
136 | # Additional templates that should be rendered to pages, maps page names to
137 | # template names.
138 | #html_additional_pages = {}
139 |
140 | # If false, no module index is generated.
141 | #html_domain_indices = True
142 |
143 | # If false, no index is generated.
144 | #html_use_index = True
145 |
146 | # If true, the index is split into individual pages for each letter.
147 | #html_split_index = False
148 |
149 | # If true, links to the reST sources are added to the pages.
150 | html_show_sourcelink = False
151 |
152 | # If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
153 | #html_show_sphinx = True
154 |
155 | # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
156 | #html_show_copyright = True
157 |
158 | # If true, an OpenSearch description file will be output, and all pages will
159 | # contain a tag referring to it. The value of this option must be the
160 | # base URL from which the finished HTML is served.
161 | #html_use_opensearch = ''
162 |
163 | # This is the file name suffix for HTML files (e.g. ".xhtml").
164 | #html_file_suffix = None
165 |
166 | # Output file base name for HTML help builder.
167 | htmlhelp_basename = 'nova-billingdoc'
168 |
169 |
170 | # -- Options for LaTeX output --------------------------------------------------
171 |
172 | # The paper size ('letter' or 'a4').
173 | #latex_paper_size = 'letter'
174 |
175 | # The font size ('10pt', '11pt' or '12pt').
176 | #latex_font_size = '10pt'
177 |
178 | # Grouping the document tree into LaTeX files. List of tuples
179 | # (source start file, target name, title, author, documentclass [howto/manual]).
180 | latex_documents = [
181 | ('index', 'nova-billing.tex', u'nova-billing Documentation',
182 | u'Alessio Ababilov, Ivan Kolodyazhny (GridDynamics Openstack Core Team)', 'manual'),
183 | ]
184 |
185 | # The name of an image file (relative to this directory) to place at the top of
186 | # the title page.
187 | #latex_logo = None
188 |
189 | # For "manual" documents, if this is true, then toplevel headings are parts,
190 | # not chapters.
191 | #latex_use_parts = False
192 |
193 | # If true, show page references after internal links.
194 | #latex_show_pagerefs = False
195 |
196 | # If true, show URL addresses after external links.
197 | #latex_show_urls = False
198 |
199 | # Additional stuff for the LaTeX preamble.
200 | #latex_preamble = ''
201 |
202 | # Documents to append as an appendix to all manuals.
203 | #latex_appendices = []
204 |
205 | # If false, no module index is generated.
206 | #latex_domain_indices = True
207 |
208 |
209 | # -- Options for manual page output --------------------------------------------
210 |
211 | # One entry per manual page. List of tuples
212 | # (source start file, name, description, authors, manual section).
213 | man_pages = [
214 | ('index', 'nova-billing', u'nova-billing Documentation',
215 | [u'Alessio Ababilov, Ivan Kolodyazhny (GridDynamics Openstack Core Team)'], 1)
216 | ]
217 |
218 | sys.path.append(os.path.abspath('_themes'))
219 | html_theme_path = ['_themes']
220 | html_theme = 'bootstrap'
221 |
--------------------------------------------------------------------------------
/nova_billing/heart/database/api.py:
--------------------------------------------------------------------------------
1 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
2 |
3 | # Nova Billing
4 | # Copyright (C) GridDynamics Openstack Core Team, GridDynamics
5 | #
6 | # This program is free software: you can redistribute it and/or modify
7 | # it under the terms of the GNU General Public License as published by
8 | # the Free Software Foundation, either version 3 of the License, or
9 | # (at your option) any later version.
10 | #
11 | # This program is distributed in the hope that it will be useful,
12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 | # GNU General Public License for more details.
15 | #
16 | # You should have received a copy of the GNU General Public License
17 | # along with this program. If not, see .
18 |
19 | """
20 | Nova Billing API.
21 | """
22 |
23 | from itertools import repeat
24 | from datetime import datetime
25 |
26 | from sqlalchemy.sql import func, and_, or_
27 | from sqlalchemy.sql.expression import text
28 |
29 | from .models import Account, Resource, Segment, Tariff
30 | from . import db
31 |
32 | from nova_billing import utils
33 |
34 |
35 | def bill_on_interval(period_start, period_stop, account_id=None):
36 | """
37 | Retrieve statistics for the given interval [``period_start``, ``period_stop``].
38 | ``account_id=None`` means all accounts.
39 |
40 | Example of the returned value:
41 |
42 | .. code-block:: python
43 |
44 | {
45 | 1: [
46 | {
47 | "name": "16",
48 | "rtype": "nova/instance",
49 | "created_at": "2011-01-02T00:00:00Z",
50 | "destroyed_at": null,
51 | "parent_id": null,
52 | "cost": 0.0,
53 | "id": 1
54 | },
55 | {
56 | "name": null,
57 | "rtype": "local_gb",
58 | "created_at": "2011-01-02T00:00:00Z",
59 | "destroyed_at": null,
60 | "parent_id": 1,
61 | "cost": 1200.0,
62 | "id": 2
63 | },
64 | {
65 | "name": null,
66 | "rtype": "memory_mb",
67 | "created_at": "2011-01-02T00:00:00Z",
68 | "destroyed_at": null,
69 | "parent_id": 1,
70 | "cost": 380928.0,
71 | "id": 3
72 | }
73 | ]
74 | }
75 |
76 | :returns: a dictionary where keys are account ids and values are billing lists.
77 | """
78 | result = (db.session.query(Segment, Resource).
79 | join(Resource).
80 | filter(Segment.begin_at < period_stop).
81 | filter(or_(Segment.end_at > period_start,
82 | Segment.end_at == None)))
83 | if account_id:
84 | result = result.filter(Resource.account_id == account_id)
85 |
86 | retval = {}
87 | rsrc_by_id = {}
88 | now = datetime.utcnow()
89 | for segment, rsrc in result:
90 | if not retval.has_key(rsrc.account_id):
91 | retval[rsrc.account_id] = []
92 | try:
93 | rsrc_descr = rsrc_by_id[rsrc.id]
94 | except KeyError:
95 | rsrc_descr = {
96 | "id": rsrc.id,
97 | "created_at": None,
98 | "destroyed_at": None,
99 | "cost": 0.0,
100 | "parent_id": rsrc.parent_id,
101 | "name": rsrc.name,
102 | "rtype": rsrc.rtype,
103 | }
104 | retval[rsrc.account_id].append(rsrc_descr)
105 | rsrc_by_id[rsrc.id] = rsrc_descr
106 | begin_at = max(segment.begin_at, period_start)
107 | end_at = min(segment.end_at or now, period_stop)
108 | rsrc_descr["cost"] += utils.cost_add(segment.cost, begin_at, end_at)
109 |
110 | result = (db.session.query(Segment,
111 | func.min(Segment.begin_at).label("min_start"),
112 | func.max(Segment.begin_at).label("max_start"),
113 | func.max(Segment.end_at).label("max_stop"),
114 | Resource.id).
115 | join(Resource).
116 | group_by(Resource.id).
117 | filter(Segment.begin_at < period_stop).
118 | filter(or_(Segment.end_at > period_start,
119 | Segment.end_at == None)))
120 | if account_id:
121 | result = result.filter(Resource.account_id == account_id)
122 |
123 | for row in result:
124 | rsrc_descr = rsrc_by_id.get(row.id, None)
125 | if not rsrc_descr:
126 | continue
127 | rsrc_descr["created_at"] = row.min_start
128 | if row.max_stop is None or row.max_start < row.max_stop:
129 | rsrc_descr["destroyed_at"] = row.max_stop
130 |
131 | return retval
132 |
133 |
134 | def account_get_or_create(name):
135 | obj = Account.query.filter_by(name=name).first()
136 | if obj == None:
137 | obj = Account(name=name)
138 | db.session.add(obj)
139 | db.session.commit()
140 | return obj
141 |
142 |
143 | def resource_get_or_create(account_id, parent_id, rtype, name):
144 | obj = Resource.query.filter_by(
145 | account_id=account_id,
146 | parent_id=parent_id,
147 | rtype=rtype,
148 | name=name).first()
149 | if obj == None:
150 | obj = Resource(
151 | account_id=account_id,
152 | parent_id=parent_id,
153 | rtype=rtype,
154 | name=name)
155 | db.session.add(obj)
156 | db.session.commit()
157 | return obj
158 |
159 |
160 | def resource_segment_end(resource_id, end_at):
161 | db.session.execute(Segment.__table__.update().
162 | values(end_at=end_at).where(
163 | Segment.resource_id == resource_id))
164 |
165 |
166 | def account_map():
167 | return dict(((obj.id, obj.name)
168 | for obj in Account.query.all()))
169 |
170 |
171 | def tariff_map():
172 | return dict(((obj.rtype, obj.multiplier)
173 | for obj in Tariff.query.all()))
174 |
175 |
176 | def resource_find(rtype, name):
177 | resource_account = (db.session.query(Resource, Account).
178 | filter(and_(Resource.rtype == rtype,
179 | and_(Resource.name == name,
180 | Resource.account_id == Account.id))).first())
181 | return resource_account[0] if resource_account else None
182 |
183 |
184 | def tariffs_migrate(old_tariffs, new_tariffs, event_datetime):
185 | new_tariffs = dict(
186 | ((key, float(value))
187 | for key, value in new_tariffs.iteritems()
188 | if value != old_tariffs.get(key, 1.0)))
189 | connection = db.session.connection()
190 | for rtype in new_tariffs:
191 | old_t = old_tariffs.get(rtype, 1.0)
192 | if old_t < 0:
193 | old_t = 1.0
194 |
195 | connection.execute(
196 | "insert into %(segment)s"
197 | " (resource_id, cost, begin_at, end_at)"
198 | " select resource_id, cost * ?, ?, NULL"
199 | " from %(segment)s, %(resource)s"
200 | " where end_at is NULL "
201 | " and %(segment)s.resource_id = %(resource)s.id"
202 | " and %(resource)s.rtype = ?" %
203 | {"segment": Segment.__tablename__,
204 | "resource": Resource.__tablename__},
205 | new_tariffs[rtype] / old_t,
206 | event_datetime,
207 | rtype)
208 |
209 | changed_keys = new_tariffs.keys()
210 | max_args = 32
211 | for i in xrange(1 + len(changed_keys) / max_args):
212 | partial_keys = changed_keys[i * max_args:(i + 1) * max_args]
213 | connection.execute(
214 | "update %(segment)s"
215 | " set end_at = ?"
216 | " where end_at is NULL"
217 | " and begin_at != ?"
218 | " and resource_id in"
219 | " (select id from %(resource)s where rtype in (%(type_list)s))" %
220 | {"segment": Segment.__tablename__,
221 | "resource": Resource.__tablename__,
222 | "type_list": ", ".join(repeat("?", len(partial_keys)))},
223 | event_datetime, event_datetime,
224 | *partial_keys)
225 |
--------------------------------------------------------------------------------
/nova_billing/heart/rest.py:
--------------------------------------------------------------------------------
1 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
2 |
3 | # Nova Billing
4 | # Copyright (C) GridDynamics Openstack Core Team, GridDynamics
5 | #
6 | # This program is free software: you can redistribute it and/or modify
7 | # it under the terms of the GNU General Public License as published by
8 | # the Free Software Foundation, either version 3 of the License, or
9 | # (at your option) any later version.
10 | #
11 | # This program is distributed in the hope that it will be useful,
12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 | # GNU General Public License for more details.
15 | #
16 | # You should have received a copy of the GNU General Public License
17 | # along with this program. If not, see .
18 |
19 | """
20 | REST API for Nova Billing Heart
21 | """
22 |
23 | import json
24 | import datetime
25 |
26 | from flask import Flask, request, session, redirect, url_for, \
27 | jsonify, Response
28 | from werkzeug.exceptions import BadRequest, Unauthorized, NotFound
29 | from . import app
30 |
31 | from .database import api as db_api
32 | from .database import db
33 | from .database.models import Account, Resource, Segment, Tariff
34 |
35 | from nova_billing import utils
36 | from nova_billing.version import version_string
37 |
38 |
39 | def request_json():
40 | ret = request.json
41 | if ret == None:
42 | raise BadRequest("Content-Type should be %s" % utils.ContentType.JSON)
43 | return ret
44 |
45 |
46 | def to_json(resp):
47 | return Response(
48 | json.dumps(resp,
49 | default=utils.datetime_to_str),
50 | mimetype=utils.ContentType.JSON)
51 |
52 |
53 | def check_attrs(rj, attr_list):
54 | for attr in attr_list:
55 | if attr not in rj:
56 | raise BadRequest(
57 | description="%s must be specified" % attr)
58 |
59 |
60 | def check_and_get_datatime(rj):
61 | ret = utils.str_to_datetime(rj.get("datetime", None))
62 | if not ret:
63 | raise BadRequest(
64 | description="valid datetime must be specified")
65 | return ret
66 |
67 |
68 | @app.route("/version")
69 | def get_version():
70 | ans_dict = {
71 | "version": version_string(),
72 | "application": "nova-billing",
73 | "links": [
74 | [{
75 | "href": "http://%s:%s/%s" %
76 | (request.environ["SERVER_NAME"],
77 | request.environ["SERVER_PORT"],
78 | url),
79 | "rel": "self",
80 | } for url in "bill", "resource", "account", "tariff" ],
81 | ],
82 | }
83 |
84 | return jsonify(ans_dict)
85 |
86 |
87 | def get_period():
88 | if not request.args.has_key("time_period"):
89 | if "period_start" in request.args:
90 | period_start = utils.str_to_datetime(request.args["period_start"])
91 | try:
92 | period_end = utils.str_to_datetime(request.args["period_end"])
93 | except KeyError:
94 | raise BadRequest(description="period_end is request.ired")
95 | if not (period_start and period_end):
96 | raise BadRequest(
97 | description="date should be in ISO 8601 format of YYYY-MM-DDThh:mm:ssZ")
98 | if period_start >= period_end:
99 | raise BadRequest(
100 | description="period_start must be less than period_end")
101 | return period_start, period_end
102 | else:
103 | now = utils.now()
104 | date_args = (now.year, now.month, 1)
105 | date_incr = 1
106 | else:
107 | time_period_splitted = request.args["time_period"].split("-", 2)
108 | date_args = [1, 1, 1]
109 | for i in xrange(min(2, len(time_period_splitted))):
110 | try:
111 | date_args[i] = int(time_period_splitted[i])
112 | except ValueError:
113 | raise BadRequest(
114 | description="invalid time_period `%s'" % request.args["time_period"])
115 | date_incr = len(time_period_splitted) - 1
116 |
117 | period_start = datetime.datetime(*date_args)
118 | if date_incr == 2:
119 | period_end = period_start + datetime.timedelta(days=1)
120 | else:
121 | year, month, day = date_args
122 | if date_incr == 1:
123 | month += 1
124 | if month > 12:
125 | month = 1
126 | year += 1
127 | else:
128 | year += 1
129 | period_end = datetime.datetime(year=year, month=month, day=day)
130 | return period_start, period_end
131 |
132 |
133 | @app.route("/bill")
134 | def get_bill():
135 | account_name = request.args.get("account", None)
136 | if account_name:
137 | account = Account.query.filter_by(name=account_name).first()
138 | if account == None:
139 | raise NotFound()
140 | account_id = account.id
141 | else:
142 | account_id = None
143 |
144 | period_start, period_end = get_period()
145 | total_statistics = db_api.bill_on_interval(
146 | period_start, period_end, account_id)
147 |
148 | accounts = db_api.account_map()
149 | ans_dict = {
150 | "period_start": period_start,
151 | "period_end": period_end,
152 | "bill": [{
153 | "id": key, "name": accounts.get(key, None),
154 | "resources": value
155 | } for key, value in total_statistics.iteritems()],
156 | }
157 | return to_json(ans_dict)
158 |
159 |
160 | def process_event(rsrc, parent_id, account_id, event_datetime, tariffs):
161 | """
162 | linear - saved as a non-negative cost
163 | fixed - saved with opposite sign (as a non-positive cost)
164 | fixed=None - closes the segment but does not create a new one
165 | """
166 | if not "rtype" in rsrc:
167 | return
168 | rsrc_obj = db_api.resource_get_or_create(
169 | account_id, parent_id,
170 | rsrc["rtype"], rsrc.get("name", None))
171 | rsrc_id = rsrc_obj.id
172 |
173 | try:
174 | attrs = rsrc["attrs"]
175 | except KeyError:
176 | pass
177 | else:
178 | if rsrc_obj.attrs:
179 | attrs.update(rsrc_obj.get_attrs())
180 | rsrc_obj.set_attrs(attrs)
181 | db.session.merge(rsrc_obj)
182 |
183 | close_segment = True
184 | if "linear" in rsrc:
185 | cost = -rsrc["linear"]
186 | elif "fixed" in rsrc:
187 | cost = rsrc["fixed"]
188 | else:
189 | cost = None
190 | close_segment = False
191 | if close_segment:
192 | db_api.resource_segment_end(rsrc_id, event_datetime)
193 | if cost is not None:
194 | obj = Segment(
195 | resource_id=rsrc_id,
196 | cost=-cost * tariffs.get(rsrc["rtype"], 1),
197 | begin_at=event_datetime)
198 | db.session.add(obj)
199 |
200 | for child in rsrc.get("children", ()):
201 | process_event(child, rsrc_id,
202 | account_id, event_datetime,
203 | tariffs)
204 |
205 |
206 | def process_resource(rsrc, parent_id, account_id):
207 | if not "rtype" in rsrc:
208 | return
209 | rsrc_obj = db_api.resource_get_or_create(
210 | account_id, parent_id,
211 | rsrc["rtype"], rsrc.get("name", None))
212 | rsrc_id = rsrc_obj.id
213 |
214 | try:
215 | attrs = rsrc["attrs"]
216 | except KeyError:
217 | pass
218 | else:
219 | rsrc_obj.set_attrs(attrs)
220 | db.session.merge(rsrc_obj)
221 |
222 | for child in rsrc.get("children", ()):
223 | process_resource(child, rsrc_id, account_id)
224 |
225 |
226 | @app.route("/event", methods=["POST"])
227 | def post_event():
228 | rj = request_json()
229 | check_attrs(rj, ("rtype", ))
230 | rj_datetime = check_and_get_datatime(rj)
231 | try:
232 | account_name = rj["account"]
233 | except KeyError:
234 | resource = db_api.resource_find(rj["rtype"], rj.get("name", None))
235 | if not resource:
236 | raise BadRequest(description="account must be specified")
237 | account_id = resource.account_id
238 | account_name = resource.name
239 | else:
240 | account = db_api.account_get_or_create(account_name)
241 | account_id = account.id
242 |
243 | tariffs = db_api.tariff_map()
244 | process_event(rj, None, account_id, rj_datetime, tariffs)
245 |
246 | db.session.commit()
247 | return to_json({"account": account_name,
248 | "rtype": rj["rtype"],
249 | "datetime": rj_datetime,
250 | "name": rj.get("name", None)})
251 |
252 |
253 | @app.route("/tariff", methods=["GET"])
254 | def get_tariff():
255 | tariffs = db_api.tariff_map()
256 | return to_json(tariffs)
257 |
258 |
259 | @app.route("/tariff", methods=["POST"])
260 | def change_tariff():
261 | rj = request_json()
262 | check_attrs(rj, ("values", ))
263 | rj_datetime = check_and_get_datatime(rj)
264 | migrate = rj.get("migrate", False)
265 |
266 | if migrate:
267 | old_tariffs = db_api.tariff_map()
268 | new_tariffs = rj["values"]
269 | for key, value in new_tariffs.iteritems():
270 | if isinstance(value, int) or isinstance(value, float):
271 | db.session.merge(Tariff(rtype=key, multiplier=value))
272 |
273 | if migrate:
274 | db_api.tariffs_migrate(
275 | old_tariffs,
276 | new_tariffs,
277 | rj_datetime)
278 |
279 | db.session.commit()
280 |
281 | return to_json(new_tariffs)
282 |
283 |
284 | @app.route("/account", methods=["GET"])
285 | def get_account():
286 | return to_json([
287 | {"id": key, "name": value}
288 | for key, value in db_api.account_map().iteritems()])
289 |
290 |
291 | @app.route("/resource", methods=["GET"])
292 | def get_resource():
293 | res = Resource.query
294 | filter = dict(((fld, request.args[fld])
295 | for fld in ("account_id", "name", "id", "rtype", "parent_id")
296 | if fld in request.args))
297 | if filter:
298 | res = res.filter_by(**filter)
299 | return to_json([
300 | {"id": obj.id,
301 | "name": obj.name,
302 | "rtype": obj.rtype,
303 | "account_id": obj.account_id,
304 | "parent_id": obj.parent_id,
305 | "attrs": obj.get_attrs(),
306 | } for obj in res.all()
307 | ])
308 |
309 |
310 | @app.route("/resource", methods=["POST"])
311 | def post_resource():
312 | rj = request_json()
313 | check_attrs(rj, ("rtype", ))
314 | try:
315 | account_name = rj["account"]
316 | except KeyError:
317 | resource = db_api.resource_find(rj["rtype"], rj.get("name", None))
318 | if not resource:
319 | raise BadRequest(description="account must be specified")
320 | account_id = resource.account_id
321 | account_name = resource.name
322 | else:
323 | account = db_api.account_get_or_create(account_name)
324 | account_id = account.id
325 |
326 | process_resource(rj, None, account_id)
327 |
328 | db.session.commit()
329 | return to_json({"account": account_name,
330 | "rtype": rj["rtype"],
331 | "name": rj.get("name", None)})
332 |
--------------------------------------------------------------------------------
/doc/source/restapi.rst:
--------------------------------------------------------------------------------
1 | REST API
2 | ===============================
3 |
4 | .. contents::
5 | :depth: 2
6 | :local:
7 |
8 | Overview
9 | --------------
10 |
11 | Nova Billing Heart supports the following requests:
12 |
13 | * ``GET /version``;
14 | * ``GET /bill``;
15 | * ``POST /event``;
16 | * ``GET /tariff`` and ``POST /tariff``;
17 | * ``GET /resource`` and ``POST /resource``;
18 | * ``GET /account``.
19 |
20 | All these requests return JSON on success. Data for POST requests also must be JSON.
21 | We use JSON schema (http://json-schema.org/) for format description.
22 |
23 | Date and time are always UTC in order to avoid problems with timezones and daylight saving time.
24 |
25 |
26 | Version
27 | -------
28 |
29 | ``GET /version`` returns information about application name, version, and available URLs.
30 |
31 | Bill
32 | ------
33 | ``GET /bill`` returns information about charged money for requested account on requested time period by resource.
34 |
35 | Time period can be specified in two forms.
36 |
37 | 1. Start and end are given explicitly with ``period_start``
38 | and ``period_end`` request parameters.
39 |
40 | 2. ``time_period`` request parameter is used. It can be a year
41 | (specified as ``year``), a month (``year-month``), or a day
42 | (``year-month-day``). All components are integers. Month and
43 | day numbers start with 1.
44 |
45 | If period is omitted, the bill will be for the current month.
46 |
47 | Account should be specified by its name with ``account`` argument.
48 |
49 | Billing report has the following schema:
50 |
51 | .. code-block:: javascript
52 |
53 | {
54 | "type": "object",
55 | "description": "Billing report",
56 | "properties": {
57 | "period_start": {
58 | "required": true,
59 | "type": "string",
60 | "description": "The beginning of the requested period",
61 | "format": "date-time"
62 | },
63 | "period_end": {
64 | "required": true,
65 | "type": "string",
66 | "description": "The end of the requested period",
67 | "format": "date-time"
68 | },
69 | "bill": {
70 | "items": {
71 | "type": "object",
72 | "description": "Array of account billing reports"
73 | },
74 | "required": true,
75 | "type": "array"
76 | }
77 | }
78 | }
79 |
80 | Account billing report has the following schema:
81 |
82 | .. code-block:: javascript
83 |
84 | {
85 | "type": "object",
86 | "description": "Account billing report",
87 | "properties": {
88 | "id": {
89 | "required": true,
90 | "type": "integer",
91 | "description": "Account ID"
92 | },
93 | "name": {
94 | "required": true,
95 | "type": "string",
96 | "description": "Account name"
97 | },
98 | "resources": {
99 | "items": {
100 | "type": "object",
101 | "description": "Array of resource billing reports"
102 | },
103 | "required": true,
104 | "type": "array"
105 | }
106 | }
107 | }
108 |
109 | Resource billing report has the following schema:
110 |
111 | .. code-block:: javascript
112 |
113 | {
114 | "type": "object",
115 | "description": "Resource billing report",
116 | "properties": {
117 | "id": {
118 | "required": true,
119 | "type": "integer",
120 | "description": "Resource ID"
121 | },
122 | "rtype": {
123 | "required": true,
124 | "type": "string",
125 | "description": "Resource type"
126 | },
127 | "name": {
128 | "required": true,
129 | "type": [
130 | "string",
131 | "null"
132 | ],
133 | "description": "Resource name or null if none"
134 | },
135 | "parent_id": {
136 | "required": true,
137 | "type": [
138 | "string",
139 | "null"
140 | ],
141 | "description": "ID of resource parent or null if none"
142 | },
143 | "created_at": {
144 | "required": true,
145 | "type": "string",
146 | "description": "Date of object creation",
147 | "format": "date-time"
148 | },
149 | "destroyed_at": {
150 | "required": true,
151 | "type": [
152 | "string",
153 | "null"
154 | ],
155 | "description": "Date of object destruction (termination) or null if not destroyed",
156 | "format": "date-time"
157 | }
158 | "cost": {
159 | "required": true,
160 | "type": "number",
161 | "description": "Billed money on the requested period"
162 | },
163 | }
164 | }
165 |
166 | Example of billing report:
167 |
168 | .. code-block:: javascript
169 |
170 | {
171 | "bill": [
172 | {
173 | "id": 1,
174 | "name": "1",
175 | "resources": [
176 | {
177 | "cost": 0.0,
178 | "created_at": "2012-01-19T17:37:24.024440Z",
179 | "destroyed_at": null,
180 | "id": 46,
181 | "name": null,
182 | "parent_id": 45,
183 | "rtype": "local_gb"
184 | },
185 | {
186 | "cost": 8434.1570370370373,
187 | "created_at": "2012-01-19T17:37:24.024440Z",
188 | "destroyed_at": null,
189 | "id": 47,
190 | "name": null,
191 | "parent_id": 45,
192 | "rtype": "memory_mb"
193 | },
194 | {
195 | "cost": 16.472962962962963,
196 | "created_at": "2012-01-19T17:37:24.024440Z",
197 | "destroyed_at": null,
198 | "id": 48,
199 | "name": null,
200 | "parent_id": 45,
201 | "rtype": "vcpus"
202 | },
203 | {
204 | "cost": 0.0,
205 | "created_at": "2012-01-19T17:37:24.024440Z",
206 | "destroyed_at": null,
207 | "id": 45,
208 | "name": "12",
209 | "parent_id": null,
210 | "rtype": "nova/instance"
211 | },
212 | {
213 | "cost": 72559316.557037041,
214 | "created_at": "2012-01-19T16:23:20.293482Z",
215 | "destroyed_at": null,
216 | "id": 75,
217 | "name": "22",
218 | "parent_id": null,
219 | "rtype": "glance/image"
220 | }
221 | ]
222 | }
223 | ],
224 | "period_end": "2012-05-01T00:00:00Z",
225 | "period_start": "2012-04-01T00:00:00Z"
226 | }
227 |
228 |
229 | Examples of billing queries.
230 |
231 | In these examples, ``999888777666`` is assumed to be a valid Admin's token.
232 |
233 | Bill for account ``1`` on 2012 year:
234 |
235 | .. code-block:: bash
236 |
237 | $ curl "http://localhost:8787/bill?account=1&time_period=2012" -H "X-Auth-Token: 999888777666"
238 |
239 | Bill for all accounts on December, 2012:
240 |
241 | .. code-block:: bash
242 |
243 | $ curl "http://localhost:8787/bill?time_period=2012-12" -H "X-Auth-Token: 999888777666"
244 |
245 | Bill for account ``2`` from ``2012-01-01 00:00:00`` till ``2012-01-01 01:00:00``:
246 |
247 | .. code-block:: bash
248 |
249 | $ curl "http://localhost:8787/bill?account=2&period_start=2012-01-01T00%3A00%3A00Z&period_end=2012-01-01T01%3A00%3A00Z" -H "X-Auth-Token: 999888777666"
250 |
251 |
252 | Event
253 | -----
254 |
255 | ``POST /event`` notifies the Heart about a new event.
256 | All appropriate resources and accounts will be created lazily, so, there is no need to create a resource before posting an event.
257 |
258 | Request data has the following schema:
259 |
260 | .. code-block:: javascript
261 |
262 | {
263 | "type": "object",
264 | "description": "Resource event",
265 | "properties": {
266 | "account": {
267 | "required": false,
268 | "type": "integer",
269 | "description": "Account name"
270 | },
271 | "datetime": {
272 | "required": true,
273 | "type": "string",
274 | "description": "Event datatime",
275 | "format": "date-time"
276 | },
277 | "name": {
278 | "required": false,
279 | "type": "string",
280 | "description": "Resource name"
281 | },
282 | "rtype": {
283 | "required": true,
284 | "type": "string",
285 | "description": "Resource type"
286 | },
287 | "attrs": {
288 | "required": false,
289 | "type": "object",
290 | "description": "Dictionary of resource attributes that should be set"
291 | },
292 | "linear": {
293 | "required": true,
294 | "type": "number",
295 | "description": "Linear price for the resource"
296 | },
297 | "fixed": {
298 | "required": true,
299 | "type": ["number", "null"],
300 | "description": "Fixed price for the resource or null to stop charging"
301 | },
302 | "children": {
303 | "items": {
304 | "type": "object",
305 | "description": "Array of events of child resources"
306 | },
307 | "required": false,
308 | "type": "array"
309 | }
310 | }
311 | }
312 |
313 | ``account`` and ``datatime`` should be present for the root resource event. They are ignored for all child resources.
314 | ``account`` can be omitted for the root resource event if the resource is already created.
315 |
316 | ``linear`` and ``fixed`` attributes control charging schemas for resources. They are mutually exclusive.
317 |
318 | * For fixed schema, charged money is the product of resource type tariff and the provided ``fixed`` value.
319 | * For linear schema, charged money is the product of resource type tariff, the provided ``linear`` value, and
320 | period length in years.
321 |
322 | If no tariff is stored for the given resource type, it will be assumed to be 1.
323 |
324 |
325 | Request data example:
326 |
327 | .. code-block:: javascript
328 |
329 | {
330 | "account": "2",
331 | "name": 16,
332 | "datetime": "2011-01-02T00:00:00Z",
333 | "attrs": {
334 | "instance_type": "m1.small"
335 | },
336 | "fixed": 0,
337 | "rtype": "nova/instance",
338 | "children": [
339 | {
340 | "rtype": "local_gb",
341 | "linear": 20
342 | },
343 | {
344 | "rtype": "memory_mb",
345 | "linear": 2048
346 | },
347 | {
348 | "rtype": "vcpus",
349 | "linear": 1
350 | }
351 | ]
352 | }
353 |
354 | Here a virtual machine instance will be charged. Its disk, RAM, and CPU will be charged after linear scheme.
355 | Its instance type is ``m1.small`` (this attribute can be retrieved with ``GET /resource`` call).
356 |
357 |
358 | Tariff
359 | ------
360 | Tariffs can be retrieved with ``GET /tariff`` and set with ``POST /tariff``. Tariff name equals to the corresponding resource type.
361 |
362 | Setting request data has the following schema:
363 |
364 | .. code-block:: javascript
365 |
366 | {
367 | "type": "object",
368 | "properties": {
369 | "datetime": {
370 | "required": true,
371 | "type": "string",
372 | "description": "Since that datatime tariffs are changed",
373 | "format": "date-time"
374 | },
375 | "migrate": {
376 | "required": false,
377 | "type": "boolean",
378 | "description": "Whether all currently charging resources should migrate to the new tariffs"
379 | },
380 | "values": {
381 | "required": false,
382 | "type": "object",
383 | "description": "Dictionary of the new tariffs"
384 | }
385 | }
386 | }
387 |
388 | Setting tariff example:
389 |
390 | .. code-block:: javascript
391 |
392 | {
393 | "datetime": "2010-01-01T00:00:00.000000Z",
394 | "migrate": false,
395 | "values": {
396 | "local_gb": 2.0,
397 | "memory_mb": 3.0,
398 | "vcpus": 0.5,
399 | "glance/image": 1.0
400 | }
401 | }
402 |
403 | Response to ``GET /tariff`` is a tariff dictionary and looks like this:
404 |
405 | .. code-block:: javascript
406 |
407 | {
408 | "local_gb": 2.0,
409 | "memory_mb": 3.0,
410 | "vcpus": 0.5,
411 | "glance/image": 1.0
412 | }
413 |
414 | Resource
415 | --------
416 |
417 | Resources can be retrieved with ``GET /resource`` and set with ``POST /resource``.
418 |
419 | Setting request data schema is nearly the same as post event schema.
420 | The difference is that ``datetime``, ``linear``, and ``fixed`` attributes
421 | are not used.
422 |
423 | Response to ``GET /resource`` is an array of resource objects and looks like this:
424 |
425 | .. code-block:: javascript
426 |
427 | [
428 | {
429 | "account_id": 1,
430 | "rtype": "nova/instance",
431 | "parent_id": null,
432 | "attrs": {
433 | "instance_type": "m1.small"
434 | },
435 | "id": 1,
436 | "name": "16"
437 | },
438 | {
439 | "account_id": 1,
440 | "rtype": "local_gb",
441 | "parent_id": 1,
442 | "attrs": {},
443 | "id": 2,
444 | "name": null
445 | },
446 | {
447 | "account_id": 1,
448 | "rtype": "memory_mb",
449 | "parent_id": 1,
450 | "attrs": {},
451 | "id": 3,
452 | "name": null
453 | },
454 | {
455 | "account_id": 1,
456 | "rtype": "vcpus",
457 | "parent_id": 1,
458 | "attrs": {},
459 | "id": 4,
460 | "name": null
461 | }
462 | ]
463 |
464 | Account
465 | -------
466 |
467 | Resources can be retrieved with ``GET /account``.
468 |
469 | Response is an array of account objects and looks like this:
470 |
471 | .. code-block:: javascript
472 |
473 | [
474 | {
475 | "id": 1,
476 | "name": "4"
477 | }
478 | {
479 | "id": 2,
480 | "name": "35"
481 | }
482 | ]
483 |
--------------------------------------------------------------------------------
/tests/api-requests.json:
--------------------------------------------------------------------------------
1 | {
2 | "/projects?time_period=2011": {
3 | "period_start": "2011-01-01T00:00:00Z",
4 | "projects": [
5 | {
6 | "url": "http://localhost:80/projects/1",
7 | "instances": {
8 | "count": 2,
9 | "usage": {
10 | "local_gb_h": 79.0,
11 | "vcpus_h": 80.0,
12 | "memory_mb_h": 55.0
13 | }
14 | },
15 | "id": "1",
16 | "name": "systenant"
17 | },
18 | {
19 | "url": "http://localhost:80/projects/12",
20 | "instances": {
21 | "count": 2,
22 | "usage": {
23 | "local_gb_h": 130.0,
24 | "vcpus_h": 42.0,
25 | "memory_mb_h": 165.0
26 | }
27 | },
28 | "id": "12",
29 | "name": "tenant12"
30 | }
31 | ],
32 | "period_end": "2012-01-01T00:00:00Z"
33 | },
34 | "/projects/1?include=images-long&period_start=2011-01-01T00%3A00%3A00Z&period_end=2012-01-01T00%3A00%3A00Z": {
35 | "period_start": "2011-01-01T00:00:00Z",
36 | "projects": [
37 | {
38 | "url": "http://localhost:80/projects/1",
39 | "images": {
40 | "count": 2,
41 | "items": [
42 | {
43 | "name": "RHEL 6.1",
44 | "created_at": "2011-01-01T00:00:00Z",
45 | "lifetime_sec": 86400,
46 | "usage": {
47 | "local_gb_h": 12.0
48 | },
49 | "destroyed_at": "2011-01-02T00:00:00Z",
50 | "id": 21
51 | },
52 | {
53 | "name": "Ubuntu kernel",
54 | "created_at": "2011-01-04T00:00:00Z",
55 | "lifetime_sec": 2419200,
56 | "usage": {
57 | "local_gb_h": 67.0
58 | },
59 | "destroyed_at": "2011-02-01T00:00:00Z",
60 | "id": 39
61 | }
62 | ],
63 | "usage": {
64 | "local_gb_h": 79.0
65 | }
66 | },
67 | "id": "1",
68 | "name": "systenant"
69 | }
70 | ],
71 | "period_end": "2012-01-01T00:00:00Z"
72 | },
73 | "/projects/1?include=instances-long&period_start=2011-01-01T00%3A00%3A00Z&period_end=2012-01-01T00%3A00%3A00Z": {
74 | "period_start": "2011-01-01T00:00:00Z",
75 | "projects": [
76 | {
77 | "url": "http://localhost:80/projects/1",
78 | "instances": {
79 | "count": 2,
80 | "items": [
81 | {
82 | "name": null,
83 | "created_at": "2011-01-01T00:00:00Z",
84 | "lifetime_sec": 86400,
85 | "usage": {
86 | "local_gb_h": 12.0,
87 | "vcpus_h": 39.0,
88 | "memory_mb_h": 45.0
89 | },
90 | "destroyed_at": "2011-01-02T00:00:00Z",
91 | "id": 12
92 | },
93 | {
94 | "name": null,
95 | "created_at": "2011-01-04T00:00:00Z",
96 | "lifetime_sec": 2419200,
97 | "usage": {
98 | "local_gb_h": 67.0,
99 | "vcpus_h": 41.0,
100 | "memory_mb_h": 10.0
101 | },
102 | "destroyed_at": "2011-02-01T00:00:00Z",
103 | "id": 14
104 | }
105 | ],
106 | "usage": {
107 | "local_gb_h": 79.0,
108 | "vcpus_h": 80.0,
109 | "memory_mb_h": 55.0
110 | }
111 | },
112 | "id": "1",
113 | "name": "systenant"
114 | }
115 | ],
116 | "period_end": "2012-01-01T00:00:00Z"
117 | },
118 | "/projects?period_start=2011-01-01T00%3A00%3A00Z&period_end=2012-01-01T00%3A00%3A00Z": {
119 | "period_start": "2011-01-01T00:00:00Z",
120 | "projects": [
121 | {
122 | "url": "http://localhost:80/projects/1",
123 | "instances": {
124 | "count": 2,
125 | "usage": {
126 | "local_gb_h": 79.0,
127 | "vcpus_h": 80.0,
128 | "memory_mb_h": 55.0
129 | }
130 | },
131 | "id": "1",
132 | "name": "systenant"
133 | },
134 | {
135 | "url": "http://localhost:80/projects/12",
136 | "instances": {
137 | "count": 2,
138 | "usage": {
139 | "local_gb_h": 130.0,
140 | "vcpus_h": 42.0,
141 | "memory_mb_h": 165.0
142 | }
143 | },
144 | "id": "12",
145 | "name": "tenant12"
146 | }
147 | ],
148 | "period_end": "2012-01-01T00:00:00Z"
149 | },
150 | "/projects?time_period=2011-01": {
151 | "period_start": "2011-01-01T00:00:00Z",
152 | "projects": [
153 | {
154 | "url": "http://localhost:80/projects/1",
155 | "instances": {
156 | "count": 2,
157 | "usage": {
158 | "local_gb_h": 79.0,
159 | "vcpus_h": 80.0,
160 | "memory_mb_h": 55.0
161 | }
162 | },
163 | "id": "1",
164 | "name": "systenant"
165 | },
166 | {
167 | "url": "http://localhost:80/projects/12",
168 | "instances": {
169 | "count": 2,
170 | "usage": {
171 | "local_gb_h": 130.0,
172 | "vcpus_h": 42.0,
173 | "memory_mb_h": 165.0
174 | }
175 | },
176 | "id": "12",
177 | "name": "tenant12"
178 | }
179 | ],
180 | "period_end": "2011-02-01T00:00:00Z"
181 | },
182 | "/projects/1?period_start=2011-01-01T00%3A00%3A00Z&period_end=2012-01-01T00%3A00%3A00Z": {
183 | "period_start": "2011-01-01T00:00:00Z",
184 | "projects": [
185 | {
186 | "url": "http://localhost:80/projects/1",
187 | "instances": {
188 | "count": 2,
189 | "usage": {
190 | "local_gb_h": 79.0,
191 | "vcpus_h": 80.0,
192 | "memory_mb_h": 55.0
193 | }
194 | },
195 | "id": "1",
196 | "name": "systenant"
197 | }
198 | ],
199 | "period_end": "2012-01-01T00:00:00Z"
200 | },
201 | "/projects/1": {
202 | "period_start": "2011-01-01T00:00:00Z",
203 | "projects": [
204 | {
205 | "url": "http://localhost:80/projects/1",
206 | "instances": {
207 | "count": 2,
208 | "items": [
209 | {
210 | "name": null,
211 | "created_at": "2011-01-01T00:00:00Z",
212 | "lifetime_sec": 86400,
213 | "usage": {
214 | "local_gb_h": 12.0,
215 | "vcpus_h": 39.0,
216 | "memory_mb_h": 45.0
217 | },
218 | "destroyed_at": "2011-01-02T00:00:00Z",
219 | "id": 12
220 | },
221 | {
222 | "name": null,
223 | "created_at": "2011-01-04T00:00:00Z",
224 | "lifetime_sec": 2419200,
225 | "usage": {
226 | "local_gb_h": 67.0,
227 | "vcpus_h": 41.0,
228 | "memory_mb_h": 10.0
229 | },
230 | "destroyed_at": "2011-02-01T00:00:00Z",
231 | "id": 14
232 | }
233 | ],
234 | "usage": {
235 | "local_gb_h": 79.0,
236 | "vcpus_h": 80.0,
237 | "memory_mb_h": 55.0
238 | }
239 | },
240 | "id": "1",
241 | "name": "systenant"
242 | }
243 | ],
244 | "period_end": "2011-02-01T00:00:00Z"
245 | },
246 | "/projects/12?time_period=2011-1-1": {
247 | "period_start": "2011-01-01T00:00:00Z",
248 | "projects": [
249 | {
250 | "url": "http://localhost:80/projects/12",
251 | "instances": {
252 | "count": 1,
253 | "items": [
254 | {
255 | "name": null,
256 | "created_at": "2011-01-01T00:00:00Z",
257 | "lifetime_sec": 86400,
258 | "usage": {
259 | "local_gb_h": 73.0,
260 | "vcpus_h": 39.0,
261 | "memory_mb_h": 66.0
262 | },
263 | "destroyed_at": "2011-01-02T00:00:00Z",
264 | "id": 54
265 | }
266 | ],
267 | "usage": {
268 | "local_gb_h": 73.0,
269 | "vcpus_h": 39.0,
270 | "memory_mb_h": 66.0
271 | }
272 | },
273 | "id": "12",
274 | "name": "tenant12"
275 | }
276 | ],
277 | "period_end": "2011-01-02T00:00:00Z"
278 | },
279 | "/projects?time_period=2011-1-1": {
280 | "period_start": "2011-01-01T00:00:00Z",
281 | "projects": [
282 | {
283 | "url": "http://localhost:80/projects/1",
284 | "instances": {
285 | "count": 1,
286 | "usage": {
287 | "local_gb_h": 12.0,
288 | "vcpus_h": 39.0,
289 | "memory_mb_h": 45.0
290 | }
291 | },
292 | "id": "1",
293 | "name": "systenant"
294 | },
295 | {
296 | "url": "http://localhost:80/projects/12",
297 | "instances": {
298 | "count": 1,
299 | "usage": {
300 | "local_gb_h": 73.0,
301 | "vcpus_h": 39.0,
302 | "memory_mb_h": 66.0
303 | }
304 | },
305 | "id": "12",
306 | "name": "tenant12"
307 | }
308 | ],
309 | "period_end": "2011-01-02T00:00:00Z"
310 | },
311 | "/projects/1?include=images&period_start=2011-01-01T00%3A00%3A00Z&period_end=2012-01-01T00%3A00%3A00Z": {
312 | "period_start": "2011-01-01T00:00:00Z",
313 | "projects": [
314 | {
315 | "url": "http://localhost:80/projects/1",
316 | "images": {
317 | "count": 2,
318 | "usage": {
319 | "local_gb_h": 79.0
320 | }
321 | },
322 | "id": "1",
323 | "name": "systenant"
324 | }
325 | ],
326 | "period_end": "2012-01-01T00:00:00Z"
327 | },
328 | "/projects/12?time_period=2011-1": {
329 | "period_start": "2011-01-01T00:00:00Z",
330 | "projects": [
331 | {
332 | "url": "http://localhost:80/projects/12",
333 | "instances": {
334 | "count": 2,
335 | "items": [
336 | {
337 | "name": null,
338 | "created_at": "2011-02-01T00:00:00Z",
339 | "lifetime_sec": 0,
340 | "usage": {
341 | "local_gb_h": 57.0,
342 | "vcpus_h": 3.0,
343 | "memory_mb_h": 99.0
344 | },
345 | "destroyed_at": "2011-02-03T00:00:00Z",
346 | "id": 67
347 | },
348 | {
349 | "name": null,
350 | "created_at": "2011-01-01T00:00:00Z",
351 | "lifetime_sec": 86400,
352 | "usage": {
353 | "local_gb_h": 73.0,
354 | "vcpus_h": 39.0,
355 | "memory_mb_h": 66.0
356 | },
357 | "destroyed_at": "2011-01-02T00:00:00Z",
358 | "id": 54
359 | }
360 | ],
361 | "usage": {
362 | "local_gb_h": 130.0,
363 | "vcpus_h": 42.0,
364 | "memory_mb_h": 165.0
365 | }
366 | },
367 | "id": "12",
368 | "name": "tenant12"
369 | }
370 | ],
371 | "period_end": "2011-02-01T00:00:00Z"
372 | },
373 | "/projects/12?time_period=2011": {
374 | "period_start": "2011-01-01T00:00:00Z",
375 | "projects": [
376 | {
377 | "url": "http://localhost:80/projects/12",
378 | "instances": {
379 | "count": 2,
380 | "usage": {
381 | "local_gb_h": 130.0,
382 | "vcpus_h": 42.0,
383 | "memory_mb_h": 165.0
384 | }
385 | },
386 | "id": "12",
387 | "name": "tenant12"
388 | }
389 | ],
390 | "period_end": "2012-01-01T00:00:00Z"
391 | },
392 | "/projects": {
393 | "period_start": "2011-01-01T00:00:00Z",
394 | "projects": [
395 | {
396 | "url": "http://localhost:80/projects/1",
397 | "instances": {
398 | "count": 2,
399 | "usage": {
400 | "local_gb_h": 79.0,
401 | "vcpus_h": 80.0,
402 | "memory_mb_h": 55.0
403 | }
404 | },
405 | "id": "1",
406 | "name": "systenant"
407 | },
408 | {
409 | "url": "http://localhost:80/projects/12",
410 | "instances": {
411 | "count": 2,
412 | "usage": {
413 | "local_gb_h": 130.0,
414 | "vcpus_h": 42.0,
415 | "memory_mb_h": 165.0
416 | }
417 | },
418 | "id": "12",
419 | "name": "tenant12"
420 | }
421 | ],
422 | "period_end": "2011-02-01T00:00:00Z"
423 | }
424 | }
--------------------------------------------------------------------------------
/COPYING:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------