Compare commits

...

2 commits
0.0.2 ... main

Author SHA1 Message Date
Alexandre HEIM
cf7586a7dc add VariableSet, VariableUnset 2025-07-23 10:56:06 +02:00
Alexandre HEIM
50b4fce8a3 add StartService to plugis 2025-06-26 18:34:53 +02:00
7 changed files with 91 additions and 77 deletions

View file

@ -2,9 +2,7 @@ package echoservice
import ( import (
"context" "context"
"github.com/nats-io/nats.go/micro"
"github.com/telemac/plugisservice" "github.com/telemac/plugisservice"
nats_service "github.com/telemac/plugisservice/pkg/nats-service"
"time" "time"
) )
@ -21,7 +19,7 @@ func NewEchoService() *EchoService {
} }
// ExecuteCommand sends a command // ExecuteCommand sends a command
func (svc *EchoService) ExecuteCommand(ctx context.Context, command string) error { func (svc *EchoService) ExecuteCommand(ctx context.Context, command string) ([]byte, error) {
subject := "ism.homelab.service.plugis.command" subject := "ism.homelab.service.plugis.command"
svc.Logger().Info("sending command", svc.Logger().Info("sending command",
@ -35,7 +33,7 @@ func (svc *EchoService) ExecuteCommand(ctx context.Context, command string) erro
"error", err, "error", err,
"command", command, "command", command,
) )
return err return nil, err
} else { } else {
svc.Logger().Info("command executed successfully", svc.Logger().Info("command executed successfully",
"command", command, "command", command,
@ -43,7 +41,7 @@ func (svc *EchoService) ExecuteCommand(ctx context.Context, command string) erro
) )
} }
return nil return msg.Data, nil
} }
// Run is the main function of the service. // Run is the main function of the service.
@ -59,37 +57,14 @@ func (svc *EchoService) Run(ctx context.Context) error {
svc.ExecuteCommand(ctx, "sleep 3") svc.ExecuteCommand(ctx, "sleep 3")
service, err := nats_service.NewNatsService(svc.Nats(), svc.Prefix(), micro.Config{ service, err := svc.StartService(svc)
Name: svc.Name(),
Endpoint: nil,
Version: svc.Version(),
Description: svc.Description(),
Metadata: svc.Metadata(),
})
if err != nil { if err != nil {
return err return err
} }
defer func() { defer func() {
service.Stop() service.Stop()
}() }()
/* pingEndpoint.UserData = svc
pingEndpoint := nats_service.EndpointConfig{
Name: "ping",
Handler: func(ctx context.Context, request micro.Request) (any, error) {
data := request.Data()
_ = data
return "ping: " + string(data), err
},
MaxConcurrency: 10,
RequestTimeout: 2 * time.Second,
Metadata: map[string]string{
"description": "ping",
"version": "0.0.1",
},
}
*/
err = service.AddEndpoint(ctx, pingEndpoint) err = service.AddEndpoint(ctx, pingEndpoint)
if err != nil { if err != nil {
return err return err

View file

@ -9,9 +9,17 @@ import (
var pingEndpoint = nats_service.EndpointConfig{ var pingEndpoint = nats_service.EndpointConfig{
Name: "ping", Name: "ping",
Handler: func(ctx context.Context, request micro.Request) (any, error) { Handler: func(ctx context.Context, request micro.Request, ec nats_service.EndpointConfig) (any, error) {
data := request.Data() data := request.Data()
_ = data _ = data
// get plugis from EndpointConfigt
echoService, ok := ec.UserData.(*EchoService)
if ok {
echoService.Logger().Info("plugis ping received")
res, err := echoService.ExecuteCommand(ctx, "hostnamectl")
return string(res), err
}
return ec, nil
return "ping: " + string(data), nil return "ping: " + string(data), nil
}, },
MaxConcurrency: 10, MaxConcurrency: 10,

11
model/variable.go Normal file
View file

@ -0,0 +1,11 @@
package model
import "time"
type Variable struct {
Name string `json:"name"`
VarType string `json:"type,omitempty"`
Value any `json:"value,omitempty"`
Created *time.Time `json:"created,omitempty"`
Updated *time.Time `json:"updated,omitempty"`
}

View file

@ -18,6 +18,7 @@ type EndpointConfig struct {
Metadata map[string]string `json:"metadata,omitempty"` Metadata map[string]string `json:"metadata,omitempty"`
QueueGroup string `json:"queue_group,omitempty"` QueueGroup string `json:"queue_group,omitempty"`
Subject string `json:"subject,omitempty"` Subject string `json:"subject,omitempty"`
UserData any `json:"-"`
} }
// setDefaults applies default values to endpoint configuration // setDefaults applies default values to endpoint configuration
@ -90,7 +91,7 @@ type PlugisServiceReply struct {
} }
// PlugisServiceHandler is the function signature for endpoint handlers // PlugisServiceHandler is the function signature for endpoint handlers
type PlugisServiceHandler func(ctx context.Context, request micro.Request) (any, error) type PlugisServiceHandler func(ctx context.Context, request micro.Request, endpoint EndpointConfig) (any, error)
// PlugisHandler manages concurrency and timeouts for a single endpoint // PlugisHandler manages concurrency and timeouts for a single endpoint
type PlugisHandler struct { type PlugisHandler struct {
@ -154,7 +155,7 @@ func (ph PlugisHandler) handleWithTimeout(req micro.Request) {
} }
}() }()
data, err := ph.plugisServiceHandler(ctx, req) data, err := ph.plugisServiceHandler(ctx, req, ph.config)
resultChan <- result{data: data, err: err} resultChan <- result{data: data, err: err}
}() }()

View file

@ -1,44 +0,0 @@
package systeminfo
import (
"fmt"
"github.com/telemac/goutils/net"
"os"
"runtime"
)
type SystemInfo struct {
Platform string `json:"platform"` // ex: linux/amd64
Docker bool `json:"docker"` // true if runnint in docker container
Hostname string `json:"hostname"`
MacAddress string `json:"mac_address"`
}
func NewSystemInfo() (*SystemInfo, error) {
var systemInfo SystemInfo
err := systemInfo.Fill()
return &systemInfo, err
}
func (si *SystemInfo) Fill() error {
var err error
si.Platform = runtime.GOOS + "/" + runtime.GOARCH
si.Docker = isRunningInDockerContainer()
si.Hostname, err = os.Hostname()
if err != nil {
return fmt.Errorf("unable to get hostname: %v", err)
}
si.MacAddress, err = net.GetMACAddress()
if err != nil {
return fmt.Errorf("unable to get MAC address: %v", err)
}
return nil
}
// isRunningInDockerContainer
func isRunningInDockerContainer() bool {
if _, err := os.Stat("/.dockerenv"); err == nil {
return true
}
return false
}

View file

@ -10,6 +10,10 @@ import (
"runtime" "runtime"
"time" "time"
"github.com/nats-io/nats.go/micro"
"github.com/telemac/plugisservice/model"
nats_service "github.com/telemac/plugisservice/pkg/nats-service"
"github.com/telemac/goutils/net" "github.com/telemac/goutils/net"
"github.com/telemac/goutils/task" "github.com/telemac/goutils/task"
@ -33,6 +37,11 @@ var (
ErrNatsConnectionNil = errors.New("nats connection is nil") ErrNatsConnectionNil = errors.New("nats connection is nil")
) )
type Event[T any] struct {
Type string `json:"type,omitempty"`
Data T `json:"data,omitempty"`
}
// SetLogger sets the logger for the Plugis instance. // SetLogger sets the logger for the Plugis instance.
func (plugis *Plugis) SetLogger(log *slog.Logger) { func (plugis *Plugis) SetLogger(log *slog.Logger) {
plugis.logger = log plugis.logger = log
@ -218,6 +227,7 @@ func NewServiceMetadata(prefix string, startedAt time.Time) (*ServiceMetadata, e
// return meta // return meta
//} //}
// Meta returns ServiceMetaData as map[string]string
func (smd *ServiceMetadata) Meta() Metadata { func (smd *ServiceMetadata) Meta() Metadata {
data, err := json.Marshal(smd) data, err := json.Marshal(smd)
if err != nil { if err != nil {
@ -229,3 +239,52 @@ func (smd *ServiceMetadata) Meta() Metadata {
} }
return meta return meta
} }
// StartService initializes and starts a NATS service for the given PlugisServiceIntf implementation.
// It returns the created NatsService and any error encountered during the creation process.
func (plugis *Plugis) StartService(svc PlugisServiceIntf) (*nats_service.NatsService, error) {
service, err := nats_service.NewNatsService(plugis.Nats(), plugis.Prefix(), micro.Config{
Name: svc.Name(),
Endpoint: nil,
Version: svc.Version(),
Description: svc.Description(),
Metadata: svc.Metadata(),
})
return service, err
}
// VariableSet sets a variable with the given name, value, and type, then publishes it to a corresponding topic.
func (plugis *Plugis) VariableSet(name string, value any, varType string) error {
variable := model.Variable{
Name: name,
Value: value,
VarType: varType,
}
event := Event[model.Variable]{
Type: "variable.set",
Data: variable,
}
topic := "variable.set." + name
payload, err := json.Marshal(event)
if err != nil {
return err
}
return plugis.Publish(topic, payload)
}
// VariableUnset unsets a variable with the given name, then publishes it to a corresponding topic.
func (plugis *Plugis) VariableUnset(name string) error {
variable := model.Variable{
Name: name,
}
event := Event[model.Variable]{
Type: "variable.unset",
Data: variable,
}
topic := "variable.unset." + name
payload, err := json.Marshal(event)
if err != nil {
return err
}
return plugis.Publish(topic, payload)
}

View file

@ -2,6 +2,7 @@ package plugisservice
import ( import (
"context" "context"
nats_service "github.com/telemac/plugisservice/pkg/nats-service"
"iter" "iter"
"log/slog" "log/slog"
"time" "time"
@ -35,6 +36,9 @@ type PlugisIntf interface {
Request(subj string, data []byte, timeout time.Duration) (*nats.Msg, error) Request(subj string, data []byte, timeout time.Duration) (*nats.Msg, error)
RequestMany(ctx context.Context, subject string, data []byte, opts ...natsext.RequestManyOpt) (iter.Seq2[*nats.Msg, error], error) RequestMany(ctx context.Context, subject string, data []byte, opts ...natsext.RequestManyOpt) (iter.Seq2[*nats.Msg, error], error)
GetServices(ctx context.Context) ([]ServiceInfo, error) GetServices(ctx context.Context) ([]ServiceInfo, error)
StartService(svc PlugisServiceIntf) (*nats_service.NatsService, error)
VariableSet(name string, value any, varType string) error
VariableUnset(name string) error
} }
// ServiceInfo is the information about a service. // ServiceInfo is the information about a service.