second_commit
diff --git a/CONTRIBUTING.rst b/CONTRIBUTING.rst
deleted file mode 100755
index 4762ce9..0000000
--- a/CONTRIBUTING.rst
+++ /dev/null
@@ -1,19 +0,0 @@
-The source repository for this project can be found at:
-
- https://opendev.org/openstack/staffeln
-
-Pull requests submitted through GitHub are not monitored.
-
-To start contributing to OpenStack, follow the steps in the contribution guide
-to set up and use Gerrit:
-
- https://docs.openstack.org/contributors/code-and-documentation/quick-start.html
-
-Bugs should be filed on Launchpad:
-
- https://bugs.launchpad.net/replace with the name of the project on Launchpad or the ID from Storyboard
-
-For more specific information about contributing to this repository, see the
-replace with the service it implements contributor guide:
-
- https://docs.openstack.org/staffeln/latest/contributor/contributing.html
diff --git a/HACKING.rst b/HACKING.rst
deleted file mode 100755
index 136de42..0000000
--- a/HACKING.rst
+++ /dev/null
@@ -1,4 +0,0 @@
-staffeln Style Commandments
-===============================================
-
-Read the OpenStack Style Commandments https://docs.openstack.org/hacking/latest/
diff --git a/LICENSE b/LICENSE
deleted file mode 100755
index 68c771a..0000000
--- a/LICENSE
+++ /dev/null
@@ -1,176 +0,0 @@
-
- Apache License
- Version 2.0, January 2004
- http://www.apache.org/licenses/
-
- TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
-
- 1. Definitions.
-
- "License" shall mean the terms and conditions for use, reproduction,
- and distribution as defined by Sections 1 through 9 of this document.
-
- "Licensor" shall mean the copyright owner or entity authorized by
- the copyright owner that is granting the License.
-
- "Legal Entity" shall mean the union of the acting entity and all
- other entities that control, are controlled by, or are under common
- control with that entity. For the purposes of this definition,
- "control" means (i) the power, direct or indirect, to cause the
- direction or management of such entity, whether by contract or
- otherwise, or (ii) ownership of fifty percent (50%) or more of the
- outstanding shares, or (iii) beneficial ownership of such entity.
-
- "You" (or "Your") shall mean an individual or Legal Entity
- exercising permissions granted by this License.
-
- "Source" form shall mean the preferred form for making modifications,
- including but not limited to software source code, documentation
- source, and configuration files.
-
- "Object" form shall mean any form resulting from mechanical
- transformation or translation of a Source form, including but
- not limited to compiled object code, generated documentation,
- and conversions to other media types.
-
- "Work" shall mean the work of authorship, whether in Source or
- Object form, made available under the License, as indicated by a
- copyright notice that is included in or attached to the work
- (an example is provided in the Appendix below).
-
- "Derivative Works" shall mean any work, whether in Source or Object
- form, that is based on (or derived from) the Work and for which the
- editorial revisions, annotations, elaborations, or other modifications
- represent, as a whole, an original work of authorship. For the purposes
- of this License, Derivative Works shall not include works that remain
- separable from, or merely link (or bind by name) to the interfaces of,
- the Work and Derivative Works thereof.
-
- "Contribution" shall mean any work of authorship, including
- the original version of the Work and any modifications or additions
- to that Work or Derivative Works thereof, that is intentionally
- submitted to Licensor for inclusion in the Work by the copyright owner
- or by an individual or Legal Entity authorized to submit on behalf of
- the copyright owner. For the purposes of this definition, "submitted"
- means any form of electronic, verbal, or written communication sent
- to the Licensor or its representatives, including but not limited to
- communication on electronic mailing lists, source code control systems,
- and issue tracking systems that are managed by, or on behalf of, the
- Licensor for the purpose of discussing and improving the Work, but
- excluding communication that is conspicuously marked or otherwise
- designated in writing by the copyright owner as "Not a Contribution."
-
- "Contributor" shall mean Licensor and any individual or Legal Entity
- on behalf of whom a Contribution has been received by Licensor and
- subsequently incorporated within the Work.
-
- 2. Grant of Copyright License. Subject to the terms and conditions of
- this License, each Contributor hereby grants to You a perpetual,
- worldwide, non-exclusive, no-charge, royalty-free, irrevocable
- copyright license to reproduce, prepare Derivative Works of,
- publicly display, publicly perform, sublicense, and distribute the
- Work and such Derivative Works in Source or Object form.
-
- 3. Grant of Patent License. Subject to the terms and conditions of
- this License, each Contributor hereby grants to You a perpetual,
- worldwide, non-exclusive, no-charge, royalty-free, irrevocable
- (except as stated in this section) patent license to make, have made,
- use, offer to sell, sell, import, and otherwise transfer the Work,
- where such license applies only to those patent claims licensable
- by such Contributor that are necessarily infringed by their
- Contribution(s) alone or by combination of their Contribution(s)
- with the Work to which such Contribution(s) was submitted. If You
- institute patent litigation against any entity (including a
- cross-claim or counterclaim in a lawsuit) alleging that the Work
- or a Contribution incorporated within the Work constitutes direct
- or contributory patent infringement, then any patent licenses
- granted to You under this License for that Work shall terminate
- as of the date such litigation is filed.
-
- 4. Redistribution. You may reproduce and distribute copies of the
- Work or Derivative Works thereof in any medium, with or without
- modifications, and in Source or Object form, provided that You
- meet the following conditions:
-
- (a) You must give any other recipients of the Work or
- Derivative Works a copy of this License; and
-
- (b) You must cause any modified files to carry prominent notices
- stating that You changed the files; and
-
- (c) You must retain, in the Source form of any Derivative Works
- that You distribute, all copyright, patent, trademark, and
- attribution notices from the Source form of the Work,
- excluding those notices that do not pertain to any part of
- the Derivative Works; and
-
- (d) If the Work includes a "NOTICE" text file as part of its
- distribution, then any Derivative Works that You distribute must
- include a readable copy of the attribution notices contained
- within such NOTICE file, excluding those notices that do not
- pertain to any part of the Derivative Works, in at least one
- of the following places: within a NOTICE text file distributed
- as part of the Derivative Works; within the Source form or
- documentation, if provided along with the Derivative Works; or,
- within a display generated by the Derivative Works, if and
- wherever such third-party notices normally appear. The contents
- of the NOTICE file are for informational purposes only and
- do not modify the License. You may add Your own attribution
- notices within Derivative Works that You distribute, alongside
- or as an addendum to the NOTICE text from the Work, provided
- that such additional attribution notices cannot be construed
- as modifying the License.
-
- You may add Your own copyright statement to Your modifications and
- may provide additional or different license terms and conditions
- for use, reproduction, or distribution of Your modifications, or
- for any such Derivative Works as a whole, provided Your use,
- reproduction, and distribution of the Work otherwise complies with
- the conditions stated in this License.
-
- 5. Submission of Contributions. Unless You explicitly state otherwise,
- any Contribution intentionally submitted for inclusion in the Work
- by You to the Licensor shall be under the terms and conditions of
- this License, without any additional terms or conditions.
- Notwithstanding the above, nothing herein shall supersede or modify
- the terms of any separate license agreement you may have executed
- with Licensor regarding such Contributions.
-
- 6. Trademarks. This License does not grant permission to use the trade
- names, trademarks, service marks, or product names of the Licensor,
- except as required for reasonable and customary use in describing the
- origin of the Work and reproducing the content of the NOTICE file.
-
- 7. Disclaimer of Warranty. Unless required by applicable law or
- agreed to in writing, Licensor provides the Work (and each
- Contributor provides its Contributions) on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
- implied, including, without limitation, any warranties or conditions
- of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
- PARTICULAR PURPOSE. You are solely responsible for determining the
- appropriateness of using or redistributing the Work and assume any
- risks associated with Your exercise of permissions under this License.
-
- 8. Limitation of Liability. In no event and under no legal theory,
- whether in tort (including negligence), contract, or otherwise,
- unless required by applicable law (such as deliberate and grossly
- negligent acts) or agreed to in writing, shall any Contributor be
- liable to You for damages, including any direct, indirect, special,
- incidental, or consequential damages of any character arising as a
- result of this License or out of the use or inability to use the
- Work (including but not limited to damages for loss of goodwill,
- work stoppage, computer failure or malfunction, or any and all
- other commercial damages or losses), even if such Contributor
- has been advised of the possibility of such damages.
-
- 9. Accepting Warranty or Additional Liability. While redistributing
- the Work or Derivative Works thereof, You may choose to offer,
- and charge a fee for, acceptance of support, warranty, indemnity,
- or other liability obligations and/or rights consistent with this
- License. However, in accepting such obligations, You may act only
- on Your own behalf and on Your sole responsibility, not on behalf
- of any other Contributor, and only if You agree to indemnify,
- defend, and hold each Contributor harmless for any liability
- incurred by, or claims asserted against, such Contributor by reason
- of your accepting any such warranty or additional liability.
-
diff --git a/README.rst b/README.rst
index 02c8e22..0146874 100755
--- a/README.rst
+++ b/README.rst
@@ -1,19 +1,112 @@
-===============================
-staffeln
-===============================
+# Staffeln
-OpenStack Boilerplate contains all the boilerplate you need to create an OpenStack package.
+## Project Description
-Please fill here a long description which must be at least 3 lines wrapped on
-80 cols, so that distribution package maintainers can use it in their packages.
-Note that this is a hard requirement.
+This solution is a volume-level scheduled backup to implement a non-intrusive automatic backup for Openstack VMs.
-* Free software: Apache license
-* Documentation: https://docs.openstack.org/staffeln/latest
-* Source: https://opendev.org/openstack/staffeln
-* Bugs: https://bugs.launchpad.net/replace with the name of the project on Launchpad or the ID from Storyboard
+All volumes attached to the specified VMs are backed up periodically.
-Features
---------
+File-level backup will not be provided. The volume can be restored and attached to the target VM to restore any needed files. Users can restore through Horizon or the cli in self-service.
-* TODO
+## Functions
+
+### Function Overview
+
+The solution backs up all volumes attached to VMs which have a pre-defined metadata set, for
+example, `backup=yes`.
+First, it gets the list of VMs which have backup metadata and the list of volumes attached to the
+VMs in the given project by consuming the Openstack API (nova-api and cinder-api). Once the
+volume list is prepared, then it consumes cinder-backup API to perform the backup.
+Once the backup is successful, the backup time is updated in the metadata - `last-backup-time` of
+the VM.
+
+* *Filtering volumes:* It skips specific volumes if the volume metadata includes a specific
+`skip-volume-backup` flag.
+* *Limitation:* The number of volumes which users can backup is limited. Once the backup
+count exceeds the quota which is defined per project, the backup job would fail.
+* *Naming convention:* The backup volume name would be
+{VOLUME_NAME}-{BACKUP_DATE}.
+* Compression: all backup volumes are compressed at the ceph level. The compression
+mode, compression algorithm and required parameters are configured by the user.
+
+### Retention
+
+Based on the configured retention policy, the volumes are removed.
+Openstack API access policies are customized to make only the retention service be able to delete
+the backups and users not.
+
+### Scaling
+
+Cinder backup service is running on the dedicated backup host and it can be scaled across multiple
+backup hosts.
+
+### Notification
+
+Once the backup is finished, the results are notified to the specified users by email regardless of
+whether it was successful or not (the email will be one digest of all backups).
+Backup result HTML Template
+- Backup time
+- Current quota usage(Quota/used number/percentage) with proper colors
+ - 50% <= Quota usage : Green
+ - 80% > Quota > 50% usage : Yellow
+ - Quota usage > 80% : Red
+- Volume list
+- Success/fail: true/false with proper colors
+ - Fail: Red
+ - Success: Green
+- Fail reason
+
+### Settings
+
+Users can configure the settings to control the backup process. The parameters are;
+- Backup period
+- Volume filtering tag
+- Volume skip filter metadata tag
+- Volume limit number
+- Retention time
+- Archival rules
+- Compression mode, algorithm and parameters
+- Notification receiver list
+- Notification email HTML template
+- Openstack Credential
+
+### User Interface
+
+- Users can get the list of backup volumes on the Horizon cinder-backup panel. This panel
+has filtering and pagination functions which are not default ones of Horizon.
+- Users cannot delete the volumes on the UI. “Delete Volume Backup” button is disabled on
+the cinder-backup panel.
+
+## Dependencies
+
+* openstacksdk (API calls)
+* Flask (HTTP API)
+* oslo.service (long-running daemon)
+* pbr (using setup.cfg for build tooling)
+* oslo.db (database connections)
+* oslo.config (configuration files)
+
+
+## Architecture
+
+### HTTP API (staffeln-api)
+
+This project will need a basic HTTP API. The primary reason for this is because when a user will attempt to delete a backup, we will use [oslo.policy via HTTP](https://docs.openstack.org/oslo.policy/victoria/user/plugins.html) to make sure that the backup they are attempting to delete is not an automated backup.
+
+This API will be unauthenticated and stateless, due to the fact that it is simply going to return the plain-text string True or fail with 401 Unauthorized. Because of the simplicity of this API, [Flask](https://flask.palletsprojects.com/en/1.1.x/) is an excellent tool to be able to build it out.
+
+The flow of the HTTP call will look like the following:
+
+1. HTTP request received through oslo.policy when backup being deleted with ID
+2. Server look up backup ID using OpenStack API
+3. If backup metadata contains `__automated_backup=True` then deny, otherwise allow.
+
+With that flow, we’ll be able to protect automated backups from being deleted automatically. In order to build a proper architecture, this application will be delivered as a WSGI application so it can be hosted via something like uWSGI later.
+
+### Daemon (staffeln-conductor)
+
+The conductor will be an independent daemon that will essentially scan all the virtual machines (grouped by project) which are marked to have automatic backups and then automatically start queueing up backups for them to be executed by Cinder.
+
+Once backups for a project are done, it should be able to start running the rotation policy that is configured on all the existing volumes and then send out a notification email afterwards to the user.
+
+The daemon should be stateful and ensure that it has its own state which is stored inside of a database.
diff --git a/doc/source/contributor/contributing.rst b/doc/source/contributor/contributing.rst
deleted file mode 100755
index 48dd47b..0000000
--- a/doc/source/contributor/contributing.rst
+++ /dev/null
@@ -1,69 +0,0 @@
-============================
-So You Want to Contribute...
-============================
-
-For general information on contributing to OpenStack, please check out the
-`contributor guide <https://docs.openstack.org/contributors/>`_ to get started.
-It covers all the basics that are common to all OpenStack projects: the accounts
-you need, the basics of interacting with our Gerrit review system, how we
-communicate as a community, etc.
-
-Below will cover the more project specific information you need to get started
-with replace with the service it implements.
-
-Communication
-~~~~~~~~~~~~~
-.. This would be a good place to put the channel you chat in as a project; when/
- where your meeting is, the tags you prepend to your ML threads, etc.
-
-Contacting the Core Team
-~~~~~~~~~~~~~~~~~~~~~~~~
-.. This section should list the core team, their irc nicks, emails, timezones
- etc. If all this info is maintained elsewhere (i.e. a wiki), you can link to
- that instead of enumerating everyone here.
-
-New Feature Planning
-~~~~~~~~~~~~~~~~~~~~
-.. This section is for talking about the process to get a new feature in. Some
- projects use blueprints, some want specs, some want both! Some projects
- stick to a strict schedule when selecting what new features will be reviewed
- for a release.
-
-Task Tracking
-~~~~~~~~~~~~~
-.. This section is about where you track tasks- launchpad? storyboard? is there
- more than one launchpad project? what's the name of the project group in
- storyboard?
-
-We track our tasks in Launchpad
-
- https://bugs.launchpad.net/replace with the name of the project on Launchpad or the ID from Storyboard
-
-If you're looking for some smaller, easier work item to pick up and get started
-on, search for the 'low-hanging-fruit' tag.
-
-.. NOTE: If your tag is not 'low-hanging-fruit' please change the text above.
-
-Reporting a Bug
-~~~~~~~~~~~~~~~
-.. Pretty self explanatory section, link directly to where people should report
- bugs for your project.
-
-You found an issue and want to make sure we are aware of it? You can do so on
-`Launchpad
-<https://bugs.launchpad.net/replace with the name of the project on Launchpad or the ID from Storyboard>`_.
-
-Getting Your Patch Merged
-~~~~~~~~~~~~~~~~~~~~~~~~~
-.. This section should have info about what it takes to get something merged. Do
- you require one or two +2's before +W? Do some of your repos require unit
- test changes with all patches? etc.
-
-Project Team Lead Duties
-~~~~~~~~~~~~~~~~~~~~~~~~
-.. this section is where you can put PTL specific duties not already listed in
- the common PTL guide (linked below), or if you already have them written
- up elsewhere you can link to that doc here.
-
-All common PTL duties are enumerated in the `PTL guide
-<https://docs.openstack.org/project-team-guide/ptl.html>`_.
diff --git a/doc/source/contributor/index.rst b/doc/source/contributor/index.rst
deleted file mode 100755
index 036e449..0000000
--- a/doc/source/contributor/index.rst
+++ /dev/null
@@ -1,9 +0,0 @@
-===========================
- Contributor Documentation
-===========================
-
-.. toctree::
- :maxdepth: 2
-
- contributing
-
diff --git a/doc/source/index.rst b/doc/source/index.rst
index 77b2ca9..69c04f8 100755
--- a/doc/source/index.rst
+++ b/doc/source/index.rst
@@ -15,7 +15,6 @@
readme
install/index
library/index
- contributor/index
configuration/index
cli/index
user/index
diff --git a/doc/source/install/install-obs.rst b/doc/source/install/install-obs.rst
deleted file mode 100755
index a37d85a..0000000
--- a/doc/source/install/install-obs.rst
+++ /dev/null
@@ -1,34 +0,0 @@
-.. _install-obs:
-
-
-Install and configure for openSUSE and SUSE Linux Enterprise
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-
-This section describes how to install and configure the replace with the service it implements service
-for openSUSE Leap 42.1 and SUSE Linux Enterprise Server 12 SP1.
-
-.. include:: common_prerequisites.rst
-
-Install and configure components
---------------------------------
-
-#. Install the packages:
-
- .. code-block:: console
-
- # zypper --quiet --non-interactive install
-
-.. include:: common_configure.rst
-
-
-Finalize installation
----------------------
-
-Start the replace with the service it implements services and configure them to start when
-the system boots:
-
-.. code-block:: console
-
- # systemctl enable openstack-staffeln-api.service
-
- # systemctl start openstack-staffeln-api.service
diff --git a/doc/source/install/install-rdo.rst b/doc/source/install/install-rdo.rst
deleted file mode 100755
index ee3ecde..0000000
--- a/doc/source/install/install-rdo.rst
+++ /dev/null
@@ -1,33 +0,0 @@
-.. _install-rdo:
-
-Install and configure for Red Hat Enterprise Linux and CentOS
-~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-
-
-This section describes how to install and configure the replace with the service it implements service
-for Red Hat Enterprise Linux 7 and CentOS 7.
-
-.. include:: common_prerequisites.rst
-
-Install and configure components
---------------------------------
-
-#. Install the packages:
-
- .. code-block:: console
-
- # yum install
-
-.. include:: common_configure.rst
-
-Finalize installation
----------------------
-
-Start the replace with the service it implements services and configure them to start when
-the system boots:
-
-.. code-block:: console
-
- # systemctl enable openstack-staffeln-api.service
-
- # systemctl start openstack-staffeln-api.service
diff --git a/doc/source/install/next-steps.rst b/doc/source/install/next-steps.rst
deleted file mode 100755
index b3cd12c..0000000
--- a/doc/source/install/next-steps.rst
+++ /dev/null
@@ -1,9 +0,0 @@
-.. _next-steps:
-
-Next steps
-~~~~~~~~~~
-
-Your OpenStack environment now includes the staffeln service.
-
-To add additional services, see
-https://docs.openstack.org/project-install-guide/ocata/.
diff --git a/releasenotes/source/conf.py b/releasenotes/source/conf.py
index a198b57..b3a878b 100755
--- a/releasenotes/source/conf.py
+++ b/releasenotes/source/conf.py
@@ -57,7 +57,8 @@
# openstackdocstheme options
openstackdocs_repo_name = 'openstack/staffeln'
-openstackdocs_bug_project = 'replace with the name of the project on Launchpad or the ID from Storyboard'
+openstackdocs_bug_project = """replace with the name of the
+project on Launchpad or the ID from Storyboard"""
openstackdocs_bug_tag = ''
openstackdocs_auto_name = 'False'
diff --git a/staffeln/api/app.py b/staffeln/api/app.py
new file mode 100755
index 0000000..0d723f0
--- /dev/null
+++ b/staffeln/api/app.py
@@ -0,0 +1,18 @@
+from flask import Flask
+from flask import jsonify
+from flask import request
+
+
+app = Flask(__name__)
+
+
+@app.route('/')
+def hello_world():
+ return 'This is my first API call!'
+
+
+@app.route('/post', methods=["POST"])
+def testpost():
+ input_json = request.get_json(force=True)
+ dictToReturn = {'text': input_json['text']}
+ return jsonify(dictToReturn)
diff --git a/staffeln/api/wsgi.py b/staffeln/api/app.wsgi
similarity index 71%
rename from staffeln/api/wsgi.py
rename to staffeln/api/app.wsgi
index 1fe7ec3..55e080f 100755
--- a/staffeln/api/wsgi.py
+++ b/staffeln/api/app.wsgi
@@ -1,4 +1,2 @@
-from validate import app
-
if __name__ == "__main__":
app.run(host="0.0.0.0", port=8080)
diff --git a/staffeln/api/middleware/parsable_error.py b/staffeln/api/middleware/parsable_error.py
new file mode 100755
index 0000000..d7ce289
--- /dev/null
+++ b/staffeln/api/middleware/parsable_error.py
@@ -0,0 +1,104 @@
+# Copyright ? 2012 New Dream Network, LLC (DreamHost)
+#
+# Licensed under the Apache License, Version 2.0 (the "License"); you may
+# not use this file except in compliance with the License. You may obtain
+# a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+# License for the specific language governing permissions and limitations
+# under the License.
+"""
+Middleware to replace the plain text message body of an error
+response with one formatted so the client can parse it.
+
+Based on pecan.middleware.errordocument
+"""
+
+from oslo_serialization import jsonutils
+
+from staffeln.i18n import _
+
+
+class ParsableErrorMiddleware(object):
+ """Replace error body with something the client can parse."""
+ def __init__(self, app):
+ self.app = app
+
+ def _update_errors(self, app_iter, status_code):
+ errs = []
+ for err_str in app_iter:
+ err = {}
+ try:
+ err = jsonutils.loads(err_str.decode('utf-8'))
+ except ValueError:
+ pass
+
+ if 'title' in err and 'description' in err:
+ title = err['title']
+ desc = err['description']
+ elif 'faultstring' in err:
+ title = err['faultstring'].split('.', 1)[0]
+ desc = err['faultstring']
+ else:
+ title = ''
+ desc = ''
+
+ code = err['faultcode'].lower() if 'faultcode' in err else ''
+
+ # if already formatted by custom exception, don't update
+ if 'min_version' in err:
+ errs.append(err)
+ else:
+ errs.append({
+ 'request_id': '',
+ 'code': code,
+ 'status': status_code,
+ 'title': title,
+ 'detail': desc,
+ 'links': []})
+
+ return errs
+
+ def __call__(self, environ, start_response):
+ # Request for this state, modified by replace_start_response()
+ # and used when an error is being reported.
+ state = {}
+
+ def replacement_start_response(status, headers, exc_info=None):
+ """Overrides the default response to make errors parsable."""
+ try:
+ status_code = int(status.split(' ')[0])
+ state['status_code'] = status_code
+ except (ValueError, TypeError): # pragma: nocover
+ raise Exception(_(
+ 'ErrorDocumentMiddleware received an invalid '
+ 'status %s') % status)
+ else:
+ if (state['status_code'] // 100) not in (2, 3):
+ # Remove some headers so we can replace them later
+ # when we have the full error message and can
+ # compute the length.
+ headers = [(h, v)
+ for (h, v) in headers
+ if h not in ('Content-Length', 'Content-Type')
+ ]
+ # Save the headers in case we need to modify them.
+ state['headers'] = headers
+
+ return start_response(status, headers, exc_info)
+
+ app_iter = self.app(environ, replacement_start_response)
+
+ if (state['status_code'] // 100) not in (2, 3):
+ errs = self._update_errors(app_iter, state['status_code'])
+ body = [jsonutils.dump_as_bytes({'errors': errs})]
+ state['headers'].append(('Content-Type', 'application/json'))
+ state['headers'].append(('Content-Length', str(len(body[0]))))
+
+ else:
+ body = app_iter
+ return body
diff --git a/staffeln/api/validate/__init__.py b/staffeln/api/validate/__init__.py
deleted file mode 100755
index c07c459..0000000
--- a/staffeln/api/validate/__init__.py
+++ /dev/null
@@ -1 +0,0 @@
-from .app import app
diff --git a/staffeln/api/validate/app.py b/staffeln/api/validate/app.py
deleted file mode 100755
index ef93079..0000000
--- a/staffeln/api/validate/app.py
+++ /dev/null
@@ -1,13 +0,0 @@
-from flask import Flask
-app = Flask(__name__)
-
-
-@app.route('/')
-def hello_world():
- return 'This is my first API call!'
-
-@app.route('/post', methods=["POST"])
-def testpost():
- input_json = request.get_json(force=True)
- dictToReturn = {'text':input_json['text']}
- return jsonify(dictToReturn)
diff --git a/staffeln/cmd/__init__.py b/staffeln/cmd/__init__.py
new file mode 100755
index 0000000..e69de29
--- /dev/null
+++ b/staffeln/cmd/__init__.py
diff --git a/staffeln/cmd/api.py b/staffeln/cmd/api.py
new file mode 100755
index 0000000..cc7b760
--- /dev/null
+++ b/staffeln/cmd/api.py
@@ -0,0 +1,54 @@
+"""Starter script for Staffeln API service"""
+import os
+import sys
+
+from oslo_log import log as logging
+from oslo_reports import guru_meditation_report as gmr
+
+from staffeln.api import app as api_app
+from staffeln.common import service
+import staffeln.conf
+from staffeln.i18n import _
+from staffeln import version
+
+CONF = staffeln.conf.CONF
+
+LOG = logging.getLogger(__name__)
+
+
+def _get_ssl_configs(use_ssl):
+ if use_ssl:
+ cert_file = CONF.api.ssl_cert_file
+ key_file = CONF.api.ssl_key_file
+
+ if cert_file and not os.path.exists(cert_file):
+ raise RuntimeError(
+ _("Unable to find cert_file : %s") % cert_file)
+
+ if key_file and not os.path.exists(key_file):
+ raise RuntimeError(
+ _("Unable to find key_file : %s") % key_file)
+
+ return cert_file, key_file
+ else:
+ return None
+
+
+def main():
+ service.prepare_service(sys.argv)
+ gmr.TextGuruMeditation.setup_autorun(version, conf=CONF)
+
+ # SSL configuration
+ use_ssl = CONF.api.enabled_ssl
+
+ # Create the WSGI server and start it
+ host, port = CONF.api.host, CONF.api.port
+
+ LOG.info('Starting server in PID %s', os.getpid())
+ LOG.debug("Configuration:")
+ CONF.log_opt_values(LOG, logging.DEBUG)
+
+ LOG.info('Serving on %(proto)s://%(host)s:%(port)s',
+ dict(proto="https" if use_ssl else "http", host=host, port=port))
+
+ api_app.run(host=host, port=port, ssl_context=_get_ssl_configs(use_ssl))
diff --git a/staffeln/cmd/conductor.py b/staffeln/cmd/conductor.py
new file mode 100755
index 0000000..2dd731d
--- /dev/null
+++ b/staffeln/cmd/conductor.py
@@ -0,0 +1,21 @@
+"""Starter script for the staffeln conductor service."""
+
+import cotyledon
+from cotyledon import oslo_config_glue
+
+from staffeln.common import service
+from staffeln import conductor
+import staffeln.conf
+
+
+CONF = staffeln.conf.CONF
+
+
+def main():
+ service.prepare_service()
+
+ sm = cotyledon.ServiceManager()
+ sm.add(conductor.BackupService,
+ workers=CONF.conductor.workers, args=(CONF,))
+ oslo_config_glue.setup(sm, CONF)
+ sm.run()
diff --git a/staffeln/common/__init__.py b/staffeln/common/__init__.py
new file mode 100755
index 0000000..e69de29
--- /dev/null
+++ b/staffeln/common/__init__.py
diff --git a/staffeln/common/config.py b/staffeln/common/config.py
new file mode 100755
index 0000000..c90aa63
--- /dev/null
+++ b/staffeln/common/config.py
@@ -0,0 +1,58 @@
+from oslo_middleware import cors
+from oslo_policy import opts
+
+# from staffeln.common import rpc
+import staffeln.conf
+from staffeln import version
+
+CONF = staffeln.conf.CONF
+
+
+def parse_args(argv, default_config_files=None):
+ # rpc.set_defaults(control_exchange='staffeln')
+ CONF(argv[1:],
+ project='staffeln',
+ version=version.version_info.release_string(),
+ default_config_files=default_config_files)
+ # rpc.init(CONF)
+
+
+def set_config_defaults():
+ """Update default value for configuration options from other namespace.
+
+ Example, oslo lib config options. This is needed for
+ config generator tool to pick these default value changes.
+ https://docs.openstack.org/oslo.config/latest/cli/
+ generator.html#modifying-defaults-from-other-namespaces
+ """
+
+ set_cors_middleware_defaults()
+
+ # TODO(gmann): Remove setting the default value of config policy_file
+ # once oslo_policy change the default value to 'policy.yaml'.
+ # https://github.com/openstack/oslo.policy/blob/a626ad12fe5a3abd49d70e3e5b95589d279ab578/oslo_policy/opts.py#L49
+ opts.set_defaults(CONF, 'policy.yaml')
+
+
+def set_cors_middleware_defaults():
+ """Update default configuration options for oslo.middleware."""
+ cors.set_defaults(
+ allow_headers=['X-Auth-Token',
+ 'X-Identity-Status',
+ 'X-Roles',
+ 'X-Service-Catalog',
+ 'X-User-Id',
+ 'X-Tenant-Id',
+ 'X-OpenStack-Request-ID',
+ 'X-Server-Management-Url'],
+ expose_headers=['X-Auth-Token',
+ 'X-Subject-Token',
+ 'X-Service-Token',
+ 'X-OpenStack-Request-ID',
+ 'X-Server-Management-Url'],
+ allow_methods=['GET',
+ 'PUT',
+ 'POST',
+ 'DELETE',
+ 'PATCH']
+ )
diff --git a/staffeln/common/service.py b/staffeln/common/service.py
new file mode 100755
index 0000000..54b1e62
--- /dev/null
+++ b/staffeln/common/service.py
@@ -0,0 +1,30 @@
+# Copyright 2013 - Red Hat, Inc.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from oslo_log import log as logging
+
+from staffeln.common import config
+import staffeln.conf
+
+CONF = staffeln.conf.CONF
+
+
+def prepare_service(argv=None):
+ if argv is None:
+ argv = []
+ logging.register_options(CONF)
+ config.parse_args(argv)
+ config.set_config_defaults()
+
+ logging.setup(CONF, 'staffeln')
diff --git a/staffeln/common/short_id.py b/staffeln/common/short_id.py
new file mode 100755
index 0000000..be719c9
--- /dev/null
+++ b/staffeln/common/short_id.py
@@ -0,0 +1,49 @@
+"""Utilities for creating short ID strings based on a random UUID.
+The IDs each comprise 12 (lower-case) alphanumeric characters.
+"""
+
+import base64
+import uuid
+
+import six
+
+from staffeln.i18n import _
+
+
+def _to_byte_string(value, num_bits):
+ """Convert an integer to a big-endian string of bytes with padding.
+
+ Padding is added at the end (i.e. after the least-significant bit) if
+ required.
+ """
+ shifts = six.moves.xrange(num_bits - 8, -8, -8)
+ byte_at = lambda off: ((value >> off # noqa: E731
+ if off >= 0 else value << -off) & 0xff)
+ return ''.join(chr(byte_at(offset)) for offset in shifts)
+
+
+def get_id(source_uuid):
+ """Derive a short (12 character) id from a random UUID.
+
+ The supplied UUID must be a version 4 UUID object.
+ """
+ if isinstance(source_uuid, six.string_types):
+ source_uuid = uuid.UUID(source_uuid)
+ if source_uuid.version != 4:
+ raise ValueError(_('Invalid UUID version (%d)') % source_uuid.version)
+
+ # The "time" field of a v4 UUID contains 60 random bits
+ # (see RFC4122, Section 4.4)
+ random_bytes = _to_byte_string(source_uuid.time, 60)
+ # The first 12 bytes (= 60 bits) of base32-encoded output is our data
+ encoded = base64.b32encode(six.b(random_bytes))[:12]
+
+ if six.PY3:
+ return encoded.lower().decode('utf-8')
+ else:
+ return encoded.lower()
+
+
+def generate_id():
+ """Generate a short (12 character), random id."""
+ return get_id(uuid.uuid4())
diff --git a/staffeln/conductor/manage.py b/staffeln/conductor/manage.py
index b8bb91f..6aecec2 100755
--- a/staffeln/conductor/manage.py
+++ b/staffeln/conductor/manage.py
@@ -1,62 +1,31 @@
-from oslo_service import periodic_task
-
+import cotyledon
+from oslo_log import log
import staffeln.conf
-from staffeln.db import base
+import sys
+import threading
+
+LOG = log.getLogger(__name__)
CONF = staffeln.conf.CONF
-class PeriodicTasks(periodic_task.PeriodicTasks):
- def __init__(self):
- super(PeriodicTasks, self).__init__(CONF)
+class BackupService(cotyledon.Service):
+ name = "conductor"
+ def __init__(self, worker_id, conf):
+ super(BackupService, self).__init__(worker_id)
+ self._shutdown = threading.Event()
+ self.conf = conf
+ LOG.error("%s init" % self.name)
-class Manager(base.Base, PeriodicTasks):
+ def run(self):
+ LOG.error("%s run" % self.name)
+ self._shutdown.wait()
- def __init__(self, host=None, service_name='undefined'):
- if not host:
- host = CONF.host
- self.host = host
- self.service_name = service_name
- super(Manager, self).__init__()
+ def terminate(self):
+ LOG.error("%s terminate" % self.name)
+ self._shutdown.set()
+ sys.exit(42)
- def periodic_tasks(self, context, raise_on_error=False):
- """Tasks to be run at a periodic interval."""
- return self.run_periodic_tasks(context, raise_on_error=raise_on_error)
-
- def init_host(self):
- """Hook to do additional manager initialization when one requests
- the service be started. This is called before any service record
- is created.
- Child classes should override this method.
- """
- pass
-
- def cleanup_host(self):
- """Hook to do cleanup work when the service shuts down.
- Child classes should override this method.
- """
- pass
-
- def pre_start_hook(self):
- """Hook to provide the manager the ability to do additional
- start-up work before any RPC queues/consumers are created. This is
- called after other initialization has succeeded and a service
- record is created.
- Child classes should override this method.
- """
- pass
-
- def post_start_hook(self):
- """Hook to provide the manager the ability to do additional
- start-up work immediately after a service creates RPC consumers
- and starts 'running'.
- Child classes should override this method.
- """
- pass
-
- def reset(self):
- """Hook called on SIGHUP to signal the manager to re-read any
- dynamic configuration or do any reconfiguration tasks.
- """
- pass
+ def reload(self):
+ LOG.error("%s reload" % self.name)
diff --git a/staffeln/conf/.conductor.py.swp b/staffeln/conf/.conductor.py.swp
deleted file mode 100755
index 687af31..0000000
--- a/staffeln/conf/.conductor.py.swp
+++ /dev/null
Binary files differ
diff --git a/staffeln/conf/__init__.py b/staffeln/conf/__init__.py
new file mode 100755
index 0000000..c934096
--- /dev/null
+++ b/staffeln/conf/__init__.py
@@ -0,0 +1,10 @@
+from oslo_config import cfg
+
+from staffeln.conf import api
+from staffeln.conf import conductor
+
+
+CONF = cfg.CONF
+
+api.register_opts(CONF)
+conductor.register_opts(CONF)
diff --git a/staffeln/conf/api.py b/staffeln/conf/api.py
new file mode 100755
index 0000000..e146689
--- /dev/null
+++ b/staffeln/conf/api.py
@@ -0,0 +1,29 @@
+from oslo_config import cfg
+
+
+api_group = cfg.OptGroup(
+ 'api',
+ title='API options',
+ help='Options under this group are used to define staffeln API.'
+)
+
+
+test_opts = [
+ cfg.StrOpt(
+ 'api_test_option',
+ default='test',
+ deprecated_group='DEFAULT',
+ help='test options'
+ ),
+]
+
+API_OPTS = (test_opts)
+
+
+def register_opts(conf):
+ conf.register_group(api_group)
+ conf.register_opts(API_OPTS, group=api_group)
+
+
+def list_opts():
+ return {api_group: API_OPTS}
diff --git a/staffeln/conf/conductor.py b/staffeln/conf/conductor.py
index 72a3482..47c86c0 100755
--- a/staffeln/conf/conductor.py
+++ b/staffeln/conf/conductor.py
@@ -3,36 +3,38 @@
conductor_group = cfg.OptGroup(
'conductor',
title='Conductor Options',
- help="""
-Options under this group are used to define Conductor's configuration.
-""",
+ help='Options under this group are used '
+ 'to define Conductor\'s configuration.',
)
-backup_opts = [
+backup_opts = [
+ cfg.IntOpt(
+ 'workers',
+ help='The maximum number of conductor processes to '
+ 'fork and run. Default to number of CPUs on the host.'),
cfg.IntOpt(
'backup_period',
default=1,
min=1,
- help="""
-The time of bakup period, the unit is one minute.
-"""),
+ help='The time of bakup period, the unit is one minute.'),
]
-rotation_opts = [
+rotation_opts = [
cfg.IntOpt(
'rotation_default_period',
default=1,
min=1,
- help="""
-The time of rotation period, the unit is one day.
-"""),
+ help='The time of rotation period, the unit is one day.'),
]
+CONDUCTOR_OPTS = (backup_opts, rotation_opts)
+
def register_opts(conf):
conf.register_group(conductor_group)
+ conf.register_opts(CONDUCTOR_OPTS, group=conductor_group)
def list_opts():
return {"DEFAULT": backup_opts,
- conductor_group: rotation_opts}
+ conductor_group: CONDUCTOR_OPTS}
diff --git a/staffeln/conf/wsgi.py b/staffeln/conf/wsgi.py
deleted file mode 100755
index 4b467b9..0000000
--- a/staffeln/conf/wsgi.py
+++ /dev/null
@@ -1,28 +0,0 @@
-from oslo_config import cfg
-
-api_group = cfg.OptGroup('api',
- title='API options',
- help="""
-Options under this group are used to define staffeln API.
-""")
-
-
-test_opts = [
- cfg.StrOpt("api_test_option",
- default="test",
- deprecated_group="DEFAULT",
- help="""
-test options
-"""),
-]
-
-API_OPTS = (test_opts)
-
-
-def register_opts(conf):
- conf.register_group(api_group)
- conf.register_opts(API_OPTS, group=api_group)
-
-
-def list_opts():
- return {api_group: API_OPTS}
diff --git a/staffeln/db/base.py b/staffeln/db/base.py
index 5eed9c3..de0d7c3 100755
--- a/staffeln/db/base.py
+++ b/staffeln/db/base.py
@@ -1,5 +1,6 @@
"""Database setup and migration commands."""
+
class base:
def __init__(self):
- pass
\ No newline at end of file
+ pass
diff --git a/staffeln/i18n.py b/staffeln/i18n.py
new file mode 100755
index 0000000..462c91c
--- /dev/null
+++ b/staffeln/i18n.py
@@ -0,0 +1,20 @@
+"""oslo.i18n integration module.
+See http://docs.openstack.org/developer/oslo.i18n/usage.html .
+"""
+
+import oslo_i18n
+
+DOMAIN = 'staffeln'
+
+_translators = oslo_i18n.TranslatorFactory(domain=DOMAIN)
+
+# The primary translation function using the well-known name "_"
+_ = _translators.primary
+
+
+def translate(value, user_locale):
+ return oslo_i18n.translate(value, user_locale)
+
+
+def get_available_languages():
+ return oslo_i18n.get_available_languages(DOMAIN)
diff --git a/staffeln/objects/__init__.py b/staffeln/objects/__init__.py
new file mode 100755
index 0000000..e69de29
--- /dev/null
+++ b/staffeln/objects/__init__.py
diff --git a/staffeln/objects/base.py b/staffeln/objects/base.py
new file mode 100755
index 0000000..88b94b7
--- /dev/null
+++ b/staffeln/objects/base.py
@@ -0,0 +1,31 @@
+"""Staffeln common internal object model"""
+
+from oslo_versionedobjects import base as ovoo_base
+# from oslo_versionedobjects import fields as ovoo_fields
+
+
+remotable_classmethod = ovoo_base.remotable_classmethod
+remotable = ovoo_base.remotable
+
+
+class StaffelnObject(ovoo_base.VersionedObject):
+ """Base class and object factory.
+
+ This forms the base of all objects that can be remoted or instantiated
+ via RPC. Simply defining a class that inherits from this base class
+ will make it remotely instantiatable. Objects should implement the
+ necessary "get" classmethod routines as well as "save" object methods
+ as appropriate.
+ """
+ OBJ_SERIAL_NAMESPACE = 'staffeln_object'
+ OBJ_PROJECT_NAMESPACE = 'staffeln'
+
+ def as_dict(self):
+ return {k: getattr(self, k)
+ for k in self.fields
+ if self.obj_attr_is_set(k)}
+
+
+class StaffelnObjectSerializer(ovoo_base.VersionedObjectSerializer):
+ # Base class to use for object hydration
+ OBJ_BASE_CLASS = StaffelnObject
diff --git a/staffeln/version.py b/staffeln/version.py
new file mode 100755
index 0000000..0f9e8d2
--- /dev/null
+++ b/staffeln/version.py
@@ -0,0 +1,5 @@
+import pbr.version
+
+
+version_info = pbr.version.VersionInfo('staffeln')
+version_string = version_info.version_string