bloodlabnet

package module
v0.4.48 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 13, 2023 License: Apache-2.0 Imports: 25 Imported by: 1

README

Go BloodLab Net

A libarary to simplify communication with laboratory instruments.

Install

go get github.com/DRK-Blutspende-BaWueHe/go-bloodlab-net

Features
  • TCP/IP Server implementation
  • TCP/IP Client implementation
  • FTP Client implementation
  • Low-level protocols :
    • RAW protocol.Raw()
    • STX-ETX protocol.STXETX()
    • MLLP (for HL7) protocol.MLLP()
    • Lis1A1 protocol.Lis1A1()
TCP/IP Client

Create a client to send data.

 tcpClient := CreateNewTCPClient("127.0.0.1", 4001, protocol.Raw(), NoLoadBalancer)

 if err := tcpClient.Connect(); err != nil {  
   log.Panic(err)
 }

 n, err := tcpClient.Send([]byte("Hello TCP/IP"))

 receivedMsg, err := tcpClient.Receive()
TCP/IP Server
package main

import (
	"fmt"
	"time"

	bloodlabnet "github.com/DRK-Blutspende-BaWueHe/go-bloodlab-net"
	"github.com/DRK-Blutspende-BaWueHe/go-bloodlab-net/protocol"
)

type MySessionHandler struct {
}

func (s *MySessionHandler) Connected(session bloodlabnet.Session) {
	fmt.Println("Disconnected Event")
}

func (s *MySessionHandler) Disconnected(session bloodlabnet.Session) {
	fmt.Println("Disconnected Event")
}

func (s *MySessionHandler) Error(session bloodlabnet.Session, errorType bloodlabnet.ErrorType, err error) {
	fmt.Println(err)
}

func (s *MySessionHandler) DataReceived(session bloodlabnet.Session, data []byte, receiveTimestamp time.Time) {
	
  rad, _ := session.RemoteAddress()
	fmt.Println("From %s received : ", rad, string(data))
	
  session.Send([]byte(fmt.Sprintf("You are sending from %s", rad)))
}

func main() {

	server := bloodlabnet.CreateNewTCPServerInstance(4009,
		protocol.STXETX(),
		bloodlabnet.HAProxySendProxyV2,
		100) // Max Connections

	server.Run(&MySessionHandler{})
}
SFTP Client

Connect as a client to an existing sftp server and keep polling.

CreateFTP(ftptype, host, port, directory, filemask, config)

ftptype
  • FTP for ftp server
  • SFTP for sftp server
Example
 
 func (h *myhandler)DataReceived(session Session, data []byte) {

 }

func main() {
 
 var hander myhandler

   server := CreateSFTPClient(SFTP, "localhost", 25, "/sourcefolder", "*.dat",
     DefaultFTPConfig()
     .UserPass("Istvan", "Pass")
     .HostKey("ajsdflkasjflksajklfjaslfjlksadfj")
	 .PollInterval(60 * Duration.Seconds)
	 .DialTimeout(10 * Duration.Seconds)
	 .DontDeleteAfterRead()
   )

	server, err := bnet.CreateSFTPClient(bnet.SFTP, "172.23.114.30", 22, "/tests", "*.dat",
		bnet.DefaultFTPConfig().UserPass("test", "testpaul").PollInterval(5*time.Second),
	)

    server.Run(handler)

	data := [][]byte{[]byte("Dolor sit amed"), []byte("This is the 2nd line")}

    // sending the file to ftp server with autogenerated names
	server.Send(data)

  server.Close()
}
Configruation

Start with DefaultFTPConfig() and continue with fluentapi

  • PollInterval(pollInterval time.Duration)
  • DeleteAfterRead()
  • DontDeleteAfterRead()
  • LineBreakCR()
  • LineBreakCRLF()
  • LineBreakLF()
  • DialTimeout(dialTimeout time.Duration)
  • FilenameGeneratorPattern(pattern string)
  • FilenameGeneratorPrefix(prefix string)
  • NoFilenamePrefix()
  • FilenameGeneratorSuffix(suffix string)
  • NoFilenameSuffix()

Protocols

Raw Protocol (TCP/Client + TCP/Server)

Raw communication for tcp-ip.

STX-ETX Protocol (TCP/Client + TCP/Server)

Mesasge are embedded in (Ascii 0x02) and (Ascii 0x03) to indicate start and end. At the end of each transmission the transmissions contents are passed further for higher level protocols.

 .... <STX>Some data<ETX> This data here is ignored <STX>More data<ETX> ....
MLLP Protocol (TCP/Client + TCP/Server)

Mesasge are embedded in (Ascii 11) and (Ascii 28) terminated with (Ascii 13) to indicate start and end. At the end of each transmission the transmissions contents are passed further for higher level protocols.

 .... <VT>Some data<FS><CR> This data here is ignored <VT>More data<FS><CR> ....

