Beispiel #1
0
    def send_event(self, event: Event) -> bool:
        """Send an event.

        :param event: an event
        :return: True if the event was sent successfully
        """
        json_content = json.dumps(event.as_dict())
        attachments = event.get_attachments()

        mail = MIMEMultipart()
        mail["Subject"] = self.subject
        mail["From"] = self.from_addr
        mail["To"] = self.to_addr
        mail["Date"] = formatdate(localtime=True)
        mail["Message-ID"] = make_msgid()
        mail.preamble = "You will not see this in a MIME-aware mail reader.\n"
        event_json = MIMEBase("application", "json")
        event_json.set_payload(json_content)
        encoders.encode_base64(event_json)
        event_json.add_header("Content-Disposition",
                              "attachment",
                              filename="event")
        mail.attach(event_json)

        result: Dict[str, Dict[str, dict]] = {"attachments": {}}

        for name, (filename, _) in list(attachments.items()):
            ctype, encoding = mimetypes.guess_type(filename)

            if encoding == "gzip" and ctype == "application/x-tar":
                attachment = MIMEBase("application", "x-tar-gz")
            elif encoding is None and ctype is not None:
                attachment = MIMEBase(*ctype.split("/", 1))
            else:
                attachment = MIMEBase("application", "octet-stream")
            with open(filename, "rb") as data_f:
                attachment.set_payload(data_f.read())

            result["attachments"][name] = {
                "path": filename,
                "encoding": encoding,
                "ctype": ctype,
            }

            encoders.encode_base64(attachment)
            attachment.add_header("Content-Disposition",
                                  "attachment",
                                  filename=name)
            mail.attach(attachment)

        return e3.net.smtp.sendmail(
            self.from_addr,
            mail["To"].split(","),
            mail.as_string(),
            self.smtp_servers,
            message_id=mail["Message-ID"],
        )
Beispiel #2
0
 def send_event(self, event: Event) -> bool:
     d = event.as_dict()
     prefix = "{}-{}".format(d["name"], d["uid"])
     log_file = os.path.join(self.log_dir, prefix + ".log")
     attach_dir = os.path.join(self.log_dir, prefix)
     mkdir(attach_dir)
     with open(log_file, "w") as fd:
         json.dump(d, fd, indent=2, sort_keys=True)
     for name, attachment in list(event.get_attachments().items()):
         cp(attachment[0], os.path.join(attach_dir, name))
     return True
Beispiel #3
0
    def send_event(self, event: Event) -> bool:
        def s3_cp(from_path: str, s3_url: str) -> bool:
            cmd = ["s3", "cp", f"--sse={self.sse}"]
            if self.aws_profile:
                cmd.append(f"--profile={self.aws_profile}")
            cmd += [from_path, s3_url]

            s3 = Run(python_script("aws") + cmd, output=None)
            return s3.status == 0

        # Push attachments to s3 and keep track of their url.
        s3_attachs = {}
        for name, attach in list(event.get_attachments().items()):
            attach_path = attach[0]
            # Push the attachment
            s3_url = f"{self.log_s3_url}/{self.s3_prefix(event)}{event.uid}/{name}"
            success = s3_cp(attach_path, s3_url)
            if not success:
                return False
            else:
                ctype, encoding = mimetypes.guess_type(attach_path)
                s3_attachs[name] = {
                    "s3_url": s3_url,
                    "encoding": encoding,
                    "ctype": ctype,
                }

        # Create the JSON to send on the event bucket
        s3_event = {"attachments": s3_attachs, "event": event.as_dict()}

        try:
            tempfile_name = None
            with closing(tempfile.NamedTemporaryFile(mode="w",
                                                     delete=False)) as fd:
                tempfile_name = fd.name
                json.dump(s3_event, fd)

            # Note that an event can be sent several times with a different
            # status. As a consequence the target url in s3 should be different
            # for call to send.
            success = s3_cp(
                tempfile_name,
                f"{self.event_s3_url}/{self.s3_prefix(event)}"
                f"{event.uid}-{unique_id()}.s3",
            )

            if not success:
                return False
            else:
                return True
        finally:
            if tempfile_name is not None:
                rm(tempfile_name)
Beispiel #4
0
 def send_event(self, event: Event) -> bool:
     d = event.as_dict()
     self.log.log(self.level, json.dumps(d, indent=2))
     return True