func()

in pcap-fsnotify/internal/gcs/exporter.go [135:261]


func (x *exporter) export(
	srcPcapFile *string,
	tgtPcapFile *string,
	outputPcapWriter ClosableWriter,
	compress bool,
	delete bool,
	callback exportCallback,
) (int64, error) {
	pcapBytes := int64(0)

	// Open source PCAP file: the one thas is being moved to the destination directory
	inputPcapWriter, err := os.OpenFile(*srcPcapFile, os.O_RDONLY|os.O_EXCL, 0)
	if err != nil {
		x.logger.LogFsEvent(
			zapcore.ErrorLevel,
			sf.Format("failed to OPEN file {0}", *srcPcapFile),
			PCAP_EXPORT,
			*srcPcapFile,
			*tgtPcapFile,
			0,
			err)
		return pcapBytes, errors.Wrap(err,
			sf.Format("failed to open source pcap: {0}", *srcPcapFile))
	}

	// Copy source PCAP into destination PCAP, compressing destination PCAP is optional
	if compress {
		// see: https://pkg.go.dev/compress/gzip#NewWriter
		gzipPcap := gzip.NewWriter(outputPcapWriter)
		pcapBytes, err = io.Copy(gzipPcap, inputPcapWriter)
		gzipPcap.Flush()
		gzipPcap.Close() // this is still required; `Close()` on parent `Writer` does not trigger `Close()` at `gzip`
	} else {
		pcapBytes, err = io.Copy(outputPcapWriter, inputPcapWriter)
	}

	if err != nil {
		inputPcapWriter.Close()
		x.logger.LogFsEvent(
			zapcore.ErrorLevel,
			sf.Format("failed to COPY file: {0}", *srcPcapFile),
			PCAP_EXPORT,
			*srcPcapFile,
			*tgtPcapFile,
			0,
			err)
		return pcapBytes, errors.Wrapf(err, "failed to COPY file: %s", *srcPcapFile)
	}

	// closing `outputPcapWriter` is responsibility of the caller of this method
	inputPcapWriter.Close()

	if err != nil {
		x.logger.LogFsEvent(
			zapcore.ErrorLevel,
			sf.Format("failed to EXPORT file: {0}", *srcPcapFile),
			PCAP_EXPORT,
			*srcPcapFile,
			*tgtPcapFile,
			pcapBytes,
			err)
		return pcapBytes, errors.Wrap(err,
			sf.Format("failed to COPY file: {0}", *srcPcapFile))
	}

	if err = callback(
		outputPcapWriter,
		srcPcapFile,
		tgtPcapFile,
		&pcapBytes,
	); err != nil {
		x.logger.LogFsEvent(
			zapcore.ErrorLevel,
			sf.Format(
				"failed to EXPORT file: {0}",
				*srcPcapFile,
			),
			PCAP_EXPORT,
			*srcPcapFile,
			*tgtPcapFile,
			pcapBytes,
			err)
		return pcapBytes, errors.Wrap(err,
			sf.Format("failed to EXPORT file: {0}", *srcPcapFile))
	}

	x.logger.LogFsEvent(
		zapcore.InfoLevel,
		sf.Format("EXPORTED: {0}", *srcPcapFile),
		PCAP_EXPORT,
		*srcPcapFile,
		*tgtPcapFile,
		pcapBytes,
		nil)

	if delete {
		// remove the source PCAP file if copying is sucessful
		err = os.Remove(*srcPcapFile)
		if err != nil {
			x.logger.LogFsEvent(
				zapcore.ErrorLevel,
				sf.Format(
					"failed to DELETE file: {0}",
					*srcPcapFile,
				),
				PCAP_EXPORT,
				*srcPcapFile,
				*tgtPcapFile,
				pcapBytes,
				err)
		} else {
			x.logger.LogFsEvent(
				zapcore.InfoLevel,
				sf.Format(
					"DELETED: {0}",
					*srcPcapFile,
				),
				PCAP_EXPORT,
				*srcPcapFile,
				*tgtPcapFile,
				pcapBytes,
				nil)
		}
	}

	return pcapBytes, nil
}