/
host_utils.go
338 lines (284 loc) · 10.5 KB
/
host_utils.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
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
package hostutil
import (
"encoding/json"
"fmt"
"net/http"
"net/url"
"path"
"regexp"
"strings"
"github.com/go-openapi/swag"
bmh_v1alpha1 "github.com/metal3-io/baremetal-operator/apis/metal3.io/v1alpha1"
"github.com/openshift/assisted-service/internal/common"
"github.com/openshift/assisted-service/models"
"github.com/openshift/assisted-service/pkg/conversions"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
"github.com/thoas/go-funk"
"gorm.io/gorm"
)
const (
MaxHostnameLength = 64
HostnamePattern = "^[a-z0-9][a-z0-9-]{0,62}(?:[.][a-z0-9-]{1,63})*$"
)
var ForbiddenHostnames = []string{
"localhost",
"localhost.localdomain",
"localhost4",
"localhost4.localdomain4",
"localhost6",
"localhost6.localdomain6",
}
func GetCurrentHostName(host *models.Host) (string, error) {
var inventory models.Inventory
if host.RequestedHostname != "" {
return host.RequestedHostname, nil
}
err := json.Unmarshal([]byte(host.Inventory), &inventory)
if err != nil {
return "", err
}
return inventory.Hostname, nil
}
func GetHostnameForMsg(host *models.Host) string {
hostName, err := GetCurrentHostName(host)
// An error here probably indicates that the agent didn't send inventory yet, fall back to UUID
if err != nil || hostName == "" {
return host.ID.String()
}
return hostName
}
func IsBeforeInstallation(status string) bool {
beforeInstallation := []string{models.HostStatusDiscovering, models.HostStatusKnown,
models.HostStatusDisconnected, models.HostStatusInsufficient,
models.HostStatusPendingForInput, models.HostStatusBinding}
return funk.ContainsString(beforeInstallation, status)
}
func GetEventSeverityFromHostStatus(status string) string {
switch status {
case models.HostStatusDisconnected:
return models.EventSeverityWarning
case models.HostStatusInstallingPendingUserAction:
return models.EventSeverityWarning
case models.HostStatusInsufficient:
return models.EventSeverityWarning
case models.HostStatusError:
return models.EventSeverityError
default:
return models.EventSeverityInfo
}
}
func ValidateHostname(hostname string) error {
if len(hostname) > MaxHostnameLength {
return common.NewApiError(http.StatusBadRequest, errors.New("hostname is too long"))
}
b, err := regexp.MatchString(HostnamePattern, hostname)
if err != nil {
return common.NewApiError(http.StatusInternalServerError, errors.Wrapf(err, "Matching hostname"))
}
if !b {
return common.NewApiError(http.StatusBadRequest, errors.Errorf("Hostname does not pass required regex validation: %s. Hostname: %s", HostnamePattern, hostname))
}
if funk.ContainsString(ForbiddenHostnames, hostname) {
return common.NewApiError(http.StatusBadRequest, errors.Errorf("The host name %s is forbidden", hostname))
}
return nil
}
func IsRoleValid(requestedRole models.HostRole, isDay2Host bool) bool {
roleSet := map[models.HostRole]struct{}{models.HostRoleAutoAssign: {}, models.HostRoleBootstrap: {}, models.HostRoleMaster: {}, models.HostRoleWorker: {}}
if isDay2Host {
roleSet = map[models.HostRole]struct{}{models.HostRoleMaster: {}, models.HostRoleWorker: {}}
}
_, exists := roleSet[requestedRole]
return exists
}
// determineDefaultInstallationDisk considers both the previously set installation disk and the current list of valid
// disks to determine the current required installation disk.
//
// Once the installation disk has been set, we usually no longer change it, even when an inventory update occurs
// that contains new disks that might be better "fit" for installation. This is because this field can also be set by
// the user via the API, and we don't want inventory updates to override the user's choice. However, if the disk that
// was set is no longer part of the inventory, the new installation disk is re-evaluated because it is not longer
// a valid choice.
func DetermineInstallationDisk(disks []*models.Disk, installationPath string) *models.Disk {
if len(disks) == 0 {
return nil
}
installationDisk := GetDiskByInstallationPath(disks, installationPath)
if installationDisk == nil {
installationDisk = disks[0]
}
return installationDisk
}
func GetHostInstallationPath(host *models.Host) string {
if host.InstallationDiskID != "" {
return host.InstallationDiskID
}
return host.InstallationDiskPath
}
func GetHostInstallationDisk(host *models.Host) (*models.Disk, error) {
inventory, err := common.UnmarshalInventory(host.Inventory)
if err != nil {
return nil, err
}
return GetDiskByInstallationPath(inventory.Disks, GetHostInstallationPath(host)), nil
}
func GetDiskByInstallationPath(disks []*models.Disk, installationPath string) *models.Disk {
if len(disks) == 0 || installationPath == "" {
return nil
}
// We changed the host.installationDiskPath to contain the disk id instead of the disk path.
// We will search for the installation path in the disk.Id and the disk.Path field for backward compatibility.
result := funk.Find(disks, func(disk *models.Disk) bool {
return disk.ID == installationPath || common.GetDeviceFullName(disk) == installationPath
})
if result == nil {
return nil
}
return result.(*models.Disk)
}
// GetAcceptableDisksWithHints finds acceptable installation disks based on the RootDeviceHints
//
// This function implements the logic to find the installation disk following what's currently
// supported by OpenShift, instead of *all* the supported cases in Ironic. The following link
// points to the RootDeviceDisk translation done by the BareMetal Operator that is then sent to
// Ironic:
// https://github.com/metal3-io/baremetal-operator/blob/dbe8780ad14f53132ba606d1baec808997febe49/pkg/provisioner/ironic/devicehints/devicehints.go#L11-L54
//
// The logic is quite straightforward and the checks done match what is in the aforementioned link.
// Some string checks require equality, others partial equality, whereas the int checks require numeric comparison.
//
// Ironic's internal filter process requires that all the disks have to fully match the RootDeviceHints (and operation),
// which is what this function does.
//
// This function also filters out disks that are not elegible for installation, as we already know those cannot be used.
func GetAcceptableDisksWithHints(disks []*models.Disk, hints *bmh_v1alpha1.RootDeviceHints) []*models.Disk {
acceptable := []*models.Disk{}
for _, disk := range disks {
if !disk.InstallationEligibility.Eligible {
continue
}
if hints != nil {
if hints.DeviceName != "" && hints.DeviceName != disk.Path && hints.DeviceName != disk.ByPath {
continue
}
if hints.HCTL != "" && hints.HCTL != disk.Hctl {
continue
}
if hints.Model != "" && !strings.Contains(disk.Model, hints.Model) {
continue
}
if hints.Vendor != "" && !strings.Contains(disk.Vendor, hints.Vendor) {
continue
}
if hints.SerialNumber != "" && hints.SerialNumber != disk.Serial {
continue
}
if hints.MinSizeGigabytes != 0 {
sizeGB := int(conversions.BytesToGb(disk.SizeBytes))
if sizeGB < hints.MinSizeGigabytes {
continue
}
}
if hints.WWN != "" && hints.WWN != disk.Wwn {
continue
}
// No WWNWithExtension
// if hints.WWWithExtension != "" && hints.WWWithExtension != disk.Wwwithextension {
// return ""
// }
// No WWNNVendorExtension
// if hints.WWNVendorExtension != "" && hints.WWNVendorExtension != disk.WwnVendorextension {
// return ""
// }
if hints.Rotational != nil && *hints.Rotational != (disk.DriveType == models.DriveTypeHDD) {
continue
}
}
acceptable = append(acceptable, disk)
}
return acceptable
}
func IgnitionFileName(host *models.Host) string {
return fmt.Sprintf("%s-%s.ign", common.GetEffectiveRole(host), host.ID)
}
func IsDay2Host(h *models.Host) bool {
return swag.StringValue(h.Kind) == models.HostKindAddToExistingClusterHost
}
func IsUnboundHost(h *models.Host) bool {
return h.ClusterID == nil
}
func MarshalConnectivityReport(report *models.ConnectivityReport) (string, error) {
if data, err := json.Marshal(report); err != nil {
return "", err
} else {
return string(data), nil
}
}
func UnmarshalConnectivityReport(reportStr string) (*models.ConnectivityReport, error) {
var report models.ConnectivityReport
if err := json.Unmarshal([]byte(reportStr), &report); err != nil {
return nil, err
}
return &report, nil
}
func GetHostCluster(log logrus.FieldLogger, db *gorm.DB, host *models.Host) (*common.Cluster, error) {
var cluster common.Cluster
err := db.First(&cluster, "id = ?", host.ClusterID).Error
if err != nil {
log.WithError(err).Errorf("Failed to find cluster %s", host.ClusterID)
return nil, errors.Errorf("Failed to find cluster %s", host.ClusterID)
}
return &cluster, nil
}
func IsSingleNode(log logrus.FieldLogger, db *gorm.DB, host *models.Host) bool {
cluster, err := GetHostCluster(log, db, host)
if err != nil {
log.Debug("Can't check if host is part of single node OpenShift")
return false
}
return common.IsSingleNodeCluster(cluster)
}
func SaveDiskPartitionsIsSet(installerArgs string) bool {
needToSaveFlags := []string{"--save-partlabel", "--save-partindex"}
for _, val := range needToSaveFlags {
if strings.Contains(installerArgs, val) {
return true
}
}
return false
}
func IsDiskEncryptionEnabledForRole(encryption models.DiskEncryption, role models.HostRole) bool {
switch swag.StringValue(encryption.EnableOn) {
case models.DiskEncryptionEnableOnAll:
return true
case models.DiskEncryptionEnableOnMasters:
return role == models.HostRoleMaster || role == models.HostRoleBootstrap
case models.DiskEncryptionEnableOnWorkers:
return role == models.HostRoleWorker
default:
return false
}
}
func GetIgnitionEndpoint(cluster *common.Cluster, host *models.Host) (string, error) {
poolName := string(common.GetEffectiveRole(host))
// At this moment the effective role should already be either master or worker. However, given that
// the default role is auto-assign, we want to explicitly handle this scenario. It should not happen
// but if there is a bug elsewhere, we need to be on the safe side.
if poolName == string(models.HostRoleAutoAssign) {
poolName = string(models.HostRoleWorker)
}
if host.MachineConfigPoolName != "" {
poolName = host.MachineConfigPoolName
}
ignitionEndpointUrl := fmt.Sprintf("http://%s:22624/config/%s", common.GetAPIHostname(cluster), poolName)
if cluster.IgnitionEndpoint != nil && cluster.IgnitionEndpoint.URL != nil {
url, err := url.Parse(*cluster.IgnitionEndpoint.URL)
if err != nil {
return "", err
}
url.Path = path.Join(url.Path, poolName)
ignitionEndpointUrl = url.String()
}
return ignitionEndpointUrl, nil
}