@@ -28,9 +28,37 @@ import (
28
28
infrav1 "sigs.k8s.io/cluster-api-provider-openstack/api/v1alpha6"
29
29
"sigs.k8s.io/cluster-api-provider-openstack/pkg/metrics"
30
30
"sigs.k8s.io/cluster-api-provider-openstack/pkg/record"
31
+ capoerrors "sigs.k8s.io/cluster-api-provider-openstack/pkg/utils/errors"
31
32
"sigs.k8s.io/cluster-api-provider-openstack/pkg/utils/names"
32
33
)
33
34
35
+ var (
36
+ ErrFilterMatch = fmt .Errorf ("filter match error" )
37
+ ErrMultipleMatches = multipleMatchesError {}
38
+ ErrNoMatches = noMatchesError {}
39
+ )
40
+
41
+ type (
42
+ multipleMatchesError struct {}
43
+ noMatchesError struct {}
44
+ )
45
+
46
+ func (e multipleMatchesError ) Error () string {
47
+ return "filter matched more than one resource"
48
+ }
49
+
50
+ func (e multipleMatchesError ) Is (err error ) bool {
51
+ return err == ErrFilterMatch
52
+ }
53
+
54
+ func (e noMatchesError ) Error () string {
55
+ return "filter matched no resources"
56
+ }
57
+
58
+ func (e noMatchesError ) Is (err error ) bool {
59
+ return err == ErrFilterMatch
60
+ }
61
+
34
62
type createOpts struct {
35
63
AdminStateUp * bool `json:"admin_state_up,omitempty"`
36
64
Name string `json:"name,omitempty"`
@@ -315,11 +343,36 @@ func (s *Service) GetSubnetsByFilter(opts subnets.ListOptsBuilder) ([]subnets.Su
315
343
return []subnets.Subnet {}, err
316
344
}
317
345
if len (subnetList ) == 0 {
318
- return nil , fmt . Errorf ( "no subnets could be found with the filters provided" )
346
+ return nil , ErrNoMatches
319
347
}
320
348
return subnetList , nil
321
349
}
322
350
351
+ // GetSubnetByFilter gets a single subnet specified by the given SubnetFilter.
352
+ // It returns an ErrFilterMatch if no or multiple subnets are found.
353
+ func (s * Service ) GetSubnetByFilter (filter * infrav1.SubnetFilter ) (* subnets.Subnet , error ) {
354
+ // If the ID is set, we can just get the subnet by ID.
355
+ if filter .ID != "" {
356
+ subnet , err := s .client .GetSubnet (filter .ID )
357
+ if capoerrors .IsNotFound (err ) {
358
+ return nil , ErrNoMatches
359
+ }
360
+ return subnet , err
361
+ }
362
+
363
+ subnets , err := s .GetSubnetsByFilter (filter .ToListOpt ())
364
+ if err != nil {
365
+ return nil , err
366
+ }
367
+ if len (subnets ) == 0 {
368
+ return nil , ErrNoMatches
369
+ }
370
+ if len (subnets ) > 1 {
371
+ return nil , ErrMultipleMatches
372
+ }
373
+ return & subnets [0 ], nil
374
+ }
375
+
323
376
func getSubnetName (clusterName string ) string {
324
377
return fmt .Sprintf ("%s-cluster-%s" , networkPrefix , clusterName )
325
378
}
0 commit comments