-
Notifications
You must be signed in to change notification settings - Fork 605
/
output.go
202 lines (173 loc) · 5.92 KB
/
output.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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
/**
# Copyright 2024 NVIDIA CORPORATION
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
**/
package lm
import (
"bytes"
"context"
"fmt"
"io"
"os"
"path/filepath"
"strings"
apiequality "k8s.io/apimachinery/pkg/api/equality"
"k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/klog/v2"
nfdv1alpha1 "sigs.k8s.io/node-feature-discovery/pkg/apis/nfd/v1alpha1"
nfdclientset "sigs.k8s.io/node-feature-discovery/pkg/generated/clientset/versioned"
spec "github.com/NVIDIA/k8s-device-plugin/api/config/v1"
"github.com/NVIDIA/k8s-device-plugin/internal/flags"
)
// Outputer defines a mechanism to output labels.
type Outputer interface {
Output(Labels) error
}
// TODO: Replace this with functional options.
func NewOutputer(config *spec.Config, nodeConfig flags.NodeConfig, clientSets flags.ClientSets) (Outputer, error) {
if config.Flags.UseNodeFeatureAPI == nil || !*config.Flags.UseNodeFeatureAPI {
return ToFile(*config.Flags.GFD.OutputFile), nil
}
if nodeConfig.Name == "" {
return nil, fmt.Errorf("required flag node-name not set")
}
if nodeConfig.Namespace == "" {
return nil, fmt.Errorf("required flag namespace not set")
}
o := nodeFeatureObject{
nodeConfig: nodeConfig,
nfdClientset: clientSets.NFD,
}
return &o, nil
}
func ToFile(path string) Outputer {
if path == "" {
return &toWriter{os.Stdout}
}
o := toFile(path)
return &o
}
// toFile writes to the specified file.
type toFile string
// toWriter writes to the specified writer
type toWriter struct {
io.Writer
}
func (path *toFile) Output(labels Labels) error {
klog.Infof("Writing labels to output file %v", *path)
buffer := new(bytes.Buffer)
output := &toWriter{buffer}
if err := output.Output(labels); err != nil {
return fmt.Errorf("error writing labels to buffer: %v", err)
}
err := writeFileAtomically(string(*path), buffer.Bytes(), 0644)
if err != nil {
return fmt.Errorf("error atomically writing file '%s': %w", *path, err)
}
return nil
}
func (output *toWriter) Output(labels Labels) error {
for k, v := range labels {
_, err := fmt.Fprintf(output, "%s=%s\n", k, v)
if err != nil {
return err
}
}
return nil
}
func writeFileAtomically(path string, contents []byte, perm os.FileMode) error {
absPath, err := filepath.Abs(path)
if err != nil {
return fmt.Errorf("failed to retrieve absolute path of output file: %v", err)
}
absDir := filepath.Dir(absPath)
tmpDir := filepath.Join(absDir, "gfd-tmp")
err = os.MkdirAll(tmpDir, os.ModePerm)
if err != nil && !os.IsExist(err) {
return fmt.Errorf("failed to create temporary directory: %v", err)
}
defer func() {
if err != nil {
os.RemoveAll(tmpDir)
}
}()
tmpFile, err := os.CreateTemp(tmpDir, "gfd-")
if err != nil {
return fmt.Errorf("fail to create temporary output file: %v", err)
}
defer func() {
if err != nil {
tmpFile.Close()
os.Remove(tmpFile.Name())
}
}()
err = os.WriteFile(tmpFile.Name(), contents, perm)
if err != nil {
return fmt.Errorf("error writing temporary file '%v': %v", tmpFile.Name(), err)
}
err = os.Rename(tmpFile.Name(), path)
if err != nil {
return fmt.Errorf("error moving temporary file to '%v': %v", path, err)
}
err = os.Chmod(path, perm)
if err != nil {
return fmt.Errorf("error setting permissions on '%v': %v", path, err)
}
return nil
}
const nodeFeatureVendorPrefix = "nvidia-features-for"
type nodeFeatureObject struct {
nodeConfig flags.NodeConfig
nfdClientset nfdclientset.Interface
}
// UpdateNodeFeatureObject creates/updates the node-specific NodeFeature custom resource.
func (n *nodeFeatureObject) Output(labels Labels) error {
nodename := n.nodeConfig.Name
if nodename == "" {
return fmt.Errorf("required flag %q not set", "node-name")
}
namespace := n.nodeConfig.Namespace
nodeFeatureName := strings.Join([]string{nodeFeatureVendorPrefix, nodename}, "-")
if nfr, err := n.nfdClientset.NfdV1alpha1().NodeFeatures(namespace).Get(context.TODO(), nodeFeatureName, metav1.GetOptions{}); errors.IsNotFound(err) {
klog.Infof("creating NodeFeature object %s", nodeFeatureName)
nfr = &nfdv1alpha1.NodeFeature{
TypeMeta: metav1.TypeMeta{},
ObjectMeta: metav1.ObjectMeta{Name: nodeFeatureName, Labels: map[string]string{nfdv1alpha1.NodeFeatureObjNodeNameLabel: nodename}},
Spec: nfdv1alpha1.NodeFeatureSpec{Features: *nfdv1alpha1.NewFeatures(), Labels: labels},
}
nfrCreated, err := n.nfdClientset.NfdV1alpha1().NodeFeatures(namespace).Create(context.TODO(), nfr, metav1.CreateOptions{})
if err != nil {
return fmt.Errorf("failed to create NodeFeature object %q: %w", nfr.Name, err)
}
klog.Infof("NodeFeature object created: %v", nfrCreated)
} else if err != nil {
return fmt.Errorf("failed to get NodeFeature object: %w", err)
} else {
nfrUpdated := nfr.DeepCopy()
nfrUpdated.Labels = map[string]string{nfdv1alpha1.NodeFeatureObjNodeNameLabel: nodename}
nfrUpdated.Spec = nfdv1alpha1.NodeFeatureSpec{Features: *nfdv1alpha1.NewFeatures(), Labels: labels}
if !apiequality.Semantic.DeepEqual(nfr, nfrUpdated) {
klog.Infof("updating NodeFeature object %s", nodeFeatureName)
nfrUpdated, err = n.nfdClientset.NfdV1alpha1().NodeFeatures(namespace).Update(context.TODO(), nfrUpdated, metav1.UpdateOptions{})
if err != nil {
return fmt.Errorf("failed to update NodeFeature object %q: %w", nfr.Name, err)
}
klog.Infof("NodeFeature object updated: %v", nfrUpdated)
} else {
klog.Infof("no changes in NodeFeature object, not updating")
}
}
return nil
}