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 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639
|
package client
import (
"context"
"errors"
"fmt"
"reflect"
"github.com/go-logr/logr"
"github.com/ovn-kubernetes/libovsdb/cache"
"github.com/ovn-kubernetes/libovsdb/model"
"github.com/ovn-kubernetes/libovsdb/ovsdb"
)
// API defines basic operations to interact with the database
type API interface {
// List populates a slice of Models objects based on their type
// The function parameter must be a pointer to a slice of Models
// Models can be structs or pointers to structs
// If the slice is null, the entire cache will be copied into the slice
// If it has a capacity != 0, only 'capacity' elements will be filled in
List(ctx context.Context, result any) error
// Create a Conditional API from a Function that is used to filter cached data
// The function must accept a Model implementation and return a boolean. E.g:
// ConditionFromFunc(func(l *LogicalSwitch) bool { return l.Enabled })
WhereCache(predicate any) ConditionalAPI
// Create a ConditionalAPI from a Model's index data, where operations
// apply to elements that match the values provided in one or more
// model.Models according to the indexes. All provided Models must be
// the same type or an error will be generated when operations are
// are performed on the ConditionalAPI.
Where(...model.Model) ConditionalAPI
// WhereAny creates a ConditionalAPI from a list of Conditions where
// operations apply to elements that match any (eg, logical OR) of the
// conditions.
WhereAny(model.Model, ...model.Condition) ConditionalAPI
// WhereAll creates a ConditionalAPI from a list of Conditions where
// operations apply to elements that match all (eg, logical AND) of the
// conditions.
WhereAll(model.Model, ...model.Condition) ConditionalAPI
// Get retrieves a model from the cache
// The way the object will be fetch depends on the data contained in the
// provided model and the indexes defined in the associated schema
// For more complex ways of searching for elements in the cache, the
// preferred way is Where({condition}).List()
Get(context.Context, model.Model) error
// Create returns the operation needed to add the model(s) to the Database
// Only fields with non-default values will be added to the transaction. If
// the field associated with column "_uuid" has some content other than a
// UUID, it will be treated as named-uuid
Create(...model.Model) ([]ovsdb.Operation, error)
}
// ConditionalAPI is an interface used to perform operations that require / use Conditions
type ConditionalAPI interface {
// List uses the condition to search on the cache and populates
// the slice of Models objects based on their type
List(ctx context.Context, result any) error
// Mutate returns the operations needed to perform the mutation specified
// By the model and the list of Mutation objects
// Depending on the Condition, it might return one or many operations
Mutate(model.Model, ...model.Mutation) ([]ovsdb.Operation, error)
// Update returns the operations needed to update any number of rows according
// to the data in the given model.
// By default, all the non-default values contained in model will be updated.
// Optional fields can be passed (pointer to fields in the model) to select the
// the fields to be updated
Update(model.Model, ...any) ([]ovsdb.Operation, error)
// Delete returns the Operations needed to delete the models selected via the condition
Delete() ([]ovsdb.Operation, error)
// Wait returns the operations needed to perform the wait specified
// by the until condition, timeout, row and columns based on provided parameters.
Wait(ovsdb.WaitCondition, *int, model.Model, ...any) ([]ovsdb.Operation, error)
}
// ErrWrongType is used to report the user provided parameter has the wrong type
type ErrWrongType struct {
inputType reflect.Type
reason string
}
func (e *ErrWrongType) Error() string {
return fmt.Sprintf("Wrong parameter type (%s): %s", e.inputType, e.reason)
}
// ErrNotFound is used to inform the object or table was not found in the cache
var ErrNotFound = errors.New("object not found")
// api struct implements both API and ConditionalAPI
// Where() can be used to create a ConditionalAPI api
type api struct {
cache *cache.TableCache
cond Conditional
logger *logr.Logger
validateModel bool
}
// List populates a slice of Models given as parameter based on the configured Condition
func (a api) List(_ context.Context, result any) error {
resultPtr := reflect.ValueOf(result)
if resultPtr.Type().Kind() != reflect.Ptr {
return &ErrWrongType{resultPtr.Type(), "Expected pointer to slice of valid Models"}
}
resultVal := reflect.Indirect(resultPtr)
if resultVal.Type().Kind() != reflect.Slice {
return &ErrWrongType{resultPtr.Type(), "Expected pointer to slice of valid Models"}
}
// List accepts a slice of Models that can be either structs or pointer to
// structs
var appendValue func(reflect.Value)
var m model.Model
if resultVal.Type().Elem().Kind() == reflect.Ptr {
m = reflect.New(resultVal.Type().Elem().Elem()).Interface()
appendValue = func(v reflect.Value) {
resultVal.Set(reflect.Append(resultVal, v))
}
} else {
m = reflect.New(resultVal.Type().Elem()).Interface()
appendValue = func(v reflect.Value) {
resultVal.Set(reflect.Append(resultVal, reflect.Indirect(v)))
}
}
table, err := a.getTableFromModel(m)
if err != nil {
return err
}
if a.cond != nil && a.cond.Table() != table {
return &ErrWrongType{resultPtr.Type(),
fmt.Sprintf("Table derived from input type (%s) does not match Table from Condition (%s)", table, a.cond.Table())}
}
tableCache := a.cache.Table(table)
if tableCache == nil {
return ErrNotFound
}
var rows map[string]model.Model
if a.cond != nil {
rows, err = a.cond.Matches()
if err != nil {
return err
}
} else {
rows = tableCache.Rows()
}
// If given a null slice, fill it in the cache table completely, if not, just up to
// its capability.
if resultVal.IsNil() || resultVal.Cap() == 0 {
resultVal.Set(reflect.MakeSlice(resultVal.Type(), 0, len(rows)))
}
i := resultVal.Len()
maxCap := resultVal.Cap()
for _, row := range rows {
if i >= maxCap {
break
}
appendValue(reflect.ValueOf(row))
i++
}
return nil
}
// Where returns a conditionalAPI based on model indexes. All provided models
// must be the same type.
func (a api) Where(models ...model.Model) ConditionalAPI {
return newConditionalAPI(a.cache, a.conditionFromModels(models), a.logger, a.validateModel)
}
// WhereAny returns a conditionalAPI based on a Condition list that matches any
// of the conditions individually
func (a api) WhereAny(m model.Model, cond ...model.Condition) ConditionalAPI {
return newConditionalAPI(a.cache, a.conditionFromExplicitConditions(false, m, cond...), a.logger, a.validateModel)
}
// WhereAll returns a conditionalAPI based on a Condition list that matches all
// of the conditions together
func (a api) WhereAll(m model.Model, cond ...model.Condition) ConditionalAPI {
return newConditionalAPI(a.cache, a.conditionFromExplicitConditions(true, m, cond...), a.logger, a.validateModel)
}
// WhereCache returns a conditionalAPI based a Predicate
func (a api) WhereCache(predicate any) ConditionalAPI {
return newConditionalAPI(a.cache, a.conditionFromFunc(predicate), a.logger, a.validateModel)
}
// Conditional interface implementation
// FromFunc returns a Condition from a function
func (a api) conditionFromFunc(predicate any) Conditional {
table, err := a.getTableFromFunc(predicate)
if err != nil {
return newErrorConditional(err)
}
condition, err := newPredicateConditional(table, a.cache, predicate)
if err != nil {
return newErrorConditional(err)
}
return condition
}
// conditionFromModels returns a Conditional from one or more models.
func (a api) conditionFromModels(models []model.Model) Conditional {
if len(models) == 0 {
return newErrorConditional(fmt.Errorf("at least one model required"))
}
tableName, err := a.getTableFromModel(models[0])
if tableName == "" {
return newErrorConditional(err)
}
conditional, err := newEqualityConditional(tableName, a.cache, models)
if err != nil {
return newErrorConditional(err)
}
return conditional
}
// conditionFromExplicitConditions returns a Conditional from a model and a set
// of explicit conditions. If matchAll is true, then models that match all the given
// conditions are selected by the Conditional. If matchAll is false, then any model
// that matches one of the conditions is selected.
func (a api) conditionFromExplicitConditions(matchAll bool, m model.Model, cond ...model.Condition) Conditional {
if len(cond) == 0 {
return newErrorConditional(fmt.Errorf("at least one condition is required"))
}
tableName, err := a.getTableFromModel(m)
if tableName == "" {
return newErrorConditional(err)
}
conditional, err := newExplicitConditional(tableName, a.cache, matchAll, m, cond...)
if err != nil {
return newErrorConditional(err)
}
return conditional
}
// Get is a generic Get function capable of returning (through a provided pointer)
// a instance of any row in the cache.
// 'result' must be a pointer to an Model that exists in the ClientDBModel
//
// The way the cache is searched depends on the fields already populated in 'result'
// Any table index (including _uuid) will be used for comparison
func (a api) Get(_ context.Context, m model.Model) error {
table, err := a.getTableFromModel(m)
if err != nil {
return err
}
tableCache := a.cache.Table(table)
if tableCache == nil {
return ErrNotFound
}
_, found, err := tableCache.RowByModel(m)
if err != nil {
return err
} else if found == nil {
return ErrNotFound
}
model.CloneInto(found, m)
return nil
}
// Create is a generic function capable of creating any row in the DB
// A valid Model (pointer to object) must be provided.
func (a api) Create(models ...model.Model) ([]ovsdb.Operation, error) {
if len(models) == 0 {
return nil, nil
}
var operations []ovsdb.Operation
var tableName string
var err error
for _, m := range models {
var realUUID, namedUUID string
var currentTable string
currentTable, err = a.getTableFromModel(m)
if err != nil {
return nil, err
}
if a.validateModel {
if err := validateModel(m); err != nil {
return nil, err
}
}
if tableName == "" {
tableName = currentTable
} else if currentTable != tableName {
return nil, fmt.Errorf("models must belong to the same table for a single Create operation (%s != %s)", currentTable, tableName)
}
// Use the DatabaseModel associated with the cache to get info
info, err := a.cache.DatabaseModel().NewModelInfo(m)
if err != nil {
return nil, err
}
if uuid, err := info.FieldByColumn("_uuid"); err == nil {
tmpUUID := uuid.(string)
if ovsdb.IsNamedUUID(tmpUUID) {
namedUUID = tmpUUID
} else if ovsdb.IsValidUUID(tmpUUID) {
realUUID = tmpUUID
}
} else {
return nil, fmt.Errorf("error accessing _uuid field: %w", err)
}
// Use the Mapper associated with the cache to create the row
row, err := a.cache.Mapper().NewRow(info)
if err != nil {
return nil, err
}
// UUID is given in the operation, not the object
delete(row, "_uuid")
op := ovsdb.Operation{
Op: ovsdb.OperationInsert,
Table: tableName,
Row: row,
UUID: realUUID,
UUIDName: namedUUID,
}
operations = append(operations, op)
}
return operations, nil
}
// Mutate returns the operations needed to transform the one Model into another one
func (a api) Mutate(model model.Model, mutationObjs ...model.Mutation) ([]ovsdb.Operation, error) {
if len(mutationObjs) < 1 {
return nil, fmt.Errorf("at least one Mutation must be provided")
}
tableName, err := a.getTableFromModel(model)
if err != nil {
return nil, err
}
tableSchema := a.cache.DatabaseModel().Schema.Table(tableName)
if tableSchema == nil {
return nil, fmt.Errorf("schema not found for table %s", tableName)
}
info, err := a.cache.DatabaseModel().NewModelInfo(model)
if err != nil {
return nil, err
}
// Validate mutations if validation is enabled
if a.validateModel {
err = validateMutations(model, info, mutationObjs...)
if err != nil {
return nil, err
}
}
// Convert model.Mutation to ovsdb.Mutation and store them
var mutations []ovsdb.Mutation
for _, mutationObj := range mutationObjs {
columnName, err := info.ColumnByPtr(mutationObj.Field)
if err != nil {
return nil, fmt.Errorf("could not get column for mutation field: %w", err)
}
mutation, err := a.cache.Mapper().NewMutation(info, columnName, mutationObj.Mutator, mutationObj.Value)
if err != nil {
return nil, fmt.Errorf("failed to create OVSDB mutation for column '%s': %w", columnName, err)
}
mutations = append(mutations, *mutation)
}
conditions, err := a.cond.Generate()
if err != nil {
return nil, err
}
var operations []ovsdb.Operation
for _, condition := range conditions {
operations = append(operations,
ovsdb.Operation{
Op: ovsdb.OperationMutate,
Table: tableName,
Where: condition,
Mutations: mutations,
},
)
}
return operations, nil
}
// Update is a generic function capable of updating any mutable field in any row in the database
// Additional fields can be passed (variadic opts) to indicate fields to be updated
// All immutable fields will be ignored
func (a api) Update(model model.Model, fields ...any) ([]ovsdb.Operation, error) {
tableName, err := a.getTableFromModel(model)
if err != nil {
return nil, err
}
if a.validateModel {
if err := validateModel(model); err != nil {
return nil, err
}
}
tableSchema := a.cache.DatabaseModel().Schema.Table(tableName)
info, err := a.cache.DatabaseModel().NewModelInfo(model)
if err != nil {
return nil, err
}
if len(fields) > 0 {
for _, f := range fields {
colName, err := info.ColumnByPtr(f)
if err != nil {
return nil, err
}
if !tableSchema.Columns[colName].Mutable() {
return nil, fmt.Errorf("unable to update field %s of table %s as it is not mutable", colName, tableName)
}
}
}
// Convert the model to a row, considering only specified fields if provided
row, err := a.cache.Mapper().NewRow(info, fields...)
if err != nil {
return nil, err
}
// Remove immutable fields from the row
for colName, column := range tableSchema.Columns {
if !column.Mutable() {
// Only delete if the key actually exists in the row map
if _, exists := row[colName]; exists {
a.logger.V(2).Info("removing immutable field from update row", "name", colName)
delete(row, colName)
}
}
}
// Also remove _uuid explicitly if it exists
delete(row, "_uuid")
// Check if the row is empty after removing immutable fields
if len(row) == 0 {
return nil, fmt.Errorf("attempted to update using an empty row. please check that all fields you wish to update are mutable")
}
conditions, err := a.cond.Generate()
if err != nil {
return nil, err
}
var operations []ovsdb.Operation
for _, condition := range conditions {
operations = append(operations,
ovsdb.Operation{
Op: ovsdb.OperationUpdate,
Table: tableName,
Row: row,
Where: condition,
},
)
}
return operations, nil
}
// Delete returns the Operation needed to delete the selected models from the database
func (a api) Delete() ([]ovsdb.Operation, error) {
var operations []ovsdb.Operation
conditions, err := a.cond.Generate()
if err != nil {
return nil, err
}
for _, condition := range conditions {
operations = append(operations,
ovsdb.Operation{
Op: ovsdb.OperationDelete,
Table: a.cond.Table(),
Where: condition,
},
)
}
return operations, nil
}
func (a api) Wait(untilConFun ovsdb.WaitCondition, timeout *int, model model.Model, fields ...any) ([]ovsdb.Operation, error) {
var operations []ovsdb.Operation
/*
Ref: https://datatracker.ietf.org/doc/html/rfc7047.txt#section-5.2.6
lb := &nbdb.LoadBalancer{}
condition := model.Condition{
Field: &lb.Name,
Function: ovsdb.ConditionEqual,
Value: "lbName",
}
timeout0 := 0
client.Where(lb, condition).Wait(
ovsdb.WaitConditionNotEqual, // Until
&timeout0, // Timeout
&lb, // Row (and Table)
&lb.Name, // Cols (aka fields)
)
*/
conditions, err := a.cond.Generate()
if err != nil {
return nil, err
}
table, err := a.getTableFromModel(model)
if err != nil {
return nil, err
}
info, err := a.cache.DatabaseModel().NewModelInfo(model)
if err != nil {
return nil, err
}
var columnNames []string
if len(fields) > 0 {
columnNames = make([]string, 0, len(fields))
for _, f := range fields {
colName, err := info.ColumnByPtr(f)
if err != nil {
return nil, err
}
columnNames = append(columnNames, colName)
}
}
row, err := a.cache.Mapper().NewRow(info, fields...)
if err != nil {
return nil, err
}
rows := []ovsdb.Row{row}
for _, condition := range conditions {
operation := ovsdb.Operation{
Op: ovsdb.OperationWait,
Table: table,
Where: condition,
Until: string(untilConFun),
Columns: columnNames,
Rows: rows,
}
if timeout != nil {
operation.Timeout = timeout
}
operations = append(operations, operation)
}
return operations, nil
}
// getTableFromModel returns the table name from a Model object after performing
// type verifications on the model
func (a api) getTableFromModel(m any) (string, error) {
if _, ok := m.(model.Model); !ok {
return "", &ErrWrongType{reflect.TypeOf(m), "Type does not implement Model interface"}
}
table := a.cache.DatabaseModel().FindTable(reflect.TypeOf(m))
if table == "" {
return "", &ErrWrongType{reflect.TypeOf(m), "Model not found in Database Model"}
}
return table, nil
}
// getTableFromModel returns the table name from a the predicate after performing
// type verifications
func (a api) getTableFromFunc(predicate any) (string, error) {
predType := reflect.TypeOf(predicate)
if predType == nil || predType.Kind() != reflect.Func {
return "", &ErrWrongType{predType, "Expected function"}
}
if predType.NumIn() != 1 || predType.NumOut() != 1 || predType.Out(0).Kind() != reflect.Bool {
return "", &ErrWrongType{predType, "Expected func(Model) bool"}
}
modelInterface := reflect.TypeOf((*model.Model)(nil)).Elem()
modelType := predType.In(0)
if !modelType.Implements(modelInterface) {
return "", &ErrWrongType{predType,
fmt.Sprintf("Type %s does not implement Model interface", modelType.String())}
}
table := a.cache.DatabaseModel().FindTable(modelType)
if table == "" {
return "", &ErrWrongType{predType,
fmt.Sprintf("Model %s not found in Database Model", modelType.String())}
}
return table, nil
}
// newAPI returns a new API to interact with the database
func newAPI(cache *cache.TableCache, logger *logr.Logger, validateModel bool) API {
return api{
cache: cache,
logger: logger,
validateModel: validateModel,
}
}
// newConditionalAPI returns a new ConditionalAPI to interact with the database
func newConditionalAPI(cache *cache.TableCache, cond Conditional, logger *logr.Logger, validateModel bool) ConditionalAPI {
return api{
cache: cache,
cond: cond,
logger: logger,
validateModel: validateModel,
}
}
|