Просмотр исходного кода

ref: delete unimportable files (#58964)

```console
$ xargs --replace bash -xc "sentry shell -c 'import {}' 2>&1 | tail -5" <<< $'sentry.auth.providers.saml2.activedirectory.views\nsentry.auth.providers.saml2.jumpcloud.views\nsentry.management.commands.serve_normalize\nsentry.queue.command'
+ sentry shell -c 'import sentry.auth.providers.saml2.activedirectory.views'
+ tail -5
    exec(options['command'], globals())
  File "<string>", line 1, in <module>
  File "/Users/asottile/workspace/sentry/src/sentry/auth/providers/saml2/activedirectory/views.py", line 1, in <module>
    from sentry.auth.providers.saml2.generic.views import GenericSAML2View
ImportError: cannot import name 'GenericSAML2View' from 'sentry.auth.providers.saml2.generic.views' (/Users/asottile/workspace/sentry/src/sentry/auth/providers/saml2/generic/views.py)
+ sentry shell -c 'import sentry.auth.providers.saml2.jumpcloud.views'
+ tail -5
    exec(options['command'], globals())
  File "<string>", line 1, in <module>
  File "/Users/asottile/workspace/sentry/src/sentry/auth/providers/saml2/jumpcloud/views.py", line 1, in <module>
    from sentry.auth.providers.saml2.generic.views import GenericSAML2View
ImportError: cannot import name 'GenericSAML2View' from 'sentry.auth.providers.saml2.generic.views' (/Users/asottile/workspace/sentry/src/sentry/auth/providers/saml2/generic/views.py)
+ sentry shell -c 'import sentry.management.commands.serve_normalize'
+ tail -5
  File "/Users/asottile/workspace/sentry/src/sentry/management/commands/serve_normalize.py", line 158, in <module>
    class Command(BaseCommand):
  File "/Users/asottile/workspace/sentry/src/sentry/management/commands/serve_normalize.py", line 161, in Command
    option_list = BaseCommand.option_list + (
AttributeError: type object 'BaseCommand' has no attribute 'option_list'
+ sentry shell -c 'import sentry.queue.command'
+ tail -5
  File "/Users/asottile/workspace/sentry/src/sentry/queue/command.py", line 8, in <module>
    class CeleryCommand(BaseCommand):
  File "/Users/asottile/workspace/sentry/src/sentry/queue/command.py", line 9, in CeleryCommand
    options = BaseCommand.option_list
AttributeError: type object 'BaseCommand' has no attribute 'option_list'
```
anthony sottile 1 год назад
Родитель
Сommit
7ccd3bd0ec

+ 0 - 4
pyproject.toml

@@ -339,9 +339,7 @@ module = [
     "sentry.auth.providers.github.views",
     "sentry.auth.providers.google.views",
     "sentry.auth.providers.oauth2",
-    "sentry.auth.providers.saml2.activedirectory.views",
     "sentry.auth.providers.saml2.generic.views",
-    "sentry.auth.providers.saml2.jumpcloud.views",
     "sentry.auth.providers.saml2.provider",
     "sentry.auth.providers.saml2.rippling.provider",
     "sentry.auth.providers.saml2.views",
@@ -484,7 +482,6 @@ module = [
     "sentry.mail.notifications",
     "sentry.management.commands.makemigrations",
     "sentry.management.commands.send_fake_data",
-    "sentry.management.commands.serve_normalize",
     "sentry.middleware.access_log",
     "sentry.middleware.auth",
     "sentry.middleware.health",
@@ -538,7 +535,6 @@ module = [
     "sentry.plugins.providers.repository",
     "sentry.profiles.task",
     "sentry.profiles.utils",
-    "sentry.queue.command",
     "sentry.quotas.redis",
     "sentry.receivers.outbox.control",
     "sentry.receivers.releases",

+ 2 - 1
src/sentry/__main__.py

@@ -1,3 +1,4 @@
 from .runner import main
 
-main()
+if __name__ == "__main__":
+    main()

+ 0 - 9
src/sentry/auth/providers/saml2/activedirectory/views.py

@@ -1,9 +0,0 @@
-from sentry.auth.providers.saml2.generic.views import GenericSAML2View
-
-
-class ActiveDirectorySAML2View(GenericSAML2View):
-    """
-    Active Directory is a subset of our generic SAML2 implementation. However,
-    this may not be obvious to end users. This inheritance class allows us to
-    explicitly surface this option to them.
-    """

+ 0 - 9
src/sentry/auth/providers/saml2/jumpcloud/views.py

@@ -1,9 +0,0 @@
-from sentry.auth.providers.saml2.generic.views import GenericSAML2View
-
-
-class JumpcloudSAML2View(GenericSAML2View):
-    """
-    Jumpcloud is a subset of our generic SAML2 implementation. However,
-    this may not be obvious to end users. This inheritance class allows us to
-    explicitly surface this option to them.
-    """

+ 0 - 236
src/sentry/management/commands/serve_normalize.py

@@ -1,236 +0,0 @@
-import base64
-import os
-import resource
-import socketserver
-import stat
-import sys
-import time
-import traceback
-from optparse import make_option
-
-from django.core.management.base import BaseCommand, CommandError
-from django.utils.encoding import force_str
-
-from sentry.utils import json
-
-
-class ForkingUnixStreamServer(socketserver.ForkingMixIn, socketserver.UnixStreamServer):
-    pass
-
-
-def catch_errors(f):
-    def wrapper(*args, **kwargs):
-        error = None
-        try:
-            return f(*args, **kwargs)
-        except Exception as e:
-            error = force_str(str(e)) + " " + force_str(traceback.format_exc())
-
-        try:
-            return encode({"result": None, "error": error, "metrics": None})
-        except (ValueError, TypeError) as e:
-            try:
-                # Encoding error, try to send the exception instead
-                return encode(
-                    {
-                        "result": None,
-                        "error": force_str(str(e)) + " " + force_str(traceback.format_exc()),
-                        "metrics": None,
-                        "encoding_error": True,
-                    }
-                )
-            except Exception:
-                return b"{}"
-
-    return wrapper
-
-
-# Here's where the normalization itself happens
-def process_event(data, meta, project_config):
-    from sentry.event_manager import EventManager
-    from sentry.relay.config import ProjectConfig
-    from sentry.tasks.store import should_process
-    from sentry.web.api import _scrub_event_data
-
-    project_config = ProjectConfig(None, **project_config)
-
-    event_manager = EventManager(
-        data,
-        client_ip=meta.get("REMOTE_ADDR"),
-        user_agent=meta.get("HTTP_USER_AGENT"),
-        auth=None,
-        key=None,
-        content_encoding=meta.get("HTTP_CONTENT_ENCODING"),
-    )
-    event_manager.normalize()
-
-    event = event_manager.get_data()
-    group_hash = None
-
-    datascrubbing_settings = project_config.config.get("datascrubbingSettings") or {}
-    event = _scrub_event_data(event, datascrubbing_settings)
-
-    if not should_process(event):
-        group_hash = event_manager._get_event_instance(project_id=1).get_hashes()
-    return {"event": dict(event), "group_hash": group_hash}
-
-
-def decode(message):
-    meta, data_encoded, project_config = json.loads(message)
-    data = base64.b64decode(data_encoded)
-    return data, meta, project_config
-
-
-def encode(data):
-    # Normalized data should be serializable
-    return json.dumps(data)
-
-
-@catch_errors
-def handle_data(data):
-    mc = MetricCollector()
-
-    metrics_before = mc.collect_metrics()
-    data, meta, project_config = decode(data)
-    rv = process_event(data, meta, project_config)
-    metrics_after = mc.collect_metrics()
-
-    return encode(
-        {"result": rv, "metrics": {"before": metrics_before, "after": metrics_after}, "error": None}
-    )
-
-
-class MetricCollector:
-    def __init__(self):
-        self.is_linux = sys.platform.startswith("linux")
-        self.pid = os.getpid()
-
-    def collect_metrics(self):
-        metrics = {"time": time.time()}
-
-        usage = resource.getrusage(resource.RUSAGE_SELF)
-        usage_dict = {attr: getattr(usage, attr) for attr in dir(usage) if attr.startswith("ru_")}
-        metrics.update(usage_dict)
-
-        if self.is_linux:
-            with open(f"/proc/{self.pid}/status") as procfh:
-                metrics["proc"] = procfh.read()
-
-        return metrics
-
-
-class EventNormalizeHandler(socketserver.BaseRequestHandler):
-    """
-    The request handler class for our server.
-    It is instantiated once per connection to the server, and must
-    override the handle() method to implement communication to the
-    client.
-    """
-
-    BUFFER_SIZE = 4096
-    SOCKET_TIMEOUT = 10.0
-
-    def handle(self):
-        self.server.socket.settimeout(self.SOCKET_TIMEOUT)
-
-        chunks = []
-
-        # Receive the data
-        while True:
-            rcvd = self.request.recv(self.BUFFER_SIZE)
-            if rcvd is None:
-                raise ValueError("Received None")
-
-            if not rcvd:
-                break
-            chunks.append(rcvd)
-
-        self.data = "".join(chunks)
-
-        response = self.handle_data()
-        self.request.sendall(response)
-        self.request.close()
-
-    def handle_data(self):
-        return handle_data(self.data)
-
-
-class Command(BaseCommand):
-    help = "Start a socket server for event normalization"
-
-    option_list = BaseCommand.option_list + (
-        make_option(
-            "--unix",
-            dest="socket_file",
-            help='Unix socket to bind to. Example: "/tmp/normalize.sock"',
-        ),
-        make_option(
-            "--net",
-            dest="network_socket",
-            help='Network socket to bind to. Example: "127.0.0.1:1234"',
-        ),
-        make_option(
-            "--threading", action="store_true", dest="threading", help="Start a threading server"
-        ),
-        make_option(
-            "--forking", action="store_true", dest="forking", help="Start a forking server"
-        ),
-    )
-
-    def _check_socket_path(self, socket_file):
-        if os.path.exists(socket_file):
-            file_mode = os.stat(socket_file).st_mode
-            if not stat.S_ISSOCK(file_mode):
-                raise CommandError("File already exists and is not a socket")
-
-        # Make sure the socket does not already exist
-        try:
-            os.unlink(socket_file)
-        except OSError:
-            if os.path.exists(socket_file):
-                raise
-
-    def handle(self, **options):
-        socket_file = options.get("socket_file")
-        network_socket = options.get("network_socket")
-        threading = options.get("threading")
-        forking = options.get("forking")
-        if threading and forking:
-            raise CommandError("Pick one: threading or forking.")
-        if socket_file and network_socket:
-            raise CommandError("Only one socket allowed at a time")
-
-        if threading:
-            server_type = "threading"
-        elif forking:
-            server_type = "forking"
-        else:
-            server_type = "single-threaded"
-        self.stdout.write(f"Server type: {server_type}\n")
-
-        if socket_file:
-            self.socket_file = os.path.abspath(socket_file)
-            self._check_socket_path(socket_file)
-            self.stdout.write(f"Binding to unix socket: {socket_file}\n")
-            if threading:
-                server = socketserver.ThreadingUnixStreamServer(socket_file, EventNormalizeHandler)
-                server.daemon_threads = True
-            elif forking:
-                server = ForkingUnixStreamServer(socket_file, EventNormalizeHandler)
-            else:
-                server = socketserver.UnixStreamServer(socket_file, EventNormalizeHandler)
-        elif network_socket:
-            host, port = network_socket.split(":")
-            port = int(port)
-            self.stdout.write(f"Binding to network socket: {host}:{port}\n")
-            if threading:
-                server = socketserver.ThreadingTCPServer((host, port), EventNormalizeHandler)
-                server.daemon_threads = True
-            elif forking:
-                server = socketserver.ForkingTCPServer((host, port), EventNormalizeHandler)
-            else:
-                server = socketserver.TCPServer((host, port), EventNormalizeHandler)
-        else:
-            raise CommandError("No connection option specified")
-
-        server.serve_forever()

+ 0 - 56
src/sentry/queue/command.py

@@ -1,56 +0,0 @@
-import os
-import sys
-
-import celery
-from django.core.management.base import BaseCommand
-
-
-class CeleryCommand(BaseCommand):
-    options = BaseCommand.option_list
-    skip_opts = ["--app", "--loader", "--config"]
-    keep_base_opts = False
-
-    def get_version(self):
-        return "celery %s" % (celery.__version__)
-
-    def execute(self, *args, **options):
-        broker = options.get("broker")
-        if broker:
-            self.set_broker(broker)
-        super().execute(*args, **options)
-
-    def set_broker(self, broker):
-        os.environ["CELERY_BROKER_URL"] = broker
-
-    def run_from_argv(self, argv):
-        self.handle_default_options(argv[2:])
-        return super().run_from_argv(argv)
-
-    def handle_default_options(self, argv):
-        acc = []
-        broker = None
-        for i, arg in enumerate(argv):
-            if "--settings=" in arg:
-                _, settings_module = arg.split("=")
-                os.environ["DJANGO_SETTINGS_MODULE"] = settings_module
-            elif "--pythonpath=" in arg:
-                _, pythonpath = arg.split("=")
-                sys.path.insert(0, pythonpath)
-            elif "--broker=" in arg:
-                _, broker = arg.split("=")
-            elif arg == "-b":
-                broker = argv[i + 1]
-            else:
-                acc.append(arg)
-        if broker:
-            self.set_broker(broker)
-        return argv if self.keep_base_opts else acc
-
-    def die(self, msg):
-        sys.stderr.write(msg)
-        sys.stderr.write("\n")
-        sys.exit()
-
-    @property
-    def option_list(self):
-        return [x for x in self.options if x._long_opts[0] not in self.skip_opts]

+ 0 - 4
tests/sentry/integrations/utils/fixtures/sentry_files.json

@@ -765,7 +765,6 @@
     "src/sentry/auth/providers/saml2/activedirectory/__init__.py",
     "src/sentry/auth/providers/saml2/activedirectory/apps.py",
     "src/sentry/auth/providers/saml2/activedirectory/provider.py",
-    "src/sentry/auth/providers/saml2/activedirectory/views.py",
     "src/sentry/auth/providers/saml2/auth0/__init__.py",
     "src/sentry/auth/providers/saml2/auth0/apps.py",
     "src/sentry/auth/providers/saml2/auth0/provider.py",
@@ -777,7 +776,6 @@
     "src/sentry/auth/providers/saml2/jumpcloud/__init__.py",
     "src/sentry/auth/providers/saml2/jumpcloud/apps.py",
     "src/sentry/auth/providers/saml2/jumpcloud/provider.py",
-    "src/sentry/auth/providers/saml2/jumpcloud/views.py",
     "src/sentry/auth/providers/saml2/okta/__init__.py",
     "src/sentry/auth/providers/saml2/okta/apps.py",
     "src/sentry/auth/providers/saml2/okta/provider.py",
@@ -1294,7 +1292,6 @@
     "src/sentry/management/commands/makemigrations.py",
     "src/sentry/management/commands/merge_users.py",
     "src/sentry/management/commands/send_fake_data.py",
-    "src/sentry/management/commands/serve_normalize.py",
     "src/sentry/mediators/__init__.py",
     "src/sentry/mediators/alert_rule_actions/__init__.py",
     "src/sentry/mediators/alert_rule_actions/creator.py",
@@ -1772,7 +1769,6 @@
     "src/sentry/projectoptions/defaults.py",
     "src/sentry/projectoptions/manager.py",
     "src/sentry/queue/__init__.py",
-    "src/sentry/queue/command.py",
     "src/sentry/queue/routers.py",
     "src/sentry/quotas/__init__.py",
     "src/sentry/quotas/base.py",