pyscripts

package
v0.46.0 Latest Latest
Warning

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

Go to latest
Published: Nov 26, 2026 License: Apache-2.0 Imports: 11 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

Pyscripts Service

The Pyscripts service stores Python scripts, runs them on demand against a message, and records the outcome of every run.

Scripts

Field Description
id Unique script identifier (UUID)
group_id ID of the group the script belongs to
name Human-readable script name
description Optional description
source Python source code

Scripts are group-scoped and authorized through the Things service: group viewers can read scripts and runs, group editors can create, update, remove and run them. Running is an editor action because it executes code inside the service.

Source is checked when it is saved: POST /groups/:id/scripts and PUT /scripts/:id reject a script that is larger than MF_PYSCRIPTS_MAX_SCRIPT_SIZE or does not compile with 400 Bad Request; for a syntax error, the response's error carries Python's message with the line number. One create request accepts at most 32 scripts.

When a group is removed, its scripts and their runs are removed with it.

Writing a script

A script is plain Python that runs top to bottom. The input is available as the global message:

readings = [r["v"] for r in message["payload"]["readings"]]
print("saw", len(readings), "readings")
sum(readings) / len(readings)
  • message["payload"] is always present. subtopic, created and thing_id are present when the caller supplies them.
  • If the last statement is an expression, its value is the run's result. Otherwise the result is null.
  • The result must be JSON-serializable and fit, together with the run's logs, within MF_PYSCRIPTS_MAX_OUTPUT_SIZE (1 MiB by default). It is never allowed to exceed 4 MiB. NumPy scalars, arrays, DataFrames, NaN and Infinity fail the run with result cannot be returned: ...; convert them with .tolist() or float() first.
  • print() and writes to sys.stderr are recorded as the run's logs, up to MF_PYSCRIPTS_MAX_LOG_LINES lines.
  • An exception fails the run, and its traceback is recorded as the run's error.
  • numpy and pandas are available. No other packages can be installed.

Runs

POST /scripts/:id/run takes a JSON body with payload (at most 1 MiB) and optional subtopic, created and thing_id, executes the script, and stores the run.

A script that raises still returns 200 OK, with status: "fail" and the traceback in error. Other status codes:

Status Cause
429 The group exceeded its rate limit (2 requests/s, burst of 10), or the group or user already has a request in progress
503 No worker became free within MF_PYSCRIPTS_ACQUIRE_TIMEOUT
500 The runner failed for a reason outside the script

The rate limit is per group and applies to creating, updating and running scripts. Those requests each occupy a worker, so a group, and a user across all of their groups, may have only one of them in progress at a time. A run that leaves its worker unusable keeps the group and user busy for another 2 seconds.

GET /scripts/:id/runs lists a script's runs, newest first by default (order=started_at, dir=desc), and can be filtered by status (success, fail) and a from/to range in Unix milliseconds. Only the newest 1000 runs per script are kept: older runs are deleted automatically when a new run is saved, and any run can be removed earlier with PATCH /runs.

Sandboxing

At startup the service launches MF_PYSCRIPTS_WORKERS Python workers that import NumPy and pandas once. Each run is executed in a child forked from a worker, so no run can affect the next one. Before any user code runs, the child:

  • sets RLIMIT_CPU, RLIMIT_DATA, RLIMIT_FSIZE and disables core dumps,
  • installs a seccomp allow-list filter that denies networking, new processes, file writes and signals to other processes,
  • starts a new session and replaces stdin, stdout and stderr with /dev/null.

The service kills the run's process group when MF_PYSCRIPTS_RUN_TIMEOUT expires and refuses to start a worker that reports no seccomp filter, so pyseccomp and libseccomp must be installed in the image.

This is meant for scripts written by trusted group editors, not for hostile multi-tenant code. Script source and run logs are readable by every group viewer, so they must not contain credentials.

Scripts run under the same uid as the service and may open any file that uid can read. The workers get none of the service's environment variables, but files are not hidden: if MF_PYSCRIPTS_SERVER_KEY or MF_PYSCRIPTS_DB_SSL_KEY point to files mounted into the container, a group editor can read them and return their contents as a run result. Do not mount private keys the service user can read, or do not enable script execution where they are mounted.

