2023-05-04 16:24:04 +00:00
|
|
|
package resourcecontrol
|
|
|
|
|
|
|
|
import (
|
2023-05-05 00:19:47 +00:00
|
|
|
"errors"
|
2023-05-04 16:24:04 +00:00
|
|
|
"fmt"
|
|
|
|
|
|
|
|
portainer "github.com/portainer/portainer/api"
|
2023-06-20 20:51:34 +00:00
|
|
|
"github.com/portainer/portainer/api/dataservices"
|
2023-05-04 16:24:04 +00:00
|
|
|
|
|
|
|
"github.com/rs/zerolog/log"
|
|
|
|
)
|
|
|
|
|
|
|
|
type ServiceTx struct {
|
2023-06-22 21:28:07 +00:00
|
|
|
dataservices.BaseDataServiceTx[portainer.ResourceControl, portainer.ResourceControlID]
|
2023-05-04 16:24:04 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// ResourceControlByResourceIDAndType returns a ResourceControl object by checking if the resourceID is equal
|
|
|
|
// to the main ResourceID or in SubResourceIDs. It also performs a check on the resource type. Return nil
|
|
|
|
// if no ResourceControl was found.
|
|
|
|
func (service ServiceTx) ResourceControlByResourceIDAndType(resourceID string, resourceType portainer.ResourceControlType) (*portainer.ResourceControl, error) {
|
|
|
|
var resourceControl *portainer.ResourceControl
|
|
|
|
stop := fmt.Errorf("ok")
|
2023-06-22 21:28:07 +00:00
|
|
|
err := service.Tx.GetAll(
|
2023-05-04 16:24:04 +00:00
|
|
|
BucketName,
|
|
|
|
&portainer.ResourceControl{},
|
|
|
|
func(obj interface{}) (interface{}, error) {
|
|
|
|
rc, ok := obj.(*portainer.ResourceControl)
|
|
|
|
if !ok {
|
|
|
|
log.Debug().Str("obj", fmt.Sprintf("%#v", obj)).Msg("failed to convert to ResourceControl object")
|
2023-06-22 21:28:07 +00:00
|
|
|
return nil, fmt.Errorf("failed to convert to ResourceControl object: %s", obj)
|
2023-05-04 16:24:04 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
if rc.ResourceID == resourceID && rc.Type == resourceType {
|
|
|
|
resourceControl = rc
|
|
|
|
return nil, stop
|
|
|
|
}
|
|
|
|
|
|
|
|
for _, subResourceID := range rc.SubResourceIDs {
|
|
|
|
if subResourceID == resourceID {
|
|
|
|
resourceControl = rc
|
|
|
|
return nil, stop
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return &portainer.ResourceControl{}, nil
|
|
|
|
})
|
2023-05-05 00:19:47 +00:00
|
|
|
if errors.Is(err, stop) {
|
2023-05-04 16:24:04 +00:00
|
|
|
return resourceControl, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
// CreateResourceControl creates a new ResourceControl object
|
|
|
|
func (service ServiceTx) Create(resourceControl *portainer.ResourceControl) error {
|
2023-06-22 21:28:07 +00:00
|
|
|
return service.Tx.CreateObject(
|
2023-05-04 16:24:04 +00:00
|
|
|
BucketName,
|
|
|
|
func(id uint64) (int, interface{}) {
|
|
|
|
resourceControl.ID = portainer.ResourceControlID(id)
|
|
|
|
return int(resourceControl.ID), resourceControl
|
|
|
|
},
|
|
|
|
)
|
|
|
|
}
|