@@ -17,15 +17,23 @@ limitations under the License.
1717package v1
1818
1919import (
20+ "context"
21+
22+ meta_util "kmodules.xyz/client-go/meta"
23+
2024 "github.com/golang/glog"
2125 "github.com/pkg/errors"
2226 core "k8s.io/api/core/v1"
2327 kerr "k8s.io/apimachinery/pkg/api/errors"
28+ "k8s.io/apimachinery/pkg/api/meta"
2429 metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
30+ "k8s.io/apimachinery/pkg/runtime"
2531 "k8s.io/apimachinery/pkg/types"
32+ "k8s.io/apimachinery/pkg/util/sets"
2633 "k8s.io/apimachinery/pkg/util/strategicpatch"
2734 "k8s.io/apimachinery/pkg/util/wait"
2835 "k8s.io/client-go/kubernetes"
36+ "k8s.io/client-go/tools/pager"
2937 kutil "kmodules.xyz/client-go"
3038)
3139
@@ -112,3 +120,56 @@ func IsMaster(node core.Node) bool {
112120 role16 , ok16 := node .Labels ["kubernetes.io/role" ]
113121 return ok17 || (ok16 && role16 == "master" )
114122}
123+
124+ func Topology (kc kubernetes.Interface ) (regions map [string ][]string , instances map [string ]int , err error ) {
125+ // TODO: Use https://github.com/kubernetes/client-go/blob/kubernetes-1.17.0/metadata/interface.go once upgraded to 1.17
126+
127+ mapRegion := make (map [string ]sets.String )
128+ instances = make (map [string ]int )
129+
130+ lister := pager .New (pager .SimplePageFunc (func (opts metav1.ListOptions ) (runtime.Object , error ) {
131+ return kc .CoreV1 ().Nodes ().List (opts )
132+ }))
133+ err = lister .EachListItem (context .Background (), metav1.ListOptions {Limit : 100 }, func (obj runtime.Object ) error {
134+ m , err := meta .Accessor (obj )
135+ if err != nil {
136+ return err
137+ }
138+
139+ annotations := m .GetAnnotations ()
140+
141+ os , _ := meta_util .GetStringValueForKeys (annotations , "kubernetes.io/os" , "beta.kubernetes.io/os" )
142+ if os != "linux" {
143+ return nil
144+ }
145+ arch , _ := meta_util .GetStringValueForKeys (annotations , "kubernetes.io/arch" , "beta.kubernetes.io/arch" )
146+ if arch != "amd64" {
147+ return nil
148+ }
149+
150+ region , _ := meta_util .GetStringValueForKeys (annotations , "topology.kubernetes.io/region" , "failure-domain.beta.kubernetes.io/region" )
151+ zone , _ := meta_util .GetStringValueForKeys (annotations , "topology.kubernetes.io/zone" , "failure-domain.beta.kubernetes.io/zone" )
152+ if _ , ok := mapRegion [region ]; ! ok {
153+ mapRegion [region ] = sets .NewString ()
154+ }
155+ mapRegion [region ].Insert (zone )
156+
157+ instance , _ := meta_util .GetStringValueForKeys (annotations , "node.kubernetes.io/instance-type" , "beta.kubernetes.io/instance-type" )
158+ if n , ok := instances [instance ]; ok {
159+ instances [instance ] = n + 1
160+ } else {
161+ instances [instance ] = 1
162+ }
163+
164+ return nil
165+ })
166+ if err != nil {
167+ return nil , nil , err
168+ }
169+
170+ regions = make (map [string ][]string )
171+ for k , v := range mapRegion {
172+ regions [k ] = v .List ()
173+ }
174+ return regions , instances , nil
175+ }
0 commit comments