Commit 1e644cab authored by Thomas Phil's avatar Thomas Phil

RM-54 tussendoorcommitje

parent 49e2f8ef
import strongr.core
from strongr.core.domain.restdomain import RestDomain
from strongr.restdomain.model.gateways import Gateways
from .wrapper import Command
from flask import Flask
class RunRestServerCommand(Command):
"""
......@@ -10,48 +8,4 @@ class RunRestServerCommand(Command):
restdomain:startserver
"""
def handle(self):
config = strongr.core.Core.config()
backend = config.restdomain.backend.strip().lower()
self.info("Starting server using {}".format(backend))
wsgi_query_factory = RestDomain.wsgiQueryFactory()
wsgi_query_bus = RestDomain.wsgiService().getQueryBus()
blueprints = wsgi_query_bus.handle(wsgi_query_factory.newRetrieveBlueprints())
app = Flask(__name__)
# the oauth2 lib can not work with templates,
# this hack was proposed as a temp fix on the
# libraries github. Use this for now, we
# should refactor this later.
# https://github.com/lepture/flask-oauthlib/issues/180
from strongr.restdomain.api.oauth2 import bind_oauth2
oauth2 = bind_oauth2(app)
app.oauth2 = oauth2
for blueprint in blueprints:
app.register_blueprint(blueprint)
if backend == 'flask':
app.run(**config.restdomain.flask.as_dict())
elif backend == 'gunicorn':
from gunicorn.app.base import BaseApplication
# put WSGIServer class here for now
# this should be refactored later
class WSGIServer(BaseApplication):
def __init__(self, app):
self.application = app
super(WSGIServer, self).__init__("%(prog)s [OPTIONS]")
def load_config(self):
for key in config.restdomain.gunicorn:
self.cfg.set(key, config[key])
def load(self):
return self.application
WSGIServer(app).run()
Gateways.app().run()
......@@ -3,4 +3,3 @@ from .listdeployedvmshandler import ListDeployedVmsHandler
from .deployvmshandler import DeployVmsHandler
from .requestjidstatushandler import RequestJidStatusHandler
from .destroyvmshandler import DestroyVmsHandler
from .jobfinishedhandler import JobFinishedHandler
from strongr.clouddomain.handler.abstract.cloud import AbstractJobFinishedHandler
class JobFinishedHandler(AbstractJobFinishedHandler):
def __call__(self, command):
pass
# convert command to inter-domain event
from strongr.clouddomain.handler.abstract.cloud import AbstractRequestJidStatusHandler
import salt.runner
import strongr.core
import strongr.core.gateways
class RequestJidStatusHandler(AbstractRequestJidStatusHandler):
def __call__(self, query):
opts = salt.config.master_config(strongr.core.Core.config().clouddomain.OpenNebula.salt_config + '/master')
opts['quiet'] = True
runner = salt.runner.RunnerClient(opts)
cache = strongr.core.gateways.Gateways.cache()
if not cache.exists('clouddomain.jobs.running'):
cache.set('clouddomain.jobs.running', runner.cmd('jobs.active'), 1)
jobs = cache.get('clouddomain.jobs.running')
if jobs is None:
jobs = {}
if query.jid not in jobs: # we only want to give status when the job is finished running
result = runner.cmd('jobs.lookup_jid', [query.jid])
return result
return None
pass # not really required yet
import strongr.core
import strongr.core.domain.restdomain
from flask_oauthlib.provider import OAuth2Provider
from datetime import datetime, timedelta
from flask import make_response, jsonify, g
from strongr.restdomain.model.oauth2 import Token
from strongr.core.gateways import Gateways
core = strongr.core.Core
rest_domain = strongr.core.domain.restdomain.RestDomain
oauth2_service = rest_domain.oauth2Service()
oauth2_command_factory = rest_domain.oauth2CommandFactory()
oauth2_command_bus = oauth2_service.getCommandBus()
oauth2_query_factory = rest_domain.oauth2QueryFactory()
oauth2_query_bus = oauth2_service.getQueryBus()
def bind_oauth2(app):
oauth = OAuth2Provider(app)
@oauth.clientgetter
def get_client(client_id):
print('get_client')
return oauth2_query_bus.handle(oauth2_query_factory.newRetrieveClient(client_id))
@oauth.grantgetter
def get_grant(client_id, code):
print('get_grant')
return oauth2_query_bus.handle(oauth2_query_factory.newRetrieveGrant(client_id, code))
@oauth.tokengetter
def get_token(access_token=None, refresh_token=None):
print('get_token')
if access_token:
return oauth2_query_bus.handle(oauth2_query_factory.newRetrieveTokenByAccessToken(access_token))
if refresh_token:
return oauth2_query_bus.handle(oauth2_query_factory.newRetrieveTokenByRefreshToken(refresh_token))
return None
@oauth.grantsetter
def set_grant(client_id, code, request, *args, **kwargs):
print('set_grant')
expires = datetime.utcnow() + timedelta(seconds=600)
oauth2_command_bus.handle(oauth2_command_factory.newAppendGrant(
client_id=client_id,
code=code['code'],
redirect_uri=request.redirect_uri,
scope=' '.join(request.scopes),
user_id=g.user.id,
expires=expires
))
@oauth.tokensetter
def set_token(token, request, *args, **kwargs):
print('set_token')
# In real project, a token is unique bound to user and client.
# Which means, you don't need to create a token every time.
tok = Token(**token)
tok.user_id = request.user.id
tok.client_id = request.client.client_id
session = Gateways.sqlalchemy_session()
session.add(tok)
session.commit()
@oauth.usergetter
def get_user(username, password, *args, **kwargs):
# # This is optional, if you don't need password credential
# # there is no need to implement this method
print('get_user')
# return User.query.filter_by(username=username).first()
@app.route('/oauth/authorize', methods=['GET', 'POST'])
@oauth.authorize_handler
def authorize(request, *args, **kwargs):
print('authorize_request')
# NOTICE: for real project, you need to require login
#if request.method == 'GET':
# render a page for user to confirm the authorization
# return render_template('confirm.html')
if request.method == 'HEAD':
# if HEAD is supported properly, request parameters like
# client_id should be validated the same way as for 'GET'
response = make_response('', 200)
response.headers['X-Client-ID'] = kwargs.get('client_id')
return response
confirm = request.form.get('confirm', 'no')
return confirm == 'yes'
@app.route('/oauth/token', methods=['POST', 'GET'])
@oauth.token_handler
def access_token():
print('access_token')
return {}
@app.route('/oauth/revoke', methods=['POST'])
@oauth.revoke_handler
def revoke_token():
print('revoke_token')
pass
@oauth.invalid_response
def require_oauth_invalid(req):
print('require_oauth_invalid')
return jsonify(message=req.error_message), 401
return oauth
from flask_restplus import Namespace
ns = Namespace('oauth', description='Operations related to oauth2 login')
@ns.route('/login')
def login():
callback_uri = url_for('.authorize', _external=True)
return oauth.twitter.authorize_redirect(callback_uri)
@ns.route('/authorize')
def authorize():
token = oauth.twitter.authorize_access_token()
# this is a pseudo method, you need to implement it yourself
MyTokenModel.save(token)
return redirect('/profile')
......@@ -20,6 +20,7 @@ class Tasks(Resource):
@ns.response(200, 'OK')
@ns.param('task_id')
def get(self):
"""Requests task status"""
schedulerService = strongr.core.getCore().domains().schedulerDomain().schedulerService()
queryFactory = strongr.core.getCore().domains().schedulerDomain().queryFactory()
......
from .queryfactory import QueryFactory
from strongr.restdomain.query.wsgi import RetrieveBlueprints
#from strongr.core.exception import InvalidParameterException
class QueryFactory:
""" This factory instantiates query objects to be sent to a rest querybus. """
def newRetrieveBlueprints(self):
""" Generates a new RetrieveBlueprints query
:returns: A RetrieveBlueprints query object
:rtype: RetrieveBlueprints
"""
return RetrieveBlueprints()
from .retrieveblueprintshandler import RetrieveBlueprintsHandler
from strongr.restdomain.api.apiv1 import blueprint as apiv1
class RetrieveBlueprintsHandler:
def __call__(self, command):
# return a list of blueprints
return [apiv1]
import dependency_injector.containers as containers
import dependency_injector.providers as providers
from flask import Flask
from authlib.flask.oauth2 import AuthorizationServer
from strongr.restdomain.api.apiv1 import blueprint as apiv1
import strongr.core
class Gateways(containers.DeclarativeContainer):
"""IoC container of gateway objects."""
_backends = providers.Object({
})
_blueprints = providers.Object([apiv1])
def _factor_app(name, blueprints):
app = Flask(__name__)
config = strongr.core.Core.config()
backend = config.restdomain.backend.strip().lower()
# the oauth2 lib can not work with templates,
# this hack was proposed as a temp fix on the
# libraries github. Use this for now, we
# should refactor this later.
# https://github.com/lepture/flask-oauthlib/issues/180
#from strongr.restdomain.api.oauth2 import bind_oauth2
#oauth2 = bind_oauth2(app)
#app.oauth2 = oauth2
for blueprint in blueprints:
app.register_blueprint(blueprint)
server = AuthorizationServer(Client, app)
if backend == 'flask':
flask_config = config.restdomain.flask.as_dict() if hasattr(config, 'restdomain') and hasattr(config.restdomain, 'flask') else {}
# monkey patch run method so that config is grabbed from config file
setattr(app, '_run_original', app.run)
app.run = lambda self=app: self._run_original(**flask_config)
return app
elif backend == 'gunicorn':
from gunicorn.app.base import BaseApplication
# put WSGIServer class here for now
# this should be refactored later
class WSGIServer(BaseApplication):
def __init__(self, app):
self.application = app
super(WSGIServer, self).__init__("%(prog)s [OPTIONS]")
def load_config(self):
for key in config.restdomain.gunicorn:
self.cfg.set(key, config.restdomain.gunicorn[key])
def load(self):
return self.application
return WSGIServer(app)
app = providers.Singleton(_factor_app, 'StrongRRestServer', _blueprints())
from .retrieveblueprints import RetrieveBlueprints
from strongr.core.abstracts.abstractservice import AbstractService
from strongr.restdomain.query.wsgi import RetrieveBlueprints
from strongr.restdomain.handler.wsgi import RetrieveBlueprintsHandler
class WsgiService(AbstractService):
_command_bus = None
_query_bus = None
def register_models(self):
pass
def getCommandBus(self):
if self._command_bus is None:
self._command_bus = self._make_default_commandbus({
})
return self._command_bus
def getQueryBus(self):
if self._query_bus is None:
self._query_bus = self._make_default_querybus({
RetrieveBlueprintsHandler: RetrieveBlueprints
})
return self._query_bus
......@@ -21,7 +21,7 @@ class Job(Base):
return_code = Column(Integer)
stdout = Column('stdout', LargeBinary) # we should update this to point to a file at some point as it will bloat the database pretty quickly
stdout = Column('stdout', LargeBinary(length=52428800)) # we should update this to point to a file at some point as it will bloat the database pretty quickly
_state = Column('state', Enum(JobState))
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment