csi-driver/pkg/csi/p5x.go

117 lines
2.7 KiB
Go
Raw Normal View History

2024-09-28 05:44:56 +00:00
package csi
import (
"bytes"
"encoding/json"
"fmt"
"io"
"k8s.io/klog"
"net/http"
)
type p5xApi struct {
endpoint string
port int64
token string
}
type p5xVolume struct {
VolumeId int64 `json:"volumeId"`
Name string `json:"name"`
SizeInBytes int64 `json:"sizeInBytes"`
}
func (p5x *p5xApi) CreateVolume(name string, sizeInBytes int64) (*p5xVolume, error) {
vol := &p5xVolume{
VolumeId: 0,
Name: name,
SizeInBytes: sizeInBytes,
}
klog.Info("p5x.CreateVolume: Attempting to create: ", vol)
2024-09-28 05:44:56 +00:00
body, err := json.Marshal(vol)
if err != nil {
return nil, err
}
resBody, err := p5x.MakeRequest(http.MethodPost, "volumes", body)
if err != nil {
return nil, err
}
err = json.Unmarshal(resBody, vol)
klog.Info("p5x.CreateVolume: Successfully created volume: ", vol)
2024-09-28 05:44:56 +00:00
return vol, nil
}
func (p5x *p5xApi) GetVolumeByName(name string) (*p5xVolume, error) {
klog.Infof("p5x.GetVolumeByName: %s", name)
route := fmt.Sprintf("volumes/%s", name)
resBody, err := p5x.MakeRequest(http.MethodGet, route, nil)
if err != nil {
return nil, err
}
2024-09-28 05:44:56 +00:00
vol := &p5xVolume{}
err = json.Unmarshal(resBody, vol)
if err != nil {
return nil, err
}
klog.Info("p5x.GetVolumeByName: Retrieved volume: ", vol)
return vol, nil
2024-09-28 05:44:56 +00:00
}
func (p5x *p5xApi) DeleteVolume(volume *p5xVolume) error {
klog.Info("p5x.DeleteVolume: ", volume)
2024-09-28 05:44:56 +00:00
route := fmt.Sprintf("volumes/%s", volume.Name)
resBody, err := p5x.MakeRequest(http.MethodDelete, route, []byte(`{}`))
if err != nil {
return err
}
klog.Infof("p5x.DeleteVolume: Successfully deleted volume %s: %s", volume.Name, resBody)
2024-09-28 05:44:56 +00:00
return nil
}
func (p5x *p5xApi) MakeRequest(method string, route string, body []byte) ([]byte, error) {
url := fmt.Sprintf("%s:%d/api/v1/%s", p5x.endpoint, p5x.port, route)
klog.Infof("p5x.MakeRequest: [%s] %s", method, url)
var res *http.Response
var err error
if method == http.MethodGet {
res, err = http.Get(url)
if err != nil {
return nil, err
}
} else {
klog.Infof("p5x.MakeRequest: body: %s", body)
bodyReader := bytes.NewReader(body)
req, err2 := http.NewRequest(method, url, bodyReader)
if err2 != nil {
klog.Errorf("p5x.MakeRequest: could not create request: %s\n", err)
return nil, err2
}
req.Header.Set("Accept", "application/json")
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", p5x.token))
req.Header.Set("Content-Type", "application/json")
res, err = http.DefaultClient.Do(req)
}
2024-09-28 05:44:56 +00:00
if err != nil {
klog.Errorf("p5x.MakeRequest: error executing request: %s\n", err)
return nil, err
}
resBody, err := io.ReadAll(res.Body)
if err != nil {
klog.Errorf("p5x.MakeRequest: could not read response body: %s\n", err)
return nil, err
}
klog.Infof("p5x.MakeRequest: response body: %s\n", resBody)
return resBody, nil
}