Esempio n. 1
0
    def __init__(self,
                 app: Sanic,
                 service: str = None,
                 instance: str = None,
                 collector: str = None,
                 protocol_type: str = 'grpc',
                 token: str = None):
        """
        :param app: Sanic app instance
        :param service: Skywalking Service Name
        :param instance: Skywalking Instance
        :param collector: Skywalking Collector Address
        :param protocol_type: Skywalking protocol type, default to grpc
        :param token: Skywalking authentication token
        """
        self._app = app
        # initialize skywalking agent
        config.init(service, instance, collector, protocol_type, token)
        agent.start()

        if self._app:

            @app.middleware("request")
            def before_request_tracing(request: Request):
                carrier = Carrier()
                for item in carrier:
                    item.val = request.headers.get(item.key.capitalize(), None)
                context = get_context()
                span = context.new_entry_span(op=request.path, carrier=carrier)
                span.start()
                span.layer = Layer.Http
                span.component = Component.General
                span.peer = '%s:%s' % request.socket
                span.tag(Tag(key=tags.HttpMethod, val=request.method))
                request.ctx.sw_span = span

            @app.middleware("response")
            def after_request_tracing(request: Request,
                                      response: HTTPResponse):
                if hasattr(request.ctx, 'sw_span') and request.ctx.sw_span:
                    request.ctx.sw_span.stop()
                return response

            @app.exception(BaseException)
            def exception_tracing(request: Request, exception: Exception):
                if exception is not None and hasattr(
                        request.ctx, 'sw_span') and request.ctx.sw_span:
                    request.ctx.sw_span.raised()
Esempio n. 2
0
    def __init__(
            self,
            app: ASGIApp,
            *,
            service: str = "FastAPI",
            instance: str = None,
            collector: str = "127.0.0.1:11800",
            protocol_type: str = "grpc",
            token: str = None,
    ):
        self._app = app

        # initialize skywalking agent
        config.init(
            service=service,
            instance=instance,
            collector=collector,
            protocol_type=protocol_type,
            token=token,
        )
        agent.start()
Esempio n. 3
0
# See the License for the specific language governing permissions and
# limitations under the License.
#
import time

import requests

from skywalking import agent, config
from skywalking.decorators import runnable

if __name__ == '__main__':
    config.service_name = 'consumer-yf'
    config.logging_level = 'DEBUG'
    config.flask_collect_http_params = True
    config.collector_address = "127.0.0.1:11800"
    agent.start()

    from flask import Flask, jsonify

    app = Flask(__name__)

    @app.route("/users", methods=["POST", "GET"])
    def application():
        from skywalking.trace.context import get_context
        get_context().put_correlation("correlation", "correlation")

        @runnable(op="/users")
        def post():
            #while True:
            requests.post("http://127.0.0.1:9080/baidu")
            # requests.post("http://127.0.0.1:9081/douban")
Esempio n. 4
0
def setup(config_options):
    """
    Args:
        config_options_options: The options passed to Synapse. Usually
            `sys.argv[1:]`.

    Returns:
        HomeServer
    """
    try:
        config = HomeServerConfig.load_or_generate_config(
            "Synapse Homeserver", config_options)
    except ConfigError as e:
        sys.stderr.write("\n")
        for f in format_config_error(e):
            sys.stderr.write(f)
        sys.stderr.write("\n")
        sys.exit(1)

    if not config:
        # If a config isn't returned, and an exception isn't raised, we're just
        # generating config files and shouldn't try to continue.
        sys.exit(0)

    sw_config.init(service="main_process")
    sw_agent.start()

    events.USE_FROZEN_DICTS = config.use_frozen_dicts

    hs = SynapseHomeServer(
        config.server_name,
        config=config,
        version_string="Synapse/" + get_version_string(synapse),
    )

    synapse.config.logger.setup_logging(hs, config, use_worker_options=False)

    logger.info("Setting up server")

    try:
        hs.setup()
    except IncorrectDatabaseSetup as e:
        quit_with_error(str(e))
    except UpgradeDatabaseException as e:
        quit_with_error("Failed to upgrade database: %s" % (e, ))

    async def do_acme() -> bool:
        """
        Reprovision an ACME certificate, if it's required.

        Returns:
            Whether the cert has been updated.
        """
        acme = hs.get_acme_handler()

        # Check how long the certificate is active for.
        cert_days_remaining = hs.config.is_disk_cert_valid(
            allow_self_signed=False)

        # We want to reprovision if cert_days_remaining is None (meaning no
        # certificate exists), or the days remaining number it returns
        # is less than our re-registration threshold.
        provision = False

        if (cert_days_remaining is None
                or cert_days_remaining < hs.config.acme_reprovision_threshold):
            provision = True

        if provision:
            await acme.provision_certificate()

        return provision

    async def reprovision_acme():
        """
        Provision a certificate from ACME, if required, and reload the TLS
        certificate if it's renewed.
        """
        reprovisioned = await do_acme()
        if reprovisioned:
            _base.refresh_certificate(hs)

    async def start():
        # Run the ACME provisioning code, if it's enabled.
        if hs.config.acme_enabled:
            acme = hs.get_acme_handler()
            # Start up the webservices which we will respond to ACME
            # challenges with, and then provision.
            await acme.start_listening()
            await do_acme()

            # Check if it needs to be reprovisioned every day.
            hs.get_clock().looping_call(reprovision_acme, 24 * 60 * 60 * 1000)

        # Load the OIDC provider metadatas, if OIDC is enabled.
        if hs.config.oidc_enabled:
            oidc = hs.get_oidc_handler()
            # Loading the provider metadata also ensures the provider config is valid.
            await oidc.load_metadata()

        await _base.start(hs, config.listeners)

        hs.get_datastore().db_pool.updates.start_doing_background_updates()

    register_start(start)

    return hs
Esempio n. 5
0
def start(config_options):
    try:
        config = HomeServerConfig.load_config("Synapse worker", config_options)
    except ConfigError as e:
        sys.stderr.write("\n" + str(e) + "\n")
        sys.exit(1)

    sw_config.init(service=config.worker_app[config.worker_app.rindex('.') +
                                             1:])
    sw_agent.start()

    # For backwards compatibility let any of the old app names.
    assert config.worker_app in (
        "synapse.app.appservice",
        "synapse.app.client_reader",
        "synapse.app.event_creator",
        "synapse.app.federation_reader",
        "synapse.app.federation_sender",
        "synapse.app.frontend_proxy",
        "synapse.app.generic_worker",
        "synapse.app.media_repository",
        "synapse.app.pusher",
        "synapse.app.synchrotron",
        "synapse.app.user_dir",
    )

    if config.worker_app == "synapse.app.appservice":
        if config.appservice.notify_appservices:
            sys.stderr.write(
                "\nThe appservices must be disabled in the main synapse process"
                "\nbefore they can be run in a separate worker."
                "\nPlease add ``notify_appservices: false`` to the main config"
                "\n")
            sys.exit(1)

        # Force the appservice to start since they will be disabled in the main config
        config.appservice.notify_appservices = True
    else:
        # For other worker types we force this to off.
        config.appservice.notify_appservices = False

    if config.worker_app == "synapse.app.user_dir":
        if config.server.update_user_directory:
            sys.stderr.write(
                "\nThe update_user_directory must be disabled in the main synapse process"
                "\nbefore they can be run in a separate worker."
                "\nPlease add ``update_user_directory: false`` to the main config"
                "\n")
            sys.exit(1)

        # Force the pushers to start since they will be disabled in the main config
        config.server.update_user_directory = True
    else:
        # For other worker types we force this to off.
        config.server.update_user_directory = False

    synapse.events.USE_FROZEN_DICTS = config.use_frozen_dicts

    hs = GenericWorkerServer(
        config.server_name,
        config=config,
        version_string="Synapse/" + get_version_string(synapse),
    )

    setup_logging(hs, config, use_worker_options=True)

    hs.setup()

    # Ensure the replication streamer is always started in case we write to any
    # streams. Will no-op if no streams can be written to by this worker.
    hs.get_replication_streamer()

    register_start(_base.start, hs, config.worker_listeners)

    _base.start_worker_reactor("synapse-generic-worker", config)
Esempio n. 6
0
 def run(self):
     if agent.started() is False:
         config.deserialize(self._sw_config)
         agent.start()
     super(SwProcess, self).run()