For some vendors start/stop - bytes might be altered. In that case you can use DefaultMLLPProtocolSettings and use SetStartByte and SetStopByte to change them.

tcpServer := bloodlabnet.CreateNewTCPServerInstance(config.TCPListenerPort,
  bloodlabnetProtocol.MLLP(bloodlabnetProtocol.DefaultMLLPProtocolSettings().SetStartByte(0)),
  bloodlabnet.HAProxySendProxyV2, config.TCPServerMaxConnections)
Lis1A1 Protocol (TCP/Client + TCP/Server)

Lis1A1 is a low level protocol for submitting data to laboratory instruments, typically via serial line.

au6xx Protocol (TCP/Client + TCP/Server)

The au6xx is the low-level protocol required for connecting to Beckman&Coulter AU6xx systems.

TCP/IP Server Configuration

Connection timeout

Portscanners or Loadbalancers do connect just to disconnect a second later. By default the session initiation happens not on connect, rather when the first byte is sent.

Notice that certain instruments require the connection to remain opened, even if there is no data.

Disable the connection-timeout
config := DefaultTCPServerSettings
config.SessionAfterFirstByte = false // Default: true
Require the first Byte to be sent within a timelimit
config := DefaultTCPServerSettings
config.SessionInitationTimeout = time.Second * 3  // Default: 0

Add low-level Logging : Protcol-Logger

Logging can be added to any protocol by wrapping the Protocol into the logger. This does not affect the functionality. In addition set the environment-variable PROTOLOG_ENABLE to true.

PROTOLOG_ENABLE = (traffic|extended)

  1. traffic = logs only the
  2. extended = would log the traffic plus the states of the FSM
set PROTOLOG_ENABLE=extended
tcpServer := bloodlabnet.CreateNewTCPServerInstance(config.TCPListenerPort,
  bloodlabnetProtocol.Logger(
    bloodlabnetProtocol.MLLP(bloodlabnetProtocol.DefaultMLLPProtocolSettings().SetStartByte(0))
  ),
  bloodlabnet.HAProxySendProxyV2, config.TCPServerMaxConnections)

Documentation

Overview

Based on https://github.com/pkg/sftp/tree/master/examples/go-sftp-server An example SFTP server implementation using the golang SSH package. Serves the whole filesystem visible to the user, and has a hard-coded username and password, so not for real use!

Index

Constants

View Source
const TESTSTRING = "٤ḞԍНǏ𝙅ƘԸⲘ"

Variables

View Source
var DefaultFTPClientTimings = TCPServerConfiguration{
	Timeout:      time.Second * 5,
	PollInterval: time.Second * 60,
}
View Source
var DefaultTCPClientSettings = TCPClientConfiguration{
	Timeout:                 time.Second * 3,
	Deadline:                time.Millisecond * 200,
	FlushBufferTimoutMs:     500,
	PollInterval:            time.Second * 60,
	SessionAfterFirstByte:   true,
	SessionInitationTimeout: time.Second * 0,
	SourceIP:                "",
}
View Source
var DefaultTCPServerSettings = TCPServerConfiguration{
	Timeout:                 time.Second * 3,
	Deadline:                time.Millisecond * 200,
	FlushBufferTimoutMs:     500,
	PollInterval:            time.Second * 60,
	SessionAfterFirstByte:   true,
	SessionInitationTimeout: time.Second * 0,
}

Functions

func CreateSFTPServer added in v0.4.3

func CreateSFTPServer(workdir string) sftpserver

func DefaultFTPConfig added in v0.4.1

func DefaultFTPConfig() *ftpConfiguration

Types

type AuthenticationMethod added in v0.4.1

type AuthenticationMethod int
const PASSWORD AuthenticationMethod = 1
const PUBKEY AuthenticationMethod = 2

type BufferedConn added in v0.2.5

type BufferedConn struct {
	net.Conn // So that most methods are embedded
	// contains filtered or unexported fields
}

-------------------------------------------------------------------------------------------- BufferedConn wrapping the net.Conn yet compatible for better reading performance and a peek preview. --------------------------------------------------------------------------------------------

func (BufferedConn) FirstByteOrError added in v0.2.5

func (b BufferedConn) FirstByteOrError(howLong time.Duration) error

func (BufferedConn) Peek added in v0.2.5

func (b BufferedConn) Peek(n int) ([]byte, error)

func (BufferedConn) Read added in v0.2.5

func (b BufferedConn) Read(p []byte) (int, error)

type ConnectionAndSessionInstance

type ConnectionAndSessionInstance interface {
	Connect() error
	ConnectionInstance
	Session
}

func CreateNewTCPClient

func CreateNewTCPClient(hostname string, port int,
	lowLevelProtocol protocol.Implementation,
	proxy ConnectionType, timing ...TCPClientConfiguration) ConnectionAndSessionInstance