Configuration

The service is configured using the environment variables from the following table. Note that any unset variables will be replaced with their default values.

Variable Description Default
MF_PYSCRIPTS_LOG_LEVEL Log level for Pyscripts (debug, info, warn, error) error
MF_PYSCRIPTS_DB_HOST Database host address localhost
MF_PYSCRIPTS_DB_PORT Database host port 5432
MF_PYSCRIPTS_DB_USER Database user mainflux
MF_PYSCRIPTS_DB_PASS Database password mainflux
MF_PYSCRIPTS_DB Name of the database used by the service pyscripts
MF_PYSCRIPTS_DB_SSL_MODE Database connection SSL mode (disable, require, verify-ca, verify-full) disable
MF_PYSCRIPTS_DB_SSL_CERT Path to the PEM encoded certificate file
MF_PYSCRIPTS_DB_SSL_KEY Path to the PEM encoded key file
MF_PYSCRIPTS_DB_SSL_ROOT_CERT Path to the PEM encoded root certificate file
MF_PYSCRIPTS_CLIENT_TLS Flag that indicates if TLS should be turned on false
MF_PYSCRIPTS_CA_CERTS Path to trusted CAs in PEM format
MF_PYSCRIPTS_HTTP_PORT Pyscripts service HTTP port 9033
MF_PYSCRIPTS_SERVER_CERT Path to server certificate in pem format
MF_PYSCRIPTS_SERVER_KEY Path to server key in pem format
MF_JAEGER_URL Jaeger server URL for distributed tracing. Leave empty to disable tracing.
MF_THINGS_AUTH_GRPC_URL Things auth service gRPC URL localhost:8183
MF_THINGS_AUTH_GRPC_TIMEOUT Things auth service gRPC request timeout 1s
MF_AUTH_GRPC_URL Auth service gRPC URL localhost:8181
MF_AUTH_GRPC_TIMEOUT Auth service gRPC request timeout 1s
MF_PYSCRIPTS_ES_URL Event store URL redis://localhost:6379/0
MF_PYSCRIPTS_PYTHON Python interpreter used for the workers python3
MF_PYSCRIPTS_WORKERS Number of pre-warmed workers, i.e. the number of concurrent runs 2
MF_PYSCRIPTS_RUN_TIMEOUT Wall-clock limit of one run 10s
MF_PYSCRIPTS_ACQUIRE_TIMEOUT How long a request waits for a free worker before failing with 503 5s
MF_PYSCRIPTS_START_TIMEOUT How long a worker may take to start 60s
MF_PYSCRIPTS_MAX_SCRIPT_SIZE Maximum script source size in bytes 65535
MF_PYSCRIPTS_MAX_OUTPUT_SIZE Maximum output a run may produce, logs and result together, in bytes 1048576
MF_PYSCRIPTS_MAX_LOG_LINES Maximum number of log lines kept per run 256
MF_PYSCRIPTS_MAX_CPU_SECONDS CPU time limit of one run (RLIMIT_CPU), in seconds 5
MF_PYSCRIPTS_MAX_MEMORY Memory one run may allocate on top of the worker's own (RLIMIT_DATA), in bytes 268435456
MF_PYSCRIPTS_MAX_FILE_SIZE File size limit of one run (RLIMIT_FSIZE), in bytes 0
MF_PYSCRIPTS_BLAS_THREADS Number of BLAS/OpenMP threads per run 1

In docker-compose the container is also bounded by MF_PYSCRIPTS_MEM_LIMIT and MF_PYSCRIPTS_PIDS_LIMIT. Keep MF_PYSCRIPTS_MEM_LIMIT above MF_PYSCRIPTS_WORKERS × (~120 MB + MF_PYSCRIPTS_MAX_MEMORY) and below the memory available to Docker, and scale the three together.

Deployment

The service is distributed as a Docker container built from docker/Dockerfile.python (make docker_pyscripts). Check the pyscripts service section in docker-compose to see how the service is deployed.

To start the service outside of the container, Python 3 with numpy, pandas and pyseccomp (and libseccomp) must be installed on a Linux host:

# Download the latest version of the service
git clone https://github.com/MainfluxLabs/mainflux

cd mainflux

# compile the pyscripts service
make pyscripts

