aboutsummaryrefslogtreecommitdiffstats
path: root/library/go/yandex/yplite/yplite.go
blob: a39d889391f46ce62bae3a74d1eedf49022bbfe6 (plain) (blame)
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
package yplite

import (
	"context"
	"encoding/json"
	"net"
	"net/http"
	"os"
	"time"

	"github.com/ydb-platform/ydb/library/go/core/xerrors"
)

const (
	PodSocketPath    = "/run/iss/pod.socket"
	NodeAgentTimeout = 1 * time.Second
)

var (
	httpClient = http.Client{
		Transport: &http.Transport{
			DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) {
				return net.DialTimeout("unix", PodSocketPath, NodeAgentTimeout)
			},
		},
		Timeout: NodeAgentTimeout,
	}
)

func IsAPIAvailable() bool {
	if _, err := os.Stat(PodSocketPath); err == nil {
		return true
	}
	return false
}

func FetchPodSpec() (*PodSpec, error) {
	res, err := httpClient.Get("http://localhost/pod_spec")
	if err != nil {
		return nil, xerrors.Errorf("failed to request pod spec: %w", err)
	}
	defer func() { _ = res.Body.Close() }()

	spec := new(PodSpec)
	err = json.NewDecoder(res.Body).Decode(spec)
	if err != nil {
		return nil, xerrors.Errorf("failed to decode pod spec: %w", err)
	}

	return spec, nil
}

func FetchPodAttributes() (*PodAttributes, error) {
	res, err := httpClient.Get("http://localhost/pod_attributes")
	if err != nil {
		return nil, xerrors.Errorf("failed to request pod attributes: %w", err)
	}
	defer func() { _ = res.Body.Close() }()

	attrs := new(PodAttributes)
	err = json.NewDecoder(res.Body).Decode(attrs)
	if err != nil {
		return nil, xerrors.Errorf("failed to decode pod attributes: %w", err)
	}

	return attrs, nil
}