type ConnectionInstance

type ConnectionInstance interface {
	// Send  data directly from instance. This will not work if the instance
	Send(data [][]byte) (int, error)
	//Receive data directly from instance. This will not work if the instance handles many connections like TCP-Servers
	Receive() ([]byte, error)
	// Run - Main-Loop
	Run(handler Handler)
	// Stop the main-loop of the Run-handler
	Stop()
	// Retrieve a session by IP. Do not use this for a normal protocol conversion of a server... Can return nil
	FindSessionsByIp(ip string) []Session
}

func CreateNewTCPServerInstance

func CreateNewTCPServerInstance(listeningPort int, protocolReceiveve protocol.Implementation,
	connectionType ConnectionType, maxConnections int, timingConfig ...TCPServerConfiguration) ConnectionInstance

func CreateSFTPClient added in v0.4.2

func CreateSFTPClient(ftptype FTPType, host string, port int, hostpath, filemask string, config *ftpConfiguration) (ConnectionInstance, error)

type ConnectionType added in v0.2.5

type ConnectionType int
const (
	NoLoadBalancer     ConnectionType = 1
	HAProxySendProxyV2 ConnectionType = 2
)

type ErrorType

type ErrorType int
const (
	ErrorConnect         ErrorType = 1
	ErrorSend            ErrorType = 2
	ErrorReceive         ErrorType = 3
	ErrorDisconnect      ErrorType = 4
	ErrorInternal        ErrorType = 5
	ErrorConnectionLimit ErrorType = 6
	ErrorAccept          ErrorType = 7 // error for Server
	ErrorMaxConnections  ErrorType = 8
	ErrorCreateSession   ErrorType = 9  // server only
	ErrorConfiguration   ErrorType = 10 // Error in configuration
	ErrorLogin           ErrorType = 11
)

type FTPConfiguration added in v0.4.1

type FTPConfiguration interface {
	UserPass(user, pass string)
	HostKey(hostkey string)
	PubKey(user, pubkey string)
	PollInterval(pollInterval time.Duration)
}

type FTPType added in v0.4.1

type FTPType int
const FTP FTPType = 1
const SFTP FTPType = 2

type FileNameGeneration

type FileNameGeneration int
const (
	Default   FileNameGeneration = 1
	TimeStamp FileNameGeneration = 1
)

type Handler

type Handler interface {
	//DataReceived event is triggered whenever the underlying protocol delivered a complete block(file/transmission) of data
	DataReceived(session Session, data []byte, receiveTimestamp time.Time) error
	// Connected event is triggered when connection is established. For client as well as for servers. 	For clients in addition every time the connection had
	// to be reestablished. If this method returns anything other but null, the connections
	// is declined and the thread ends
	Connected(session Session) error
	// Disconnected event is triggered when connection
	// is terminated.
	//For Servers: when the client ends the session
	// For clients: when the only client connection ends (inc.eof)
	Disconnected(session Session)

	// Error is called from async process (Run) when
	// status messages regarding the connection is available
	Error(session Session, typeOfError ErrorType, err error)
}

type LINEBREAK added in v0.4.2

type LINEBREAK int
const LINEBREAK_CR LINEBREAK = 0x0d
const LINEBREAK_CRLF LINEBREAK = 0x0d0a
const LINEBREAK_LF LINEBREAK = 0x0a

type ReadFilePolicy

type ReadFilePolicy int
const (
	ReadAndLeaveFile ReadFilePolicy = 1
	DeleteWhenRead   ReadFilePolicy = 2
	RenameWhenRead   ReadFilePolicy = 3
)

type SecureConnectionOptions added in v0.2.3

type SecureConnectionOptions struct {
	PublicKey string
}

type Session

type Session interface {
	IsAlive() bool
	Send(msg [][]byte) (int, error)
	Receive() ([]byte, error)
	Close() error
	WaitTermination() error
	RemoteAddress() (string, error)
}

type TCPClientConfiguration added in v0.4.0

type TCPClientConfiguration struct {
	Timeout                 time.Duration
	Deadline                time.Duration
	FlushBufferTimoutMs     int
	PollInterval            time.Duration
	SessionAfterFirstByte   bool
	SessionInitationTimeout time.Duration
	SourceIP                string
}

func (TCPClientConfiguration) SetSourceIP added in v0.4.0

func (s TCPClientConfiguration) SetSourceIP(sourceIP string) TCPClientConfiguration

type TCPServerConfiguration added in v0.2.5

type TCPServerConfiguration struct {
	Timeout                 time.Duration
	Deadline                time.Duration
	FlushBufferTimoutMs     int
	PollInterval            time.Duration
	SessionAfterFirstByte   bool
	SessionInitationTimeout time.Duration
}

Directories

Path Synopsis
example

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL