-
Notifications
You must be signed in to change notification settings - Fork 6
/
lib_remote_config.go
84 lines (78 loc) · 2 KB
/
lib_remote_config.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
package omcmd
import (
"context"
"fmt"
"net/http"
"os"
"github.com/opensvc/om3/core/client"
"github.com/opensvc/om3/core/naming"
)
func createTempRemoteConfig(p naming.Path, c *client.T) (string, error) {
var (
err error
buff []byte
f *os.File
)
if c, err = remoteClient(p, c); err != nil {
return "", err
}
if buff, err = fetchConfig(p, c); err != nil {
return "", err
}
if f, err = os.CreateTemp("", ".opensvc.remote.config.*"); err != nil {
return "", err
}
filename := f.Name()
if _, err = f.Write(buff); err != nil {
os.Remove(filename)
return "", err
}
return filename, nil
}
func remoteClient(p naming.Path, c *client.T) (*client.T, error) {
resp, err := c.GetObjectWithResponse(context.Background(), p.Namespace, p.Kind, p.Name)
if err != nil {
return nil, err
}
if resp.StatusCode() != http.StatusOK {
return nil, fmt.Errorf("get object %s data from %s: %s", p, c.URL(), resp.Status())
}
var nodename string
for k := range resp.JSON200.Data.Instances {
nodename = k
break
}
if nodename == "" {
return nil, fmt.Errorf("%s has no instance", p)
}
if c, err = client.New(client.WithURL(nodename)); err != nil {
return nil, err
}
return c, nil
}
func fetchConfig(p naming.Path, c *client.T) ([]byte, error) {
resp, err := c.GetObjectConfigFileWithResponse(context.Background(), p.Namespace, p.Kind, p.Name)
if err != nil {
return nil, err
} else if resp.StatusCode() != http.StatusOK {
return nil, fmt.Errorf("get object %s file from %s: %s", p, c.URL(), resp.Status())
}
return resp.Body, nil
}
func putConfig(p naming.Path, fName string, c *client.T) (err error) {
file, err := os.Open(fName)
if err != nil {
return err
}
defer file.Close()
resp, err := c.PutObjectConfigFileWithBody(context.Background(), p.Namespace, p.Kind, p.Name, "application/octet-stream", file)
if err != nil {
return err
}
switch resp.StatusCode {
case http.StatusOK:
return nil
default:
return fmt.Errorf("put object %s file from %s: %s", p, c.URL(), resp.Status)
}
}