|
| 1 | +/* |
| 2 | + Copyright © 2024 The CDI Authors |
| 3 | +
|
| 4 | + Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | + you may not use this file except in compliance with the License. |
| 6 | + You may obtain a copy of the License at |
| 7 | +
|
| 8 | + http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | +
|
| 10 | + Unless required by applicable law or agreed to in writing, software |
| 11 | + distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | + See the License for the specific language governing permissions and |
| 14 | + limitations under the License. |
| 15 | +*/ |
| 16 | + |
| 17 | +package cdi |
| 18 | + |
| 19 | +import ( |
| 20 | + "sync" |
| 21 | + |
| 22 | + oci "github.com/opencontainers/runtime-spec/specs-go" |
| 23 | +) |
| 24 | + |
| 25 | +var ( |
| 26 | + defaultCache *Cache |
| 27 | + getDefaultOnce sync.Once |
| 28 | +) |
| 29 | + |
| 30 | +func getOrCreateDefaultCache(options ...Option) (*Cache, bool) { |
| 31 | + var created bool |
| 32 | + getDefaultOnce.Do(func() { |
| 33 | + defaultCache = newCache(options...) |
| 34 | + created = true |
| 35 | + }) |
| 36 | + return defaultCache, created |
| 37 | +} |
| 38 | + |
| 39 | +// GetDefaultCache returns the default CDI cache instance. |
| 40 | +func GetDefaultCache() *Cache { |
| 41 | + cache, _ := getOrCreateDefaultCache() |
| 42 | + return cache |
| 43 | +} |
| 44 | + |
| 45 | +// Configure applies options to the default CDI cache. Updates and refreshes |
| 46 | +// the default cache if options are not empty. |
| 47 | +func Configure(options ...Option) { |
| 48 | + cache, created := getOrCreateDefaultCache(options...) |
| 49 | + if len(options) == 0 || created { |
| 50 | + return |
| 51 | + } |
| 52 | + cache.Configure(options...) |
| 53 | +} |
| 54 | + |
| 55 | +// Refresh explicitly refreshes the default CDI cache instance. |
| 56 | +func Refresh() error { |
| 57 | + return GetDefaultCache().Refresh() |
| 58 | +} |
| 59 | + |
| 60 | +// InjectDevices injects the given qualified devices to the given OCI Spec. |
| 61 | +// using the default CDI cache instance to resolve devices. |
| 62 | +func InjectDevices(ociSpec *oci.Spec, devices ...string) ([]string, error) { |
| 63 | + return GetDefaultCache().InjectDevices(ociSpec, devices...) |
| 64 | +} |
| 65 | + |
| 66 | +// GetErrors returns all errors encountered during the last refresh of |
| 67 | +// the default CDI cache instance. |
| 68 | +func GetErrors() map[string][]error { |
| 69 | + return GetDefaultCache().GetErrors() |
| 70 | +} |
0 commit comments