|
| 1 | +package icingadb |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "github.com/icinga/icinga-go-library/database" |
| 6 | + "github.com/icinga/icinga-go-library/types" |
| 7 | + v1 "github.com/icinga/icingadb/pkg/icingadb/v1" |
| 8 | + "github.com/pkg/errors" |
| 9 | + "golang.org/x/sync/errgroup" |
| 10 | + "time" |
| 11 | +) |
| 12 | + |
| 13 | +// CreateSlaLifecyclesFromCheckables transforms the given checkables to sla lifecycle struct |
| 14 | +// and streams them into a returned channel. |
| 15 | +func CreateSlaLifecyclesFromCheckables( |
| 16 | + ctx context.Context, subject database.Entity, g *errgroup.Group, entities <-chan database.Entity, isDeleteEvent bool, |
| 17 | +) <-chan database.Entity { |
| 18 | + slaLifecycles := make(chan database.Entity, 1) |
| 19 | + |
| 20 | + g.Go(func() error { |
| 21 | + defer close(slaLifecycles) |
| 22 | + |
| 23 | + env, ok := v1.EnvironmentFromContext(ctx) |
| 24 | + if !ok { |
| 25 | + return errors.New("can't get environment from context") |
| 26 | + } |
| 27 | + |
| 28 | + for { |
| 29 | + select { |
| 30 | + case <-ctx.Done(): |
| 31 | + return ctx.Err() |
| 32 | + case checkable, ok := <-entities: |
| 33 | + if !ok { |
| 34 | + return nil |
| 35 | + } |
| 36 | + |
| 37 | + sl := &v1.SlaLifecycle{ |
| 38 | + EnvironmentMeta: v1.EnvironmentMeta{EnvironmentId: env.Id}, |
| 39 | + CreateTime: types.UnixMilli(time.Now()), |
| 40 | + DeleteTime: types.UnixMilli(time.Unix(0, 0)), |
| 41 | + } |
| 42 | + |
| 43 | + if isDeleteEvent { |
| 44 | + sl.DeleteTime = types.UnixMilli(time.Now()) |
| 45 | + sl.CreateTime = types.UnixMilli(time.Unix(0, 0)) |
| 46 | + } |
| 47 | + |
| 48 | + switch subject.(type) { |
| 49 | + case *v1.Host: |
| 50 | + sl.Id = checkable.ID().(types.Binary) |
| 51 | + sl.HostId = sl.Id |
| 52 | + case *v1.Service: |
| 53 | + sl.Id = checkable.ID().(types.Binary) |
| 54 | + sl.ServiceId = sl.Id |
| 55 | + sl.HostId = checkable.(*v1.Service).HostId |
| 56 | + default: |
| 57 | + return errors.Errorf("sla lifecycle for type %T is not supported", checkable) |
| 58 | + } |
| 59 | + |
| 60 | + select { |
| 61 | + case slaLifecycles <- sl: |
| 62 | + case <-ctx.Done(): |
| 63 | + return ctx.Err() |
| 64 | + } |
| 65 | + } |
| 66 | + } |
| 67 | + }) |
| 68 | + |
| 69 | + return slaLifecycles |
| 70 | +} |
0 commit comments