Beispiel #1
0
 def initialize_handlers(self):
     self.handlers.extend([
         ('cylc/version', CylcVersionHandler),
         (
             'cylc/graphql',
             UIServerGraphQLHandler,
             {
                 'schema': schema,
                 'resolvers': self.resolvers,
                 'backend': CylcGraphQLBackend(),
                 'middleware': [IgnoreFieldMiddleware],
             }
         ),
         (
             'cylc/graphql/batch',
             UIServerGraphQLHandler,
             {
                 'schema': schema,
                 'resolvers': self.resolvers,
                 'backend': CylcGraphQLBackend(),
                 'middleware': [IgnoreFieldMiddleware],
                 'batch': True,
             }
         ),
         (
             'cylc/subscriptions',
             SubscriptionHandler,
             {
                 'sub_server': self.subscription_server,
                 'resolvers': self.resolvers,
             }
         ),
         (
             'cylc/userprofile',
             UserProfileHandler,
         ),
         (
             'cylc/(.*)?',
             CylcStaticHandler,
             {
                 'path': str(self.ui_path),
                 'default_filename': 'index.html'
             }
         ),
         (
             # redirect '/cylc' to '/cylc/'
             'cylc',
             RedirectHandler,
             {
                 'url': 'cylc/'
             }
         )
     ])
Beispiel #2
0
 def set_sub_server(self):
     self.subscription_server = TornadoSubscriptionServer(
         schema,
         backend=CylcGraphQLBackend(),
         middleware=[
             IgnoreFieldMiddleware,
             AuthorizationMiddleware,
         ],
         auth=self.authobj)
Beispiel #3
0
    def graphql(self,
                request_string: Optional[str] = None,
                variables: Optional[Dict[str, Any]] = None,
                meta: Optional[Dict[str, Any]] = None):
        """Return the GraphQL schema execution result.

        Args:
            request_string: GraphQL request passed to Graphene.
            variables: Dict of variables passed to Graphene.
            meta: Dict containing auth user etc.

        Returns:
            object: Execution result, or a list with errors.
        """
        try:
            executed: ExecutionResult = schema.execute(
                request_string,
                variable_values=variables,
                context_value={
                    'resolvers': self.resolvers,
                    'meta': meta or {},
                },
                backend=CylcGraphQLBackend(),
                middleware=list(instantiate_middleware(self.middleware)),
                executor=AsyncioExecutor(),
                validate=True,  # validate schema (dev only? default is True)
                return_promise=False,
            )
        except Exception as exc:
            return 'ERROR: GraphQL execution error \n%s' % exc
        if executed.errors:
            errors: List[Any] = []
            for error in executed.errors:
                if hasattr(error, '__traceback__'):
                    import traceback
                    errors.append({
                        'error': {
                            'message':
                            str(error),
                            'traceback':
                            traceback.format_exception(error.__class__, error,
                                                       error.__traceback__)
                        }
                    })
                    continue
                errors.append(getattr(error, 'message', None))
            return errors
        return executed.data
Beispiel #4
0
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.workflows_mgr = WorkflowsManager(self, log=self.log)
        self.data_store_mgr = DataStoreMgr(self.workflows_mgr, self.log)
        self.resolvers = Resolvers(
            self.data_store_mgr,
            log=self.log,
            workflows_mgr=self.workflows_mgr,
        )
        self.subscription_server = TornadoSubscriptionServer(
            schema,
            backend=CylcGraphQLBackend(),
            middleware=[IgnoreFieldMiddleware],
        )

        ioloop.IOLoop.current().add_callback(self.workflows_mgr.update)
Beispiel #5
0
    def _make_app(self, debug: bool):
        """Crete a Tornado web application.

        Args:
            debug (bool): flag to set debugging in the Tornado application
        """
        logger.info(self._static)
        # subscription/websockets server
        subscription_server = TornadoSubscriptionServer(
            schema,
            backend=CylcGraphQLBackend(),
            middleware=[IgnoreFieldMiddleware],
        )
        return MyApplication(
            static_path=self._static,
            debug=debug,
            handlers=[
                # static content
                self._create_static_handler(".*.(css|js)"),
                self._create_static_handler("(fonts|img)/.*"),
                self._create_static_handler("favicon.png"),
                # normal handlers, with auth
                self._create_handler("oauth_callback",
                                     HubOAuthCallbackHandler),
                self._create_handler("userprofile", UserProfileHandler),
                # graphql handlers
                self._create_graphql_handler(
                    "graphql",
                    UIServerGraphQLHandler,
                ),
                self._create_graphql_handler("graphql/batch",
                                             UIServerGraphQLHandler,
                                             batch=True),
                # subscription/websockets handler
                self._create_handler("subscriptions",
                                     SubscriptionHandler,
                                     sub_server=subscription_server,
                                     resolvers=self.resolvers),
                # main handler
                (rf"{self._jupyter_hub_service_prefix}?", MainHandler, {
                    "path": self._static
                })
            ],
            # always generate a new cookie secret on launch
            # ensures that each spawn clears any cookies from
            # previous session, triggering OAuth again
            cookie_secret=os.urandom(32))
Beispiel #6
0
    def _create_graphql_handler(
            self, path: str, clazz: Type[TornadoGraphQLHandler],
            **kwargs: Any) -> Tuple[str, Type[web.RequestHandler], dict]:
        """
        Create a GraphQL handler.

        Args:
            path (str): handler path
            clazz (class): handler class
            kwargs: extra params
        Returns:
            Tornado handler tuple
        """
        return self._create_handler(path,
                                    clazz,
                                    schema=schema,
                                    resolvers=self.resolvers,
                                    backend=CylcGraphQLBackend(),
                                    middleware=[IgnoreFieldMiddleware],
                                    **kwargs)