# Copy binary to bin
make install

# set the environment variables and run the service
MF_PYSCRIPTS_LOG_LEVEL=[Pyscripts log level] \
MF_PYSCRIPTS_DB_HOST=[Database host address] \
MF_PYSCRIPTS_DB_PORT=[Database host port] \
MF_PYSCRIPTS_DB_USER=[Database user] \
MF_PYSCRIPTS_DB_PASS=[Database password] \
MF_PYSCRIPTS_DB=[Name of the database used by the service] \
MF_PYSCRIPTS_HTTP_PORT=[Service HTTP port] \
MF_THINGS_AUTH_GRPC_URL=[Things auth service gRPC URL] \
MF_AUTH_GRPC_URL=[Auth service gRPC URL] \
MF_PYSCRIPTS_ES_URL=[Event store URL] \
MF_PYSCRIPTS_PYTHON=[Python interpreter] \
$GOBIN/mainfluxlabs-pyscripts

Usage

For the full HTTP API reference, see the OpenAPI specification.

Documentation

Index

Constants

View Source
const (
	ScriptRunStatusSuccess = "success"
	ScriptRunStatusFail    = "fail"
)

Variables

View Source
var (
	ErrScriptSize   = errors.New("script size exceeds limit")
	ErrScriptSyntax = errors.New("script is not valid python")
	ErrRunnerBusy   = errors.New("no python worker available")
	ErrRunnerFailed = errors.New("python worker failed")
	ErrOutputLimit  = errors.New("output limit exceeded")
	ErrRunnerClosed = errors.New("runner is closed")
	ErrRateLimited  = errors.New("too many requests, retry later")
)
View Source
var ScriptOrderFields = map[string]string{
	"id":         "id",
	"name":       "LOWER(name)",
	"created_at": "created_at",
	"updated_at": "updated_at",
}

ScriptOrderFields maps API-facing order keys to SQL column expressions for the scripts table.

View Source
var ScriptRunOrderFields = map[string]string{
	"id":         "id",
	"started_at": "started_at",
	"status":     "status",
}

ScriptRunOrderFields maps API-facing order keys to SQL column expressions for the script_runs table.

Functions

func Checksum

func Checksum(source string) string

Checksum returns the hex-encoded SHA-256 of a script source.

Types

type Input

type Input struct {
	Payload  map[string]any `json:"payload"`
	Subtopic string         `json:"subtopic,omitempty"`
	Created  int64          `json:"created,omitempty"`
	ThingID  string         `json:"thing_id,omitempty"`
}

Input is what a run is given. It is the message shape the Python side sees as its "message" global, so the json tags are part of the contract with it.

type PageMetadata

type PageMetadata struct {
	Total  uint64    `json:"total,omitempty"`
	Offset uint64    `json:"offset,omitempty"`
	Limit  uint64    `json:"limit,omitempty"`
	Order  string    `json:"order,omitempty"`
	Dir    string    `json:"dir,omitempty"`
	Name   string    `json:"name,omitempty"`
	Status string    `json:"status,omitempty"`
	From   time.Time `json:"from,omitempty"`
	To     time.Time `json:"to,omitempty"`
}

type Result

type Result struct {
	Value      any
	Logs       []string
	Error      string
	StartedAt  time.Time
	FinishedAt time.Time
	Retired    bool
}

Result is the outcome of one run. Error is either the script's own failure or the reason the run was cut short; the two are not distinguished here because a caller records both the same way.

type Runner

type Runner interface {
	Run(ctx context.Context, code string, in Input) (Result, error)

	// Validate compiles code without executing it. It returns the Python syntax
	// error as a string when the source does not compile, and an empty string
	// when it does. A non-nil error means the check itself could not be run.
	Validate(ctx context.Context, code string) (string, error)

	Close() error
}

type Script

type Script struct {
	ID          string
	GroupID     string
	Name        string
	Description string
	Source      string
	Checksum    string
	CreatedAt   time.Time
	UpdatedAt   time.Time
}

type ScriptRepository

