|
| 1 | +package icingadb |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "crypto/rand" |
| 6 | + "github.com/icinga/icingadb/pkg/com" |
| 7 | + "github.com/icinga/icingadb/pkg/contracts" |
| 8 | + v1 "github.com/icinga/icingadb/pkg/icingadb/v1" |
| 9 | + "github.com/icinga/icingadb/pkg/types" |
| 10 | + "github.com/icinga/icingadb/pkg/utils" |
| 11 | + "github.com/pkg/errors" |
| 12 | + "golang.org/x/sync/errgroup" |
| 13 | +) |
| 14 | + |
| 15 | +type SlaHistoryTrail struct { |
| 16 | + v1.EntityWithoutChecksum `json:",inline"` |
| 17 | + EnvironmentId types.Binary `json:"environment_id"` |
| 18 | + ObjectType string `json:"object_type"` |
| 19 | + HostId types.Binary `json:"host_id"` |
| 20 | + ServiceId types.Binary `json:"service_id"` |
| 21 | + EventTime types.UnixMilli `json:"event_time"` |
| 22 | + EventType string `json:"event_type"` |
| 23 | +} |
| 24 | + |
| 25 | +func CheckableToSlaTrailEntities(ctx context.Context, checkables <-chan contracts.Entity, eventType string) (<-chan contracts.Entity, <-chan error) { |
| 26 | + entities := make(chan contracts.Entity) |
| 27 | + g, ctx := errgroup.WithContext(ctx) |
| 28 | + |
| 29 | + g.Go(func() error { |
| 30 | + defer close(entities) |
| 31 | + |
| 32 | + for { |
| 33 | + select { |
| 34 | + case checkable, ok := <-checkables: |
| 35 | + if !ok { |
| 36 | + return nil |
| 37 | + } |
| 38 | + |
| 39 | + id, err := generateBinaryId() |
| 40 | + if err != nil { |
| 41 | + return errors.Wrap(err, "can't generate sla history trail ID") |
| 42 | + } |
| 43 | + |
| 44 | + entity := &SlaHistoryTrail{ |
| 45 | + EntityWithoutChecksum: v1.EntityWithoutChecksum{ |
| 46 | + IdMeta: v1.IdMeta{Id: id}, |
| 47 | + }, |
| 48 | + ObjectType: utils.Name(checkable), |
| 49 | + EventTime: types.UnixMilli{}, |
| 50 | + EventType: eventType, |
| 51 | + } |
| 52 | + |
| 53 | + switch ptr := checkable.(type) { |
| 54 | + case *v1.Host: |
| 55 | + entity.HostId = ptr.Id |
| 56 | + entity.EnvironmentId = ptr.EnvironmentId |
| 57 | + case *v1.Service: |
| 58 | + entity.HostId = ptr.HostId |
| 59 | + entity.ServiceId = ptr.Id |
| 60 | + entity.EnvironmentId = ptr.EnvironmentId |
| 61 | + } |
| 62 | + |
| 63 | + entities <- entity |
| 64 | + case <-ctx.Done(): |
| 65 | + return ctx.Err() |
| 66 | + } |
| 67 | + } |
| 68 | + }) |
| 69 | + |
| 70 | + return entities, com.WaitAsync(g) |
| 71 | +} |
| 72 | + |
| 73 | +// GenerateBinaryId generates a 20 byte length random id |
| 74 | +func generateBinaryId() (types.Binary, error) { |
| 75 | + id := make([]byte, 20) |
| 76 | + _, err := rand.Read(id) |
| 77 | + |
| 78 | + return id, err |
| 79 | +} |
0 commit comments