Files
supermq/tools/provision/provision.go
T
b1ackd0t b3e2f41194 NOISSUE - Add Alarms (#106)
* WIP: alarms service

* fix(alarms): remove rule entity since it is not stored here

Signed-off-by: Rodney Osodo <socials@rodneyosodo.com>

* test(alarms): add tests cases for invalid alarms

* feat(alarms): add authorization

* feat(alarms): add docker deployment files

Signed-off-by: Rodney Osodo <socials@rodneyosodo.com>

* fix: update go mod file

* feat(alarms): support filtering by resolved_by, updated_by and severity

Signed-off-by: Rodney Osodo <socials@rodneyosodo.com>

* style: fix linter errors

Signed-off-by: Rodney Osodo <socials@rodneyosodo.com>

* fix(alarms): provide correct otel naming for create alarm

Fixes https://github.com/absmach/magistrala/pull/106#discussion_r2030151971

Signed-off-by: Rodney Osodo <socials@rodneyosodo.com>

* fix(alarms): group routes appropriately

Resolves https://github.com/absmach/magistrala/pull/106#discussion_r2030160891

Signed-off-by: Rodney Osodo <socials@rodneyosodo.com>

* fix(alarms): extract alarm id from url path rather than query params

Signed-off-by: Rodney Osodo <socials@rodneyosodo.com>

* fix(alarms): add all status to help in decoding

Signed-off-by: Rodney Osodo <socials@rodneyosodo.com>

* style(alarms): maintain consistent import as naming for supermq api package

Signed-off-by: Rodney Osodo <socials@rodneyosodo.com>

* refactor(alarms): update supermq dependecy to the latest

Signed-off-by: Rodney Osodo <socials@rodneyosodo.com>

* fix(alarms): Add domains gRPC service config to alarms service

Signed-off-by: Rodney Osodo <socials@rodneyosodo.com>

* test(alarms): all CRUD operations from the service

Return empty results instead of nil

This standardizes error responses across alarm endpoints to return empty
result structs rather than nil. Also renames entityReq to alarmReq and
adds HTTP status codes for created/deleted alarms.

Signed-off-by: Rodney Osodo <socials@rodneyosodo.com>

* test(alarms): fix failing tests due to introduction of context on sdk

Signed-off-by: Rodney Osodo <socials@rodneyosodo.com>

* fix(alarms): remove channel id

Signed-off-by: Rodney Osodo <socials@rodneyosodo.com>

* fix(alarms): standardize error handling across CRUD operations

Updated error responses to use specific repository errors for consistency

Signed-off-by: Rodney Osodo <socials@rodneyosodo.com>

* feat(alarms): add assignment fields to Alarm model and database

Introduced AssignedAt and AssignedBy fields to the Alarm struct and updated the database schema accordingly. Enhanced the UpdateAlarm function to handle these new fields, ensuring proper assignment tracking in the alarms system.

Signed-off-by: Rodney Osodo <socials@rodneyosodo.com>

* feat(alarms): enhance Alarm model with measurement attributes

Updated the Alarm struct to include Measurement, Value, Unit, and Cause fields. Modified the validation logic to ensure these fields are present. Adjusted logging and tracing middleware to reflect the new attributes. Updated database schema and related functions to accommodate these changes, ensuring comprehensive alarm data management.

Signed-off-by: Rodney Osodo <socials@rodneyosodo.com>

* feat(alarms): consume events from pubsub for creation of alarms

Removed session dependencies from CreateAlarm method and enhanced alarm validation to ensure all required fields are present

Signed-off-by: Rodney Osodo <socials@rodneyosodo.com>

* style(alarms): add newline at the end of docker compose

Signed-off-by: Rodney Osodo <socials@rodneyosodo.com>

* fix(alarms): Add assignee id and metadata fields when consuming messages

Signed-off-by: Rodney Osodo <socials@rodneyosodo.com>

* feat(alarms): add acknowledged field

Signed-off-by: Rodney Osodo <socials@rodneyosodo.com>

* feat(alarms): Add threshold value for the specific measurement

Signed-off-by: Rodney Osodo <socials@rodneyosodo.com>

* feat(alarms): Add channel, thing, and subtopic fields to Alarm model

This change adds required fields for tracking alarm sources and reorganizes
alarm-related fields for better grouping. Alarms now track the channel,
thing, and subtopic that triggered them, along with domain and rule info.

Signed-off-by: Rodney Osodo <socials@rodneyosodo.com>

* test(alarms): add service layer tests

Signed-off-by: Rodney Osodo <socials@rodneyosodo.com>

* fix(alarms): consume created at from message rather than creating it

Signed-off-by: Rodney Osodo <socials@rodneyosodo.com>

* feat(alarms): ready alarm as a gob encoded object

Signed-off-by: Rodney Osodo <socials@rodneyosodo.com>

* fix(alarms): read alarms from alarms queue and remove transformer

g

Signed-off-by: Rodney Osodo <socials@rodneyosodo.com>

* feat(alarms): update version of supermq

Signed-off-by: Rodney Osodo <socials@rodneyosodo.com>

* feat(alarms): add gob transformer

Signed-off-by: Rodney Osodo <socials@rodneyosodo.com>

* fix(alarms): rename thing id to client id

Signed-off-by: Rodney Osodo <socials@rodneyosodo.com>

* fix(alarms): create alarms stream

Signed-off-by: Rodney Osodo <socials@rodneyosodo.com>

* fix(alarms): check on logic to create new alarm

create new alarm if severity, status, subtopic changes
enhance logging with additional details for alarms management

Signed-off-by: Rodney Osodo <socials@rodneyosodo.com>

* remove conusmer and use pubsub

Signed-off-by: Rodney Osodo <socials@rodneyosodo.com>

* fix(alarms): use build tags for rabbitmq and nats

* fix(alarms): add health and metrics endpoint

* fix(magistrala): use supermq as build flags to see version and commit

* fix(alarms): use js config

* fix(alarms): remove validation when updating an alarm

fix authorization too

---------

Signed-off-by: Rodney Osodo <socials@rodneyosodo.com>
2025-04-15 19:32:09 +02:00

302 lines
7.4 KiB
Go

// Copyright (c) Abstract Machines
// SPDX-License-Identifier: Apache-2.0
package provision
import (
"bufio"
"bytes"
"context"
"crypto/ecdsa"
"crypto/rand"
"crypto/rsa"
"crypto/tls"
"crypto/x509"
"crypto/x509/pkix"
"encoding/pem"
"fmt"
"log"
"math/big"
"os"
"strings"
"time"
"github.com/0x6flab/namegenerator"
sdk "github.com/absmach/magistrala/pkg/sdk"
supermqSDK "github.com/absmach/supermq/pkg/sdk"
)
const (
defPass = "12345678"
defReaderURL = "http://localhost:9005"
)
var namesgenerator = namegenerator.NewGenerator()
// MgConn - structure describing SuperMQ connection set.
type MgConn struct {
ClientID string
ClinetSecret string
ChannelID string
MTLSCert string
MTLSKey string
}
// Config - provisioning configuration.
type Config struct {
Host string
Username string
Email string
Password string
Num int
SSL bool
CA string
CAKey string
Prefix string
}
// Provision - function that does actual provisiong.
func Provision(ctx context.Context, conf Config) error {
const (
rsaBits = 4096
ttl = "2400h"
)
msgContentType := string(supermqSDK.CTJSONSenML)
sdkConf := sdk.Config{
ClientsURL: conf.Host,
UsersURL: conf.Host,
ReaderURL: defReaderURL,
HTTPAdapterURL: fmt.Sprintf("%s/http", conf.Host),
BootstrapURL: conf.Host,
CertsURL: conf.Host,
MsgContentType: supermqSDK.ContentType(msgContentType),
TLSVerification: false,
}
s := sdk.NewSDK(sdkConf)
user := supermqSDK.User{
Email: conf.Email,
Credentials: supermqSDK.Credentials{
Username: conf.Username,
Secret: conf.Password,
},
}
if user.Email == "" {
user.Email = fmt.Sprintf("%s@email.com", namesgenerator.Generate())
user.Credentials.Secret = defPass
}
// Create new user
if _, err := s.CreateUser(ctx, user, ""); err != nil {
return fmt.Errorf("unable to create new user: %s", err.Error())
}
var err error
// Login user
token, err := s.CreateToken(ctx, supermqSDK.Login{Username: user.Credentials.Username, Password: user.Credentials.Secret})
if err != nil {
return fmt.Errorf("unable to login user: %s", err.Error())
}
// Create new domain
dname := fmt.Sprintf("%s%s", conf.Prefix, namesgenerator.Generate())
domain := supermqSDK.Domain{
Name: dname,
Route: strings.ToLower(dname),
Permission: "admin",
}
domain, err = s.CreateDomain(ctx, domain, token.AccessToken)
if err != nil {
return fmt.Errorf("unable to create domain: %w", err)
}
// Login to domain
token, err = s.CreateToken(ctx, supermqSDK.Login{
Username: user.Credentials.Username,
Password: user.Credentials.Secret,
})
if err != nil {
return fmt.Errorf("unable to login user: %w", err)
}
var tlsCert tls.Certificate
var caCert *x509.Certificate
if conf.SSL {
tlsCert, err = tls.LoadX509KeyPair(conf.CA, conf.CAKey)
if err != nil {
return fmt.Errorf("failed to load CA cert")
}
b, err := os.ReadFile(conf.CA)
if err != nil {
return fmt.Errorf("failed to load CA cert")
}
block, _ := pem.Decode(b)
if block == nil {
return fmt.Errorf("no PEM data found, failed to decode CA")
}
caCert, err = x509.ParseCertificate(block.Bytes)
if err != nil {
return fmt.Errorf("failed to decode certificate - %s", err.Error())
}
}
// Create clients and channels
clients := make([]supermqSDK.Client, conf.Num)
channels := make([]supermqSDK.Channel, conf.Num)
cIDs := []string{}
tIDs := []string{}
fmt.Println("# List of clients that can be connected to MQTT broker")
for i := 0; i < conf.Num; i++ {
clients[i] = supermqSDK.Client{Name: fmt.Sprintf("%s-client-%d", conf.Prefix, i)}
channels[i] = supermqSDK.Channel{Name: fmt.Sprintf("%s-channel-%d", conf.Prefix, i)}
}
clients, err = s.CreateClients(ctx, clients, domain.ID, token.AccessToken)
if err != nil {
return fmt.Errorf("failed to create the clients: %s", err.Error())
}
var chs []supermqSDK.Channel
for _, c := range channels {
c, err = s.CreateChannel(ctx, c, domain.ID, token.AccessToken)
if err != nil {
return fmt.Errorf("failed to create the chennels: %s", err.Error())
}
chs = append(chs, c)
}
channels = chs
for _, t := range clients {
tIDs = append(tIDs, t.ID)
}
for _, c := range channels {
cIDs = append(cIDs, c.ID)
}
for i := 0; i < conf.Num; i++ {
cert := ""
key := ""
if conf.SSL {
var priv interface{}
priv, _ = rsa.GenerateKey(rand.Reader, rsaBits)
notBefore := time.Now()
validFor, err := time.ParseDuration(ttl)
if err != nil {
return fmt.Errorf("failed to set date %v", validFor)
}
notAfter := notBefore.Add(validFor)
serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128)
serialNumber, err := rand.Int(rand.Reader, serialNumberLimit)
if err != nil {
return fmt.Errorf("failed to generate serial number: %s", err)
}
tmpl := x509.Certificate{
SerialNumber: serialNumber,
Subject: pkix.Name{
Organization: []string{"SuperMQ"},
CommonName: clients[i].Credentials.Secret,
OrganizationalUnit: []string{"supermq"},
},
NotBefore: notBefore,
NotAfter: notAfter,
KeyUsage: x509.KeyUsageDigitalSignature,
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth, x509.ExtKeyUsageServerAuth},
SubjectKeyId: []byte{1, 2, 3, 4, 6},
}
derBytes, err := x509.CreateCertificate(rand.Reader, &tmpl, caCert, publicKey(priv), tlsCert.PrivateKey)
if err != nil {
return fmt.Errorf("failed to create certificate: %s", err)
}
var bw, keyOut bytes.Buffer
buffWriter := bufio.NewWriter(&bw)
buffKeyOut := bufio.NewWriter(&keyOut)
if err := pem.Encode(buffWriter, &pem.Block{Type: "CERTIFICATE", Bytes: derBytes}); err != nil {
return fmt.Errorf("failed to write cert pem data: %s", err)
}
buffWriter.Flush()
cert = bw.String()
if err := pem.Encode(buffKeyOut, pemBlockForKey(priv)); err != nil {
return fmt.Errorf("failed to write key pem data: %s", err)
}
buffKeyOut.Flush()
key = keyOut.String()
}
// Print output
fmt.Printf("[[clients]]\nclient_id = \"%s\"\nclient_key = \"%s\"\n", clients[i].ID, clients[i].Credentials.Secret)
if conf.SSL {
fmt.Printf("mtls_cert = \"\"\"%s\"\"\"\n", cert)
fmt.Printf("mtls_key = \"\"\"%s\"\"\"\n", key)
}
fmt.Println("")
}
fmt.Printf("# List of channels that clients can publish to\n" +
"# each channel is connected to each client from clients list\n")
for i := 0; i < conf.Num; i++ {
fmt.Printf("[[channels]]\nchannel_id = \"%s\"\n\n", cIDs[i])
}
for _, cID := range cIDs {
for _, tID := range tIDs {
conIDs := supermqSDK.Connection{
ClientIDs: []string{tID},
ChannelIDs: []string{cID},
Types: []string{"publish", "subscribe"},
}
if err := s.Connect(ctx, conIDs, domain.ID, token.AccessToken); err != nil {
log.Fatalf("Failed to connect clients %s to channels %s: %s", tID, cID, err)
}
}
}
return nil
}
func publicKey(priv interface{}) interface{} {
switch k := priv.(type) {
case *rsa.PrivateKey:
return &k.PublicKey
case *ecdsa.PrivateKey:
return &k.PublicKey
default:
return nil
}
}
func pemBlockForKey(priv interface{}) *pem.Block {
switch k := priv.(type) {
case *rsa.PrivateKey:
return &pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(k)}
case *ecdsa.PrivateKey:
b, err := x509.MarshalECPrivateKey(k)
if err != nil {
fmt.Fprintf(os.Stderr, "Unable to marshal ECDSA private key: %v", err)
os.Exit(2)
}
return &pem.Block{Type: "EC PRIVATE KEY", Bytes: b}
default:
return nil
}
}