type ScriptRepository interface {
	// SaveScripts persists multiple Python scripts.
	SaveScripts(ctx context.Context, scripts ...Script) ([]Script, error)

	// RetrieveScriptByID retrieves a single Script denoted by ID.
	RetrieveScriptByID(ctx context.Context, id string) (Script, error)

	// RetrieveGroupIDsByScripts retrieves the distinct IDs of the Groups the Scripts denoted by the provided IDs belong to.
	RetrieveGroupIDsByScripts(ctx context.Context, ids ...string) ([]string, error)

	// RetrieveScriptsByGroup retrieves a list of Scripts belonging to a specific Group, without their source.
	RetrieveScriptsByGroup(ctx context.Context, groupID string, pm PageMetadata) (ScriptsPage, error)

	// UpdateScript updates the Script denoted by script.ID.
	UpdateScript(ctx context.Context, script Script) error

	// RemoveScripts removes the Scripts denoted by the provided IDs.
	RemoveScripts(ctx context.Context, ids ...string) error

	// RemoveScriptsByGroup removes all Scripts belonging to a specific Group.
	RemoveScriptsByGroup(ctx context.Context, groupID string) error

	// SaveRuns persists multiple Script Runs.
	SaveRuns(ctx context.Context, runs ...ScriptRun) ([]ScriptRun, error)

	// RetrieveRunByID retrieves a single Run denoted by ID.
	RetrieveRunByID(ctx context.Context, id string) (ScriptRun, error)

	// RetrieveGroupIDsByRuns retrieves the distinct IDs of the Groups the Runs denoted by the provided IDs belong to.
	RetrieveGroupIDsByRuns(ctx context.Context, ids ...string) ([]string, error)

	// RetrieveRunsByScript retrieves a list of Runs belonging to a specific Script.
	RetrieveRunsByScript(ctx context.Context, scriptID string, pm PageMetadata) (ScriptRunsPage, error)

	// RemoveRuns removes the Runs denoted by the provided IDs.
	RemoveRuns(ctx context.Context, ids ...string) error
}

type ScriptRun

type ScriptRun struct {
	ID             string
	ScriptID       string
	ScriptChecksum string
	Value          any
	Logs           []string
	StartedAt      time.Time
	FinishedAt     time.Time
	Status         string
	Error          string
}

type ScriptRunsPage

type ScriptRunsPage struct {
	Total uint64
	Runs  []ScriptRun
}

type ScriptsPage

type ScriptsPage struct {
	Total   uint64
	Scripts []Script
}

type Service

type Service interface {
	// CreateScripts persists multiple Python scripts.
	CreateScripts(ctx context.Context, token, groupID string, scripts ...Script) ([]Script, error)

	// ListScriptsByGroup retrieves a list of scripts belonging to a specific Group.
	ListScriptsByGroup(ctx context.Context, token, groupID string, pm PageMetadata) (ScriptsPage, error)

	// ViewScript retrieves a specific Script by its ID.
	ViewScript(ctx context.Context, token, id string) (Script, error)

	// UpdateScript updates the Script identified by the provided ID.
	UpdateScript(ctx context.Context, token string, script Script) error

	// RemoveScripts removes the Scripts identified by the provided IDs.
	RemoveScripts(ctx context.Context, token string, ids ...string) error

	// RemoveScriptsByGroup removes all Scripts belonging to a specific Group.
	RemoveScriptsByGroup(ctx context.Context, groupID string) error

	// RunScript executes the Script identified by the provided ID and records the run.
	RunScript(ctx context.Context, token, id string, in Input) (ScriptRun, error)

	// ListRunsByScript retrieves a list of Runs belonging to a specific Script.
	ListRunsByScript(ctx context.Context, token, scriptID string, pm PageMetadata) (ScriptRunsPage, error)

	// RemoveRuns removes the Runs identified by the provided IDs.
	RemoveRuns(ctx context.Context, token string, ids ...string) error
}

Service specifies an API that must be fulfilled by the domain service implementation, and all of its decorators (e.g. logging & metrics). All methods that accept a token parameter use it to identify and authorize the user performing the operation.

func New

func New(scripts ScriptRepository, run Runner, things domain.ThingsClient, idp uuid.IDProvider, logger logger.Logger, maxScriptSize int) Service

New instantiates the pyscripts service implementation.

Directories

Path Synopsis
api

Jump to

Keyboard shortcuts

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