File ardana-installer-server-8.0+git.1542817521.6bc7c3b.obscpio of Package ardana-installer-server
07070100000000000081A40000000000000000000000015BF586F10000006B000000000000000000000000000000000000003E00000000ardana-installer-server-8.0+git.1542817521.6bc7c3b/.gitignore.venv
.tox
dist
.eggs
*egg-info/
build
/data
log
local.cfg
*.pyc
AUTHORS
ChangeLog
etc/service.conf.sample
07070100000001000081A40000000000000000000000015BF586F1000027A1000000000000000000000000000000000000003B00000000ardana-installer-server-8.0+git.1542817521.6bc7c3b/LICENSE
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.
07070100000002000081A40000000000000000000000015BF586F100000473000000000000000000000000000000000000003E00000000ardana-installer-server-8.0+git.1542817521.6bc7c3b/README.rst..
(c) Copyright 2017-2018 SUSE LLC
==============================
Ardana Installer Server
==============================
REST server for Ardana cloud installer
---------------
Getting Started
---------------
Start the service using::
Use 'tox -e runserver' to start the server (on port 8081)
---
API
---
All REST endpoints begin with ``/api/v1``. The following endpoints are
supported:
``/api/v1/progress`` (``GET`` or ``POST``)
Data to track the progress of the installer.
``/api/v1/server`` (``GET``,``POST``,``PUT``,``DELETE``)
Scratch space for general server details
``/api/v1/sm/servers`` (``GET``)
Retrieves a list of servers from SUSE Manager
``/api/v1/sm/servers/{id}`` (``GET``)
Retrieves the details of the given server from SUSE Manager
``/api/v1/ov/servers`` (``GET``)
Retrieves a list of servers from HPE OneView
``/api/v1/ov/servers/{id}`` (``GET``)
Retrieves the details of the given server from HPE OneView
``/api/v1/clm/...``
Requests to this URL are forwarded to the corresponding
endpoint under ``/api/v2`` in the Ardana Service
07070100000003000041ED0000000000000000000000025BF586F100000000000000000000000000000000000000000000004B00000000ardana-installer-server-8.0+git.1542817521.6bc7c3b/ardana_installer_server07070100000004000081A40000000000000000000000015BF586F10000047C000000000000000000000000000000000000005700000000ardana-installer-server-8.0+git.1542817521.6bc7c3b/ardana_installer_server/__init__.py# (c) Copyright 2017-2018 SUSE LLC
#
# 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 eventlet import monkey_patch as monkey_patch
from flask_socketio import SocketIO
# IMPORTANT!
# When using eventlet, monkey_patch is needed in order to propertly handle
# IO asyncronously. Without this, the reading of stdout from the playbook
# run will block until after that playbook has finished.
monkey_patch()
# When using eventlet, it is important to monkeypatch so that the IO does not
# hang. When using the "threading" model, long polling is used instead of
# WebSockets, and its performance is a bit lower
socketio = SocketIO(async_mode="eventlet")
07070100000005000081A40000000000000000000000015BF586F100000709000000000000000000000000000000000000005400000000ardana-installer-server-8.0+git.1542817521.6bc7c3b/ardana_installer_server/admin.py# (c) Copyright 2018 SUSE LLC
#
# 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 flask import Blueprint
from flask import jsonify
from flask import request
from oslo_config import cfg
import threading
import time
from util import ping
bp = Blueprint('admin', __name__)
CONF = cfg.CONF
SUCCESS = {"success": True}
def update_trigger_file():
with open(CONF.general.restart_trigger_file, 'w') as f:
f.write("Triggered restart at %s\n" % time.asctime())
@bp.route("/api/v1/restart", methods=['POST'])
def restart():
"""Requests the service to restart after a specified delay, in seconds
.. :quickref: Admin; Requests a service restart after a delay
**Example Request**:
.. sourcecode:: http
POST /api/v2/user HTTP/1.1
Content-Type: application/json
{
"delay": 60
}
"""
info = request.get_json() or {}
delay_secs = int(info.get('delay', 0))
t = threading.Timer(delay_secs, update_trigger_file)
t.start()
return jsonify(SUCCESS)
@bp.route("/api/v1/connection_test", methods=['POST'])
def connection_test():
body = request.get_json() or {}
host = body['host']
try:
ping(host, 22)
return jsonify('Success')
except Exception as e:
return jsonify(error=str(e)), 404
07070100000006000081A40000000000000000000000015BF586F100000396000000000000000000000000000000000000005500000000ardana-installer-server-8.0+git.1542817521.6bc7c3b/ardana_installer_server/ardana.py# (c) Copyright 2017-2018 SUSE LLC
#
# 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 . import util
from flask import Blueprint
from flask import request
from oslo_config import cfg
bp = Blueprint('ardana', __name__)
@bp.route("/api/v1/clm/<path:url>", methods=['GET', 'POST', 'PUT', 'DELETE'])
def ardana(url):
url = cfg.CONF.general.ardana_service_url + "/api/v2/" + url
return util.forward(url, request)
07070100000007000081A40000000000000000000000015BF586F100000864000000000000000000000000000000000000005500000000ardana-installer-server-8.0+git.1542817521.6bc7c3b/ardana_installer_server/config.py# (c) Copyright 2017-2018 SUSE LLC
#
# 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_config import cfg
general_opts = [
cfg.IPOpt('host',
default='0.0.0.0',
help='IP address to listen on.'),
cfg.PortOpt('port',
default=2209,
help='Port number to listen on.'),
cfg.StrOpt('db_file',
default='/tmp/db.json',
help='Location of database for discovered servers'),
cfg.StrOpt('progress_file',
default='/tmp/progress.json',
help='Location of file to track progress through UI'),
cfg.StrOpt('restart_trigger_file',
default='/tmp/cloud_install_ui_trigger.txt',
help='Location of file to trigger a flask restart to pickup new configs'),
cfg.StrOpt('ui_home',
default='web',
help='Location of static files to serve'),
cfg.URIOpt('ardana_service_url',
default='http://localhost:9085',
help='URL of ardana service'),
]
url_opts = [
cfg.StrOpt('horizon',
help='Location of horizon UI'),
cfg.StrOpt('opsconsole',
help='Location of operations console UI'),
]
url_group = cfg.OptGroup(name='urls',
title='URLs to be displayed on the completion page')
CONF = cfg.CONF
CONF.register_opts(general_opts, 'general')
CONF.register_group(url_group)
CONF.register_opts(url_opts, url_group)
# This function is used by "tox -e genopts" to generate a config file
# containing all options
def list_opts():
return [('general', general_opts), ('urls', url_opts)]
07070100000008000081A40000000000000000000000015BF586F100000C26000000000000000000000000000000000000005300000000ardana-installer-server-8.0+git.1542817521.6bc7c3b/ardana_installer_server/main.py# (c) Copyright 2017-2018 SUSE LLC
#
# 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 flask import Flask
from flask_cors import CORS
import os
from oslo_config import cfg
from oslo_log import log as logging
import time
from ardana_installer_server import admin
from ardana_installer_server import ardana
from ardana_installer_server import config # noqa: F401
from ardana_installer_server import oneview
from ardana_installer_server import socket_proxy
from ardana_installer_server import socketio
from ardana_installer_server import suse_manager
from ardana_installer_server import ui
from ardana_installer_server.util import CustomJSONEncoder
LOG = logging.getLogger(__name__)
CONF = cfg.CONF
logging.register_options(CONF)
# Load config options from config file or command line
CONF()
# Setup the logging per the config options
logging.setup(CONF, 'ardana_installer_service')
app = Flask(__name__,
static_url_path='',
static_folder=CONF.general.ui_home)
app.register_blueprint(admin.bp)
app.register_blueprint(ardana.bp)
app.register_blueprint(ui.bp)
app.register_blueprint(oneview.bp)
app.register_blueprint(suse_manager.bp)
app.register_blueprint(socket_proxy.bp)
app.json_encoder = CustomJSONEncoder
# Flask logging is broken, and it is a time bomb: by default it does nothing,
# but the first time an exception happens, it creates a new logger that
# interferes with normal python logging, which messes up all subsequent log
# messages. This bug was reported in
# https://github.com/pallets/flask/issues/641 and is expected to be fixed in
# the future when Flask 1.0 ships. Referring to app.logger forces this
# creation via Flask's logger property handler. We then clean up the mess it
# makes
app.logger # initialize flask logging (screwing up logging)
app.logger.handlers = [] # clear out the newly creating logger
app.logger.propagate = True # let messages be handled by normal logging
CORS(app)
@app.route('/')
def root():
return app.send_static_file('index.html')
def main():
socketio.init_app(app)
with open(CONF.general.restart_trigger_file , 'w') as f:
f.write("Started at %s\n" % time.asctime())
# The 'log' parameter avoids running in debug mode, which suppresses the
# debug message that is emitted on *every* incoming request.
socketio.run(app,
host=CONF.general.host,
port=CONF.general.port,
log=LOG,
use_reloader=True,
extra_files=[CONF.general.restart_trigger_file])
if __name__ == "__main__":
main()
07070100000009000081A40000000000000000000000015BF586F100000B72000000000000000000000000000000000000005600000000ardana-installer-server-8.0+git.1542817521.6bc7c3b/ardana_installer_server/oneview.py# (c) Copyright 2017-2018 SUSE LLC
#
# 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 flask import abort
from flask import Blueprint
from flask import jsonify
from flask import request
import json
import requests
from util import ping
bp = Blueprint('oneview', __name__)
"""
Calls to HPE OneView
"""
@bp.route("/api/v1/ov/connection_test", methods=['POST'])
def connection_test():
creds = request.get_json() or {}
host = creds['host']
try:
ping(host, 443)
except Exception as e:
return jsonify(error=str(e)), 404
verify = True
secured = request.headers.get('Secured')
if secured == 'false':
verify = False
try:
url = "https://" + host + "/rest/login-sessions"
headers = {'X-Api-Version': '200', 'Content-Type': 'application/json'}
data = {'userName': creds['username'], 'password': creds['password']}
response = requests.post(url, data=json.dumps(data), headers=headers,
verify=verify)
except Exception as e:
if 'SSLError' in str(e):
return jsonify(error=str(e)), 403
else:
return jsonify(error=str(e)), 401
if not response.status_code == 200:
return jsonify(error=response.json()['message']), 400
return jsonify(response.json())
@bp.route("/api/v1/ov/servers")
def ov_server_list():
verify = True
secured = request.headers.get('Secured')
if secured == 'false':
verify = False
key = request.headers.get('Auth-Token')
url = request.headers.get('Ov-Url')
try:
request_url = url + \
'/rest/server-hardware?start=0&count=-1&sort=position:desc'
head = {'Auth': key, 'X-Api-Version': '200'}
response = requests.get(request_url, headers=head, verify=verify)
return jsonify(response.json())
except Exception:
abort(400)
@bp.route("/api/v1/ov/servers/<id>")
def ov_server_details(id):
verify = True
secured = request.headers.get('Secured')
if secured == 'false':
verify = False
key = request.headers.get('Auth-Token')
url = request.headers.get('Ov-Url')
try:
request_url = url + '/rest/server-hardware/' + id
head = {'Auth': key, 'X-Api-Version': '200'}
response = requests.get(request_url, headers=head, verify=verify)
return jsonify(response.json())
except Exception:
abort(400)
0707010000000A000081A40000000000000000000000015BF586F100000ACB000000000000000000000000000000000000005B00000000ardana-installer-server-8.0+git.1542817521.6bc7c3b/ardana_installer_server/socket_proxy.py# (c) Copyright 2017-2018 SUSE LLC
#
# 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 . import socketio
import eventlet
from flask import Blueprint
from flask import copy_current_request_context
from flask import request
from flask_socketio import emit
from oslo_config import cfg
from oslo_log import log as logging
from socketIO_client import BaseNamespace
from socketIO_client import SocketIO
import sys
if sys.version_info.major < 3:
from urlparse import urlparse
else:
from urllib.parse import urlparse
CONF = cfg.CONF
LOG = logging.getLogger(__name__)
bp = Blueprint('socket_proxy', __name__)
LOG_NAMESPACE = '/log'
EVENT_NAMESPACE = '/event'
class SocketProxy(object):
def __init__(self, id, host, port):
self.client = SocketIO(host, port, BaseNamespace)
self.client.on('log', self.on_log)
self.client.on('end', self.on_end)
self.client.on('playbook-start', self.on_playbook_start)
self.client.on('playbook-stop', self.on_playbook_stop)
self.client.on('playbook-error', self.on_playbook_error)
self.client.emit('join', id)
def on_log(self, message):
emit("log", message)
def on_end(self, message):
emit("end")
self.client.disconnect()
def on_playbook_start(self, playbook):
emit("playbook-start", playbook)
def on_playbook_stop(self, playbook):
emit("playbook-stop", playbook)
def on_playbook_error(self, playbook):
emit("playbook-error", playbook)
def wait(self):
self.client.wait() # seconds=5)
# Hack! _close is needed to *really* close the connection
self.client._close()
@socketio.on('join')
def on_join(id):
LOG.debug("Received request by %s to join %s", request.sid, id)
@copy_current_request_context
def wait_for_messages(id):
# Per the socketIO-client documentation, the hostname parameter
# must be prefixed with https:// in order to use SSL.
url = urlparse(CONF.general.ardana_service_url)
if url.scheme == 'https':
host = 'https://' + url.hostname
else:
host = url.hostname
proxy = SocketProxy(id, host, url.port)
proxy.wait()
eventlet.spawn(wait_for_messages, id)
0707010000000B000081A40000000000000000000000015BF586F100000D52000000000000000000000000000000000000005B00000000ardana-installer-server-8.0+git.1542817521.6bc7c3b/ardana_installer_server/suse_manager.py# (c) Copyright 2017-2018 SUSE LLC
#
# 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 flask import Blueprint
from flask import jsonify
from flask import request
import socket
import ssl
import sys
if sys.version_info.major < 3:
from xmlrpclib import ServerProxy
else:
from xmlrpc.client import ServerProxy
bp = Blueprint('suse-manager', __name__)
TIMEOUT = 2
"""
Calls to SUSE Manager
"""
def get_client(url, verify_ssl):
context = ssl._create_default_https_context()
if verify_ssl == 'false':
context = ssl._create_unverified_context()
client = ServerProxy(url, verbose=0, context=context)
return client
@bp.route("/api/v1/sm/connection_test", methods=['POST'])
def connection_test():
context = ssl._create_default_https_context()
verify_ssl = request.headers.get('Secured')
if verify_ssl == 'false':
context = ssl._create_unverified_context()
creds = request.get_json() or {}
port = "443"
if creds['port'] and creds['port'] != 0:
port = creds['port']
# check the host and port first before login
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(TIMEOUT)
s.connect((creds['host'], int(port)))
except Exception as e:
return jsonify(error=str(e)), 404
# login
try:
suma_url = "https://" + creds['host'] + ":" + str(port) + "/rpc/api"
suma_username = creds['username']
suma_password = creds['password']
client = ServerProxy(suma_url, verbose=0, context=context)
key = client.auth.login(suma_username, suma_password)
return jsonify(key)
except Exception as e:
if 'SSL:' in str(e) or 'doesn\'t match' in str(e):
return jsonify(error=str(e)), 403
else:
return jsonify(error=str(e)), 401
@bp.route("/api/v1/sm/servers")
def sm_server_list():
try:
key = request.headers.get('Auth-Token')
url = request.headers.get('Suse-Manager-Url')
verify_ssl = request.headers.get('Secured')
client = get_client(url, verify_ssl)
server_list = client.system.listActiveSystems(key)
return jsonify(server_list)
except Exception as e:
return jsonify(error=str(e)), 400
@bp.route("/api/v1/sm/servers/<id>")
def sm_server_details(id):
try:
key = request.headers.get('Auth-Token')
url = request.headers.get('Suse-Manager-Url')
verify_ssl = request.headers.get('Secured')
client = get_client(url, verify_ssl)
detail_list = client.system.listActiveSystemsDetails(key, int(id))
detail = detail_list[0]
detail.update(client.system.getDetails(key, int(id)))
detail.update({"running_kernel": client.system.getRunningKernel(
key, int(id))})
return jsonify(detail)
except Exception as e:
return jsonify(error=str(e)), 400
0707010000000C000081A40000000000000000000000015BF586F100001EF2000000000000000000000000000000000000005100000000ardana-installer-server-8.0+git.1542817521.6bc7c3b/ardana_installer_server/ui.py# (c) Copyright 2017-2018 SUSE LLC
#
# 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 flask import abort
from flask import Blueprint
from flask import jsonify
from flask import request
import json
import os
from oslo_config import cfg
import pwd
import re
import subprocess
from tinydb import Query
from tinydb import TinyDB
bp = Blueprint('ui', __name__)
SUCCESS = {"success": True}
CONF = cfg.CONF
"""
Calls handled locally to support the UI
"""
@bp.route("/api/v1/progress", methods=['GET'])
def get_progress():
contents = ''
try:
with open(CONF.general.progress_file) as f:
contents = json.load(f)
except IOError:
pass
return jsonify(contents)
@bp.route("/api/v1/progress", methods=['POST'])
def save_progress():
data = request.get_json()
try:
with open(CONF.general.progress_file, "w") as f:
json.dump(data, f)
return jsonify(SUCCESS)
except Exception:
abort(400)
# /server CRUD operations
@bp.route("/api/v1/server", methods=['POST'])
def insert_servers():
"""Inserts a list of servers to the server table.
'uid' and 'source' fields must be unique
**Example Request**:
.. sourcecode:: http
POST /api/v1/server HTTP/1.1
where the body contains a list of server dictionaries
"""
db = TinyDB(CONF.general.db_file)
server_table = db.table('servers')
server = Query()
try:
data = request.get_json()
# Check for dupes and missing uid & server keys
for entry in data:
if not set(['id', 'uid', 'source']).issubset(entry):
return jsonify(error="There is one or more entries missing "
"id , uid or source"), 400
sid = entry['uid']
src = entry['source']
if not set(src.split(',')).issubset(['sm', 'ov', 'manual']):
return jsonify(error="source=%s for uid=%s is "
"invalid" % (src, sid)), 400
server_entries = server_table.search(
(server.uid == sid) & (server.source == src))
if server_entries:
return jsonify(error="There is an entry already matching "
"uid=%s and server=%s" % (sid, src)), 400
server_table.insert_multiple(server for server in data)
return jsonify(SUCCESS)
except Exception:
abort(400)
@bp.route("/api/v1/server", methods=['GET'])
def get_servers():
"""Returns a list of server(s) given a list of 'source'
'source' is a comma-delimited list joined by an OR statement
**Example Request**:
.. sourcecode:: http
GET /api/v1/server?source=src1,src2 HTTP/1.1
"""
db = TinyDB(CONF.general.db_file)
server_table = db.table('servers')
try:
src = request.args.get('source', None)
if not src:
return jsonify(server_table.all())
results = server_table.search(create_query(src))
return jsonify(results)
except Exception:
abort(400)
@bp.route("/api/v1/server", methods=['PUT'])
def update_server():
"""Update a single server entry (dict) into the server table.
'id' and 'source' fields must be unique
**Example Request**:
.. sourcecode:: http
PUT /api/v1/server HTTP/1.1
where the body contains a dictionary containing a server's details
"""
db = TinyDB(CONF.general.db_file)
server_table = db.table('servers')
server = Query()
try:
entry = request.get_json()
if not set(['uid', 'source']).issubset(entry):
return jsonify(error="There is one or more entries missing "
"uid or source"), 400
sid = entry['uid']
src = entry['source']
if not set(src.split(',')).issubset(['sm', 'ov', 'manual']):
return jsonify(error="source=%s for uid=%s is "
"invalid" % (src, sid)), 400
server_entries = server_table.search(
(server.uid == sid) & (server.source == src))
if not server_entries:
return jsonify(error="uid:%s; source:%s not found "
"to be updated" % (sid, src)), 404
server_table.remove(
(server.uid == sid) & (server.source == src))
server_table.insert(entry)
return jsonify(SUCCESS)
except Exception:
abort(400)
@bp.route("/api/v1/server", methods=['DELETE'])
def delete_server():
"""Removes servers given a set of search parameters.
The search parameters used are the same as get_servers()
**Example Request**:
.. sourcecode:: http
DELETE /api/v1/server?source=src1,src2&uid=1234 HTTP/1.1
"""
db = TinyDB(CONF.general.db_file)
server_table = db.table('servers')
try:
src = request.args.get('source', None)
uid = request.args.get('uid', None)
if not src:
return jsonify(error="source must be specified"), 400
server_table.remove(create_query(src, uid))
return jsonify(SUCCESS)
except Exception:
abort(400)
def create_query(src, uid=None):
q = Query()
if uid:
return (q.uid == uid)
if src:
if not set(src.split(',')).issubset(['sm', 'ov', 'manual']):
return jsonify(error="specified sources are invalid"), 400
query = None
for source in src.split(','):
if query is None:
query = (q.source == source)
else:
query |= (q.source == source)
return query
@bp.route("/api/v1/ips", methods=['GET'])
def get_ips():
"""Returns list of ip addresses of the local host
**Example Request**:
.. sourcecode:: http
GET /api/v1/ips HTTP/1.1
**Example Response**:
.. sourcecode:: http
HTTP/1.1 200 OK
[
"127.0.0.1",
"192.168.1.200"
]
"""
ips = []
pattern = re.compile(r'inet +([0-9.]+)')
try:
lines = subprocess.check_output(["ip", "-o", "-4", "addr", "show"],
universal_newlines=True)
for line in lines.split('\n'):
match = pattern.search(line)
if match:
ips.append(match.group(1))
except subprocess.CalledProcessError:
pass
return jsonify(ips)
@bp.route("/api/v1/external_urls", methods=['GET'])
def get_external_urls():
"""Returns list of external URLs
Returns the list of external URLs that the customer can access via the
browser once cloud deployment is complete
**Example Request**:
.. sourcecode:: http
GET /api/v1/external_urls HTTP/1.1
**Example Response**:
.. sourcecode:: http
HTTP/1.1 200 OK
{
"horizon": "https://192.168.245.6:443",
"opsconsole": "https://192.168.245.5:9095"
}
"""
cfg.CONF.reload_config_files()
return jsonify(dict(cfg.CONF.urls.items()))
@bp.route("/api/v1/user", methods=['GET'])
def get_user():
"""Returns the username the service is running under
**Example Request**:
.. sourcecode:: http
GET /api/v1/user/1.1
**Example Response**:
.. sourcecode:: http
HTTP/1.1 200 OK
{"username": "myusername"}
"""
user_dict = {'username': pwd.getpwuid(os.getuid()).pw_name}
return jsonify(user_dict)
0707010000000D000081A40000000000000000000000015BF586F1000006E4000000000000000000000000000000000000005300000000ardana-installer-server-8.0+git.1542817521.6bc7c3b/ardana_installer_server/util.py# (c) Copyright 2017-2018 SUSE LLC
#
# 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.
import datetime
from flask import abort
from flask.json import JSONEncoder
import requests
import socket
import sys
if sys.version_info.major < 3:
from xmlrpclib import DateTime
else:
from xmlrpc.client import DateTime
TIMEOUT = 2
class CustomJSONEncoder(JSONEncoder):
def default(self, obj):
try:
if isinstance(obj, DateTime):
return datetime.datetime.strptime(
obj.value, "%Y%m%dT%H:%M:%S").isoformat()
iterable = iter(obj)
except TypeError:
pass
else:
return list(iterable)
return JSONEncoder.default(self, obj)
# Forward the url to the given destination
def forward(url, request):
req = requests.Request(method=request.method, url=url, params=request.args,
headers=request.headers, data=request.data)
resp = requests.Session().send(req.prepare())
return (resp.text, resp.status_code, resp.headers.items())
def ping(host, port):
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(TIMEOUT)
s.connect((host, port))
except Exception:
abort(404)
0707010000000E000041ED0000000000000000000000025BF586F100000000000000000000000000000000000000000000003700000000ardana-installer-server-8.0+git.1542817521.6bc7c3b/etc0707010000000F000081A40000000000000000000000015BF586F100000091000000000000000000000000000000000000004D00000000ardana-installer-server-8.0+git.1542817521.6bc7c3b/etc/config-generator.conf[DEFAULT]
output_file = etc/service.conf.sample
wrap_width = 79
namespace = ardana_installer_server
namespace = oslo.config
namespace = oslo.log
07070100000010000081A40000000000000000000000015BF586F1000001B2000000000000000000000000000000000000004400000000ardana-installer-server-8.0+git.1542817521.6bc7c3b/etc/devtest.conf[DEFAULT]
# Direct logs to a file if desired:
# log_file = /tmp/server.log
# The default level of INFO for engineio and socketio yields messages
# for every line of every log that is transferred through the socket.
# WARN avoids that.
default_log_levels = engineio=WARN,socketio=WARN
[general]
host = 0.0.0.0
port = 8081
db_file = /tmp/db.json
progress_file = /tmp/progress.json
ardana_service_url = http://localhost:9085
[urls]
07070100000011000081A40000000000000000000000015BF586F100000101000000000000000000000000000000000000004400000000ardana-installer-server-8.0+git.1542817521.6bc7c3b/requirements.txteventlet>=0.20.0 # MIT
Flask>=0.10,<1.0 # BSD
Flask-Cors # MIT
Flask-SocketIO # MIT
PyYAML>=3.10.0 # MIT
requests # APACHE2
socketIO-client>=0.7.0 # MIT
tinydb>=3.5.0 # MIT
oslo.config>=4.11.0 # Apache-2.0
oslo.log>=3.30.0 # Apache-2.0
07070100000012000081ED0000000000000000000000015BF586F100000383000000000000000000000000000000000000003D00000000ardana-installer-server-8.0+git.1542817521.6bc7c3b/setup.cfg[metadata]
name = ardana-installer-server
summary = Ardana OpenStack Cloud Installer Server
description-file =
README.rst
author = Ardana developers
author-email = ardana@googlegroups.com
home-page = https://github.com/ArdanaCLM/ardana-installer-server
classifier =
Environment :: OpenStack
Intended Audience :: Information Technology
Intended Audience :: System Administrators
License :: OSI Approved :: Apache Software License
Operating System :: POSIX :: Linux
Programming Language :: Python
Programming Language :: Python :: 2
Programming Language :: Python :: 2.7
Programming Language :: Python :: 3.5
[global]
setup-hooks =
pbr.hooks.setup_hook
[files]
packages = ardana_installer_server
[entry_points]
oslo.config_opts =
ardana_installer_server = ardana_installer_server.config:list_opts
console_scripts =
ardana-installer-server = ardana_installer_server.main:main
07070100000013000081A40000000000000000000000015BF586F1000003EA000000000000000000000000000000000000003C00000000ardana-installer-server-8.0+git.1542817521.6bc7c3b/setup.py# (c) Copyright 2017-2018 SUSE LLC
#
# 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.
#
# THIS FILE IS MANAGED BY THE GLOBAL REQUIREMENTS REPO - DO NOT EDIT
import setuptools
# In python < 2.7.4, a lazy loading of package `pbr` will break
# setuptools if some other modules registered functions in `atexit`.
# solution from: http://bugs.python.org/issue15881#msg170215
try:
import multiprocessing # noqa
except ImportError:
pass
setuptools.setup(
setup_requires=['pbr>=2.0.0'],
pbr=True)
07070100000014000081A40000000000000000000000015BF586F100000236000000000000000000000000000000000000004900000000ardana-installer-server-8.0+git.1542817521.6bc7c3b/test-requirements.txt# The order of packages is significant, because pip processes them in the order
# of appearance. Changing the order has an impact on the overall integration
# process, which may cause wedges in the gate later.
# Order matters to the pip dependency resolver, so sorting this file
# changes how packages are installed. New dependencies should be
# added in alphabetical order, however, some dependencies may need to
# be installed in a specific order.
#
# Hacking should appear first in case something else depends on pep8
hacking!=0.13.0,<0.14,>=0.12.0 # Apache-2.0
07070100000015000081A40000000000000000000000015BF586F100000448000000000000000000000000000000000000003B00000000ardana-installer-server-8.0+git.1542817521.6bc7c3b/tox.ini[tox]
envlist = py27,py34,pep8
minversion = 2.0
skipsdist = True
[testenv]
usedevelop = True
install_command = pip install -c{env:UPPER_CONSTRAINTS_FILE:https://git.openstack.org/cgit/openstack/requirements/plain/upper-constraints.txt} {opts} {packages}
setenv = VIRTUAL_ENV={envdir}
deps =
-r{toxinidir}/requirements.txt
-r{toxinidir}/test-requirements.txt
commands =
venv: {posargs}
whitelist_externals =
bash
[testenv:runserver]
passenv = REQUESTS_CA_BUNDLE
commands =
{envpython} ardana_installer_server/main.py --config-file etc/devtest.conf {posargs}
[testenv:py27]
commands =
{envpython} {toxinidir}/setup.py test {posargs}
[testenv:py34]
commands =
{envpython} {toxinidir}/setup.py test {posargs}
[testenv:pep8]
commands =
{envbindir}/flake8 {posargs} .
[testenv:testclient]
commands =
{envpython} client.py {posargs}
[testenv:genconfig]
commands = oslo-config-generator --config-file=etc/config-generator.conf
[flake8]
# H102 not ready to require license headers
ignore = E251,H102,H304
exclude = .git,.venv,.tox,dist,*egg-info,build,.eggs
max-complexity=30
07070100000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000B00000000TRAILER!!!94 blocks