@@ -7,11 +7,23 @@ import (
77 "fmt"
88 "strings"
99
10+ mapset "github.com/deckarep/golang-set/v2"
11+
1012 "github.com/hashicorp/consul/agent/dns"
13+ "github.com/hashicorp/consul/proto-public/pbresource"
1114)
1215
16+ // MaxNameLength is the maximum length of a resource name.
1317const MaxNameLength = 63
1418
19+ // DeletionTimestampKey is the key in a resource's metadata that stores the timestamp
20+ // when a resource was marked for deletion. This only applies to resources with finalizers.
21+ const DeletionTimestampKey = "deletionTimestamp"
22+
23+ // FinalizerKey is the key in resource's metadata that stores the whitespace separated
24+ // list of finalizers.
25+ const FinalizerKey = "finalizers"
26+
1527// ValidateName returns an error a name is not a valid resource name.
1628// The error will contain reference to what constitutes a valid resource name.
1729func ValidateName (name string ) error {
@@ -20,3 +32,55 @@ func ValidateName(name string) error {
2032 }
2133 return nil
2234}
35+
36+ // IsMarkedForDeletion returns true if a resource has been marked for deletion,
37+ // false otherwise.
38+ func IsMarkedForDeletion (res * pbresource.Resource ) bool {
39+ if res .Metadata == nil {
40+ return false
41+ }
42+ _ , ok := res .Metadata [DeletionTimestampKey ]
43+ return ok
44+ }
45+
46+ // HasFinalizers returns true if a resource has one or more finalizers, false otherwise.
47+ func HasFinalizers (res * pbresource.Resource ) bool {
48+ return GetFinalizers (res ).Cardinality () >= 1
49+ }
50+
51+ // HasFinalizer returns true if a resource has a given finalizers, false otherwise.
52+ func HasFinalizer (res * pbresource.Resource , finalizer string ) bool {
53+ return GetFinalizers (res ).Contains (finalizer )
54+ }
55+
56+ // AddFinalizer adds a finalizer to the given resource.
57+ func AddFinalizer (res * pbresource.Resource , finalizer string ) {
58+ finalizerSet := GetFinalizers (res )
59+ finalizerSet .Add (finalizer )
60+ if res .Metadata == nil {
61+ res .Metadata = map [string ]string {}
62+ }
63+ res .Metadata [FinalizerKey ] = strings .Join (finalizerSet .ToSlice (), " " )
64+ }
65+
66+ // RemoveFinalizer removes a finalizer from the given resource.
67+ func RemoveFinalizer (res * pbresource.Resource , finalizer string ) {
68+ finalizerSet := GetFinalizers (res )
69+ finalizerSet .Remove (finalizer )
70+ if res .Metadata == nil {
71+ res .Metadata = map [string ]string {}
72+ }
73+ res .Metadata [FinalizerKey ] = strings .Join (finalizerSet .ToSlice (), " " )
74+ }
75+
76+ // GetFinalizers returns the set of finalizers for the given resource.
77+ func GetFinalizers (res * pbresource.Resource ) mapset.Set [string ] {
78+ if res .Metadata == nil {
79+ return mapset .NewSet [string ]()
80+ }
81+ finalizers , ok := res .Metadata [FinalizerKey ]
82+ if ! ok {
83+ return mapset .NewSet [string ]()
84+ }
85+ return mapset .NewSet [string ](strings .Fields (finalizers )... )
86+ }
0 commit comments