93 lines
2.6 KiB
Go
93 lines
2.6 KiB
Go
package live
|
|
|
|
import (
|
|
"encoding/json"
|
|
"errors"
|
|
|
|
"cloud.o-forge.io/core/oc-lib/logs"
|
|
"cloud.o-forge.io/core/oc-lib/models/utils"
|
|
"cloud.o-forge.io/core/oc-lib/tools"
|
|
)
|
|
|
|
type computeUnitsMongoAccessor[T LiveInterface] struct {
|
|
utils.AbstractAccessor[LiveInterface] // AbstractAccessor contains the basic fields of an accessor (model, caller)
|
|
}
|
|
|
|
// New creates a new instance of the computeUnitsMongoAccessor
|
|
func NewAccessor[T LiveInterface](t tools.DataType, request *tools.APIRequest) *computeUnitsMongoAccessor[T] {
|
|
return &computeUnitsMongoAccessor[T]{
|
|
AbstractAccessor: utils.AbstractAccessor[LiveInterface]{
|
|
Logger: logs.CreateLogger(t.String()), // Create a logger with the data type
|
|
Request: request,
|
|
Type: t,
|
|
New: func() LiveInterface {
|
|
switch t {
|
|
case tools.LIVE_DATACENTER:
|
|
return &LiveDatacenter{}
|
|
case tools.LIVE_STORAGE:
|
|
return &LiveStorage{}
|
|
}
|
|
return &LiveDatacenter{}
|
|
},
|
|
},
|
|
}
|
|
}
|
|
|
|
/*
|
|
* Nothing special here, just the basic CRUD operations
|
|
*/
|
|
func (a *computeUnitsMongoAccessor[T]) CopyOne(data utils.DBObject) (utils.DBObject, int, error) {
|
|
// is a publisher... that become a resources.
|
|
if data.IsDrafted() {
|
|
return nil, 422, errors.New("can't publish a drafted compute units")
|
|
}
|
|
live := data.(T)
|
|
if live.GetMonitorPath() == "" || live.GetID() != "" {
|
|
return nil, 422, errors.New("publishing is only allowed is it can be monitored and be accessible")
|
|
}
|
|
if res, code, err := a.LoadOne(live.GetID()); err != nil {
|
|
return nil, code, err
|
|
} else {
|
|
live = res.(T)
|
|
}
|
|
resAccess := live.GetResourceAccessor(a.Request)
|
|
instance := live.GetResourceInstance()
|
|
b, _ := json.Marshal(live)
|
|
json.Unmarshal(b, instance)
|
|
|
|
if len(live.GetResourcesID()) > 0 {
|
|
for _, r := range live.GetResourcesID() {
|
|
// TODO dependent of a existing resource
|
|
res, code, err := resAccess.LoadOne(r)
|
|
if err == nil {
|
|
return nil, code, err
|
|
}
|
|
existingResource := live.GetResource()
|
|
b, _ := json.Marshal(res)
|
|
json.Unmarshal(b, existingResource)
|
|
live.SetResourceInstance(existingResource, instance)
|
|
resAccess.UpdateOne(existingResource, existingResource.GetID())
|
|
}
|
|
if live.GetID() != "" {
|
|
return a.LoadOne(live.GetID())
|
|
} else {
|
|
return a.StoreOne(live)
|
|
}
|
|
} else {
|
|
r := live.GetResource()
|
|
b, _ := json.Marshal(live)
|
|
json.Unmarshal(b, &r)
|
|
live.SetResourceInstance(r, instance)
|
|
res, code, err := resAccess.StoreOne(r)
|
|
if err != nil {
|
|
return nil, code, err
|
|
}
|
|
live.SetResourcesID(res.GetID())
|
|
if live.GetID() != "" {
|
|
return a.UpdateOne(live, live.GetID())
|
|
} else {
|
|
return a.StoreOne(live)
|
|
}
|
|
}
|
|
}
|