eindelijk weer eens een push

This commit is contained in:
allard committed 2026-05-31 16:07:30 +02:00
1 parent 01cff8e165
commit ff21c258e0
2747 files changed
+302316 -131101

No files matched your search

+24
View File
@@ -0,0 +1,24 @@
FROM debian:bookworm-slim
# Minimal runtime dependencies
RUN apt-get update && apt-get install -y ca-certificates && rm -rf /var/lib/apt/lists/*
# Copy the compiled binary (already includes embedded Web UI)
COPY node-balancer /usr/local/bin/node-balancer
RUN chmod +x /usr/local/bin/node-balancer
# Web UI files (NEW)
COPY web /web
# Environment defaults (can be overridden)
ENV CPU_OVERLOAD_THRESHOLD=80
ENV MEMORY_OVERLOAD_THRESHOLD=80
ENV CPU_UNDERLOAD_THRESHOLD=50
ENV MEMORY_UNDERLOAD_THRESHOLD=50
ENV CLUSTER_NAME=cluster1
# Expose the WebUI port
EXPOSE 8080
# Start the node-balancer (and embedded WebUI)
ENTRYPOINT ["/usr/local/bin/node-balancer"]
+47
View File
@@ -0,0 +1,47 @@
module node-balancer
go 1.22.2
require (
k8s.io/api v0.29.3
k8s.io/apimachinery v0.29.3
k8s.io/client-go v0.29.3
k8s.io/metrics v0.29.3
)
require (
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/emicklei/go-restful/v3 v3.11.0 // indirect
github.com/go-logr/logr v1.3.0 // indirect
github.com/go-openapi/jsonpointer v0.19.6 // indirect
github.com/go-openapi/jsonreference v0.20.2 // indirect
github.com/go-openapi/swag v0.22.3 // indirect
github.com/gogo/protobuf v1.3.2 // indirect
github.com/golang/protobuf v1.5.4 // indirect
github.com/google/gnostic-models v0.6.8 // indirect
github.com/google/gofuzz v1.2.0 // indirect
github.com/google/uuid v1.3.0 // indirect
github.com/josharian/intern v1.0.0 // indirect
github.com/json-iterator/go v1.1.12 // indirect
github.com/mailru/easyjson v0.7.7 // indirect
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
github.com/modern-go/reflect2 v1.0.2 // indirect
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect
golang.org/x/net v0.19.0 // indirect
golang.org/x/oauth2 v0.10.0 // indirect
golang.org/x/sys v0.15.0 // indirect
golang.org/x/term v0.15.0 // indirect
golang.org/x/text v0.14.0 // indirect
golang.org/x/time v0.3.0 // indirect
google.golang.org/appengine v1.6.7 // indirect
google.golang.org/protobuf v1.33.0 // indirect
gopkg.in/inf.v0 v0.9.1 // indirect
gopkg.in/yaml.v2 v2.4.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
k8s.io/klog/v2 v2.110.1 // indirect
k8s.io/kube-openapi v0.0.0-20231010175941-2dd684a91f00 // indirect
k8s.io/utils v0.0.0-20230726121419-3b25d923346b // indirect
sigs.k8s.io/json v0.0.0-20221116044647-bc3834ca7abd // indirect
sigs.k8s.io/structured-merge-diff/v4 v4.4.1 // indirect
sigs.k8s.io/yaml v1.3.0 // indirect
)
+152
View File
@@ -0,0 +1,152 @@
github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/emicklei/go-restful/v3 v3.11.0 h1:rAQeMHw1c7zTmncogyy8VvRZwtkmkZ4FxERmMY4rD+g=
github.com/emicklei/go-restful/v3 v3.11.0/go.mod h1:6n3XBCmQQb25CM2LCACGz8ukIrRry+4bhvbpWn3mrbc=
github.com/go-logr/logr v1.3.0 h1:2y3SDp0ZXuc6/cjLSZ+Q3ir+QB9T/iG5yYRXqsagWSY=
github.com/go-logr/logr v1.3.0/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=
github.com/go-openapi/jsonpointer v0.19.6 h1:eCs3fxoIi3Wh6vtgmLTOjdhSpiqphQ+DaPn38N2ZdrE=
github.com/go-openapi/jsonpointer v0.19.6/go.mod h1:osyAmYz/mB/C3I+WsTTSgw1ONzaLJoLCyoi6/zppojs=
github.com/go-openapi/jsonreference v0.20.2 h1:3sVjiK66+uXK/6oQ8xgcRKcFgQ5KXa2KvnJRumpMGbE=
github.com/go-openapi/jsonreference v0.20.2/go.mod h1:Bl1zwGIM8/wsvqjsOQLJ/SH+En5Ap4rVB5KVcIDZG2k=
github.com/go-openapi/swag v0.22.3 h1:yMBqmnQ0gyZvEb/+KzuWZOXgllrXT4SADYbvDaXHv/g=
github.com/go-openapi/swag v0.22.3/go.mod h1:UzaqsxGiab7freDnrUUra0MwWfN/q7tE4j+VcZ0yl14=
github.com/go-task/slim-sprig v0.0.0-20230315185526-52ccab3ef572 h1:tfuBGBXKqDEevZMzYi5KSi8KkcZtzBcTgAUUtapy0OI=
github.com/go-task/slim-sprig v0.0.0-20230315185526-52ccab3ef572/go.mod h1:9Pwr4B2jHnOSGXyyzV8ROjYa2ojvAY6HCGYYfMoC3Ls=
github.com/gogo/protobuf v1.3.2 h1:Ov1cvc58UF3b5XjBnZv7+opcTcQFZebYjWzi34vdm4Q=
github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q=
github.com/golang/protobuf v1.3.1/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek=
github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps=
github.com/google/gnostic-models v0.6.8 h1:yo/ABAfM5IMRsS1VnXjTBvUb61tFIHozhlYvRgGre9I=
github.com/google/gnostic-models v0.6.8/go.mod h1:5n7qKqH0f5wFt+aWF8CW6pZLLNOfYuF5OpfBSENuI8U=
github.com/google/go-cmp v0.5.9/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=
github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
github.com/google/gofuzz v1.2.0 h1:xRy4A+RhZaiKjJ1bPfwQ8sedCA+YS2YcCHW6ec7JMi0=
github.com/google/gofuzz v1.2.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
github.com/google/pprof v0.0.0-20210720184732-4bb14d4b1be1 h1:K6RDEckDVWvDI9JAJYCmNdQXq6neHJOYx3V6jnqNEec=
github.com/google/pprof v0.0.0-20210720184732-4bb14d4b1be1/go.mod h1:kpwsk12EmLew5upagYY7GY0pfYCcupk39gWOCRROcvE=
github.com/google/uuid v1.3.0 h1:t6JiXgmwXMjEs8VusXIJk2BXHsn+wx8BZdTaoZ5fu7I=
github.com/google/uuid v1.3.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/josharian/intern v1.0.0 h1:vlS4z54oSdjm0bgjRigI+G1HpF+tI+9rE5LLzOg8HmY=
github.com/josharian/intern v1.0.0/go.mod h1:5DoeVV0s6jJacbCEi61lwdGj/aVlrQvzHFFd8Hwg//Y=
github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=
github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=
github.com/kisielk/errcheck v1.5.0/go.mod h1:pFxgyoBC7bSaBwPgfKdkLd5X25qrDl4LWUI2bnpBCr8=
github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck=
github.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI=
github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
github.com/mailru/easyjson v0.7.7 h1:UGYAvKxe3sBsEDzO8ZeWOSlIQfWFlxbzLZe7hwFURr0=
github.com/mailru/easyjson v0.7.7/go.mod h1:xzfreul335JAWq5oZzymOObrkdz5UnU4kGfJJLY9Nlc=
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M=
github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 h1:C3w9PqII01/Oq1c1nUAm88MOHcQC9l5mIlSMApZMrHA=
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ=
github.com/onsi/ginkgo/v2 v2.13.0 h1:0jY9lJquiL8fcf3M4LAXN5aMlS/b2BV86HFFPCPMgE4=
github.com/onsi/ginkgo/v2 v2.13.0/go.mod h1:TE309ZR8s5FsKKpuB1YAQYBzCaAfUgatB/xlT/ETL/o=
github.com/onsi/gomega v1.29.0 h1:KIA/t2t5UBzoirT4H9tsML45GEbo3ouUnBHsCfD2tVg=
github.com/onsi/gomega v1.29.0/go.mod h1:9sxs+SwGrKI0+PWe4Fxa9tFQQBG5xSsSbMXOI8PPpoQ=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/rogpeppe/go-internal v1.10.0 h1:TMyTOH3F/DB16zRVcYyreMH6GnZZrwQVAoYjRBZyWFQ=
github.com/rogpeppe/go-internal v1.10.0/go.mod h1:UQnix2H7Ngw/k4C5ijL5+65zddjncjaFoBhdsK/akog=
github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA=
github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk=
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20190603091049-60506f45cf65/go.mod h1:HSz+uSET+XFnRR8LxR5pz3Of3rY3CfYBVs4xY44aLks=
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20200226121028-0de0cce0169b/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU=
golang.org/x/net v0.19.0 h1:zTwKpTd2XuCqf8huc7Fo2iSy+4RHPd10s4KzeTnVr1c=
golang.org/x/net v0.19.0/go.mod h1:CfAk/cbD4CthTvqiEl8NpboMuiuOYsAr/7NOjZJtv1U=
golang.org/x/oauth2 v0.10.0 h1:zHCpF2Khkwy4mMB4bv0U37YtJdTGW8jI0glAApi0Kh8=
golang.org/x/oauth2 v0.10.0/go.mod h1:kTpgurOux7LqtuxjuyZa4Gj2gdezIt/jQtGnNFfypQI=
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.15.0 h1:h48lPFYpsTvQJZF4EKyI4aLHaev3CxivZmv7yZig9pc=
golang.org/x/sys v0.15.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/term v0.15.0 h1:y/Oo/a/q3IXu26lQgl04j/gjuBDOBlx7X6Om1j2CPW4=
golang.org/x/term v0.15.0/go.mod h1:BDl952bC7+uMoWR75FIrCDx79TPU9oHkTZ9yRbYOrX0=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk=
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.14.0 h1:ScX5w1eTa3QqT8oi6+ziP7dTV1S2+ALU0bI+0zXKWiQ=
golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
golang.org/x/time v0.3.0 h1:rg5rLMjNzMS1RkNLzCG38eapWhnYLFYXDXj2gOlr8j4=
golang.org/x/time v0.3.0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.0.0-20200619180055-7c47624df98f/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE=
golang.org/x/tools v0.0.0-20210106214847-113979e3529a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA=
golang.org/x/tools v0.16.1 h1:TLyB3WofjdOEepBHAU20JdNC1Zbg87elYofWYAY5oZA=
golang.org/x/tools v0.16.1/go.mod h1:kYVVN6I1mBNoB1OX+noeBjbRk4IUEPa7JJ+TJMEooJ0=
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
google.golang.org/appengine v1.6.7 h1:FZR1q0exgwxzPzp/aF+VccGrSfxfPpkBqjIIEq3ru6c=
google.golang.org/appengine v1.6.7/go.mod h1:8WjMMxjGQR8xUklV/ARdw2HLXBOI7O7uCIDZVag1xfc=
google.golang.org/protobuf v1.33.0 h1:uNO2rsAINq/JlFpSdYEKIZ0uKD/R9cpdv0T+yoGwGmI=
google.golang.org/protobuf v1.33.0/go.mod h1:c6P6GXX6sHbq/GpV6MGZEdwhWPcYBgnhAHhKbcUYpos=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=
gopkg.in/inf.v0 v0.9.1 h1:73M5CoZyi3ZLMOyDlQh031Cx6N9NDJ2Vvfl76EDAgDc=
gopkg.in/inf.v0 v0.9.1/go.mod h1:cWUDdTG/fYaXco+Dcufb5Vnc6Gp2YChqWtbxRZE0mXw=
gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY=
gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
k8s.io/api v0.29.3 h1:2ORfZ7+bGC3YJqGpV0KSDDEVf8hdGQ6A03/50vj8pmw=
k8s.io/api v0.29.3/go.mod h1:y2yg2NTyHUUkIoTC+phinTnEa3KFM6RZ3szxt014a80=
k8s.io/apimachinery v0.29.3 h1:2tbx+5L7RNvqJjn7RIuIKu9XTsIZ9Z5wX2G22XAa5EU=
k8s.io/apimachinery v0.29.3/go.mod h1:hx/S4V2PNW4OMg3WizRrHutyB5la0iCUbZym+W0EQIU=
k8s.io/client-go v0.29.3 h1:R/zaZbEAxqComZ9FHeQwOh3Y1ZUs7FaHKZdQtIc2WZg=
k8s.io/client-go v0.29.3/go.mod h1:tkDisCvgPfiRpxGnOORfkljmS+UrW+WtXAy2fTvXJB0=
k8s.io/klog/v2 v2.110.1 h1:U/Af64HJf7FcwMcXyKm2RPM22WZzyR7OSpYj5tg3cL0=
k8s.io/klog/v2 v2.110.1/go.mod h1:YGtd1984u+GgbuZ7e08/yBuAfKLSO0+uR1Fhi6ExXjo=
k8s.io/kube-openapi v0.0.0-20231010175941-2dd684a91f00 h1:aVUu9fTY98ivBPKR9Y5w/AuzbMm96cd3YHRTU83I780=
k8s.io/kube-openapi v0.0.0-20231010175941-2dd684a91f00/go.mod h1:AsvuZPBlUDVuCdzJ87iajxtXuR9oktsTctW/R9wwouA=
k8s.io/metrics v0.29.3 h1:nN+eavbMQ7Kuif2tIdTr2/F2ec2E/SIAWSruTZ+Ye6U=
k8s.io/metrics v0.29.3/go.mod h1:kb3tGGC4ZcIDIuvXyUE291RwJ5WmDu0tB4wAVZM6h2I=
k8s.io/utils v0.0.0-20230726121419-3b25d923346b h1:sgn3ZU783SCgtaSJjpcVVlRqd6GSnlTLKgpAAttJvpI=
k8s.io/utils v0.0.0-20230726121419-3b25d923346b/go.mod h1:OLgZIPagt7ERELqWJFomSt595RzquPNLL48iOWgYOg0=
sigs.k8s.io/json v0.0.0-20221116044647-bc3834ca7abd h1:EDPBXCAspyGV4jQlpZSudPeMmr1bNJefnuqLsRAsHZo=
sigs.k8s.io/json v0.0.0-20221116044647-bc3834ca7abd/go.mod h1:B8JuhiUyNFVKdsE8h686QcCxMaH6HrOAZj4vswFpcB0=
sigs.k8s.io/structured-merge-diff/v4 v4.4.1 h1:150L+0vs/8DA78h1u02ooW1/fFq/Lwr+sGiqlzvrtq4=
sigs.k8s.io/structured-merge-diff/v4 v4.4.1/go.mod h1:N8hJocpFajUSSeSJ9bOZ77VzejKZaXsTtZo4/u7Io08=
sigs.k8s.io/yaml v1.3.0 h1:a2VclLzOGrwOHDiV8EfBGhvjHvP46CtW5j6POvhYGGo=
sigs.k8s.io/yaml v1.3.0/go.mod h1:GeOyir5tyXNByN85N/dRIT9es5UQNerPYEKK56eTBm8=
+1
View File
@@ -0,0 +1 @@
microk8s kubectl logs deploy/node-balancer -n kube-system --follow
+205
View File
@@ -0,0 +1,205 @@
package main
import (
"context"
"fmt"
"log"
"os"
"strconv"
"time"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
metricsv "k8s.io/metrics/pkg/client/clientset/versioned"
)
var (
CPUOverloadThreshold int64
MemoryOverloadThreshold int64
CPUUnderloadThreshold int64
MemoryUnderloadThreshold int64
)
func getEnvInt64(name string, defaultVal int64) int64 {
valStr := os.Getenv(name)
if valStr == "" {
return defaultVal
}
val, err := strconv.ParseInt(valStr, 10, 64)
if err != nil {
log.Printf("Invalid %s: %s, using default %d", name, valStr, defaultVal)
return defaultVal
}
return val
}
func init() {
CPUOverloadThreshold = getEnvInt64("CPU_OVERLOAD_THRESHOLD", 80)
MemoryOverloadThreshold = getEnvInt64("MEMORY_OVERLOAD_THRESHOLD", 80)
CPUUnderloadThreshold = getEnvInt64("CPU_UNDERLOAD_THRESHOLD", 50)
MemoryUnderloadThreshold = getEnvInt64("MEMORY_UNDERLOAD_THRESHOLD", 50)
}
func main() {
config, err := rest.InClusterConfig()
if err != nil {
log.Fatal(err)
}
clientset, err := kubernetes.NewForConfig(config)
if err != nil {
log.Fatal(err)
}
metricsClient, err := metricsv.NewForConfig(config)
if err != nil {
log.Fatal(err)
}
for {
balanceNodes(clientset, metricsClient)
time.Sleep(2 * time.Minute)
}
}
func balanceNodes(clientset *kubernetes.Clientset, metricsClient *metricsv.Clientset) {
ctx := context.Background()
// Get node metrics
nodeMetricsList, err := metricsClient.MetricsV1beta1().NodeMetricses().List(ctx, metav1.ListOptions{})
if err != nil {
log.Println("Failed to get node metrics:", err)
return
}
nodeUsage := make(map[string]map[string]int64)
for _, m := range nodeMetricsList.Items {
nodeUsage[m.Name] = map[string]int64{
"cpu": m.Usage.Cpu().MilliValue(),
"mem": m.Usage.Memory().Value() / (1024 * 1024),
}
}
// Get node capacity
nodes, err := clientset.CoreV1().Nodes().List(ctx, metav1.ListOptions{})
if err != nil {
log.Println("Failed to list nodes:", err)
return
}
nodeCapacity := make(map[string]map[string]int64)
for _, n := range nodes.Items {
nodeCapacity[n.Name] = map[string]int64{
"cpu": n.Status.Capacity.Cpu().MilliValue(),
"mem": n.Status.Capacity.Memory().Value() / (1024 * 1024),
}
}
// Identify overloaded and underloaded nodes
var overloaded, underloaded []string
for node, usage := range nodeUsage {
cpuPercent := usage["cpu"] * 100 / nodeCapacity[node]["cpu"]
memPercent := usage["mem"] * 100 / nodeCapacity[node]["mem"]
if cpuPercent > CPUOverloadThreshold || memPercent > MemoryOverloadThreshold {
overloaded = append(overloaded, node)
} else if cpuPercent < CPUUnderloadThreshold && memPercent < MemoryUnderloadThreshold {
underloaded = append(underloaded, node)
}
}
if len(overloaded) == 0 || len(underloaded) == 0 {
return
}
// Evict one pod at a time from the most overloaded node
for _, node := range overloaded {
pods, err := clientset.CoreV1().Pods("").List(ctx, metav1.ListOptions{
FieldSelector: fmt.Sprintf("spec.nodeName=%s", node),
})
if err != nil {
log.Println("Failed to list pods for node", node, err)
continue
}
for _, pod := range pods.Items {
if pod.Namespace == "kube-system" || isDaemonSet(&pod) {
continue
}
// Pick the best target node
targetNode := pickTargetNode(underloaded, nodeUsage, nodeCapacity)
if targetNode == "" {
log.Println("No suitable underloaded node available")
break
}
fmt.Printf("Rescheduling pod %s/%s from %s to %s\n", pod.Namespace, pod.Name, node, targetNode)
grace := int64(0)
err = clientset.CoreV1().Pods(pod.Namespace).Delete(ctx, pod.Name, metav1.DeleteOptions{
GracePeriodSeconds: &grace,
})
if err != nil {
log.Println("Failed to delete pod", pod.Name, err)
continue
}
// Update in-memory usage
nodeUsage[node]["cpu"] -= estimatePodCPU(&pod)
nodeUsage[node]["mem"] -= estimatePodMem(&pod)
nodeUsage[targetNode]["cpu"] += estimatePodCPU(&pod)
nodeUsage[targetNode]["mem"] += estimatePodMem(&pod)
// Only evict one pod per run, then return
return
}
}
}
func isDaemonSet(pod *corev1.Pod) bool {
for _, owner := range pod.OwnerReferences {
if owner.Kind == "DaemonSet" {
return true
}
}
return false
}
// pickTargetNode chooses the underloaded node with lowest combined CPU+Memory usage
func pickTargetNode(nodes []string, usage map[string]map[string]int64, capacity map[string]map[string]int64) string {
var bestNode string
bestLoad := int64(1 << 62) // very high
for _, n := range nodes {
cpuPercent := usage[n]["cpu"] * 100 / capacity[n]["cpu"]
memPercent := usage[n]["mem"] * 100 / capacity[n]["mem"]
load := cpuPercent + memPercent
if load < bestLoad {
bestLoad = load
bestNode = n
}
}
return bestNode
}
// estimatePodCPU/Mem returns an approximate CPU/memory usage for the pod (from requests)
func estimatePodCPU(pod *corev1.Pod) int64 {
var cpu int64
for _, c := range pod.Spec.Containers {
if q, ok := c.Resources.Requests[corev1.ResourceCPU]; ok {
cpu += q.MilliValue()
}
}
return cpu
}
func estimatePodMem(pod *corev1.Pod) int64 {
var mem int64
for _, c := range pod.Spec.Containers {
if q, ok := c.Resources.Requests[corev1.ResourceMemory]; ok {
mem += q.Value() / (1024 * 1024) // MiB
}
}
return mem
}
+496
View File
@@ -0,0 +1,496 @@
package main
import (
"context"
"encoding/json"
"fmt"
"log"
"net/http"
"os"
"strconv"
"sync"
"time"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
"k8s.io/apimachinery/pkg/types"
metricsv "k8s.io/metrics/pkg/client/clientset/versioned"
)
var (
CPUOverloadThreshold int64
MemoryOverloadThreshold int64
CPUUnderloadThreshold int64
MemoryUnderloadThreshold int64
PodEvictionInterval time.Duration
PodAnimationDuration time.Duration
)
func getEnvInt64(name string, defaultVal int64) int64 {
valStr := os.Getenv(name)
if valStr == "" {
return defaultVal
}
val, err := strconv.ParseInt(valStr, 10, 64)
if err != nil {
log.Printf("Invalid %s: %s, using default %d", name, valStr, defaultVal)
return defaultVal
}
return val
}
func getEnvSecondsDuration(name string, defaultSec int64) time.Duration {
valStr := os.Getenv(name)
if valStr == "" {
return time.Duration(defaultSec) * time.Second
}
sec, err := strconv.ParseInt(valStr, 10, 64)
if err != nil {
log.Printf("Invalid %s: %s, using default %d seconds", name, valStr, defaultSec)
return time.Duration(defaultSec) * time.Second
}
return time.Duration(sec) * time.Second
}
func init() {
CPUOverloadThreshold = getEnvInt64("CPU_OVERLOAD_THRESHOLD", 80)
MemoryOverloadThreshold = getEnvInt64("MEMORY_OVERLOAD_THRESHOLD", 80)
CPUUnderloadThreshold = getEnvInt64("CPU_UNDERLOAD_THRESHOLD", 50)
MemoryUnderloadThreshold = getEnvInt64("MEMORY_UNDERLOAD_THRESHOLD", 50)
PodEvictionInterval = getEnvSecondsDuration("POD_EVICTION_INTERVAL", 120) // default 2 min
PodAnimationDuration = getEnvSecondsDuration("POD_ANIMATION_DURATION", 2) // default 2 sec
}
type PodMoveEvent struct {
Time time.Time `json:"time"`
Namespace string `json:"namespace"`
Pod string `json:"pod"`
FromNode string `json:"fromNode"`
ToNode string `json:"toNode"`
Reason string `json:"reason"`
}
type EventBus struct {
mu sync.Mutex
history []PodMoveEvent
clients map[chan PodMoveEvent]struct{}
}
func NewEventBus() *EventBus {
return &EventBus{
history: make([]PodMoveEvent, 0, 100),
clients: make(map[chan PodMoveEvent]struct{}),
}
}
func (b *EventBus) Emit(evt PodMoveEvent) {
b.mu.Lock()
defer b.mu.Unlock()
if len(b.history) == 100 {
b.history = b.history[1:]
}
b.history = append(b.history, evt)
for ch := range b.clients {
select {
case ch <- evt:
default:
}
}
}
func (b *EventBus) History() []PodMoveEvent {
b.mu.Lock()
defer b.mu.Unlock()
out := make([]PodMoveEvent, len(b.history))
copy(out, b.history)
return out
}
func (b *EventBus) Subscribe() chan PodMoveEvent {
b.mu.Lock()
defer b.mu.Unlock()
ch := make(chan PodMoveEvent, 10)
b.clients[ch] = struct{}{}
return ch
}
func (b *EventBus) Unsubscribe(ch chan PodMoveEvent) {
b.mu.Lock()
defer b.mu.Unlock()
delete(b.clients, ch)
close(ch)
}
func main() {
config, err := rest.InClusterConfig()
if err != nil {
log.Fatal(err)
}
clientset, err := kubernetes.NewForConfig(config)
if err != nil {
log.Fatal(err)
}
metricsClient, err := metricsv.NewForConfig(config)
if err != nil {
log.Fatal(err)
}
eventBus := NewEventBus()
go startWebUI(eventBus, clientset)
for {
balanceNodes(clientset, metricsClient, eventBus)
time.Sleep(PodEvictionInterval)
}
}
func startWebUI(bus *EventBus, clientset *kubernetes.Clientset) {
mux := http.NewServeMux()
mux.Handle("/", http.FileServer(http.Dir("/web")))
mux.HandleFunc("/api/events", func(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(bus.History())
})
mux.HandleFunc("/api/stream", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/event-stream")
w.Header().Set("Cache-Control", "no-cache")
flusher, ok := w.(http.Flusher)
if !ok {
http.Error(w, "streaming unsupported", 500)
return
}
ch := bus.Subscribe()
defer bus.Unsubscribe(ch)
for {
select {
case evt := <-ch:
data, _ := json.Marshal(evt)
fmt.Fprintf(w, "data: %s\n\n", data)
flusher.Flush()
case <-r.Context().Done():
return
}
}
})
log.Println("WebUI listening on :8080")
mux.HandleFunc("/api/nodes", func(w http.ResponseWriter, r *http.Request) {
nodes, err := clientset.CoreV1().Nodes().List(context.Background(), metav1.ListOptions{})
if err != nil {
http.Error(w, "failed to list nodes", http.StatusInternalServerError)
return
}
names := []string{}
for _, n := range nodes.Items {
names = append(names, n.Name)
}
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(names)
})
mux.HandleFunc("/api/pods", func(w http.ResponseWriter, r *http.Request) {
ctx := context.Background()
pods, err := clientset.CoreV1().Pods("").List(ctx, metav1.ListOptions{})
if err != nil {
http.Error(w, "failed to list pods", http.StatusInternalServerError)
return
}
// group pods by node
podsByNode := map[string][]string{}
for _, pod := range pods.Items {
if pod.Spec.NodeName == "" {
continue
}
if _, ok := podsByNode[pod.Spec.NodeName]; !ok {
podsByNode[pod.Spec.NodeName] = []string{}
}
podsByNode[pod.Spec.NodeName] = append(podsByNode[pod.Spec.NodeName], pod.Name)
}
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(podsByNode)
})
mux.HandleFunc("/api/config", func(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "application/json")
cfg := map[string]interface{}{
"animationDurationMs": int64(2000), // number
"version": "1.1", // string
"clusterName": os.Getenv("CLUSTER_NAME"), // string
}
_ = json.NewEncoder(w).Encode(cfg)
})
_ = http.ListenAndServe(":8080", mux)
}
func balanceNodes(clientset *kubernetes.Clientset, metricsClient *metricsv.Clientset, bus *EventBus) {
ctx := context.Background()
// --- get node metrics ---
nodeMetricsList, err := metricsClient.MetricsV1beta1().NodeMetricses().List(ctx, metav1.ListOptions{})
if err != nil {
log.Println("Failed to get node metrics:", err)
return
}
nodeUsage := make(map[string]map[string]int64)
for _, m := range nodeMetricsList.Items {
nodeUsage[m.Name] = map[string]int64{
"cpu": m.Usage.Cpu().MilliValue(),
"mem": m.Usage.Memory().Value() / (1024 * 1024),
}
}
// --- get node capacities ---
nodes, err := clientset.CoreV1().Nodes().List(ctx, metav1.ListOptions{})
if err != nil {
log.Println("Failed to list nodes:", err)
return
}
nodeCapacity := make(map[string]map[string]int64)
for _, n := range nodes.Items {
nodeCapacity[n.Name] = map[string]int64{
"cpu": n.Status.Capacity.Cpu().MilliValue(),
"mem": n.Status.Capacity.Memory().Value() / (1024 * 1024),
}
}
// --- find overloaded and underloaded nodes ---
var overloaded, underloaded []string
for node, usage := range nodeUsage {
cpuPercent := usage["cpu"] * 100 / nodeCapacity[node]["cpu"]
memPercent := usage["mem"] * 100 / nodeCapacity[node]["mem"]
if cpuPercent > CPUOverloadThreshold || memPercent > MemoryOverloadThreshold {
overloaded = append(overloaded, node)
} else if cpuPercent < CPUUnderloadThreshold && memPercent < MemoryUnderloadThreshold {
underloaded = append(underloaded, node)
}
}
fmt.Println("Overloaded nodes:", overloaded)
fmt.Println("Underloaded nodes:", underloaded)
if len(overloaded) == 0 || len(underloaded) == 0 {
return
}
// --- move pods from overloaded to underloaded ---
for _, node := range overloaded {
pods, err := clientset.CoreV1().Pods("").List(ctx, metav1.ListOptions{
FieldSelector: fmt.Sprintf("spec.nodeName=%s", node),
})
if err != nil {
log.Println("Failed to list pods for node", node, err)
continue
}
for _, pod := range pods.Items {
if pod.Namespace == "kube-system" || isDaemonSet(&pod) {
continue
}
// Skip pods not in Running state
if pod.Status.Phase != corev1.PodRunning {
continue
}
// --- choose target before deletion ---
targetNode := pickTargetNode(underloaded, nodeUsage, nodeCapacity)
if targetNode == "" {
// fallback: just skip this pod
continue
}
// --- emit event for GUI ---
bus.Emit(PodMoveEvent{
Time: time.Now(),
Namespace: pod.Namespace,
Pod: pod.Name,
FromNode: node,
ToNode: targetNode,
Reason: "node-utilization-imbalance",
})
fmt.Printf("Rescheduling pod %s/%s from %s to %s\n", pod.Namespace, pod.Name, node, targetNode)
// --- cordon the node ---
if err := cordonNode(clientset, node); err != nil {
log.Println("Failed to cordon node", node, err)
continue
}
// --- delete pod immediately ---
grace := int64(0)
err = clientset.CoreV1().Pods(pod.Namespace).Delete(ctx, pod.Name, metav1.DeleteOptions{
GracePeriodSeconds: &grace,
})
if err != nil {
log.Println("Failed to delete pod", pod.Name, err)
_ = uncordonNode(clientset, node)
continue
}
// --- wait for new pod from deployment ---
var ownerUID types.UID
if len(pod.OwnerReferences) > 0 {
ownerUID = pod.OwnerReferences[0].UID
}
var newPod corev1.Pod
for {
podsList, err := clientset.CoreV1().Pods(pod.Namespace).List(ctx, metav1.ListOptions{})
if err != nil {
log.Println("Failed to list pods:", err)
time.Sleep(2 * time.Second)
continue
}
found := true
for _, p := range podsList.Items {
if p.Name == pod.Name {
continue
}
for _, ref := range p.OwnerReferences {
if ref.UID == ownerUID && p.Status.Phase == corev1.PodRunning {
newPod = p
found = true
break
}
}
if found {
break
}
}
if found {
break
}
fmt.Println("Waiting for replacement pod to be Running...")
time.Sleep(2 * time.Second)
}
// --- uncordon the node now that pod has moved ---
if err := uncordonNode(clientset, node); err != nil {
log.Println("Failed to uncordon node", node, err)
}
// --- update node usage safely ---
if nodeUsage[node] != nil {
nodeUsage[node]["cpu"] -= estimatePodCPU(&pod)
nodeUsage[node]["mem"] -= estimatePodMem(&pod)
}
if nodeUsage[newPod.Spec.NodeName] == nil {
nodeUsage[newPod.Spec.NodeName] = map[string]int64{"cpu": 0, "mem": 0}
}
nodeUsage[newPod.Spec.NodeName]["cpu"] += estimatePodCPU(&pod)
nodeUsage[newPod.Spec.NodeName]["mem"] += estimatePodMem(&pod)
// only move one pod per invocation
return
}
}
}
//
// ─── HELPERS ────────────────────────────────────────────────────────────────────
//
func mustEnv(key, def string) string {
if val := os.Getenv(key); val != "" {
return val
}
return def
}
func cordonNode(clientset *kubernetes.Clientset, nodeName string) error {
ctx := context.Background()
node, err := clientset.CoreV1().Nodes().Get(ctx, nodeName, metav1.GetOptions{})
if err != nil {
return err
}
if node.Spec.Unschedulable {
return nil
}
node.Spec.Unschedulable = true
_, err = clientset.CoreV1().Nodes().Update(ctx, node, metav1.UpdateOptions{})
return err
}
func uncordonNode(clientset *kubernetes.Clientset, nodeName string) error {
ctx := context.Background()
node, err := clientset.CoreV1().Nodes().Get(ctx, nodeName, metav1.GetOptions{})
if err != nil {
return err
}
node.Spec.Unschedulable = false
_, err = clientset.CoreV1().Nodes().Update(ctx, node, metav1.UpdateOptions{})
return err
}
func isDaemonSet(pod *corev1.Pod) bool {
for _, owner := range pod.OwnerReferences {
if owner.Kind == "DaemonSet" {
return true
}
}
return false
}
func pickTargetNode(nodes []string, usage map[string]map[string]int64, capacity map[string]map[string]int64) string {
var bestNode string
bestLoad := int64(1 << 62)
for _, n := range nodes {
cpuPercent := usage[n]["cpu"] * 100 / capacity[n]["cpu"]
memPercent := usage[n]["mem"] * 100 / capacity[n]["mem"]
load := cpuPercent + memPercent
if load < bestLoad {
bestLoad = load
bestNode = n
}
}
return bestNode
}
func estimatePodCPU(pod *corev1.Pod) int64 {
var cpu int64
for _, c := range pod.Spec.Containers {
if q, ok := c.Resources.Requests[corev1.ResourceCPU]; ok {
cpu += q.MilliValue()
}
}
return cpu
}
func estimatePodMem(pod *corev1.Pod) int64 {
var mem int64
for _, c := range pod.Spec.Containers {
if q, ok := c.Resources.Requests[corev1.ResourceMemory]; ok {
mem += q.Value() / (1024 * 1024)
}
}
return mem
}
+496
View File
@@ -0,0 +1,496 @@
package main
import (
"context"
"encoding/json"
"fmt"
"log"
"net/http"
"os"
"strconv"
"sync"
"time"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
"k8s.io/apimachinery/pkg/types"
metricsv "k8s.io/metrics/pkg/client/clientset/versioned"
)
var (
CPUOverloadThreshold int64
MemoryOverloadThreshold int64
CPUUnderloadThreshold int64
MemoryUnderloadThreshold int64
PodEvictionInterval time.Duration
PodAnimationDuration time.Duration
)
func getEnvInt64(name string, defaultVal int64) int64 {
valStr := os.Getenv(name)
if valStr == "" {
return defaultVal
}
val, err := strconv.ParseInt(valStr, 10, 64)
if err != nil {
log.Printf("Invalid %s: %s, using default %d", name, valStr, defaultVal)
return defaultVal
}
return val
}
func getEnvSecondsDuration(name string, defaultSec int64) time.Duration {
valStr := os.Getenv(name)
if valStr == "" {
return time.Duration(defaultSec) * time.Second
}
sec, err := strconv.ParseInt(valStr, 10, 64)
if err != nil {
log.Printf("Invalid %s: %s, using default %d seconds", name, valStr, defaultSec)
return time.Duration(defaultSec) * time.Second
}
return time.Duration(sec) * time.Second
}
func init() {
CPUOverloadThreshold = getEnvInt64("CPU_OVERLOAD_THRESHOLD", 80)
MemoryOverloadThreshold = getEnvInt64("MEMORY_OVERLOAD_THRESHOLD", 80)
CPUUnderloadThreshold = getEnvInt64("CPU_UNDERLOAD_THRESHOLD", 50)
MemoryUnderloadThreshold = getEnvInt64("MEMORY_UNDERLOAD_THRESHOLD", 50)
PodEvictionInterval = getEnvSecondsDuration("POD_EVICTION_INTERVAL", 120) // default 2 min
PodAnimationDuration = getEnvSecondsDuration("POD_ANIMATION_DURATION", 2) // default 2 sec
}
type PodMoveEvent struct {
Time time.Time `json:"time"`
Namespace string `json:"namespace"`
Pod string `json:"pod"`
FromNode string `json:"fromNode"`
ToNode string `json:"toNode"`
Reason string `json:"reason"`
}
type EventBus struct {
mu sync.Mutex
history []PodMoveEvent
clients map[chan PodMoveEvent]struct{}
}
func NewEventBus() *EventBus {
return &EventBus{
history: make([]PodMoveEvent, 0, 100),
clients: make(map[chan PodMoveEvent]struct{}),
}
}
func (b *EventBus) Emit(evt PodMoveEvent) {
b.mu.Lock()
defer b.mu.Unlock()
if len(b.history) == 100 {
b.history = b.history[1:]
}
b.history = append(b.history, evt)
for ch := range b.clients {
select {
case ch <- evt:
default:
}
}
}
func (b *EventBus) History() []PodMoveEvent {
b.mu.Lock()
defer b.mu.Unlock()
out := make([]PodMoveEvent, len(b.history))
copy(out, b.history)
return out
}
func (b *EventBus) Subscribe() chan PodMoveEvent {
b.mu.Lock()
defer b.mu.Unlock()
ch := make(chan PodMoveEvent, 10)
b.clients[ch] = struct{}{}
return ch
}
func (b *EventBus) Unsubscribe(ch chan PodMoveEvent) {
b.mu.Lock()
defer b.mu.Unlock()
delete(b.clients, ch)
close(ch)
}
func main() {
config, err := rest.InClusterConfig()
if err != nil {
log.Fatal(err)
}
clientset, err := kubernetes.NewForConfig(config)
if err != nil {
log.Fatal(err)
}
metricsClient, err := metricsv.NewForConfig(config)
if err != nil {
log.Fatal(err)
}
eventBus := NewEventBus()
go startWebUI(eventBus, clientset)
for {
balanceNodes(clientset, metricsClient, eventBus)
time.Sleep(PodEvictionInterval)
}
}
func startWebUI(bus *EventBus, clientset *kubernetes.Clientset) {
mux := http.NewServeMux()
mux.Handle("/", http.FileServer(http.Dir("/web")))
mux.HandleFunc("/api/events", func(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(bus.History())
})
mux.HandleFunc("/api/stream", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/event-stream")
w.Header().Set("Cache-Control", "no-cache")
flusher, ok := w.(http.Flusher)
if !ok {
http.Error(w, "streaming unsupported", 500)
return
}
ch := bus.Subscribe()
defer bus.Unsubscribe(ch)
for {
select {
case evt := <-ch:
data, _ := json.Marshal(evt)
fmt.Fprintf(w, "data: %s\n\n", data)
flusher.Flush()
case <-r.Context().Done():
return
}
}
})
log.Println("WebUI listening on :8080")
mux.HandleFunc("/api/nodes", func(w http.ResponseWriter, r *http.Request) {
nodes, err := clientset.CoreV1().Nodes().List(context.Background(), metav1.ListOptions{})
if err != nil {
http.Error(w, "failed to list nodes", http.StatusInternalServerError)
return
}
names := []string{}
for _, n := range nodes.Items {
names = append(names, n.Name)
}
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(names)
})
mux.HandleFunc("/api/pods", func(w http.ResponseWriter, r *http.Request) {
ctx := context.Background()
pods, err := clientset.CoreV1().Pods("").List(ctx, metav1.ListOptions{})
if err != nil {
http.Error(w, "failed to list pods", http.StatusInternalServerError)
return
}
// group pods by node
podsByNode := map[string][]string{}
for _, pod := range pods.Items {
if pod.Spec.NodeName == "" {
continue
}
if _, ok := podsByNode[pod.Spec.NodeName]; !ok {
podsByNode[pod.Spec.NodeName] = []string{}
}
podsByNode[pod.Spec.NodeName] = append(podsByNode[pod.Spec.NodeName], pod.Name)
}
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(podsByNode)
})
mux.HandleFunc("/api/config", func(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "application/json")
cfg := map[string]interface{}{
"animationDurationMs": int64(2000), // number
"version": "1.1", // string
"clusterName": os.Getenv("CLUSTER_NAME"), // string
}
_ = json.NewEncoder(w).Encode(cfg)
})
_ = http.ListenAndServe(":8080", mux)
}
func balanceNodes(clientset *kubernetes.Clientset, metricsClient *metricsv.Clientset, bus *EventBus) {
ctx := context.Background()
// --- get node metrics ---
nodeMetricsList, err := metricsClient.MetricsV1beta1().NodeMetricses().List(ctx, metav1.ListOptions{})
if err != nil {
log.Println("Failed to get node metrics:", err)
return
}
nodeUsage := make(map[string]map[string]int64)
for _, m := range nodeMetricsList.Items {
nodeUsage[m.Name] = map[string]int64{
"cpu": m.Usage.Cpu().MilliValue(),
"mem": m.Usage.Memory().Value() / (1024 * 1024),
}
}
// --- get node capacities ---
nodes, err := clientset.CoreV1().Nodes().List(ctx, metav1.ListOptions{})
if err != nil {
log.Println("Failed to list nodes:", err)
return
}
nodeCapacity := make(map[string]map[string]int64)
for _, n := range nodes.Items {
nodeCapacity[n.Name] = map[string]int64{
"cpu": n.Status.Capacity.Cpu().MilliValue(),
"mem": n.Status.Capacity.Memory().Value() / (1024 * 1024),
}
}
// --- find overloaded and underloaded nodes ---
var overloaded, underloaded []string
for node, usage := range nodeUsage {
cpuPercent := usage["cpu"] * 100 / nodeCapacity[node]["cpu"]
memPercent := usage["mem"] * 100 / nodeCapacity[node]["mem"]
if cpuPercent > CPUOverloadThreshold || memPercent > MemoryOverloadThreshold {
overloaded = append(overloaded, node)
} else if cpuPercent < CPUUnderloadThreshold && memPercent < MemoryUnderloadThreshold {
underloaded = append(underloaded, node)
}
}
fmt.Println("Overloaded nodes:", overloaded)
fmt.Println("Underloaded nodes:", underloaded)
if len(overloaded) == 0 || len(underloaded) == 0 {
return
}
// --- move pods from overloaded to underloaded ---
for _, node := range overloaded {
pods, err := clientset.CoreV1().Pods("").List(ctx, metav1.ListOptions{
FieldSelector: fmt.Sprintf("spec.nodeName=%s", node),
})
if err != nil {
log.Println("Failed to list pods for node", node, err)
continue
}
for _, pod := range pods.Items {
if pod.Namespace == "kube-system" || isDaemonSet(&pod) {
continue
}
// Skip pods not in Running state
if pod.Status.Phase != corev1.PodRunning {
continue
}
// --- choose target before deletion ---
targetNode := pickTargetNode(underloaded, nodeUsage, nodeCapacity)
if targetNode == "" {
// fallback: just skip this pod
continue
}
// --- emit event for GUI ---
bus.Emit(PodMoveEvent{
Time: time.Now(),
Namespace: pod.Namespace,
Pod: pod.Name,
FromNode: node,
ToNode: targetNode,
Reason: "node-utilization-imbalance",
})
fmt.Printf("Rescheduling pod %s/%s from %s to %s\n", pod.Namespace, pod.Name, node, targetNode)
// --- cordon the node ---
if err := cordonNode(clientset, node); err != nil {
log.Println("Failed to cordon node", node, err)
continue
}
// --- delete pod immediately ---
grace := int64(0)
err = clientset.CoreV1().Pods(pod.Namespace).Delete(ctx, pod.Name, metav1.DeleteOptions{
GracePeriodSeconds: &grace,
})
if err != nil {
log.Println("Failed to delete pod", pod.Name, err)
_ = uncordonNode(clientset, node)
continue
}
// --- wait for new pod from deployment ---
var ownerUID types.UID
if len(pod.OwnerReferences) > 0 {
ownerUID = pod.OwnerReferences[0].UID
}
var newPod corev1.Pod
for {
podsList, err := clientset.CoreV1().Pods(pod.Namespace).List(ctx, metav1.ListOptions{})
if err != nil {
log.Println("Failed to list pods:", err)
time.Sleep(2 * time.Second)
continue
}
found := true
for _, p := range podsList.Items {
if p.Name == pod.Name {
continue
}
for _, ref := range p.OwnerReferences {
if ref.UID == ownerUID && p.Status.Phase == corev1.PodRunning {
newPod = p
found = true
break
}
}
if found {
break
}
}
if found {
break
}
fmt.Println("Waiting for replacement pod to be Running...")
time.Sleep(2 * time.Second)
}
// --- uncordon the node now that pod has moved ---
if err := uncordonNode(clientset, node); err != nil {
log.Println("Failed to uncordon node", node, err)
}
// --- update node usage safely ---
if nodeUsage[node] != nil {
nodeUsage[node]["cpu"] -= estimatePodCPU(&pod)
nodeUsage[node]["mem"] -= estimatePodMem(&pod)
}
if nodeUsage[newPod.Spec.NodeName] == nil {
nodeUsage[newPod.Spec.NodeName] = map[string]int64{"cpu": 0, "mem": 0}
}
nodeUsage[newPod.Spec.NodeName]["cpu"] += estimatePodCPU(&pod)
nodeUsage[newPod.Spec.NodeName]["mem"] += estimatePodMem(&pod)
// only move one pod per invocation
return
}
}
}
//
// ─── HELPERS ────────────────────────────────────────────────────────────────────
//
func mustEnv(key, def string) string {
if val := os.Getenv(key); val != "" {
return val
}
return def
}
func cordonNode(clientset *kubernetes.Clientset, nodeName string) error {
ctx := context.Background()
node, err := clientset.CoreV1().Nodes().Get(ctx, nodeName, metav1.GetOptions{})
if err != nil {
return err
}
if node.Spec.Unschedulable {
return nil
}
node.Spec.Unschedulable = true
_, err = clientset.CoreV1().Nodes().Update(ctx, node, metav1.UpdateOptions{})
return err
}
func uncordonNode(clientset *kubernetes.Clientset, nodeName string) error {
ctx := context.Background()
node, err := clientset.CoreV1().Nodes().Get(ctx, nodeName, metav1.GetOptions{})
if err != nil {
return err
}
node.Spec.Unschedulable = false
_, err = clientset.CoreV1().Nodes().Update(ctx, node, metav1.UpdateOptions{})
return err
}
func isDaemonSet(pod *corev1.Pod) bool {
for _, owner := range pod.OwnerReferences {
if owner.Kind == "DaemonSet" {
return true
}
}
return false
}
func pickTargetNode(nodes []string, usage map[string]map[string]int64, capacity map[string]map[string]int64) string {
var bestNode string
bestLoad := int64(1 << 62)
for _, n := range nodes {
cpuPercent := usage[n]["cpu"] * 100 / capacity[n]["cpu"]
memPercent := usage[n]["mem"] * 100 / capacity[n]["mem"]
load := cpuPercent + memPercent
if load < bestLoad {
bestLoad = load
bestNode = n
}
}
return bestNode
}
func estimatePodCPU(pod *corev1.Pod) int64 {
var cpu int64
for _, c := range pod.Spec.Containers {
if q, ok := c.Resources.Requests[corev1.ResourceCPU]; ok {
cpu += q.MilliValue()
}
}
return cpu
}
func estimatePodMem(pod *corev1.Pod) int64 {
var mem int64
for _, c := range pod.Spec.Containers {
if q, ok := c.Resources.Requests[corev1.ResourceMemory]; ok {
mem += q.Value() / (1024 * 1024)
}
}
return mem
}
+528
View File
@@ -0,0 +1,528 @@
package main
import (
"context"
"encoding/json"
"fmt"
"log"
"net/http"
"os"
"strconv"
"sync"
"time"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
"k8s.io/apimachinery/pkg/types"
metricsv "k8s.io/metrics/pkg/client/clientset/versioned"
)
var (
CPUOverloadThreshold int64
MemoryOverloadThreshold int64
CPUUnderloadThreshold int64
MemoryUnderloadThreshold int64
PodEvictionInterval time.Duration
PodAnimationDuration time.Duration
PodRespawnTimeout time.Duration
)
func getEnvInt64(name string, defaultVal int64) int64 {
valStr := os.Getenv(name)
if valStr == "" {
return defaultVal
}
val, err := strconv.ParseInt(valStr, 10, 64)
if err != nil {
log.Printf("Invalid %s: %s, using default %d", name, valStr, defaultVal)
return defaultVal
}
return val
}
func getEnvSecondsDuration(name string, defaultSec int64) time.Duration {
valStr := os.Getenv(name)
if valStr == "" {
return time.Duration(defaultSec) * time.Second
}
sec, err := strconv.ParseInt(valStr, 10, 64)
if err != nil {
log.Printf("Invalid %s: %s, using default %d seconds", name, valStr, defaultSec)
return time.Duration(defaultSec) * time.Second
}
return time.Duration(sec) * time.Second
}
func init() {
CPUOverloadThreshold = getEnvInt64("CPU_OVERLOAD_THRESHOLD", 80)
MemoryOverloadThreshold = getEnvInt64("MEMORY_OVERLOAD_THRESHOLD", 80)
CPUUnderloadThreshold = getEnvInt64("CPU_UNDERLOAD_THRESHOLD", 50)
MemoryUnderloadThreshold = getEnvInt64("MEMORY_UNDERLOAD_THRESHOLD", 50)
PodEvictionInterval = getEnvSecondsDuration("POD_EVICTION_INTERVAL", 30) // default 2 min
PodAnimationDuration = getEnvSecondsDuration("POD_ANIMATION_DURATION", 2) // default 2 sec
func init() {
CPUOverloadThreshold = getEnvInt64("CPU_OVERLOAD_THRESHOLD", 80)
MemoryOverloadThreshold = getEnvInt64("MEMORY_OVERLOAD_THRESHOLD", 80)
CPUUnderloadThreshold = getEnvInt64("CPU_UNDERLOAD_THRESHOLD", 50)
MemoryUnderloadThreshold = getEnvInt64("MEMORY_UNDERLOAD_THRESHOLD", 50)
PodEvictionInterval = getEnvSecondsDuration("POD_EVICTION_INTERVAL", 30)
PodAnimationDuration = getEnvSecondsDuration("POD_ANIMATION_DURATION", 2)
PodRespawnTimeout = getEnvSecondsDuration("POD_RESPAWN_TIMEOUT", 60)
}
type PodMoveEvent struct {
Time time.Time `json:"time"`
Namespace string `json:"namespace"`
Pod string `json:"pod"`
FromNode string `json:"fromNode"`
ToNode string `json:"toNode"`
Reason string `json:"reason"`
}
type EventBus struct {
mu sync.Mutex
history []PodMoveEvent
clients map[chan PodMoveEvent]struct{}
}
func NewEventBus() *EventBus {
return &EventBus{
history: make([]PodMoveEvent, 0, 100),
clients: make(map[chan PodMoveEvent]struct{}),
}
}
func (b *EventBus) Emit(evt PodMoveEvent) {
b.mu.Lock()
defer b.mu.Unlock()
if len(b.history) == 100 {
b.history = b.history[1:]
}
b.history = append(b.history, evt)
for ch := range b.clients {
select {
case ch <- evt:
default:
}
}
}
func (b *EventBus) History() []PodMoveEvent {
b.mu.Lock()
defer b.mu.Unlock()
out := make([]PodMoveEvent, len(b.history))
copy(out, b.history)
return out
}
func (b *EventBus) Subscribe() chan PodMoveEvent {
b.mu.Lock()
defer b.mu.Unlock()
ch := make(chan PodMoveEvent, 10)
b.clients[ch] = struct{}{}
return ch
}
func (b *EventBus) Unsubscribe(ch chan PodMoveEvent) {
b.mu.Lock()
defer b.mu.Unlock()
delete(b.clients, ch)
close(ch)
}
func main() {
config, err := rest.InClusterConfig()
if err != nil {
log.Fatal(err)
}
clientset, err := kubernetes.NewForConfig(config)
if err != nil {
log.Fatal(err)
}
metricsClient, err := metricsv.NewForConfig(config)
if err != nil {
log.Fatal(err)
}
eventBus := NewEventBus()
go startWebUI(eventBus, clientset)
for {
balanceNodes(clientset, metricsClient, eventBus)
time.Sleep(PodEvictionInterval)
}
}
func startWebUI(bus *EventBus, clientset *kubernetes.Clientset) {
mux := http.NewServeMux()
mux.Handle("/", http.FileServer(http.Dir("/web")))
mux.HandleFunc("/api/events", func(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(bus.History())
})
mux.HandleFunc("/api/stream", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/event-stream")
w.Header().Set("Cache-Control", "no-cache")
flusher, ok := w.(http.Flusher)
if !ok {
http.Error(w, "streaming unsupported", 500)
return
}
ch := bus.Subscribe()
defer bus.Unsubscribe(ch)
for {
select {
case evt := <-ch:
data, _ := json.Marshal(evt)
fmt.Fprintf(w, "data: %s\n\n", data)
flusher.Flush()
case <-r.Context().Done():
return
}
}
})
log.Println("WebUI listening on :8080")
mux.HandleFunc("/api/nodes", func(w http.ResponseWriter, r *http.Request) {
nodes, err := clientset.CoreV1().Nodes().List(context.Background(), metav1.ListOptions{})
if err != nil {
http.Error(w, "failed to list nodes", http.StatusInternalServerError)
return
}
names := []string{}
for _, n := range nodes.Items {
names = append(names, n.Name)
}
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(names)
})
mux.HandleFunc("/api/pods", func(w http.ResponseWriter, r *http.Request) {
ctx := context.Background()
pods, err := clientset.CoreV1().Pods("").List(ctx, metav1.ListOptions{})
if err != nil {
http.Error(w, "failed to list pods", http.StatusInternalServerError)
return
}
// group pods by node
podsByNode := map[string][]string{}
for _, pod := range pods.Items {
if pod.Spec.NodeName == "" {
continue
}
if _, ok := podsByNode[pod.Spec.NodeName]; !ok {
podsByNode[pod.Spec.NodeName] = []string{}
}
podsByNode[pod.Spec.NodeName] = append(podsByNode[pod.Spec.NodeName], pod.Name)
}
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(podsByNode)
})
mux.HandleFunc("/api/config", func(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "application/json")
cfg := map[string]interface{}{
"animationDurationMs": int64(2000), // number
"version": "1.1", // string
"clusterName": os.Getenv("CLUSTER_NAME"), // string
}
_ = json.NewEncoder(w).Encode(cfg)
})
_ = http.ListenAndServe(":8080", mux)
}
func balanceNodes(clientset *kubernetes.Clientset, metricsClient *metricsv.Clientset, bus *EventBus) {
ctx := context.Background()
// --- get node metrics ---
nodeMetricsList, err := metricsClient.MetricsV1beta1().NodeMetricses().List(ctx, metav1.ListOptions{})
if err != nil {
log.Println("Failed to get node metrics:", err)
return
}
nodeUsage := make(map[string]map[string]int64)
for _, m := range nodeMetricsList.Items {
nodeUsage[m.Name] = map[string]int64{
"cpu": m.Usage.Cpu().MilliValue(),
"mem": m.Usage.Memory().Value() / (1024 * 1024),
}
}
// --- get node capacities ---
nodes, err := clientset.CoreV1().Nodes().List(ctx, metav1.ListOptions{})
if err != nil {
log.Println("Failed to list nodes:", err)
return
}
nodeCapacity := make(map[string]map[string]int64)
for _, n := range nodes.Items {
nodeCapacity[n.Name] = map[string]int64{
"cpu": n.Status.Capacity.Cpu().MilliValue(),
"mem": n.Status.Capacity.Memory().Value() / (1024 * 1024),
}
}
// --- find overloaded and underloaded nodes ---
var overloaded, underloaded []string
for node, usage := range nodeUsage {
cpuPercent := usage["cpu"] * 100 / nodeCapacity[node]["cpu"]
memPercent := usage["mem"] * 100 / nodeCapacity[node]["mem"]
// if cpuPercent > CPUOverloadThreshold || memPercent > MemoryOverloadThreshold {
if cpuPercent > CPUOverloadThreshold {
overloaded = append(overloaded, node)
// } else if cpuPercent < CPUUnderloadThreshold && memPercent < MemoryUnderloadThreshold {
} else if cpuPercent < CPUUnderloadThreshold {
underloaded = append(underloaded, node)
}
}
fmt.Println("Overloaded nodes:", overloaded)
fmt.Println("Underloaded nodes:", underloaded)
if len(overloaded) == 0 || len(underloaded) == 0 {
return
}
// --- move pods from overloaded to underloaded ---
for _, node := range overloaded {
pods, err := clientset.CoreV1().Pods("").List(ctx, metav1.ListOptions{
FieldSelector: fmt.Sprintf("spec.nodeName=%s", node),
})
if err != nil {
log.Println("Failed to list pods for node", node, err)
continue
}
for _, pod := range pods.Items {
if pod.Namespace == "kube-system" || isDaemonSet(&pod) {
continue
}
// Skip pods not in Running state
if pod.Status.Phase != corev1.PodRunning {
continue
}
// --- choose target before deletion ---
targetNode := pickTargetNode(underloaded, nodeUsage, nodeCapacity)
if targetNode == "" {
// fallback: just skip this pod
continue
}
fmt.Printf("Rescheduling pod %s/%s from %s to another node\n", pod.Namespace, pod.Name, node)
// --- cordon the node ---
if err := cordonNode(clientset, node); err != nil {
log.Println("Failed to cordon node", node, err)
continue
}
fmt.Println("Succesfully cordoned node", node)
// --- delete pod immediately ---
grace := int64(0)
err = clientset.CoreV1().Pods(pod.Namespace).Delete(ctx, pod.Name, metav1.DeleteOptions{
GracePeriodSeconds: &grace,
})
if err != nil {
log.Println("Failed to delete pod", pod.Name, err)
_ = uncordonNode(clientset, node)
continue
}
fmt.Println("Deleted pod", pod.Name)
// --- wait for new pod from controller ---
var ownerUID types.UID
if len(pod.OwnerReferences) > 0 {
ownerUID = pod.OwnerReferences[0].UID
}
var newPod corev1.Pod
for {
podsList, err := clientset.CoreV1().
Pods(pod.Namespace).
List(ctx, metav1.ListOptions{})
if err != nil {
log.Println("Failed to list pods:", err)
time.Sleep(2 * time.Second)
continue
}
found := false
for _, p := range podsList.Items {
if p.Status.Phase != corev1.PodRunning {
continue
}
for _, ref := range p.OwnerReferences {
if ref.UID == ownerUID {
newPod = p
found = true
break
}
}
if found {
break
}
}
if found {
log.Println("Replacement pod found")
break
}
log.Println("Waiting for replacement pod to be Running...")
time.Sleep(2 * time.Second)
}
// --- uncordon the node now that pod has moved ---
if err := uncordonNode(clientset, node); err != nil {
log.Println("Failed to uncordon node", node, err)
}
fmt.Println("Succesfuly uncordoned node", node)
// --- emit event for GUI ---
bus.Emit(PodMoveEvent{
Time: time.Now(),
Namespace: pod.Namespace,
Pod: pod.Name,
FromNode: node,
ToNode: targetNode,
Reason: "node-utilization-imbalance",
})
// --- update node usage safely ---
if nodeUsage[node] != nil {
nodeUsage[node]["cpu"] -= estimatePodCPU(&pod)
nodeUsage[node]["mem"] -= estimatePodMem(&pod)
}
if nodeUsage[newPod.Spec.NodeName] == nil {
nodeUsage[newPod.Spec.NodeName] = map[string]int64{"cpu": 0, "mem": 0}
}
nodeUsage[newPod.Spec.NodeName]["cpu"] += estimatePodCPU(&pod)
nodeUsage[newPod.Spec.NodeName]["mem"] += estimatePodMem(&pod)
// only move one pod per invocation
return
}
}
}
//
// ─── HELPERS ────────────────────────────────────────────────────────────────────
//
func mustEnv(key, def string) string {
if val := os.Getenv(key); val != "" {
return val
}
return def
}
func cordonNode(clientset *kubernetes.Clientset, nodeName string) error {
ctx := context.Background()
for i := 0; i < 5; i++ { // retry up to 5 times
node, err := clientset.CoreV1().Nodes().Get(ctx, nodeName, metav1.GetOptions{})
if err != nil {
return err
}
if node.Spec.Unschedulable {
return nil // already cordoned
}
node.Spec.Unschedulable = true
_, err = clientset.CoreV1().Nodes().Update(ctx, node, metav1.UpdateOptions{})
if err == nil {
return nil
}
log.Println("Cordoning failed, retrying:", err)
time.Sleep(500 * time.Millisecond)
}
return fmt.Errorf("failed to cordon node %s after retries", nodeName)
}
func uncordonNode(clientset *kubernetes.Clientset, nodeName string) error {
ctx := context.Background()
for i := 0; i < 5; i++ {
node, err := clientset.CoreV1().Nodes().Get(ctx, nodeName, metav1.GetOptions{})
if err != nil {
return err
}
if !node.Spec.Unschedulable {
return nil // already uncordoned
}
node.Spec.Unschedulable = false
_, err = clientset.CoreV1().Nodes().Update(ctx, node, metav1.UpdateOptions{})
if err == nil {
return nil
}
log.Println("Uncordoning failed, retrying:", err)
time.Sleep(500 * time.Millisecond)
}
return fmt.Errorf("failed to uncordon node %s after retries", nodeName)
}
func isDaemonSet(pod *corev1.Pod) bool {
for _, owner := range pod.OwnerReferences {
if owner.Kind == "DaemonSet" {
return true
}
}
return false
}
func pickTargetNode(nodes []string, usage map[string]map[string]int64, capacity map[string]map[string]int64) string {
var bestNode string
bestLoad := int64(1 << 62)
for _, n := range nodes {
cpuPercent := usage[n]["cpu"] * 100 / capacity[n]["cpu"]
memPercent := usage[n]["mem"] * 100 / capacity[n]["mem"]
load := cpuPercent + memPercent
if load < bestLoad {
bestLoad = load
bestNode = n
}
}
return bestNode
}
func estimatePodCPU(pod *corev1.Pod) int64 {
var cpu int64
for _, c := range pod.Spec.Containers {
if q, ok := c.Resources.Requests[corev1.ResourceCPU]; ok {
cpu += q.MilliValue()
}
}
return cpu
}
func estimatePodMem(pod *corev1.Pod) int64 {
var mem int64
for _, c := range pod.Spec.Containers {
if q, ok := c.Resources.Requests[corev1.ResourceMemory]; ok {
mem += q.Value() / (1024 * 1024)
}
}
return mem
}
+531
View File
@@ -0,0 +1,531 @@
package main
import (
"context"
"encoding/json"
"fmt"
"log"
"net/http"
"os"
"strconv"
"sync"
"time"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
"k8s.io/apimachinery/pkg/types"
metricsv "k8s.io/metrics/pkg/client/clientset/versioned"
)
var (
CPUOverloadThreshold int64
MemoryOverloadThreshold int64
CPUUnderloadThreshold int64
MemoryUnderloadThreshold int64
PodEvictionInterval time.Duration
PodAnimationDuration time.Duration
PodRespawnTimeout time.Duration
)
func getEnvInt64(name string, defaultVal int64) int64 {
valStr := os.Getenv(name)
if valStr == "" {
return defaultVal
}
val, err := strconv.ParseInt(valStr, 10, 64)
if err != nil {
log.Printf("Invalid %s: %s, using default %d", name, valStr, defaultVal)
return defaultVal
}
return val
}
func getEnvSecondsDuration(name string, defaultSec int64) time.Duration {
valStr := os.Getenv(name)
if valStr == "" {
return time.Duration(defaultSec) * time.Second
}
sec, err := strconv.ParseInt(valStr, 10, 64)
if err != nil {
log.Printf("Invalid %s: %s, using default %d seconds", name, valStr, defaultSec)
return time.Duration(defaultSec) * time.Second
}
return time.Duration(sec) * time.Second
}
func init() {
CPUOverloadThreshold = getEnvInt64("CPU_OVERLOAD_THRESHOLD", 80)
MemoryOverloadThreshold = getEnvInt64("MEMORY_OVERLOAD_THRESHOLD", 80)
CPUUnderloadThreshold = getEnvInt64("CPU_UNDERLOAD_THRESHOLD", 50)
MemoryUnderloadThreshold = getEnvInt64("MEMORY_UNDERLOAD_THRESHOLD", 50)
PodEvictionInterval = getEnvSecondsDuration("POD_EVICTION_INTERVAL", 30)
PodAnimationDuration = getEnvSecondsDuration("POD_ANIMATION_DURATION", 2)
PodRespawnTimeout = getEnvSecondsDuration("POD_RESPAWN_TIMEOUT", 60)
log.Println("──────────── CONFIG ────────────")
log.Printf("CPU_OVERLOAD_THRESHOLD = %d%%", CPUOverloadThreshold)
log.Printf("MEMORY_OVERLOAD_THRESHOLD = %d%%", MemoryOverloadThreshold)
log.Printf("CPU_UNDERLOAD_THRESHOLD = %d%%", CPUUnderloadThreshold)
log.Printf("MEMORY_UNDERLOAD_THRESHOLD = %d%%", MemoryUnderloadThreshold)
log.Printf("POD_EVICTION_INTERVAL = %v", PodEvictionInterval)
log.Printf("POD_ANIMATION_DURATION = %v", PodAnimationDuration)
log.Printf("POD_RESPAWN_TIMEOUT = %v", PodRespawnTimeout)
log.Println("───────────────────────────────")
}
type PodMoveEvent struct {
Time time.Time `json:"time"`
Namespace string `json:"namespace"`
Pod string `json:"pod"`
FromNode string `json:"fromNode"`
ToNode string `json:"toNode"`
Reason string `json:"reason"`
}
type EventBus struct {
mu sync.Mutex
history []PodMoveEvent
clients map[chan PodMoveEvent]struct{}
}
func NewEventBus() *EventBus {
return &EventBus{
history: make([]PodMoveEvent, 0, 100),
clients: make(map[chan PodMoveEvent]struct{}),
}
}
func (b *EventBus) Emit(evt PodMoveEvent) {
b.mu.Lock()
defer b.mu.Unlock()
if len(b.history) == 100 {
b.history = b.history[1:]
}
b.history = append(b.history, evt)
for ch := range b.clients {
select {
case ch <- evt:
default:
}
}
}
func (b *EventBus) History() []PodMoveEvent {
b.mu.Lock()
defer b.mu.Unlock()
out := make([]PodMoveEvent, len(b.history))
copy(out, b.history)
return out
}
func (b *EventBus) Subscribe() chan PodMoveEvent {
b.mu.Lock()
defer b.mu.Unlock()
ch := make(chan PodMoveEvent, 10)
b.clients[ch] = struct{}{}
return ch
}
func (b *EventBus) Unsubscribe(ch chan PodMoveEvent) {
b.mu.Lock()
defer b.mu.Unlock()
delete(b.clients, ch)
close(ch)
}
func main() {
config, err := rest.InClusterConfig()
if err != nil {
log.Fatal(err)
}
clientset, err := kubernetes.NewForConfig(config)
if err != nil {
log.Fatal(err)
}
metricsClient, err := metricsv.NewForConfig(config)
if err != nil {
log.Fatal(err)
}
eventBus := NewEventBus()
go startWebUI(eventBus, clientset)
for {
balanceNodes(clientset, metricsClient, eventBus)
time.Sleep(PodEvictionInterval)
}
}
func startWebUI(bus *EventBus, clientset *kubernetes.Clientset) {
mux := http.NewServeMux()
mux.Handle("/", http.FileServer(http.Dir("/web")))
mux.HandleFunc("/api/events", func(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(bus.History())
})
mux.HandleFunc("/api/stream", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/event-stream")
w.Header().Set("Cache-Control", "no-cache")
flusher, ok := w.(http.Flusher)
if !ok {
http.Error(w, "streaming unsupported", 500)
return
}
ch := bus.Subscribe()
defer bus.Unsubscribe(ch)
for {
select {
case evt := <-ch:
data, _ := json.Marshal(evt)
fmt.Fprintf(w, "data: %s\n\n", data)
flusher.Flush()
case <-r.Context().Done():
return
}
}
})
log.Println("WebUI listening on :8080")
mux.HandleFunc("/api/nodes", func(w http.ResponseWriter, r *http.Request) {
nodes, err := clientset.CoreV1().Nodes().List(context.Background(), metav1.ListOptions{})
if err != nil {
http.Error(w, "failed to list nodes", http.StatusInternalServerError)
return
}
names := []string{}
for _, n := range nodes.Items {
names = append(names, n.Name)
}
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(names)
})
mux.HandleFunc("/api/pods", func(w http.ResponseWriter, r *http.Request) {
ctx := context.Background()
pods, err := clientset.CoreV1().Pods("").List(ctx, metav1.ListOptions{})
if err != nil {
http.Error(w, "failed to list pods", http.StatusInternalServerError)
return
}
// group pods by node
podsByNode := map[string][]string{}
for _, pod := range pods.Items {
if pod.Spec.NodeName == "" {
continue
}
if _, ok := podsByNode[pod.Spec.NodeName]; !ok {
podsByNode[pod.Spec.NodeName] = []string{}
}
podsByNode[pod.Spec.NodeName] = append(podsByNode[pod.Spec.NodeName], pod.Name)
}
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(podsByNode)
})
mux.HandleFunc("/api/config", func(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "application/json")
cfg := map[string]interface{}{
"animationDurationMs": int64(2000), // number
"version": "1.1", // string
"clusterName": os.Getenv("CLUSTER_NAME"), // string
}
_ = json.NewEncoder(w).Encode(cfg)
})
_ = http.ListenAndServe(":8080", mux)
}
func balanceNodes(clientset *kubernetes.Clientset, metricsClient *metricsv.Clientset, bus *EventBus) {
ctx := context.Background()
// --- get node metrics ---
nodeMetricsList, err := metricsClient.MetricsV1beta1().NodeMetricses().List(ctx, metav1.ListOptions{})
if err != nil {
log.Println("Failed to get node metrics:", err)
return
}
nodeUsage := make(map[string]map[string]int64)
for _, m := range nodeMetricsList.Items {
nodeUsage[m.Name] = map[string]int64{
"cpu": m.Usage.Cpu().MilliValue(),
"mem": m.Usage.Memory().Value() / (1024 * 1024),
}
}
// --- get node capacities ---
nodes, err := clientset.CoreV1().Nodes().List(ctx, metav1.ListOptions{})
if err != nil {
log.Println("Failed to list nodes:", err)
return
}
nodeCapacity := make(map[string]map[string]int64)
for _, n := range nodes.Items {
nodeCapacity[n.Name] = map[string]int64{
"cpu": n.Status.Capacity.Cpu().MilliValue(),
"mem": n.Status.Capacity.Memory().Value() / (1024 * 1024),
}
}
// --- find overloaded and underloaded nodes ---
var overloaded, underloaded []string
for node, usage := range nodeUsage {
cpuPercent := usage["cpu"] * 100 / nodeCapacity[node]["cpu"]
// memPercent := usage["mem"] * 100 / nodeCapacity[node]["mem"]
// if cpuPercent > CPUOverloadThreshold || memPercent > MemoryOverloadThreshold {
if cpuPercent > CPUOverloadThreshold {
overloaded = append(overloaded, node)
// } else if cpuPercent < CPUUnderloadThreshold && memPercent < MemoryUnderloadThreshold {
} else if cpuPercent < CPUUnderloadThreshold {
underloaded = append(underloaded, node)
}
}
fmt.Println("Overloaded nodes:", overloaded)
fmt.Println("Underloaded nodes:", underloaded)
if len(overloaded) == 0 || len(underloaded) == 0 {
return
}
// --- move pods from overloaded to underloaded ---
for _, node := range overloaded {
pods, err := clientset.CoreV1().Pods("").List(ctx, metav1.ListOptions{
FieldSelector: fmt.Sprintf("spec.nodeName=%s", node),
})
if err != nil {
log.Println("Failed to list pods for node", node, err)
continue
}
for _, pod := range pods.Items {
if pod.Namespace == "kube-system" || isDaemonSet(&pod) {
continue
}
// Skip pods not in Running state
if pod.Status.Phase != corev1.PodRunning {
continue
}
// --- choose target before deletion ---
targetNode := pickTargetNode(underloaded, nodeUsage, nodeCapacity)
if targetNode == "" {
// fallback: just skip this pod
continue
}
fmt.Printf("Rescheduling pod %s/%s from %s to another node\n", pod.Namespace, pod.Name, node)
// --- cordon the node ---
if err := cordonNode(clientset, node); err != nil {
log.Println("Failed to cordon node", node, err)
continue
}
fmt.Println("Succesfully cordoned node", node)
// --- delete pod immediately ---
grace := int64(0)
err = clientset.CoreV1().Pods(pod.Namespace).Delete(ctx, pod.Name, metav1.DeleteOptions{
GracePeriodSeconds: &grace,
})
if err != nil {
log.Println("Failed to delete pod", pod.Name, err)
_ = uncordonNode(clientset, node)
continue
}
fmt.Println("Deleted pod", pod.Name)
// --- wait for new pod from controller ---
var ownerUID types.UID
if len(pod.OwnerReferences) > 0 {
ownerUID = pod.OwnerReferences[0].UID
}
var newPod corev1.Pod
for {
podsList, err := clientset.CoreV1().
Pods(pod.Namespace).
List(ctx, metav1.ListOptions{})
if err != nil {
log.Println("Failed to list pods:", err)
time.Sleep(2 * time.Second)
continue
}
found := false
for _, p := range podsList.Items {
if p.Status.Phase != corev1.PodRunning {
continue
}
for _, ref := range p.OwnerReferences {
if ref.UID == ownerUID {
newPod = p
found = true
break
}
}
if found {
break
}
}
if found {
log.Println("Replacement pod found")
break
}
log.Println("Waiting for replacement pod to be Running...")
time.Sleep(2 * time.Second)
}
// --- uncordon the node now that pod has moved ---
if err := uncordonNode(clientset, node); err != nil {
log.Println("Failed to uncordon node", node, err)
}
fmt.Println("Succesfuly uncordoned node", node)
// --- emit event for GUI ---
bus.Emit(PodMoveEvent{
Time: time.Now(),
Namespace: pod.Namespace,
Pod: pod.Name,
FromNode: node,
ToNode: targetNode,
Reason: "node-utilization-imbalance",
})
// --- update node usage safely ---
if nodeUsage[node] != nil {
nodeUsage[node]["cpu"] -= estimatePodCPU(&pod)
nodeUsage[node]["mem"] -= estimatePodMem(&pod)
}
if nodeUsage[newPod.Spec.NodeName] == nil {
nodeUsage[newPod.Spec.NodeName] = map[string]int64{"cpu": 0, "mem": 0}
}
nodeUsage[newPod.Spec.NodeName]["cpu"] += estimatePodCPU(&pod)
nodeUsage[newPod.Spec.NodeName]["mem"] += estimatePodMem(&pod)
// only move one pod per invocation
return
}
}
}
//
// ─── HELPERS ────────────────────────────────────────────────────────────────────
//
func mustEnv(key, def string) string {
if val := os.Getenv(key); val != "" {
return val
}
return def
}
func cordonNode(clientset *kubernetes.Clientset, nodeName string) error {
ctx := context.Background()
for i := 0; i < 5; i++ { // retry up to 5 times
node, err := clientset.CoreV1().Nodes().Get(ctx, nodeName, metav1.GetOptions{})
if err != nil {
return err
}
if node.Spec.Unschedulable {
return nil // already cordoned
}
node.Spec.Unschedulable = true
_, err = clientset.CoreV1().Nodes().Update(ctx, node, metav1.UpdateOptions{})
if err == nil {
return nil
}
log.Println("Cordoning failed, retrying:", err)
time.Sleep(500 * time.Millisecond)
}
return fmt.Errorf("failed to cordon node %s after retries", nodeName)
}
func uncordonNode(clientset *kubernetes.Clientset, nodeName string) error {
ctx := context.Background()
for i := 0; i < 5; i++ {
node, err := clientset.CoreV1().Nodes().Get(ctx, nodeName, metav1.GetOptions{})
if err != nil {
return err
}
if !node.Spec.Unschedulable {
return nil // already uncordoned
}
node.Spec.Unschedulable = false
_, err = clientset.CoreV1().Nodes().Update(ctx, node, metav1.UpdateOptions{})
if err == nil {
return nil
}
log.Println("Uncordoning failed, retrying:", err)
time.Sleep(500 * time.Millisecond)
}
return fmt.Errorf("failed to uncordon node %s after retries", nodeName)
}
func isDaemonSet(pod *corev1.Pod) bool {
for _, owner := range pod.OwnerReferences {
if owner.Kind == "DaemonSet" {
return true
}
}
return false
}
func pickTargetNode(nodes []string, usage map[string]map[string]int64, capacity map[string]map[string]int64) string {
var bestNode string
bestLoad := int64(1 << 62)
for _, n := range nodes {
cpuPercent := usage[n]["cpu"] * 100 / capacity[n]["cpu"]
memPercent := usage[n]["mem"] * 100 / capacity[n]["mem"]
load := cpuPercent + memPercent
if load < bestLoad {
bestLoad = load
bestNode = n
}
}
return bestNode
}
func estimatePodCPU(pod *corev1.Pod) int64 {
var cpu int64
for _, c := range pod.Spec.Containers {
if q, ok := c.Resources.Requests[corev1.ResourceCPU]; ok {
cpu += q.MilliValue()
}
}
return cpu
}
func estimatePodMem(pod *corev1.Pod) int64 {
var mem int64
for _, c := range pod.Spec.Containers {
if q, ok := c.Resources.Requests[corev1.ResourceMemory]; ok {
mem += q.Value() / (1024 * 1024)
}
}
return mem
}
+559
View File
@@ -0,0 +1,559 @@
package main
import (
"context"
"encoding/json"
"fmt"
"log"
"net/http"
"os"
"strconv"
"sync"
"time"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
"k8s.io/apimachinery/pkg/types"
metricsv "k8s.io/metrics/pkg/client/clientset/versioned"
)
var (
CPUOverloadThreshold int64
MemoryOverloadThreshold int64
CPUUnderloadThreshold int64
MemoryUnderloadThreshold int64
PodEvictionInterval time.Duration
PodAnimationDuration time.Duration
PodRespawnTimeout time.Duration
)
func getEnvInt64(name string, defaultVal int64) int64 {
valStr := os.Getenv(name)
if valStr == "" {
return defaultVal
}
val, err := strconv.ParseInt(valStr, 10, 64)
if err != nil {
log.Printf("Invalid %s: %s, using default %d", name, valStr, defaultVal)
return defaultVal
}
return val
}
func getEnvSecondsDuration(name string, defaultSec int64) time.Duration {
valStr := os.Getenv(name)
if valStr == "" {
return time.Duration(defaultSec) * time.Second
}
sec, err := strconv.ParseInt(valStr, 10, 64)
if err != nil {
log.Printf("Invalid %s: %s, using default %d seconds", name, valStr, defaultSec)
return time.Duration(defaultSec) * time.Second
}
return time.Duration(sec) * time.Second
}
func init() {
CPUOverloadThreshold = getEnvInt64("CPU_OVERLOAD_THRESHOLD", 80)
MemoryOverloadThreshold = getEnvInt64("MEMORY_OVERLOAD_THRESHOLD", 80)
CPUUnderloadThreshold = getEnvInt64("CPU_UNDERLOAD_THRESHOLD", 50)
MemoryUnderloadThreshold = getEnvInt64("MEMORY_UNDERLOAD_THRESHOLD", 50)
PodEvictionInterval = getEnvSecondsDuration("POD_EVICTION_INTERVAL", 30)
PodAnimationDuration = getEnvSecondsDuration("POD_ANIMATION_DURATION", 2)
PodRespawnTimeout = getEnvSecondsDuration("POD_RESPAWN_TIMEOUT", 60)
log.Println("──────────── CONFIG ────────────")
log.Printf("CPU_OVERLOAD_THRESHOLD = %d%%", CPUOverloadThreshold)
log.Printf("MEMORY_OVERLOAD_THRESHOLD = %d%%", MemoryOverloadThreshold)
log.Printf("CPU_UNDERLOAD_THRESHOLD = %d%%", CPUUnderloadThreshold)
log.Printf("MEMORY_UNDERLOAD_THRESHOLD = %d%%", MemoryUnderloadThreshold)
log.Printf("POD_EVICTION_INTERVAL = %v", PodEvictionInterval)
log.Printf("POD_ANIMATION_DURATION = %v", PodAnimationDuration)
log.Printf("POD_RESPAWN_TIMEOUT = %v", PodRespawnTimeout)
log.Println("───────────────────────────────")
}
type PodMoveEvent struct {
Time time.Time `json:"time"`
Namespace string `json:"namespace"`
Pod string `json:"pod"`
FromNode string `json:"fromNode"`
ToNode string `json:"toNode"`
Reason string `json:"reason"`
}
type EventBus struct {
mu sync.Mutex
history []PodMoveEvent
clients map[chan PodMoveEvent]struct{}
}
func NewEventBus() *EventBus {
return &EventBus{
history: make([]PodMoveEvent, 0, 100),
clients: make(map[chan PodMoveEvent]struct{}),
}
}
func (b *EventBus) Emit(evt PodMoveEvent) {
b.mu.Lock()
defer b.mu.Unlock()
if len(b.history) == 100 {
b.history = b.history[1:]
}
b.history = append(b.history, evt)
for ch := range b.clients {
select {
case ch <- evt:
default:
}
}
}
func (b *EventBus) History() []PodMoveEvent {
b.mu.Lock()
defer b.mu.Unlock()
out := make([]PodMoveEvent, len(b.history))
copy(out, b.history)
return out
}
func (b *EventBus) Subscribe() chan PodMoveEvent {
b.mu.Lock()
defer b.mu.Unlock()
ch := make(chan PodMoveEvent, 10)
b.clients[ch] = struct{}{}
return ch
}
func (b *EventBus) Unsubscribe(ch chan PodMoveEvent) {
b.mu.Lock()
defer b.mu.Unlock()
delete(b.clients, ch)
close(ch)
}
func main() {
config, err := rest.InClusterConfig()
if err != nil {
log.Fatal(err)
}
clientset, err := kubernetes.NewForConfig(config)
if err != nil {
log.Fatal(err)
}
metricsClient, err := metricsv.NewForConfig(config)
if err != nil {
log.Fatal(err)
}
eventBus := NewEventBus()
go startWebUI(eventBus, clientset)
for {
balanceNodes(clientset, metricsClient, eventBus)
time.Sleep(PodEvictionInterval)
}
}
func startWebUI(bus *EventBus, clientset *kubernetes.Clientset) {
mux := http.NewServeMux()
mux.Handle("/", http.FileServer(http.Dir("/web")))
mux.HandleFunc("/api/events", func(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(bus.History())
})
mux.HandleFunc("/api/stream", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/event-stream")
w.Header().Set("Cache-Control", "no-cache")
flusher, ok := w.(http.Flusher)
if !ok {
http.Error(w, "streaming unsupported", 500)
return
}
ch := bus.Subscribe()
defer bus.Unsubscribe(ch)
for {
select {
case evt := <-ch:
data, _ := json.Marshal(evt)
fmt.Fprintf(w, "data: %s\n\n", data)
flusher.Flush()
case <-r.Context().Done():
return
}
}
})
log.Println("WebUI listening on :8080")
mux.HandleFunc("/api/nodes", func(w http.ResponseWriter, r *http.Request) {
nodes, err := clientset.CoreV1().Nodes().List(context.Background(), metav1.ListOptions{})
if err != nil {
http.Error(w, "failed to list nodes", http.StatusInternalServerError)
return
}
names := []string{}
for _, n := range nodes.Items {
names = append(names, n.Name)
}
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(names)
})
mux.HandleFunc("/api/pods", func(w http.ResponseWriter, r *http.Request) {
ctx := context.Background()
pods, err := clientset.CoreV1().Pods("").List(ctx, metav1.ListOptions{})
if err != nil {
http.Error(w, "failed to list pods", http.StatusInternalServerError)
return
}
// group pods by node
podsByNode := map[string][]string{}
for _, pod := range pods.Items {
if pod.Spec.NodeName == "" {
continue
}
if _, ok := podsByNode[pod.Spec.NodeName]; !ok {
podsByNode[pod.Spec.NodeName] = []string{}
}
podsByNode[pod.Spec.NodeName] = append(podsByNode[pod.Spec.NodeName], pod.Name)
}
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(podsByNode)
})
mux.HandleFunc("/api/config", func(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "application/json")
cfg := map[string]interface{}{
"animationDurationMs": int64(2000), // number
"version": "1.1", // string
"clusterName": os.Getenv("CLUSTER_NAME"), // string
}
_ = json.NewEncoder(w).Encode(cfg)
})
_ = http.ListenAndServe(":8080", mux)
}
func balanceNodes(clientset *kubernetes.Clientset, metricsClient *metricsv.Clientset, bus *EventBus) {
ctx := context.Background()
// --- get node metrics ---
nodeMetricsList, err := metricsClient.MetricsV1beta1().NodeMetricses().List(ctx, metav1.ListOptions{})
if err != nil {
log.Println("Failed to get node metrics:", err)
return
}
nodeUsage := make(map[string]map[string]int64)
for _, m := range nodeMetricsList.Items {
nodeUsage[m.Name] = map[string]int64{
"cpu": m.Usage.Cpu().MilliValue(),
"mem": m.Usage.Memory().Value() / (1024 * 1024),
}
}
// --- get node capacities ---
nodes, err := clientset.CoreV1().Nodes().List(ctx, metav1.ListOptions{})
if err != nil {
log.Println("Failed to list nodes:", err)
return
}
nodeCapacity := make(map[string]map[string]int64)
for _, n := range nodes.Items {
nodeCapacity[n.Name] = map[string]int64{
"cpu": n.Status.Capacity.Cpu().MilliValue(),
"mem": n.Status.Capacity.Memory().Value() / (1024 * 1024),
}
}
// --- find overloaded and underloaded nodes ---
var overloaded, underloaded []string
for node, usage := range nodeUsage {
cpuPercent := usage["cpu"] * 100 / nodeCapacity[node]["cpu"]
if cpuPercent > CPUOverloadThreshold {
overloaded = append(overloaded, node)
} else if cpuPercent < CPUUnderloadThreshold {
underloaded = append(underloaded, node)
}
}
log.Println("Overloaded nodes:", overloaded)
log.Println("Underloaded nodes:", underloaded)
if len(overloaded) == 0 || len(underloaded) == 0 {
return
}
// --- move pods from overloaded to underloaded ---
for _, node := range overloaded {
pods, err := clientset.CoreV1().Pods("").List(ctx, metav1.ListOptions{
FieldSelector: fmt.Sprintf("spec.nodeName=%s", node),
})
if err != nil {
log.Println("Failed to list pods for node", node, err)
continue
}
for _, pod := range pods.Items {
if pod.Namespace == "kube-system" || isDaemonSet(&pod) {
continue
}
// Skip pods not in Running state
if pod.Status.Phase != corev1.PodRunning {
continue
}
// Skip pods using hostpath storage
if usesHostPath(&pod) {
log.Printf("Skipping pod %s/%s (uses hostPath)", pod.Namespace, pod.Name)
continue
}
// --- choose target before deletion ---
targetNode := pickTargetNode(underloaded, nodeUsage, nodeCapacity)
if targetNode == "" {
continue
}
log.Printf("Rescheduling pod %s/%s from %s to another node\n",
pod.Namespace, pod.Name, node)
// --- cordon the node ---
if err := cordonNode(clientset, node); err != nil {
log.Println("Failed to cordon node", node, err)
continue
}
log.Println("Succesfully cordoned node", node)
// --- delete pod immediately ---
grace := int64(0)
err = clientset.CoreV1().Pods(pod.Namespace).Delete(ctx, pod.Name, metav1.DeleteOptions{
GracePeriodSeconds: &grace,
})
if err != nil {
log.Println("Failed to delete pod", pod.Name, err)
_ = uncordonNode(clientset, node)
continue
}
log.Println("Deleted pod", pod.Name)
// --- wait for replacement pod (with timeout) ---
var ownerUID types.UID
if len(pod.OwnerReferences) > 0 {
ownerUID = pod.OwnerReferences[0].UID
}
var newPod corev1.Pod
timeoutCtx, cancel := context.WithTimeout(ctx, PodRespawnTimeout)
defer cancel()
ticker := time.NewTicker(2 * time.Second)
defer ticker.Stop()
found := false
WAIT_LOOP:
for {
select {
case <-timeoutCtx.Done():
log.Println("Pod respawn timeout reached")
break WAIT_LOOP
case <-ticker.C:
podsList, err := clientset.CoreV1().
Pods(pod.Namespace).
List(ctx, metav1.ListOptions{})
if err != nil {
log.Println("Failed to list pods:", err)
continue
}
for _, p := range podsList.Items {
if p.Status.Phase != corev1.PodRunning {
continue
}
for _, ref := range p.OwnerReferences {
if ref.UID == ownerUID {
newPod = p
found = true
break
}
}
if found {
break
}
}
if found {
log.Println("Replacement pod found")
break WAIT_LOOP
}
log.Println("Waiting for replacement pod to be Running...")
}
}
// --- uncordon the node now that pod has moved ---
if err := uncordonNode(clientset, node); err != nil {
log.Println("Failed to uncordon node", node, err)
}
log.Println("Succesfuly uncordoned node", node)
// --- emit event for GUI ---
log.Println("About to emit PodMoveEvent")
bus.Emit(PodMoveEvent{
Time: time.Now(),
Namespace: pod.Namespace,
Pod: pod.Name,
FromNode: node,
ToNode: targetNode,
Reason: "node-utilization-imbalance",
})
// --- update node usage safely ---
if nodeUsage[node] != nil {
nodeUsage[node]["cpu"] -= estimatePodCPU(&pod)
nodeUsage[node]["mem"] -= estimatePodMem(&pod)
}
if nodeUsage[newPod.Spec.NodeName] == nil {
nodeUsage[newPod.Spec.NodeName] = map[string]int64{"cpu": 0, "mem": 0}
}
nodeUsage[newPod.Spec.NodeName]["cpu"] += estimatePodCPU(&pod)
nodeUsage[newPod.Spec.NodeName]["mem"] += estimatePodMem(&pod)
// only move one pod per invocation
return
}
}
}
//
// ─── HELPERS ────────────────────────────────────────────────────────────────────
//
func mustEnv(key, def string) string {
if val := os.Getenv(key); val != "" {
return val
}
return def
}
func cordonNode(clientset *kubernetes.Clientset, nodeName string) error {
ctx := context.Background()
for i := 0; i < 5; i++ { // retry up to 5 times
node, err := clientset.CoreV1().Nodes().Get(ctx, nodeName, metav1.GetOptions{})
if err != nil {
return err
}
if node.Spec.Unschedulable {
return nil // already cordoned
}
node.Spec.Unschedulable = true
_, err = clientset.CoreV1().Nodes().Update(ctx, node, metav1.UpdateOptions{})
if err == nil {
return nil
}
log.Println("Cordoning failed, retrying:", err)
time.Sleep(500 * time.Millisecond)
}
return fmt.Errorf("failed to cordon node %s after retries", nodeName)
}
func uncordonNode(clientset *kubernetes.Clientset, nodeName string) error {
ctx := context.Background()
for i := 0; i < 5; i++ {
node, err := clientset.CoreV1().Nodes().Get(ctx, nodeName, metav1.GetOptions{})
if err != nil {
return err
}
if !node.Spec.Unschedulable {
return nil // already uncordoned
}
node.Spec.Unschedulable = false
_, err = clientset.CoreV1().Nodes().Update(ctx, node, metav1.UpdateOptions{})
if err == nil {
return nil
}
log.Println("Uncordoning failed, retrying:", err)
time.Sleep(500 * time.Millisecond)
}
return fmt.Errorf("failed to uncordon node %s after retries", nodeName)
}
func isDaemonSet(pod *corev1.Pod) bool {
for _, owner := range pod.OwnerReferences {
if owner.Kind == "DaemonSet" {
return true
}
}
return false
}
func usesHostPath(pod *corev1.Pod) bool {
for _, vol := range pod.Spec.Volumes {
if vol.HostPath != nil {
return true
}
}
return false
}
func pickTargetNode(nodes []string, usage map[string]map[string]int64, capacity map[string]map[string]int64) string {
var bestNode string
bestLoad := int64(1 << 62)
for _, n := range nodes {
cpuPercent := usage[n]["cpu"] * 100 / capacity[n]["cpu"]
memPercent := usage[n]["mem"] * 100 / capacity[n]["mem"]
load := cpuPercent + memPercent
if load < bestLoad {
bestLoad = load
bestNode = n
}
}
return bestNode
}
func estimatePodCPU(pod *corev1.Pod) int64 {
var cpu int64
for _, c := range pod.Spec.Containers {
if q, ok := c.Resources.Requests[corev1.ResourceCPU]; ok {
cpu += q.MilliValue()
}
}
return cpu
}
func estimatePodMem(pod *corev1.Pod) int64 {
var mem int64
for _, c := range pod.Spec.Containers {
if q, ok := c.Resources.Requests[corev1.ResourceMemory]; ok {
mem += q.Value() / (1024 * 1024)
}
}
return mem
}
+498
View File
@@ -0,0 +1,498 @@
package main
import (
"context"
"encoding/json"
"fmt"
"log"
"net/http"
"os"
"strconv"
"sync"
"time"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
"k8s.io/apimachinery/pkg/types"
metricsv "k8s.io/metrics/pkg/client/clientset/versioned"
)
var (
CPUOverloadThreshold int64
MemoryOverloadThreshold int64
CPUUnderloadThreshold int64
MemoryUnderloadThreshold int64
PodEvictionInterval time.Duration
PodAnimationDuration time.Duration
PodRespawnTimeout time.Duration
)
func getEnvInt64(name string, defaultVal int64) int64 {
valStr := os.Getenv(name)
if valStr == "" {
return defaultVal
}
val, err := strconv.ParseInt(valStr, 10, 64)
if err != nil {
log.Printf("Invalid %s: %s, using default %d", name, valStr, defaultVal)
return defaultVal
}
return val
}
func getEnvSecondsDuration(name string, defaultSec int64) time.Duration {
valStr := os.Getenv(name)
if valStr == "" {
return time.Duration(defaultSec) * time.Second
}
sec, err := strconv.ParseInt(valStr, 10, 64)
if err != nil {
log.Printf("Invalid %s: %s, using default %d seconds", name, valStr, defaultSec)
return time.Duration(defaultSec) * time.Second
}
return time.Duration(sec) * time.Second
}
func init() {
CPUOverloadThreshold = getEnvInt64("CPU_OVERLOAD_THRESHOLD", 80)
MemoryOverloadThreshold = getEnvInt64("MEMORY_OVERLOAD_THRESHOLD", 80)
CPUUnderloadThreshold = getEnvInt64("CPU_UNDERLOAD_THRESHOLD", 50)
MemoryUnderloadThreshold = getEnvInt64("MEMORY_UNDERLOAD_THRESHOLD", 50)
PodEvictionInterval = getEnvSecondsDuration("POD_EVICTION_INTERVAL", 30) // default 2 min
PodAnimationDuration = getEnvSecondsDuration("POD_ANIMATION_DURATION", 2) // default 2 sec
func init() {
CPUOverloadThreshold = getEnvInt64("CPU_OVERLOAD_THRESHOLD", 80)
MemoryOverloadThreshold = getEnvInt64("MEMORY_OVERLOAD_THRESHOLD", 80)
CPUUnderloadThreshold = getEnvInt64("CPU_UNDERLOAD_THRESHOLD", 50)
MemoryUnderloadThreshold = getEnvInt64("MEMORY_UNDERLOAD_THRESHOLD", 50)
PodEvictionInterval = getEnvSecondsDuration("POD_EVICTION_INTERVAL", 30)
PodAnimationDuration = getEnvSecondsDuration("POD_ANIMATION_DURATION", 2)
PodRespawnTimeout = getEnvSecondsDuration("POD_RESPAWN_TIMEOUT", 60)
}
type PodMoveEvent struct {
Time time.Time `json:"time"`
Namespace string `json:"namespace"`
Pod string `json:"pod"`
FromNode string `json:"fromNode"`
ToNode string `json:"toNode"`
Reason string `json:"reason"`
}
type EventBus struct {
mu sync.Mutex
history []PodMoveEvent
clients map[chan PodMoveEvent]struct{}
}
func NewEventBus() *EventBus {
return &EventBus{
history: make([]PodMoveEvent, 0, 100),
clients: make(map[chan PodMoveEvent]struct{}),
}
}
func (b *EventBus) Emit(evt PodMoveEvent) {
b.mu.Lock()
defer b.mu.Unlock()
if len(b.history) == 100 {
b.history = b.history[1:]
}
b.history = append(b.history, evt)
for ch := range b.clients {
select {
case ch <- evt:
default:
}
}
}
func (b *EventBus) History() []PodMoveEvent {
b.mu.Lock()
defer b.mu.Unlock()
out := make([]PodMoveEvent, len(b.history))
copy(out, b.history)
return out
}
func (b *EventBus) Subscribe() chan PodMoveEvent {
b.mu.Lock()
defer b.mu.Unlock()
ch := make(chan PodMoveEvent, 10)
b.clients[ch] = struct{}{}
return ch
}
func (b *EventBus) Unsubscribe(ch chan PodMoveEvent) {
b.mu.Lock()
defer b.mu.Unlock()
delete(b.clients, ch)
close(ch)
}
func main() {
config, err := rest.InClusterConfig()
if err != nil {
log.Fatal(err)
}
clientset, err := kubernetes.NewForConfig(config)
if err != nil {
log.Fatal(err)
}
metricsClient, err := metricsv.NewForConfig(config)
if err != nil {
log.Fatal(err)
}
eventBus := NewEventBus()
go startWebUI(eventBus, clientset)
for {
balanceNodes(clientset, metricsClient, eventBus)
time.Sleep(PodEvictionInterval)
}
}
func startWebUI(bus *EventBus, clientset *kubernetes.Clientset) {
mux := http.NewServeMux()
mux.Handle("/", http.FileServer(http.Dir("/web")))
mux.HandleFunc("/api/events", func(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(bus.History())
})
mux.HandleFunc("/api/stream", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/event-stream")
w.Header().Set("Cache-Control", "no-cache")
flusher, ok := w.(http.Flusher)
if !ok {
http.Error(w, "streaming unsupported", 500)
return
}
ch := bus.Subscribe()
defer bus.Unsubscribe(ch)
for {
select {
case evt := <-ch:
data, _ := json.Marshal(evt)
fmt.Fprintf(w, "data: %s\n\n", data)
flusher.Flush()
case <-r.Context().Done():
return
}
}
})
log.Println("WebUI listening on :8080")
mux.HandleFunc("/api/nodes", func(w http.ResponseWriter, r *http.Request) {
nodes, err := clientset.CoreV1().Nodes().List(context.Background(), metav1.ListOptions{})
if err != nil {
http.Error(w, "failed to list nodes", http.StatusInternalServerError)
return
}
names := []string{}
for _, n := range nodes.Items {
names = append(names, n.Name)
}
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(names)
})
mux.HandleFunc("/api/pods", func(w http.ResponseWriter, r *http.Request) {
ctx := context.Background()
pods, err := clientset.CoreV1().Pods("").List(ctx, metav1.ListOptions{})
if err != nil {
http.Error(w, "failed to list pods", http.StatusInternalServerError)
return
}
// group pods by node
podsByNode := map[string][]string{}
for _, pod := range pods.Items {
if pod.Spec.NodeName == "" {
continue
}
if _, ok := podsByNode[pod.Spec.NodeName]; !ok {
podsByNode[pod.Spec.NodeName] = []string{}
}
podsByNode[pod.Spec.NodeName] = append(podsByNode[pod.Spec.NodeName], pod.Name)
}
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(podsByNode)
})
mux.HandleFunc("/api/config", func(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "application/json")
cfg := map[string]interface{}{
"animationDurationMs": int64(2000), // number
"version": "1.1", // string
"clusterName": os.Getenv("CLUSTER_NAME"), // string
}
_ = json.NewEncoder(w).Encode(cfg)
})
_ = http.ListenAndServe(":8080", mux)
}
//
// ─── balance nodes ────────────────────────────────────────────────────────────────────
//
func balanceNodes(clientset *kubernetes.Clientset) {
log.Println("Starting balance cycle")
nodes, err := clientset.CoreV1().Nodes().List(context.Background(), metav1.ListOptions{})
if err != nil {
log.Printf("Error listing nodes: %v", err)
return
}
podCounts := make(map[string]int)
for _, node := range nodes.Items {
if node.Spec.Unschedulable {
continue
}
pods, err := clientset.CoreV1().Pods("").List(context.Background(), metav1.ListOptions{
FieldSelector: fmt.Sprintf("spec.nodeName=%s,status.phase=Running", node.Name),
})
if err != nil {
log.Printf("Error listing pods for node %s: %v", node.Name, err)
continue
}
podCounts[node.Name] = len(pods.Items)
}
if len(podCounts) < 2 {
return
}
var overloadedNode, underloadedNode string
maxPods := -1
minPods := int(^uint(0) >> 1)
for node, count := range podCounts {
if count > maxPods {
maxPods = count
overloadedNode = node
}
if count < minPods {
minPods = count
underloadedNode = node
}
}
if maxPods-minPods <= 1 {
log.Println("Cluster balanced")
return
}
pods, err := clientset.CoreV1().Pods("").List(context.Background(), metav1.ListOptions{
FieldSelector: fmt.Sprintf("spec.nodeName=%s,status.phase=Running", overloadedNode),
})
if err != nil || len(pods.Items) == 0 {
log.Println("No movable pods found")
return
}
pod := pods.Items[0]
log.Printf("Rescheduling pod %s/%s from %s",
pod.Namespace, pod.Name, overloadedNode)
// Cordon overloaded node
nodeObj, err := clientset.CoreV1().Nodes().Get(context.Background(), overloadedNode, metav1.GetOptions{})
if err != nil {
log.Printf("Failed to get node: %v", err)
return
}
nodeObj.Spec.Unschedulable = true
_, err = clientset.CoreV1().Nodes().Update(context.Background(), nodeObj, metav1.UpdateOptions{})
if err != nil {
log.Printf("Failed to cordon node: %v", err)
return
}
log.Printf("Successfully cordoned node %s", overloadedNode)
// Delete pod
err = clientset.CoreV1().Pods(pod.Namespace).Delete(context.Background(), pod.Name, metav1.DeleteOptions{})
if err != nil {
log.Printf("Failed to delete pod: %v", err)
return
}
log.Printf("Deleted pod %s", pod.Name)
// -------- WAIT FOR REPLACEMENT (FIXED) --------
respawnCtx, cancel := context.WithTimeout(context.Background(), PodRespawnTimeout)
log.Printf("PodRespawnTimeout = %v", PodRespawnTimeout)
ticker := time.NewTicker(2 * time.Second)
for {
select {
case <-respawnCtx.Done():
log.Println("Timeout waiting for replacement pod")
ticker.Stop()
cancel()
// Uncordon node before exit
nodeObj.Spec.Unschedulable = false
_, _ = clientset.CoreV1().Nodes().Update(context.Background(), nodeObj, metav1.UpdateOptions{})
log.Printf("Uncordoned node %s after timeout", overloadedNode)
return
case <-ticker.C:
podsList, err := clientset.CoreV1().
Pods(pod.Namespace).
List(context.Background(), metav1.ListOptions{})
if err != nil {
log.Printf("Error listing pods: %v", err)
continue
}
for _, p := range podsList.Items {
if p.Name != pod.Name &&
p.Spec.NodeName != overloadedNode &&
p.Status.Phase == v1.PodRunning {
log.Printf("Replacement pod %s is Running on %s",
p.Name, p.Spec.NodeName)
ticker.Stop()
cancel()
// Uncordon original node
nodeObj.Spec.Unschedulable = false
_, _ = clientset.CoreV1().Nodes().Update(context.Background(), nodeObj, metav1.UpdateOptions{})
log.Printf("Uncordoned node %s", overloadedNode)
return
}
}
log.Println("Waiting for replacement pod to be Running...")
}
}
}
//
// ─── HELPERS ────────────────────────────────────────────────────────────────────
//
func mustEnv(key, def string) string {
if val := os.Getenv(key); val != "" {
return val
}
return def
}
func cordonNode(clientset *kubernetes.Clientset, nodeName string) error {
ctx := context.Background()
for i := 0; i < 5; i++ { // retry up to 5 times
node, err := clientset.CoreV1().Nodes().Get(ctx, nodeName, metav1.GetOptions{})
if err != nil {
return err
}
if node.Spec.Unschedulable {
return nil // already cordoned
}
node.Spec.Unschedulable = true
_, err = clientset.CoreV1().Nodes().Update(ctx, node, metav1.UpdateOptions{})
if err == nil {
return nil
}
log.Println("Cordoning failed, retrying:", err)
time.Sleep(500 * time.Millisecond)
}
return fmt.Errorf("failed to cordon node %s after retries", nodeName)
}
func uncordonNode(clientset *kubernetes.Clientset, nodeName string) error {
ctx := context.Background()
for i := 0; i < 5; i++ {
node, err := clientset.CoreV1().Nodes().Get(ctx, nodeName, metav1.GetOptions{})
if err != nil {
return err
}
if !node.Spec.Unschedulable {
return nil // already uncordoned
}
node.Spec.Unschedulable = false
_, err = clientset.CoreV1().Nodes().Update(ctx, node, metav1.UpdateOptions{})
if err == nil {
return nil
}
log.Println("Uncordoning failed, retrying:", err)
time.Sleep(500 * time.Millisecond)
}
return fmt.Errorf("failed to uncordon node %s after retries", nodeName)
}
func isDaemonSet(pod *corev1.Pod) bool {
for _, owner := range pod.OwnerReferences {
if owner.Kind == "DaemonSet" {
return true
}
}
return false
}
func pickTargetNode(nodes []string, usage map[string]map[string]int64, capacity map[string]map[string]int64) string {
var bestNode string
bestLoad := int64(1 << 62)
for _, n := range nodes {
cpuPercent := usage[n]["cpu"] * 100 / capacity[n]["cpu"]
memPercent := usage[n]["mem"] * 100 / capacity[n]["mem"]
load := cpuPercent + memPercent
if load < bestLoad {
bestLoad = load
bestNode = n
}
}
return bestNode
}
func estimatePodCPU(pod *corev1.Pod) int64 {
var cpu int64
for _, c := range pod.Spec.Containers {
if q, ok := c.Resources.Requests[corev1.ResourceCPU]; ok {
cpu += q.MilliValue()
}
}
return cpu
}
func estimatePodMem(pod *corev1.Pod) int64 {
var mem int64
for _, c := range pod.Spec.Containers {
if q, ok := c.Resources.Requests[corev1.ResourceMemory]; ok {
mem += q.Value() / (1024 * 1024)
}
}
return mem
}
+216
View File
@@ -0,0 +1,216 @@
package main
import (
"context"
"fmt"
"log"
"os"
"strconv"
"time"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
metricsv "k8s.io/metrics/pkg/client/clientset/versioned"
)
var (
CPUOverloadThreshold int64
MemoryOverloadThreshold int64
CPUUnderloadThreshold int64
MemoryUnderloadThreshold int64
)
func getEnvInt64(name string, defaultVal int64) int64 {
valStr := os.Getenv(name)
if valStr == "" {
return defaultVal
}
val, err := strconv.ParseInt(valStr, 10, 64)
if err != nil {
log.Printf("Invalid %s: %s, using default %d", name, valStr, defaultVal)
return defaultVal
}
return val
}
func init() {
CPUOverloadThreshold = getEnvInt64("CPU_OVERLOAD_THRESHOLD", 80)
MemoryOverloadThreshold = getEnvInt64("MEMORY_OVERLOAD_THRESHOLD", 80)
CPUUnderloadThreshold = getEnvInt64("CPU_UNDERLOAD_THRESHOLD", 50)
MemoryUnderloadThreshold = getEnvInt64("MEMORY_UNDERLOAD_THRESHOLD", 50)
}
func main() {
config, err := rest.InClusterConfig()
if err != nil {
log.Fatal(err)
}
clientset, err := kubernetes.NewForConfig(config)
if err != nil {
log.Fatal(err)
}
metricsClient, err := metricsv.NewForConfig(config)
if err != nil {
log.Fatal(err)
}
for {
balanceNodes(clientset, metricsClient)
time.Sleep(2 * time.Minute)
}
}
func balanceNodes(clientset *kubernetes.Clientset, metricsClient *metricsv.Clientset) {
ctx := context.Background()
// Get node metrics
nodeMetricsList, err := metricsClient.MetricsV1beta1().NodeMetricses().List(ctx, metav1.ListOptions{})
if err != nil {
log.Println("Failed to get node metrics:", err)
return
}
nodeUsage := make(map[string]map[string]int64)
for _, m := range nodeMetricsList.Items {
nodeUsage[m.Name] = map[string]int64{
"cpu": m.Usage.Cpu().MilliValue(),
"mem": m.Usage.Memory().Value() / (1024 * 1024), // MiB
}
}
// Get node capacity
nodes, err := clientset.CoreV1().Nodes().List(ctx, metav1.ListOptions{})
if err != nil {
log.Println("Failed to list nodes:", err)
return
}
nodeCapacity := make(map[string]map[string]int64)
for _, n := range nodes.Items {
nodeCapacity[n.Name] = map[string]int64{
"cpu": n.Status.Capacity.Cpu().MilliValue(),
"mem": n.Status.Capacity.Memory().Value() / (1024 * 1024),
}
}
// Identify overloaded and underloaded nodes
var overloaded, underloaded []string
for node, usage := range nodeUsage {
cpuPercent := usage["cpu"] * 100 / nodeCapacity[node]["cpu"]
memPercent := usage["mem"] * 100 / nodeCapacity[node]["mem"]
if cpuPercent > CPUOverloadThreshold || memPercent > MemoryOverloadThreshold {
overloaded = append(overloaded, node)
} else if cpuPercent < CPUUnderloadThreshold && memPercent < MemoryUnderloadThreshold {
underloaded = append(underloaded, node)
}
}
// ORIGINAL LOGGING – preserved
fmt.Println("Overloaded nodes:", overloaded)
fmt.Println("Underloaded nodes:", underloaded)
if len(overloaded) == 0 || len(underloaded) == 0 {
return
}
// Evict exactly ONE pod, then return
for _, node := range overloaded {
pods, err := clientset.CoreV1().Pods("").List(ctx, metav1.ListOptions{
FieldSelector: fmt.Sprintf("spec.nodeName=%s", node),
})
if err != nil {
log.Println("Failed to list pods for node", node, err)
continue
}
for _, pod := range pods.Items {
if pod.Namespace == "kube-system" || isDaemonSet(&pod) {
continue
}
targetNode := pickTargetNode(underloaded, nodeUsage, nodeCapacity)
if targetNode == "" {
log.Println("No suitable underloaded node available")
return
}
// ORIGINAL LOGGING – preserved
fmt.Printf(
"Rescheduling pod %s/%s from %s to %s\n",
pod.Namespace,
pod.Name,
node,
targetNode,
)
grace := int64(0)
err = clientset.CoreV1().Pods(pod.Namespace).Delete(ctx, pod.Name, metav1.DeleteOptions{
GracePeriodSeconds: &grace,
})
if err != nil {
log.Println("Failed to delete pod", pod.Name, err)
return
}
// Update in-memory usage
nodeUsage[node]["cpu"] -= estimatePodCPU(&pod)
nodeUsage[node]["mem"] -= estimatePodMem(&pod)
nodeUsage[targetNode]["cpu"] += estimatePodCPU(&pod)
nodeUsage[targetNode]["mem"] += estimatePodMem(&pod)
// IMPORTANT: stop after one eviction
return
}
}
}
func isDaemonSet(pod *corev1.Pod) bool {
for _, owner := range pod.OwnerReferences {
if owner.Kind == "DaemonSet" {
return true
}
}
return false
}
// pickTargetNode chooses the underloaded node with lowest combined CPU+Memory usage
func pickTargetNode(nodes []string, usage map[string]map[string]int64, capacity map[string]map[string]int64) string {
var bestNode string
bestLoad := int64(1 << 62) // very high
for _, n := range nodes {
cpuPercent := usage[n]["cpu"] * 100 / capacity[n]["cpu"]
memPercent := usage[n]["mem"] * 100 / capacity[n]["mem"]
load := cpuPercent + memPercent
if load < bestLoad {
bestLoad = load
bestNode = n
}
}
return bestNode
}
// estimatePodCPU/Mem returns an approximate CPU/memory usage for the pod (from requests)
func estimatePodCPU(pod *corev1.Pod) int64 {
var cpu int64
for _, c := range pod.Spec.Containers {
if q, ok := c.Resources.Requests[corev1.ResourceCPU]; ok {
cpu += q.MilliValue()
}
}
return cpu
}
func estimatePodMem(pod *corev1.Pod) int64 {
var mem int64
for _, c := range pod.Spec.Containers {
if q, ok := c.Resources.Requests[corev1.ResourceMemory]; ok {
mem += q.Value() / (1024 * 1024) // MiB
}
}
return mem
}
+354
View File
@@ -0,0 +1,354 @@
package main
import (
"context"
"embed"
"encoding/json"
"fmt"
"log"
"net/http"
"os"
"strconv"
"sync"
"time"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
metricsv "k8s.io/metrics/pkg/client/clientset/versioned"
)
//
// ─── EMBEDDED WEB UI ────────────────────────────────────────────────────────────
//
//go:embed web/*
var webFS embed.FS
//
// ─── CONFIG ─────────────────────────────────────────────────────────────────────
//
var (
CPUOverloadThreshold int64
MemoryOverloadThreshold int64
CPUUnderloadThreshold int64
MemoryUnderloadThreshold int64
)
func getEnvInt64(name string, defaultVal int64) int64 {
valStr := os.Getenv(name)
if valStr == "" {
return defaultVal
}
val, err := strconv.ParseInt(valStr, 10, 64)
if err != nil {
log.Printf("Invalid %s: %s, using default %d", name, valStr, defaultVal)
return defaultVal
}
return val
}
func init() {
CPUOverloadThreshold = getEnvInt64("CPU_OVERLOAD_THRESHOLD", 80)
MemoryOverloadThreshold = getEnvInt64("MEMORY_OVERLOAD_THRESHOLD", 80)
CPUUnderloadThreshold = getEnvInt64("CPU_UNDERLOAD_THRESHOLD", 50)
MemoryUnderloadThreshold = getEnvInt64("MEMORY_UNDERLOAD_THRESHOLD", 50)
}
//
// ─── EVENT MODEL + BUS ──────────────────────────────────────────────────────────
//
type PodMoveEvent struct {
Time time.Time `json:"time"`
Namespace string `json:"namespace"`
Pod string `json:"pod"`
FromNode string `json:"fromNode"`
ToNode string `json:"toNode"`
Reason string `json:"reason"`
}
type EventBus struct {
mu sync.Mutex
history []PodMoveEvent
clients map[chan PodMoveEvent]struct{}
}
func NewEventBus() *EventBus {
return &EventBus{
history: make([]PodMoveEvent, 0, 100),
clients: make(map[chan PodMoveEvent]struct{}),
}
}
func (b *EventBus) Emit(evt PodMoveEvent) {
b.mu.Lock()
defer b.mu.Unlock()
if len(b.history) == 100 {
b.history = b.history[1:]
}
b.history = append(b.history, evt)
for ch := range b.clients {
select {
case ch <- evt:
default:
}
}
}
func (b *EventBus) History() []PodMoveEvent {
b.mu.Lock()
defer b.mu.Unlock()
out := make([]PodMoveEvent, len(b.history))
copy(out, b.history)
return out
}
func (b *EventBus) Subscribe() chan PodMoveEvent {
b.mu.Lock()
defer b.mu.Unlock()
ch := make(chan PodMoveEvent, 10)
b.clients[ch] = struct{}{}
return ch
}
func (b *EventBus) Unsubscribe(ch chan PodMoveEvent) {
b.mu.Lock()
defer b.mu.Unlock()
delete(b.clients, ch)
close(ch)
}
//
// ─── MAIN ───────────────────────────────────────────────────────────────────────
//
func main() {
config, err := rest.InClusterConfig()
if err != nil {
log.Fatal(err)
}
clientset, err := kubernetes.NewForConfig(config)
if err != nil {
log.Fatal(err)
}
metricsClient, err := metricsv.NewForConfig(config)
if err != nil {
log.Fatal(err)
}
eventBus := NewEventBus()
go startWebUI(eventBus)
for {
balanceNodes(clientset, metricsClient, eventBus)
time.Sleep(2 * time.Minute)
}
}
//
// ─── WEB UI SERVER (SAME PROCESS) ───────────────────────────────────────────────
//
func startWebUI(bus *EventBus) {
mux := http.NewServeMux()
mux.Handle("/", http.FileServer(http.FS(webFS)))
mux.HandleFunc("/api/events", func(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(bus.History())
})
mux.HandleFunc("/api/stream", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/event-stream")
w.Header().Set("Cache-Control", "no-cache")
flusher, ok := w.(http.Flusher)
if !ok {
http.Error(w, "streaming unsupported", 500)
return
}
ch := bus.Subscribe()
defer bus.Unsubscribe(ch)
for {
select {
case evt := <-ch:
data, _ := json.Marshal(evt)
fmt.Fprintf(w, "data: %s\n\n", data)
flusher.Flush()
case <-r.Context().Done():
return
}
}
})
log.Println("WebUI listening on :8080")
_ = http.ListenAndServe(":8080", mux)
}
//
// ─── BALANCER (MINIMALLY MODIFIED) ──────────────────────────────────────────────
//
func balanceNodes(clientset *kubernetes.Clientset, metricsClient *metricsv.Clientset, bus *EventBus) {
ctx := context.Background()
nodeMetricsList, err := metricsClient.MetricsV1beta1().NodeMetricses().List(ctx, metav1.ListOptions{})
if err != nil {
log.Println("Failed to get node metrics:", err)
return
}
nodeUsage := make(map[string]map[string]int64)
for _, m := range nodeMetricsList.Items {
nodeUsage[m.Name] = map[string]int64{
"cpu": m.Usage.Cpu().MilliValue(),
"mem": m.Usage.Memory().Value() / (1024 * 1024),
}
}
nodes, err := clientset.CoreV1().Nodes().List(ctx, metav1.ListOptions{})
if err != nil {
log.Println("Failed to list nodes:", err)
return
}
nodeCapacity := make(map[string]map[string]int64)
for _, n := range nodes.Items {
nodeCapacity[n.Name] = map[string]int64{
"cpu": n.Status.Capacity.Cpu().MilliValue(),
"mem": n.Status.Capacity.Memory().Value() / (1024 * 1024),
}
}
var overloaded, underloaded []string
for node, usage := range nodeUsage {
cpuPercent := usage["cpu"] * 100 / nodeCapacity[node]["cpu"]
memPercent := usage["mem"] * 100 / nodeCapacity[node]["mem"]
if cpuPercent > CPUOverloadThreshold || memPercent > MemoryOverloadThreshold {
overloaded = append(overloaded, node)
} else if cpuPercent < CPUUnderloadThreshold && memPercent < MemoryUnderloadThreshold {
underloaded = append(underloaded, node)
}
}
fmt.Println("Overloaded nodes:", overloaded)
fmt.Println("Underloaded nodes:", underloaded)
if len(overloaded) == 0 || len(underloaded) == 0 {
return
}
for _, node := range overloaded {
pods, err := clientset.CoreV1().Pods("").List(ctx, metav1.ListOptions{
FieldSelector: fmt.Sprintf("spec.nodeName=%s", node),
})
if err != nil {
log.Println("Failed to list pods for node", node, err)
continue
}
for _, pod := range pods.Items {
if pod.Namespace == "kube-system" || isDaemonSet(&pod) {
continue
}
targetNode := pickTargetNode(underloaded, nodeUsage, nodeCapacity)
if targetNode == "" {
return
}
fmt.Printf(
"Rescheduling pod %s/%s from %s to %s\n",
pod.Namespace,
pod.Name,
node,
targetNode,
)
// 🔴 EMIT EVENT FOR WEB UI
bus.Emit(PodMoveEvent{
Time: time.Now(),
Namespace: pod.Namespace,
Pod: pod.Name,
FromNode: node,
ToNode: targetNode,
Reason: "node-utilization-imbalance",
})
grace := int64(0)
err = clientset.CoreV1().Pods(pod.Namespace).Delete(ctx, pod.Name, metav1.DeleteOptions{
GracePeriodSeconds: &grace,
})
if err != nil {
log.Println("Failed to delete pod", pod.Name, err)
return
}
nodeUsage[node]["cpu"] -= estimatePodCPU(&pod)
nodeUsage[node]["mem"] -= estimatePodMem(&pod)
nodeUsage[targetNode]["cpu"] += estimatePodCPU(&pod)
nodeUsage[targetNode]["mem"] += estimatePodMem(&pod)
return
}
}
}
//
// ─── HELPERS ────────────────────────────────────────────────────────────────────
//
func isDaemonSet(pod *corev1.Pod) bool {
for _, owner := range pod.OwnerReferences {
if owner.Kind == "DaemonSet" {
return true
}
}
return false
}
func pickTargetNode(nodes []string, usage map[string]map[string]int64, capacity map[string]map[string]int64) string {
var bestNode string
bestLoad := int64(1 << 62)
for _, n := range nodes {
cpuPercent := usage[n]["cpu"] * 100 / capacity[n]["cpu"]
memPercent := usage[n]["mem"] * 100 / capacity[n]["mem"]
load := cpuPercent + memPercent
if load < bestLoad {
bestLoad = load
bestNode = n
}
}
return bestNode
}
func estimatePodCPU(pod *corev1.Pod) int64 {
var cpu int64
for _, c := range pod.Spec.Containers {
if q, ok := c.Resources.Requests[corev1.ResourceCPU]; ok {
cpu += q.MilliValue()
}
}
return cpu
}
func estimatePodMem(pod *corev1.Pod) int64 {
var mem int64
for _, c := range pod.Spec.Containers {
if q, ok := c.Resources.Requests[corev1.ResourceMemory]; ok {
mem += q.Value() / (1024 * 1024)
}
}
return mem
}
+365
View File
@@ -0,0 +1,365 @@
package main
import (
"context"
"embed"
"encoding/json"
"fmt"
"log"
"net/http"
"os"
"strconv"
"sync"
"time"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
metricsv "k8s.io/metrics/pkg/client/clientset/versioned"
)
//
// ─── EMBEDDED WEB UI ────────────────────────────────────────────────────────────
//
//go:embed web/*
var webFS embed.FS
//
// ─── CONFIG ─────────────────────────────────────────────────────────────────────
//
var (
CPUOverloadThreshold int64
MemoryOverloadThreshold int64
CPUUnderloadThreshold int64
MemoryUnderloadThreshold int64
)
func getEnvInt64(name string, defaultVal int64) int64 {
valStr := os.Getenv(name)
if valStr == "" {
return defaultVal
}
val, err := strconv.ParseInt(valStr, 10, 64)
if err != nil {
log.Printf("Invalid %s: %s, using default %d", name, valStr, defaultVal)
return defaultVal
}
return val
}
func init() {
CPUOverloadThreshold = getEnvInt64("CPU_OVERLOAD_THRESHOLD", 80)
MemoryOverloadThreshold = getEnvInt64("MEMORY_OVERLOAD_THRESHOLD", 80)
CPUUnderloadThreshold = getEnvInt64("CPU_UNDERLOAD_THRESHOLD", 50)
MemoryUnderloadThreshold = getEnvInt64("MEMORY_UNDERLOAD_THRESHOLD", 50)
}
//
// ─── EVENT MODEL + BUS ──────────────────────────────────────────────────────────
//
type PodMoveEvent struct {
Time time.Time `json:"time"`
Namespace string `json:"namespace"`
Pod string `json:"pod"`
FromNode string `json:"fromNode"`
ToNode string `json:"toNode"`
Reason string `json:"reason"`
}
type EventBus struct {
mu sync.Mutex
history []PodMoveEvent
clients map[chan PodMoveEvent]struct{}
}
func NewEventBus() *EventBus {
return &EventBus{
history: make([]PodMoveEvent, 0, 100),
clients: make(map[chan PodMoveEvent]struct{}),
}
}
func (b *EventBus) Emit(evt PodMoveEvent) {
b.mu.Lock()
defer b.mu.Unlock()
if len(b.history) == 100 {
b.history = b.history[1:]
}
b.history = append(b.history, evt)
for ch := range b.clients {
select {
case ch <- evt:
default:
}
}
}
func (b *EventBus) History() []PodMoveEvent {
b.mu.Lock()
defer b.mu.Unlock()
out := make([]PodMoveEvent, len(b.history))
copy(out, b.history)
return out
}
func (b *EventBus) Subscribe() chan PodMoveEvent {
b.mu.Lock()
defer b.mu.Unlock()
ch := make(chan PodMoveEvent, 10)
b.clients[ch] = struct{}{}
return ch
}
func (b *EventBus) Unsubscribe(ch chan PodMoveEvent) {
b.mu.Lock()
defer b.mu.Unlock()
delete(b.clients, ch)
close(ch)
}
//
// ─── MAIN ───────────────────────────────────────────────────────────────────────
//
func main() {
config, err := rest.InClusterConfig()
if err != nil {
log.Fatal(err)
}
clientset, err := kubernetes.NewForConfig(config)
if err != nil {
log.Fatal(err)
}
metricsClient, err := metricsv.NewForConfig(config)
if err != nil {
log.Fatal(err)
}
eventBus := NewEventBus()
go startWebUI(eventBus, clientset)
for {
balanceNodes(clientset, metricsClient, eventBus)
time.Sleep(1 * time.Minute)
}
}
//
// ─── WEB UI SERVER (SAME PROCESS) ───────────────────────────────────────────────
//
func startWebUI(bus *EventBus, clientset *kubernetes.Clientset) {
mux := http.NewServeMux()
mux.Handle("/", http.FileServer(http.FS(webFS)))
mux.HandleFunc("/api/events", func(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(bus.History())
})
mux.HandleFunc("/api/stream", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/event-stream")
w.Header().Set("Cache-Control", "no-cache")
flusher, ok := w.(http.Flusher)
if !ok {
http.Error(w, "streaming unsupported", 500)
return
}
ch := bus.Subscribe()
defer bus.Unsubscribe(ch)
for {
select {
case evt := <-ch:
data, _ := json.Marshal(evt)
fmt.Fprintf(w, "data: %s\n\n", data)
flusher.Flush()
case <-r.Context().Done():
return
}
}
})
log.Println("WebUI listening on :8080")
mux.HandleFunc("/api/nodes", func(w http.ResponseWriter, r *http.Request) {
nodes, err := clientset.CoreV1().Nodes().List(context.Background(), metav1.ListOptions{})
if err != nil {
http.Error(w, "failed to list nodes", http.StatusInternalServerError)
return
}
names := []string{}
for _, n := range nodes.Items {
names = append(names, n.Name)
}
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(names)
})
_ = http.ListenAndServe(":8080", mux)
}
//
// ─── BALANCER (MINIMALLY MODIFIED) ──────────────────────────────────────────────
//
func balanceNodes(clientset *kubernetes.Clientset, metricsClient *metricsv.Clientset, bus *EventBus) {
ctx := context.Background()
nodeMetricsList, err := metricsClient.MetricsV1beta1().NodeMetricses().List(ctx, metav1.ListOptions{})
if err != nil {
log.Println("Failed to get node metrics:", err)
return
}
nodeUsage := make(map[string]map[string]int64)
for _, m := range nodeMetricsList.Items {
nodeUsage[m.Name] = map[string]int64{
"cpu": m.Usage.Cpu().MilliValue(),
"mem": m.Usage.Memory().Value() / (1024 * 1024),
}
}
nodes, err := clientset.CoreV1().Nodes().List(ctx, metav1.ListOptions{})
if err != nil {
log.Println("Failed to list nodes:", err)
return
}
nodeCapacity := make(map[string]map[string]int64)
for _, n := range nodes.Items {
nodeCapacity[n.Name] = map[string]int64{
"cpu": n.Status.Capacity.Cpu().MilliValue(),
"mem": n.Status.Capacity.Memory().Value() / (1024 * 1024),
}
}
var overloaded, underloaded []string
for node, usage := range nodeUsage {
cpuPercent := usage["cpu"] * 100 / nodeCapacity[node]["cpu"]
memPercent := usage["mem"] * 100 / nodeCapacity[node]["mem"]
if cpuPercent > CPUOverloadThreshold || memPercent > MemoryOverloadThreshold {
overloaded = append(overloaded, node)
} else if cpuPercent < CPUUnderloadThreshold && memPercent < MemoryUnderloadThreshold {
underloaded = append(underloaded, node)
}
}
fmt.Println("Overloaded nodes:", overloaded)
fmt.Println("Underloaded nodes:", underloaded)
if len(overloaded) == 0 || len(underloaded) == 0 {
return
}
for _, node := range overloaded {
pods, err := clientset.CoreV1().Pods("").List(ctx, metav1.ListOptions{
FieldSelector: fmt.Sprintf("spec.nodeName=%s", node),
})
if err != nil {
log.Println("Failed to list pods for node", node, err)
continue
}
for _, pod := range pods.Items {
if pod.Namespace == "kube-system" || isDaemonSet(&pod) {
continue
}
targetNode := pickTargetNode(underloaded, nodeUsage, nodeCapacity)
if targetNode == "" {
return
}
fmt.Printf(
"Rescheduling pod %s/%s from %s to %s\n",
pod.Namespace,
pod.Name,
node,
targetNode,
)
// 🔴 EMIT EVENT FOR WEB UI
bus.Emit(PodMoveEvent{
Time: time.Now(),
Namespace: pod.Namespace,
Pod: pod.Name,
FromNode: node,
ToNode: targetNode,
Reason: "node-utilization-imbalance",
})
grace := int64(0)
err = clientset.CoreV1().Pods(pod.Namespace).Delete(ctx, pod.Name, metav1.DeleteOptions{
GracePeriodSeconds: &grace,
})
if err != nil {
log.Println("Failed to delete pod", pod.Name, err)
return
}
nodeUsage[node]["cpu"] -= estimatePodCPU(&pod)
nodeUsage[node]["mem"] -= estimatePodMem(&pod)
nodeUsage[targetNode]["cpu"] += estimatePodCPU(&pod)
nodeUsage[targetNode]["mem"] += estimatePodMem(&pod)
return
}
}
}
//
// ─── HELPERS ────────────────────────────────────────────────────────────────────
//
func isDaemonSet(pod *corev1.Pod) bool {
for _, owner := range pod.OwnerReferences {
if owner.Kind == "DaemonSet" {
return true
}
}
return false
}
func pickTargetNode(nodes []string, usage map[string]map[string]int64, capacity map[string]map[string]int64) string {
var bestNode string
bestLoad := int64(1 << 62)
for _, n := range nodes {
cpuPercent := usage[n]["cpu"] * 100 / capacity[n]["cpu"]
memPercent := usage[n]["mem"] * 100 / capacity[n]["mem"]
load := cpuPercent + memPercent
if load < bestLoad {
bestLoad = load
bestNode = n
}
}
return bestNode
}
func estimatePodCPU(pod *corev1.Pod) int64 {
var cpu int64
for _, c := range pod.Spec.Containers {
if q, ok := c.Resources.Requests[corev1.ResourceCPU]; ok {
cpu += q.MilliValue()
}
}
return cpu
}
func estimatePodMem(pod *corev1.Pod) int64 {
var mem int64
for _, c := range pod.Spec.Containers {
if q, ok := c.Resources.Requests[corev1.ResourceMemory]; ok {
mem += q.Value() / (1024 * 1024)
}
}
return mem
}
+387
View File
@@ -0,0 +1,387 @@
package main
import (
"context"
"embed"
"encoding/json"
"fmt"
"log"
"net/http"
"os"
"strconv"
"sync"
"time"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
metricsv "k8s.io/metrics/pkg/client/clientset/versioned"
)
//
// ─── EMBEDDED WEB UI ────────────────────────────────────────────────────────────
//
//go:embed web/*
var webFS embed.FS
//
// ─── CONFIG ─────────────────────────────────────────────────────────────────────
//
var (
CPUOverloadThreshold int64
MemoryOverloadThreshold int64
CPUUnderloadThreshold int64
MemoryUnderloadThreshold int64
PodEvictionInterval time.Duration
PodAnimationDuration time.Duration
)
func getEnvInt64(name string, defaultVal int64) int64 {
valStr := os.Getenv(name)
if valStr == "" {
return defaultVal
}
val, err := strconv.ParseInt(valStr, 10, 64)
if err != nil {
log.Printf("Invalid %s: %s, using default %d", name, valStr, defaultVal)
return defaultVal
}
return val
}
func getEnvSecondsDuration(name string, defaultSec int64) time.Duration {
valStr := os.Getenv(name)
if valStr == "" {
return time.Duration(defaultSec) * time.Second
}
sec, err := strconv.ParseInt(valStr, 10, 64)
if err != nil {
log.Printf("Invalid %s: %s, using default %d seconds", name, valStr, defaultSec)
return time.Duration(defaultSec) * time.Second
}
return time.Duration(sec) * time.Second
}
func init() {
CPUOverloadThreshold = getEnvInt64("CPU_OVERLOAD_THRESHOLD", 80)
MemoryOverloadThreshold = getEnvInt64("MEMORY_OVERLOAD_THRESHOLD", 80)
CPUUnderloadThreshold = getEnvInt64("CPU_UNDERLOAD_THRESHOLD", 50)
MemoryUnderloadThreshold = getEnvInt64("MEMORY_UNDERLOAD_THRESHOLD", 50)
PodEvictionInterval = getEnvSecondsDuration("POD_EVICTION_INTERVAL", 120) // default 2 min
PodAnimationDuration = getEnvSecondsDuration("POD_ANIMATION_DURATION", 2) // default 2 sec
}
//
// ─── EVENT MODEL + BUS ──────────────────────────────────────────────────────────
//
type PodMoveEvent struct {
Time time.Time `json:"time"`
Namespace string `json:"namespace"`
Pod string `json:"pod"`
FromNode string `json:"fromNode"`
ToNode string `json:"toNode"`
Reason string `json:"reason"`
}
type EventBus struct {
mu sync.Mutex
history []PodMoveEvent
clients map[chan PodMoveEvent]struct{}
}
func NewEventBus() *EventBus {
return &EventBus{
history: make([]PodMoveEvent, 0, 100),
clients: make(map[chan PodMoveEvent]struct{}),
}
}
func (b *EventBus) Emit(evt PodMoveEvent) {
b.mu.Lock()
defer b.mu.Unlock()
if len(b.history) == 100 {
b.history = b.history[1:]
}
b.history = append(b.history, evt)
for ch := range b.clients {
select {
case ch <- evt:
default:
}
}
}
func (b *EventBus) History() []PodMoveEvent {
b.mu.Lock()
defer b.mu.Unlock()
out := make([]PodMoveEvent, len(b.history))
copy(out, b.history)
return out
}
func (b *EventBus) Subscribe() chan PodMoveEvent {
b.mu.Lock()
defer b.mu.Unlock()
ch := make(chan PodMoveEvent, 10)
b.clients[ch] = struct{}{}
return ch
}
func (b *EventBus) Unsubscribe(ch chan PodMoveEvent) {
b.mu.Lock()
defer b.mu.Unlock()
delete(b.clients, ch)
close(ch)
}
//
// ─── MAIN ───────────────────────────────────────────────────────────────────────
//
func main() {
config, err := rest.InClusterConfig()
if err != nil {
log.Fatal(err)
}
clientset, err := kubernetes.NewForConfig(config)
if err != nil {
log.Fatal(err)
}
metricsClient, err := metricsv.NewForConfig(config)
if err != nil {
log.Fatal(err)
}
eventBus := NewEventBus()
go startWebUI(eventBus, clientset)
for {
balanceNodes(clientset, metricsClient, eventBus)
time.Sleep(PodEvictionInterval)
}
}
//
// ─── WEB UI SERVER (SAME PROCESS) ───────────────────────────────────────────────
//
func startWebUI(bus *EventBus, clientset *kubernetes.Clientset) {
mux := http.NewServeMux()
mux.Handle("/", http.FileServer(http.FS(webFS)))
mux.HandleFunc("/api/events", func(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(bus.History())
})
mux.HandleFunc("/api/stream", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/event-stream")
w.Header().Set("Cache-Control", "no-cache")
flusher, ok := w.(http.Flusher)
if !ok {
http.Error(w, "streaming unsupported", 500)
return
}
ch := bus.Subscribe()
defer bus.Unsubscribe(ch)
for {
select {
case evt := <-ch:
data, _ := json.Marshal(evt)
fmt.Fprintf(w, "data: %s\n\n", data)
flusher.Flush()
case <-r.Context().Done():
return
}
}
})
log.Println("WebUI listening on :8080")
mux.HandleFunc("/api/nodes", func(w http.ResponseWriter, r *http.Request) {
nodes, err := clientset.CoreV1().Nodes().List(context.Background(), metav1.ListOptions{})
if err != nil {
http.Error(w, "failed to list nodes", http.StatusInternalServerError)
return
}
names := []string{}
for _, n := range nodes.Items {
names = append(names, n.Name)
}
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(names)
})
mux.HandleFunc("/api/config", func(w http.ResponseWriter, r *http.Request) {
cfg := map[string]int64{
"animationDurationMs": PodAnimationDuration.Milliseconds(),
}
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(cfg)
})
_ = http.ListenAndServe(":8080", mux)
}
//
// ─── BALANCER (MINIMALLY MODIFIED) ──────────────────────────────────────────────
//
func balanceNodes(clientset *kubernetes.Clientset, metricsClient *metricsv.Clientset, bus *EventBus) {
ctx := context.Background()
nodeMetricsList, err := metricsClient.MetricsV1beta1().NodeMetricses().List(ctx, metav1.ListOptions{})
if err != nil {
log.Println("Failed to get node metrics:", err)
return
}
nodeUsage := make(map[string]map[string]int64)
for _, m := range nodeMetricsList.Items {
nodeUsage[m.Name] = map[string]int64{
"cpu": m.Usage.Cpu().MilliValue(),
"mem": m.Usage.Memory().Value() / (1024 * 1024),
}
}
nodes, err := clientset.CoreV1().Nodes().List(ctx, metav1.ListOptions{})
if err != nil {
log.Println("Failed to list nodes:", err)
return
}
nodeCapacity := make(map[string]map[string]int64)
for _, n := range nodes.Items {
nodeCapacity[n.Name] = map[string]int64{
"cpu": n.Status.Capacity.Cpu().MilliValue(),
"mem": n.Status.Capacity.Memory().Value() / (1024 * 1024),
}
}
var overloaded, underloaded []string
for node, usage := range nodeUsage {
cpuPercent := usage["cpu"] * 100 / nodeCapacity[node]["cpu"]
memPercent := usage["mem"] * 100 / nodeCapacity[node]["mem"]
if cpuPercent > CPUOverloadThreshold || memPercent > MemoryOverloadThreshold {
overloaded = append(overloaded, node)
} else if cpuPercent < CPUUnderloadThreshold && memPercent < MemoryUnderloadThreshold {
underloaded = append(underloaded, node)
}
}
fmt.Println("Overloaded nodes:", overloaded)
fmt.Println("Underloaded nodes:", underloaded)
if len(overloaded) == 0 || len(underloaded) == 0 {
return
}
for _, node := range overloaded {
pods, err := clientset.CoreV1().Pods("").List(ctx, metav1.ListOptions{
FieldSelector: fmt.Sprintf("spec.nodeName=%s", node),
})
if err != nil {
log.Println("Failed to list pods for node", node, err)
continue
}
for _, pod := range pods.Items {
if pod.Namespace == "kube-system" || isDaemonSet(&pod) {
continue
}
targetNode := pickTargetNode(underloaded, nodeUsage, nodeCapacity)
if targetNode == "" {
return
}
fmt.Printf(
"Rescheduling pod %s/%s from %s to %s\n",
pod.Namespace,
pod.Name,
node,
targetNode,
)
// 🔴 EMIT EVENT FOR WEB UI
bus.Emit(PodMoveEvent{
Time: time.Now(),
Namespace: pod.Namespace,
Pod: pod.Name,
FromNode: node,
ToNode: targetNode,
Reason: "node-utilization-imbalance",
})
grace := int64(0)
err = clientset.CoreV1().Pods(pod.Namespace).Delete(ctx, pod.Name, metav1.DeleteOptions{
GracePeriodSeconds: &grace,
})
if err != nil {
log.Println("Failed to delete pod", pod.Name, err)
return
}
nodeUsage[node]["cpu"] -= estimatePodCPU(&pod)
nodeUsage[node]["mem"] -= estimatePodMem(&pod)
nodeUsage[targetNode]["cpu"] += estimatePodCPU(&pod)
nodeUsage[targetNode]["mem"] += estimatePodMem(&pod)
return
}
}
}
//
// ─── HELPERS ────────────────────────────────────────────────────────────────────
//
func isDaemonSet(pod *corev1.Pod) bool {
for _, owner := range pod.OwnerReferences {
if owner.Kind == "DaemonSet" {
return true
}
}
return false
}
func pickTargetNode(nodes []string, usage map[string]map[string]int64, capacity map[string]map[string]int64) string {
var bestNode string
bestLoad := int64(1 << 62)
for _, n := range nodes {
cpuPercent := usage[n]["cpu"] * 100 / capacity[n]["cpu"]
memPercent := usage[n]["mem"] * 100 / capacity[n]["mem"]
load := cpuPercent + memPercent
if load < bestLoad {
bestLoad = load
bestNode = n
}
}
return bestNode
}
func estimatePodCPU(pod *corev1.Pod) int64 {
var cpu int64
for _, c := range pod.Spec.Containers {
if q, ok := c.Resources.Requests[corev1.ResourceCPU]; ok {
cpu += q.MilliValue()
}
}
return cpu
}
func estimatePodMem(pod *corev1.Pod) int64 {
var mem int64
for _, c := range pod.Spec.Containers {
if q, ok := c.Resources.Requests[corev1.ResourceMemory]; ok {
mem += q.Value() / (1024 * 1024)
}
}
return mem
}
+451
View File
@@ -0,0 +1,451 @@
package main
import (
"context"
"embed"
"encoding/json"
"fmt"
"log"
"net/http"
"os"
"strconv"
"sync"
"time"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
"k8s.io/apimachinery/pkg/types"
metricsv "k8s.io/metrics/pkg/client/clientset/versioned"
apierrors "k8s.io/apimachinery/pkg/api/errors"
)
//go:embed web/*
var webFS embed.FS
var (
CPUOverloadThreshold int64
MemoryOverloadThreshold int64
CPUUnderloadThreshold int64
MemoryUnderloadThreshold int64
PodEvictionInterval time.Duration
PodAnimationDuration time.Duration
)
func getEnvInt64(name string, defaultVal int64) int64 {
valStr := os.Getenv(name)
if valStr == "" {
return defaultVal
}
val, err := strconv.ParseInt(valStr, 10, 64)
if err != nil {
log.Printf("Invalid %s: %s, using default %d", name, valStr, defaultVal)
return defaultVal
}
return val
}
func getEnvSecondsDuration(name string, defaultSec int64) time.Duration {
valStr := os.Getenv(name)
if valStr == "" {
return time.Duration(defaultSec) * time.Second
}
sec, err := strconv.ParseInt(valStr, 10, 64)
if err != nil {
log.Printf("Invalid %s: %s, using default %d seconds", name, valStr, defaultSec)
return time.Duration(defaultSec) * time.Second
}
return time.Duration(sec) * time.Second
}
func init() {
CPUOverloadThreshold = getEnvInt64("CPU_OVERLOAD_THRESHOLD", 80)
MemoryOverloadThreshold = getEnvInt64("MEMORY_OVERLOAD_THRESHOLD", 80)
CPUUnderloadThreshold = getEnvInt64("CPU_UNDERLOAD_THRESHOLD", 50)
MemoryUnderloadThreshold = getEnvInt64("MEMORY_UNDERLOAD_THRESHOLD", 50)
PodEvictionInterval = getEnvSecondsDuration("POD_EVICTION_INTERVAL", 120) // default 2 min
PodAnimationDuration = getEnvSecondsDuration("POD_ANIMATION_DURATION", 2) // default 2 sec
}
type PodMoveEvent struct {
Time time.Time `json:"time"`
Namespace string `json:"namespace"`
Pod string `json:"pod"`
FromNode string `json:"fromNode"`
ToNode string `json:"toNode"`
Reason string `json:"reason"`
}
type EventBus struct {
mu sync.Mutex
history []PodMoveEvent
clients map[chan PodMoveEvent]struct{}
}
func NewEventBus() *EventBus {
return &EventBus{
history: make([]PodMoveEvent, 0, 100),
clients: make(map[chan PodMoveEvent]struct{}),
}
}
func (b *EventBus) Emit(evt PodMoveEvent) {
b.mu.Lock()
defer b.mu.Unlock()
if len(b.history) == 100 {
b.history = b.history[1:]
}
b.history = append(b.history, evt)
for ch := range b.clients {
select {
case ch <- evt:
default:
}
}
}
func (b *EventBus) History() []PodMoveEvent {
b.mu.Lock()
defer b.mu.Unlock()
out := make([]PodMoveEvent, len(b.history))
copy(out, b.history)
return out
}
func (b *EventBus) Subscribe() chan PodMoveEvent {
b.mu.Lock()
defer b.mu.Unlock()
ch := make(chan PodMoveEvent, 10)
b.clients[ch] = struct{}{}
return ch
}
func (b *EventBus) Unsubscribe(ch chan PodMoveEvent) {
b.mu.Lock()
defer b.mu.Unlock()
delete(b.clients, ch)
close(ch)
}
func main() {
config, err := rest.InClusterConfig()
if err != nil {
log.Fatal(err)
}
clientset, err := kubernetes.NewForConfig(config)
if err != nil {
log.Fatal(err)
}
metricsClient, err := metricsv.NewForConfig(config)
if err != nil {
log.Fatal(err)
}
eventBus := NewEventBus()
go startWebUI(eventBus, clientset)
for {
balanceNodes(clientset, metricsClient, eventBus)
time.Sleep(PodEvictionInterval)
}
}
func startWebUI(bus *EventBus, clientset *kubernetes.Clientset) {
mux := http.NewServeMux()
mux.Handle("/", http.FileServer(http.FS(webFS)))
mux.HandleFunc("/api/events", func(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(bus.History())
})
mux.HandleFunc("/api/stream", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/event-stream")
w.Header().Set("Cache-Control", "no-cache")
flusher, ok := w.(http.Flusher)
if !ok {
http.Error(w, "streaming unsupported", 500)
return
}
ch := bus.Subscribe()
defer bus.Unsubscribe(ch)
for {
select {
case evt := <-ch:
data, _ := json.Marshal(evt)
fmt.Fprintf(w, "data: %s\n\n", data)
flusher.Flush()
case <-r.Context().Done():
return
}
}
})
log.Println("WebUI listening on :8080")
mux.HandleFunc("/api/nodes", func(w http.ResponseWriter, r *http.Request) {
nodes, err := clientset.CoreV1().Nodes().List(context.Background(), metav1.ListOptions{})
if err != nil {
http.Error(w, "failed to list nodes", http.StatusInternalServerError)
return
}
names := []string{}
for _, n := range nodes.Items {
names = append(names, n.Name)
}
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(names)
})
mux.HandleFunc("/api/pods", func(w http.ResponseWriter, r *http.Request) {
ctx := context.Background()
pods, err := clientset.CoreV1().Pods("").List(ctx, metav1.ListOptions{})
if err != nil {
http.Error(w, "failed to list pods", http.StatusInternalServerError)
return
}
// group pods by node
podsByNode := map[string][]string{}
for _, pod := range pods.Items {
if pod.Spec.NodeName == "" {
continue
}
if _, ok := podsByNode[pod.Spec.NodeName]; !ok {
podsByNode[pod.Spec.NodeName] = []string{}
}
podsByNode[pod.Spec.NodeName] = append(podsByNode[pod.Spec.NodeName], pod.Name)
}
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(podsByNode)
})
mux.HandleFunc("/api/config", func(w http.ResponseWriter, r *http.Request) {
cfg := map[string]int64{
"animationDurationMs": PodAnimationDuration.Milliseconds(),
}
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(cfg)
})
_ = http.ListenAndServe(":8080", mux)
}
func balanceNodes(clientset *kubernetes.Clientset, metricsClient *metricsv.Clientset, bus *EventBus) {
ctx := context.Background()
nodeMetricsList, err := metricsClient.MetricsV1beta1().NodeMetricses().List(ctx, metav1.ListOptions{})
if err != nil {
log.Println("Failed to get node metrics:", err)
return
}
nodeUsage := make(map[string]map[string]int64)
for _, m := range nodeMetricsList.Items {
nodeUsage[m.Name] = map[string]int64{
"cpu": m.Usage.Cpu().MilliValue(),
"mem": m.Usage.Memory().Value() / (1024 * 1024),
}
}
nodes, err := clientset.CoreV1().Nodes().List(ctx, metav1.ListOptions{})
if err != nil {
log.Println("Failed to list nodes:", err)
return
}
nodeCapacity := make(map[string]map[string]int64)
for _, n := range nodes.Items {
nodeCapacity[n.Name] = map[string]int64{
"cpu": n.Status.Capacity.Cpu().MilliValue(),
"mem": n.Status.Capacity.Memory().Value() / (1024 * 1024),
}
}
var overloaded, underloaded []string
for node, usage := range nodeUsage {
cpuPercent := usage["cpu"] * 100 / nodeCapacity[node]["cpu"]
memPercent := usage["mem"] * 100 / nodeCapacity[node]["mem"]
if cpuPercent > CPUOverloadThreshold || memPercent > MemoryOverloadThreshold {
overloaded = append(overloaded, node)
} else if cpuPercent < CPUUnderloadThreshold && memPercent < MemoryUnderloadThreshold {
underloaded = append(underloaded, node)
}
}
fmt.Println("Overloaded nodes:", overloaded)
fmt.Println("Underloaded nodes:", underloaded)
if len(overloaded) == 0 || len(underloaded) == 0 {
return
}
for _, node := range overloaded {
pods, err := clientset.CoreV1().Pods("").List(ctx, metav1.ListOptions{
FieldSelector: fmt.Sprintf("spec.nodeName=%s", node),
})
if err != nil {
log.Println("Failed to list pods for node", node, err)
continue
}
for _, pod := range pods.Items {
if pod.Namespace == "kube-system" || isDaemonSet(&pod) {
continue
}
targetNode := pickTargetNode(underloaded, nodeUsage, nodeCapacity)
if targetNode == "" {
return
}
fmt.Printf("Rescheduling pod %s/%s from %s to %s\n", pod.Namespace, pod.Name, node, targetNode)
grace := int64(0)
err = clientset.CoreV1().Pods(pod.Namespace).Delete(ctx, pod.Name, metav1.DeleteOptions{
GracePeriodSeconds: &grace,
})
if err != nil {
log.Println("Failed to delete pod", pod.Name, err)
return
}
// Wait until pod is fully deleted
for {
_, err := clientset.CoreV1().Pods(pod.Namespace).Get(ctx, pod.Name, metav1.GetOptions{})
if apierrors.IsNotFound(err) {
fmt.Println("Pod deletion confirmed")
break
}
fmt.Printf("Waiting for pod %s/%s to terminate...\n", pod.Namespace, pod.Name)
time.Sleep(2 * time.Second)
}
// Wait for new pod from Deployment
var ownerUID types.UID
if len(pod.OwnerReferences) > 0 {
ownerUID = pod.OwnerReferences[0].UID
}
var newPod corev1.Pod
for {
pods, err := clientset.CoreV1().Pods(pod.Namespace).List(ctx, metav1.ListOptions{})
if err != nil {
log.Println("Failed to list pods:", err)
time.Sleep(2 * time.Second)
continue
}
found := false
for _, p := range pods.Items {
if p.Name == pod.Name {
continue
}
for _, ref := range p.OwnerReferences {
if ref.UID == ownerUID && p.Status.Phase == corev1.PodRunning {
newPod = p
found = true
break
}
}
if found {
break
}
}
if found {
fmt.Printf("✅ Pod %s successfully moved from %s to %s\n",
newPod.Name, node, newPod.Spec.NodeName)
break
}
fmt.Println("Waiting for replacement pod to be Running...")
time.Sleep(2 * time.Second)
}
// Update node usage after pod move
nodeUsage[node]["cpu"] -= estimatePodCPU(&pod)
nodeUsage[node]["mem"] -= estimatePodMem(&pod)
nodeUsage[targetNode]["cpu"] += estimatePodCPU(&pod)
nodeUsage[targetNode]["mem"] += estimatePodMem(&pod)
// Emit event for GUI
bus.Emit(PodMoveEvent{
Time: time.Now(),
Namespace: pod.Namespace,
Pod: newPod.Name,
FromNode: node,
ToNode: targetNode,
Reason: "node-utilization-imbalance",
})
// Only move one pod per invocation
return
}
}
}
//
// ─── HELPERS ────────────────────────────────────────────────────────────────────
//
func isDaemonSet(pod *corev1.Pod) bool {
for _, owner := range pod.OwnerReferences {
if owner.Kind == "DaemonSet" {
return true
}
}
return false
}
func pickTargetNode(nodes []string, usage map[string]map[string]int64, capacity map[string]map[string]int64) string {
var bestNode string
bestLoad := int64(1 << 62)
for _, n := range nodes {
cpuPercent := usage[n]["cpu"] * 100 / capacity[n]["cpu"]
memPercent := usage[n]["mem"] * 100 / capacity[n]["mem"]
load := cpuPercent + memPercent
if load < bestLoad {
bestLoad = load
bestNode = n
}
}
return bestNode
}
func estimatePodCPU(pod *corev1.Pod) int64 {
var cpu int64
for _, c := range pod.Spec.Containers {
if q, ok := c.Resources.Requests[corev1.ResourceCPU]; ok {
cpu += q.MilliValue()
}
}
return cpu
}
func estimatePodMem(pod *corev1.Pod) int64 {
var mem int64
for _, c := range pod.Spec.Containers {
if q, ok := c.Resources.Requests[corev1.ResourceMemory]; ok {
mem += q.Value() / (1024 * 1024)
}
}
return mem
}
+489
View File
@@ -0,0 +1,489 @@
package main
import (
"context"
"embed"
"encoding/json"
"fmt"
"log"
"net/http"
"os"
"strconv"
"sync"
"time"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
"k8s.io/apimachinery/pkg/types"
metricsv "k8s.io/metrics/pkg/client/clientset/versioned"
)
//go:embed web/*
var webFS embed.FS
var (
CPUOverloadThreshold int64
MemoryOverloadThreshold int64
CPUUnderloadThreshold int64
MemoryUnderloadThreshold int64
PodEvictionInterval time.Duration
PodAnimationDuration time.Duration
)
func getEnvInt64(name string, defaultVal int64) int64 {
valStr := os.Getenv(name)
if valStr == "" {
return defaultVal
}
val, err := strconv.ParseInt(valStr, 10, 64)
if err != nil {
log.Printf("Invalid %s: %s, using default %d", name, valStr, defaultVal)
return defaultVal
}
return val
}
func getEnvSecondsDuration(name string, defaultSec int64) time.Duration {
valStr := os.Getenv(name)
if valStr == "" {
return time.Duration(defaultSec) * time.Second
}
sec, err := strconv.ParseInt(valStr, 10, 64)
if err != nil {
log.Printf("Invalid %s: %s, using default %d seconds", name, valStr, defaultSec)
return time.Duration(defaultSec) * time.Second
}
return time.Duration(sec) * time.Second
}
func init() {
CPUOverloadThreshold = getEnvInt64("CPU_OVERLOAD_THRESHOLD", 80)
MemoryOverloadThreshold = getEnvInt64("MEMORY_OVERLOAD_THRESHOLD", 80)
CPUUnderloadThreshold = getEnvInt64("CPU_UNDERLOAD_THRESHOLD", 50)
MemoryUnderloadThreshold = getEnvInt64("MEMORY_UNDERLOAD_THRESHOLD", 50)
PodEvictionInterval = getEnvSecondsDuration("POD_EVICTION_INTERVAL", 120) // default 2 min
PodAnimationDuration = getEnvSecondsDuration("POD_ANIMATION_DURATION", 2) // default 2 sec
}
type PodMoveEvent struct {
Time time.Time `json:"time"`
Namespace string `json:"namespace"`
Pod string `json:"pod"`
FromNode string `json:"fromNode"`
ToNode string `json:"toNode"`
Reason string `json:"reason"`
}
type EventBus struct {
mu sync.Mutex
history []PodMoveEvent
clients map[chan PodMoveEvent]struct{}
}
func NewEventBus() *EventBus {
return &EventBus{
history: make([]PodMoveEvent, 0, 100),
clients: make(map[chan PodMoveEvent]struct{}),
}
}
func (b *EventBus) Emit(evt PodMoveEvent) {
b.mu.Lock()
defer b.mu.Unlock()
if len(b.history) == 100 {
b.history = b.history[1:]
}
b.history = append(b.history, evt)
for ch := range b.clients {
select {
case ch <- evt:
default:
}
}
}
func (b *EventBus) History() []PodMoveEvent {
b.mu.Lock()
defer b.mu.Unlock()
out := make([]PodMoveEvent, len(b.history))
copy(out, b.history)
return out
}
func (b *EventBus) Subscribe() chan PodMoveEvent {
b.mu.Lock()
defer b.mu.Unlock()
ch := make(chan PodMoveEvent, 10)
b.clients[ch] = struct{}{}
return ch
}
func (b *EventBus) Unsubscribe(ch chan PodMoveEvent) {
b.mu.Lock()
defer b.mu.Unlock()
delete(b.clients, ch)
close(ch)
}
func main() {
config, err := rest.InClusterConfig()
if err != nil {
log.Fatal(err)
}
clientset, err := kubernetes.NewForConfig(config)
if err != nil {
log.Fatal(err)
}
metricsClient, err := metricsv.NewForConfig(config)
if err != nil {
log.Fatal(err)
}
eventBus := NewEventBus()
go startWebUI(eventBus, clientset)
for {
balanceNodes(clientset, metricsClient, eventBus)
time.Sleep(PodEvictionInterval)
}
}
func startWebUI(bus *EventBus, clientset *kubernetes.Clientset) {
mux := http.NewServeMux()
mux.Handle("/", http.FileServer(http.FS(webFS)))
mux.HandleFunc("/api/events", func(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(bus.History())
})
mux.HandleFunc("/api/stream", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/event-stream")
w.Header().Set("Cache-Control", "no-cache")
flusher, ok := w.(http.Flusher)
if !ok {
http.Error(w, "streaming unsupported", 500)
return
}
ch := bus.Subscribe()
defer bus.Unsubscribe(ch)
for {
select {
case evt := <-ch:
data, _ := json.Marshal(evt)
fmt.Fprintf(w, "data: %s\n\n", data)
flusher.Flush()
case <-r.Context().Done():
return
}
}
})
log.Println("WebUI listening on :8080")
mux.HandleFunc("/api/nodes", func(w http.ResponseWriter, r *http.Request) {
nodes, err := clientset.CoreV1().Nodes().List(context.Background(), metav1.ListOptions{})
if err != nil {
http.Error(w, "failed to list nodes", http.StatusInternalServerError)
return
}
names := []string{}
for _, n := range nodes.Items {
names = append(names, n.Name)
}
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(names)
})
mux.HandleFunc("/api/pods", func(w http.ResponseWriter, r *http.Request) {
ctx := context.Background()
pods, err := clientset.CoreV1().Pods("").List(ctx, metav1.ListOptions{})
if err != nil {
http.Error(w, "failed to list pods", http.StatusInternalServerError)
return
}
// group pods by node
podsByNode := map[string][]string{}
for _, pod := range pods.Items {
if pod.Spec.NodeName == "" {
continue
}
if _, ok := podsByNode[pod.Spec.NodeName]; !ok {
podsByNode[pod.Spec.NodeName] = []string{}
}
podsByNode[pod.Spec.NodeName] = append(podsByNode[pod.Spec.NodeName], pod.Name)
}
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(podsByNode)
})
mux.HandleFunc("/api/config", func(w http.ResponseWriter, r *http.Request) {
cfg := map[string]int64{
"animationDurationMs": PodAnimationDuration.Milliseconds(),
}
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(cfg)
})
_ = http.ListenAndServe(":8080", mux)
}
func balanceNodes(clientset *kubernetes.Clientset, metricsClient *metricsv.Clientset, bus *EventBus) {
ctx := context.Background()
// --- get node metrics ---
nodeMetricsList, err := metricsClient.MetricsV1beta1().NodeMetricses().List(ctx, metav1.ListOptions{})
if err != nil {
log.Println("Failed to get node metrics:", err)
return
}
nodeUsage := make(map[string]map[string]int64)
for _, m := range nodeMetricsList.Items {
nodeUsage[m.Name] = map[string]int64{
"cpu": m.Usage.Cpu().MilliValue(),
"mem": m.Usage.Memory().Value() / (1024 * 1024),
}
}
// --- get node capacities ---
nodes, err := clientset.CoreV1().Nodes().List(ctx, metav1.ListOptions{})
if err != nil {
log.Println("Failed to list nodes:", err)
return
}
nodeCapacity := make(map[string]map[string]int64)
for _, n := range nodes.Items {
nodeCapacity[n.Name] = map[string]int64{
"cpu": n.Status.Capacity.Cpu().MilliValue(),
"mem": n.Status.Capacity.Memory().Value() / (1024 * 1024),
}
}
// --- find overloaded and underloaded nodes ---
var overloaded, underloaded []string
for node, usage := range nodeUsage {
cpuPercent := usage["cpu"] * 100 / nodeCapacity[node]["cpu"]
memPercent := usage["mem"] * 100 / nodeCapacity[node]["mem"]
if cpuPercent > CPUOverloadThreshold || memPercent > MemoryOverloadThreshold {
overloaded = append(overloaded, node)
} else if cpuPercent < CPUUnderloadThreshold && memPercent < MemoryUnderloadThreshold {
underloaded = append(underloaded, node)
}
}
fmt.Println("Overloaded nodes:", overloaded)
fmt.Println("Underloaded nodes:", underloaded)
if len(overloaded) == 0 || len(underloaded) == 0 {
return
}
// --- move pods from overloaded to underloaded ---
for _, node := range overloaded {
pods, err := clientset.CoreV1().Pods("").List(ctx, metav1.ListOptions{
FieldSelector: fmt.Sprintf("spec.nodeName=%s", node),
})
if err != nil {
log.Println("Failed to list pods for node", node, err)
continue
}
for _, pod := range pods.Items {
if pod.Namespace == "kube-system" || isDaemonSet(&pod) {
continue
}
// Skip pods not in Running state
if pod.Status.Phase != corev1.PodRunning {
continue
}
// --- choose target before deletion ---
targetNode := pickTargetNode(underloaded, nodeUsage, nodeCapacity)
if targetNode == "" {
// fallback: just skip this pod
continue
}
fmt.Printf("Rescheduling pod %s/%s from %s to %s\n", pod.Namespace, pod.Name, node, targetNode)
// --- cordon the node ---
if err := cordonNode(clientset, node); err != nil {
log.Println("Failed to cordon node", node, err)
continue
}
// --- delete pod immediately ---
grace := int64(0)
err = clientset.CoreV1().Pods(pod.Namespace).Delete(ctx, pod.Name, metav1.DeleteOptions{
GracePeriodSeconds: &grace,
})
if err != nil {
log.Println("Failed to delete pod", pod.Name, err)
_ = uncordonNode(clientset, node)
continue
}
// --- wait for new pod from deployment ---
var ownerUID types.UID
if len(pod.OwnerReferences) > 0 {
ownerUID = pod.OwnerReferences[0].UID
}
var newPod corev1.Pod
for {
podsList, err := clientset.CoreV1().Pods(pod.Namespace).List(ctx, metav1.ListOptions{})
if err != nil {
log.Println("Failed to list pods:", err)
time.Sleep(2 * time.Second)
continue
}
found := false
for _, p := range podsList.Items {
if p.Name == pod.Name {
continue
}
for _, ref := range p.OwnerReferences {
if ref.UID == ownerUID && p.Status.Phase == corev1.PodRunning {
newPod = p
found = true
break
}
}
if found {
break
}
}
if found {
break
}
fmt.Println("Waiting for replacement pod to be Running...")
time.Sleep(2 * time.Second)
}
// --- uncordon the node now that pod has moved ---
if err := uncordonNode(clientset, node); err != nil {
log.Println("Failed to uncordon node", node, err)
}
// --- update node usage safely ---
if nodeUsage[node] != nil {
nodeUsage[node]["cpu"] -= estimatePodCPU(&pod)
nodeUsage[node]["mem"] -= estimatePodMem(&pod)
}
if nodeUsage[newPod.Spec.NodeName] == nil {
nodeUsage[newPod.Spec.NodeName] = map[string]int64{"cpu": 0, "mem": 0}
}
nodeUsage[newPod.Spec.NodeName]["cpu"] += estimatePodCPU(&pod)
nodeUsage[newPod.Spec.NodeName]["mem"] += estimatePodMem(&pod)
// --- emit event for GUI ---
bus.Emit(PodMoveEvent{
Time: time.Now(),
Namespace: pod.Namespace,
Pod: newPod.Name,
FromNode: node,
ToNode: newPod.Spec.NodeName,
Reason: "node-utilization-imbalance",
})
// only move one pod per invocation
return
}
}
}
//
// ─── HELPERS ────────────────────────────────────────────────────────────────────
//
func cordonNode(clientset *kubernetes.Clientset, nodeName string) error {
ctx := context.Background()
node, err := clientset.CoreV1().Nodes().Get(ctx, nodeName, metav1.GetOptions{})
if err != nil {
return err
}
if node.Spec.Unschedulable {
return nil
}
node.Spec.Unschedulable = true
_, err = clientset.CoreV1().Nodes().Update(ctx, node, metav1.UpdateOptions{})
return err
}
func uncordonNode(clientset *kubernetes.Clientset, nodeName string) error {
ctx := context.Background()
node, err := clientset.CoreV1().Nodes().Get(ctx, nodeName, metav1.GetOptions{})
if err != nil {
return err
}
node.Spec.Unschedulable = false
_, err = clientset.CoreV1().Nodes().Update(ctx, node, metav1.UpdateOptions{})
return err
}
func isDaemonSet(pod *corev1.Pod) bool {
for _, owner := range pod.OwnerReferences {
if owner.Kind == "DaemonSet" {
return true
}
}
return false
}
func pickTargetNode(nodes []string, usage map[string]map[string]int64, capacity map[string]map[string]int64) string {
var bestNode string
bestLoad := int64(1 << 62)
for _, n := range nodes {
cpuPercent := usage[n]["cpu"] * 100 / capacity[n]["cpu"]
memPercent := usage[n]["mem"] * 100 / capacity[n]["mem"]
load := cpuPercent + memPercent
if load < bestLoad {
bestLoad = load
bestNode = n
}
}
return bestNode
}
func estimatePodCPU(pod *corev1.Pod) int64 {
var cpu int64
for _, c := range pod.Spec.Containers {
if q, ok := c.Resources.Requests[corev1.ResourceCPU]; ok {
cpu += q.MilliValue()
}
}
return cpu
}
func estimatePodMem(pod *corev1.Pod) int64 {
var mem int64
for _, c := range pod.Spec.Containers {
if q, ok := c.Resources.Requests[corev1.ResourceMemory]; ok {
mem += q.Value() / (1024 * 1024)
}
}
return mem
}
+489
View File
@@ -0,0 +1,489 @@
package main
import (
"context"
"embed"
"encoding/json"
"fmt"
"log"
"net/http"
"os"
"strconv"
"sync"
"time"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
"k8s.io/apimachinery/pkg/types"
metricsv "k8s.io/metrics/pkg/client/clientset/versioned"
)
//go:embed web/*
var webFS embed.FS
var (
CPUOverloadThreshold int64
MemoryOverloadThreshold int64
CPUUnderloadThreshold int64
MemoryUnderloadThreshold int64
PodEvictionInterval time.Duration
PodAnimationDuration time.Duration
)
func getEnvInt64(name string, defaultVal int64) int64 {
valStr := os.Getenv(name)
if valStr == "" {
return defaultVal
}
val, err := strconv.ParseInt(valStr, 10, 64)
if err != nil {
log.Printf("Invalid %s: %s, using default %d", name, valStr, defaultVal)
return defaultVal
}
return val
}
func getEnvSecondsDuration(name string, defaultSec int64) time.Duration {
valStr := os.Getenv(name)
if valStr == "" {
return time.Duration(defaultSec) * time.Second
}
sec, err := strconv.ParseInt(valStr, 10, 64)
if err != nil {
log.Printf("Invalid %s: %s, using default %d seconds", name, valStr, defaultSec)
return time.Duration(defaultSec) * time.Second
}
return time.Duration(sec) * time.Second
}
func init() {
CPUOverloadThreshold = getEnvInt64("CPU_OVERLOAD_THRESHOLD", 80)
MemoryOverloadThreshold = getEnvInt64("MEMORY_OVERLOAD_THRESHOLD", 80)
CPUUnderloadThreshold = getEnvInt64("CPU_UNDERLOAD_THRESHOLD", 50)
MemoryUnderloadThreshold = getEnvInt64("MEMORY_UNDERLOAD_THRESHOLD", 50)
PodEvictionInterval = getEnvSecondsDuration("POD_EVICTION_INTERVAL", 120) // default 2 min
PodAnimationDuration = getEnvSecondsDuration("POD_ANIMATION_DURATION", 2) // default 2 sec
}
type PodMoveEvent struct {
Time time.Time `json:"time"`
Namespace string `json:"namespace"`
Pod string `json:"pod"`
FromNode string `json:"fromNode"`
ToNode string `json:"toNode"`
Reason string `json:"reason"`
}
type EventBus struct {
mu sync.Mutex
history []PodMoveEvent
clients map[chan PodMoveEvent]struct{}
}
func NewEventBus() *EventBus {
return &EventBus{
history: make([]PodMoveEvent, 0, 100),
clients: make(map[chan PodMoveEvent]struct{}),
}
}
func (b *EventBus) Emit(evt PodMoveEvent) {
b.mu.Lock()
defer b.mu.Unlock()
if len(b.history) == 100 {
b.history = b.history[1:]
}
b.history = append(b.history, evt)
for ch := range b.clients {
select {
case ch <- evt:
default:
}
}
}
func (b *EventBus) History() []PodMoveEvent {
b.mu.Lock()
defer b.mu.Unlock()
out := make([]PodMoveEvent, len(b.history))
copy(out, b.history)
return out
}
func (b *EventBus) Subscribe() chan PodMoveEvent {
b.mu.Lock()
defer b.mu.Unlock()
ch := make(chan PodMoveEvent, 10)
b.clients[ch] = struct{}{}
return ch
}
func (b *EventBus) Unsubscribe(ch chan PodMoveEvent) {
b.mu.Lock()
defer b.mu.Unlock()
delete(b.clients, ch)
close(ch)
}
func main() {
config, err := rest.InClusterConfig()
if err != nil {
log.Fatal(err)
}
clientset, err := kubernetes.NewForConfig(config)
if err != nil {
log.Fatal(err)
}
metricsClient, err := metricsv.NewForConfig(config)
if err != nil {
log.Fatal(err)
}
eventBus := NewEventBus()
go startWebUI(eventBus, clientset)
for {
balanceNodes(clientset, metricsClient, eventBus)
time.Sleep(PodEvictionInterval)
}
}
func startWebUI(bus *EventBus, clientset *kubernetes.Clientset) {
mux := http.NewServeMux()
mux.Handle("/", http.FileServer(http.FS(webFS)))
mux.HandleFunc("/api/events", func(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(bus.History())
})
mux.HandleFunc("/api/stream", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/event-stream")
w.Header().Set("Cache-Control", "no-cache")
flusher, ok := w.(http.Flusher)
if !ok {
http.Error(w, "streaming unsupported", 500)
return
}
ch := bus.Subscribe()
defer bus.Unsubscribe(ch)
for {
select {
case evt := <-ch:
data, _ := json.Marshal(evt)
fmt.Fprintf(w, "data: %s\n\n", data)
flusher.Flush()
case <-r.Context().Done():
return
}
}
})
log.Println("WebUI listening on :8080")
mux.HandleFunc("/api/nodes", func(w http.ResponseWriter, r *http.Request) {
nodes, err := clientset.CoreV1().Nodes().List(context.Background(), metav1.ListOptions{})
if err != nil {
http.Error(w, "failed to list nodes", http.StatusInternalServerError)
return
}
names := []string{}
for _, n := range nodes.Items {
names = append(names, n.Name)
}
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(names)
})
mux.HandleFunc("/api/pods", func(w http.ResponseWriter, r *http.Request) {
ctx := context.Background()
pods, err := clientset.CoreV1().Pods("").List(ctx, metav1.ListOptions{})
if err != nil {
http.Error(w, "failed to list pods", http.StatusInternalServerError)
return
}
// group pods by node
podsByNode := map[string][]string{}
for _, pod := range pods.Items {
if pod.Spec.NodeName == "" {
continue
}
if _, ok := podsByNode[pod.Spec.NodeName]; !ok {
podsByNode[pod.Spec.NodeName] = []string{}
}
podsByNode[pod.Spec.NodeName] = append(podsByNode[pod.Spec.NodeName], pod.Name)
}
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(podsByNode)
})
mux.HandleFunc("/api/config", func(w http.ResponseWriter, r *http.Request) {
cfg := map[string]int64{
"animationDurationMs": PodAnimationDuration.Milliseconds(),
}
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(cfg)
})
_ = http.ListenAndServe(":8080", mux)
}
func balanceNodes(clientset *kubernetes.Clientset, metricsClient *metricsv.Clientset, bus *EventBus) {
ctx := context.Background()
// --- get node metrics ---
nodeMetricsList, err := metricsClient.MetricsV1beta1().NodeMetricses().List(ctx, metav1.ListOptions{})
if err != nil {
log.Println("Failed to get node metrics:", err)
return
}
nodeUsage := make(map[string]map[string]int64)
for _, m := range nodeMetricsList.Items {
nodeUsage[m.Name] = map[string]int64{
"cpu": m.Usage.Cpu().MilliValue(),
"mem": m.Usage.Memory().Value() / (1024 * 1024),
}
}
// --- get node capacities ---
nodes, err := clientset.CoreV1().Nodes().List(ctx, metav1.ListOptions{})
if err != nil {
log.Println("Failed to list nodes:", err)
return
}
nodeCapacity := make(map[string]map[string]int64)
for _, n := range nodes.Items {
nodeCapacity[n.Name] = map[string]int64{
"cpu": n.Status.Capacity.Cpu().MilliValue(),
"mem": n.Status.Capacity.Memory().Value() / (1024 * 1024),
}
}
// --- find overloaded and underloaded nodes ---
var overloaded, underloaded []string
for node, usage := range nodeUsage {
cpuPercent := usage["cpu"] * 100 / nodeCapacity[node]["cpu"]
memPercent := usage["mem"] * 100 / nodeCapacity[node]["mem"]
if cpuPercent > CPUOverloadThreshold || memPercent > MemoryOverloadThreshold {
overloaded = append(overloaded, node)
} else if cpuPercent < CPUUnderloadThreshold && memPercent < MemoryUnderloadThreshold {
underloaded = append(underloaded, node)
}
}
fmt.Println("Overloaded nodes:", overloaded)
fmt.Println("Underloaded nodes:", underloaded)
if len(overloaded) == 0 || len(underloaded) == 0 {
return
}
// --- move pods from overloaded to underloaded ---
for _, node := range overloaded {
pods, err := clientset.CoreV1().Pods("").List(ctx, metav1.ListOptions{
FieldSelector: fmt.Sprintf("spec.nodeName=%s", node),
})
if err != nil {
log.Println("Failed to list pods for node", node, err)
continue
}
for _, pod := range pods.Items {
if pod.Namespace == "kube-system" || isDaemonSet(&pod) {
continue
}
// Skip pods not in Running state
if pod.Status.Phase != corev1.PodRunning {
continue
}
// --- choose target before deletion ---
targetNode := pickTargetNode(underloaded, nodeUsage, nodeCapacity)
if targetNode == "" {
// fallback: just skip this pod
continue
}
fmt.Printf("Rescheduling pod %s/%s from %s to %s\n", pod.Namespace, pod.Name, node, targetNode)
// --- cordon the node ---
if err := cordonNode(clientset, node); err != nil {
log.Println("Failed to cordon node", node, err)
continue
}
// --- delete pod immediately ---
grace := int64(0)
err = clientset.CoreV1().Pods(pod.Namespace).Delete(ctx, pod.Name, metav1.DeleteOptions{
GracePeriodSeconds: &grace,
})
if err != nil {
log.Println("Failed to delete pod", pod.Name, err)
_ = uncordonNode(clientset, node)
continue
}
// --- wait for new pod from deployment ---
var ownerUID types.UID
if len(pod.OwnerReferences) > 0 {
ownerUID = pod.OwnerReferences[0].UID
}
var newPod corev1.Pod
for {
podsList, err := clientset.CoreV1().Pods(pod.Namespace).List(ctx, metav1.ListOptions{})
if err != nil {
log.Println("Failed to list pods:", err)
time.Sleep(2 * time.Second)
continue
}
found := true
for _, p := range podsList.Items {
if p.Name == pod.Name {
continue
}
for _, ref := range p.OwnerReferences {
if ref.UID == ownerUID && p.Status.Phase == corev1.PodRunning {
newPod = p
found = true
break
}
}
if found {
break
}
}
if found {
break
}
fmt.Println("Waiting for replacement pod to be Running...")
time.Sleep(2 * time.Second)
}
// --- uncordon the node now that pod has moved ---
if err := uncordonNode(clientset, node); err != nil {
log.Println("Failed to uncordon node", node, err)
}
// --- update node usage safely ---
if nodeUsage[node] != nil {
nodeUsage[node]["cpu"] -= estimatePodCPU(&pod)
nodeUsage[node]["mem"] -= estimatePodMem(&pod)
}
if nodeUsage[newPod.Spec.NodeName] == nil {
nodeUsage[newPod.Spec.NodeName] = map[string]int64{"cpu": 0, "mem": 0}
}
nodeUsage[newPod.Spec.NodeName]["cpu"] += estimatePodCPU(&pod)
nodeUsage[newPod.Spec.NodeName]["mem"] += estimatePodMem(&pod)
// --- emit event for GUI ---
bus.Emit(PodMoveEvent{
Time: time.Now(),
Namespace: pod.Namespace,
Pod: newPod.Name,
FromNode: node,
ToNode: newPod.Spec.NodeName,
Reason: "node-utilization-imbalance",
})
// only move one pod per invocation
return
}
}
}
//
// ─── HELPERS ────────────────────────────────────────────────────────────────────
//
func cordonNode(clientset *kubernetes.Clientset, nodeName string) error {
ctx := context.Background()
node, err := clientset.CoreV1().Nodes().Get(ctx, nodeName, metav1.GetOptions{})
if err != nil {
return err
}
if node.Spec.Unschedulable {
return nil
}
node.Spec.Unschedulable = true
_, err = clientset.CoreV1().Nodes().Update(ctx, node, metav1.UpdateOptions{})
return err
}
func uncordonNode(clientset *kubernetes.Clientset, nodeName string) error {
ctx := context.Background()
node, err := clientset.CoreV1().Nodes().Get(ctx, nodeName, metav1.GetOptions{})
if err != nil {
return err
}
node.Spec.Unschedulable = false
_, err = clientset.CoreV1().Nodes().Update(ctx, node, metav1.UpdateOptions{})
return err
}
func isDaemonSet(pod *corev1.Pod) bool {
for _, owner := range pod.OwnerReferences {
if owner.Kind == "DaemonSet" {
return true
}
}
return false
}
func pickTargetNode(nodes []string, usage map[string]map[string]int64, capacity map[string]map[string]int64) string {
var bestNode string
bestLoad := int64(1 << 62)
for _, n := range nodes {
cpuPercent := usage[n]["cpu"] * 100 / capacity[n]["cpu"]
memPercent := usage[n]["mem"] * 100 / capacity[n]["mem"]
load := cpuPercent + memPercent
if load < bestLoad {
bestLoad = load
bestNode = n
}
}
return bestNode
}
func estimatePodCPU(pod *corev1.Pod) int64 {
var cpu int64
for _, c := range pod.Spec.Containers {
if q, ok := c.Resources.Requests[corev1.ResourceCPU]; ok {
cpu += q.MilliValue()
}
}
return cpu
}
func estimatePodMem(pod *corev1.Pod) int64 {
var mem int64
for _, c := range pod.Spec.Containers {
if q, ok := c.Resources.Requests[corev1.ResourceMemory]; ok {
mem += q.Value() / (1024 * 1024)
}
}
return mem
}
+483
View File
@@ -0,0 +1,483 @@
package main
import (
"context"
"encoding/json"
"fmt"
"log"
"net/http"
"os"
"strconv"
"sync"
"time"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
"k8s.io/apimachinery/pkg/types"
metricsv "k8s.io/metrics/pkg/client/clientset/versioned"
)
var (
CPUOverloadThreshold int64
MemoryOverloadThreshold int64
CPUUnderloadThreshold int64
MemoryUnderloadThreshold int64
PodEvictionInterval time.Duration
PodAnimationDuration time.Duration
)
func getEnvInt64(name string, defaultVal int64) int64 {
valStr := os.Getenv(name)
if valStr == "" {
return defaultVal
}
val, err := strconv.ParseInt(valStr, 10, 64)
if err != nil {
log.Printf("Invalid %s: %s, using default %d", name, valStr, defaultVal)
return defaultVal
}
return val
}
func getEnvSecondsDuration(name string, defaultSec int64) time.Duration {
valStr := os.Getenv(name)
if valStr == "" {
return time.Duration(defaultSec) * time.Second
}
sec, err := strconv.ParseInt(valStr, 10, 64)
if err != nil {
log.Printf("Invalid %s: %s, using default %d seconds", name, valStr, defaultSec)
return time.Duration(defaultSec) * time.Second
}
return time.Duration(sec) * time.Second
}
func init() {
CPUOverloadThreshold = getEnvInt64("CPU_OVERLOAD_THRESHOLD", 80)
MemoryOverloadThreshold = getEnvInt64("MEMORY_OVERLOAD_THRESHOLD", 80)
CPUUnderloadThreshold = getEnvInt64("CPU_UNDERLOAD_THRESHOLD", 50)
MemoryUnderloadThreshold = getEnvInt64("MEMORY_UNDERLOAD_THRESHOLD", 50)
PodEvictionInterval = getEnvSecondsDuration("POD_EVICTION_INTERVAL", 120) // default 2 min
PodAnimationDuration = getEnvSecondsDuration("POD_ANIMATION_DURATION", 2) // default 2 sec
}
type PodMoveEvent struct {
Time time.Time `json:"time"`
Namespace string `json:"namespace"`
Pod string `json:"pod"`
FromNode string `json:"fromNode"`
ToNode string `json:"toNode"`
Reason string `json:"reason"`
}
type EventBus struct {
mu sync.Mutex
history []PodMoveEvent
clients map[chan PodMoveEvent]struct{}
}
func NewEventBus() *EventBus {
return &EventBus{
history: make([]PodMoveEvent, 0, 100),
clients: make(map[chan PodMoveEvent]struct{}),
}
}
func (b *EventBus) Emit(evt PodMoveEvent) {
b.mu.Lock()
defer b.mu.Unlock()
if len(b.history) == 100 {
b.history = b.history[1:]
}
b.history = append(b.history, evt)
for ch := range b.clients {
select {
case ch <- evt:
default:
}
}
}
func (b *EventBus) History() []PodMoveEvent {
b.mu.Lock()
defer b.mu.Unlock()
out := make([]PodMoveEvent, len(b.history))
copy(out, b.history)
return out
}
func (b *EventBus) Subscribe() chan PodMoveEvent {
b.mu.Lock()
defer b.mu.Unlock()
ch := make(chan PodMoveEvent, 10)
b.clients[ch] = struct{}{}
return ch
}
func (b *EventBus) Unsubscribe(ch chan PodMoveEvent) {
b.mu.Lock()
defer b.mu.Unlock()
delete(b.clients, ch)
close(ch)
}
func main() {
config, err := rest.InClusterConfig()
if err != nil {
log.Fatal(err)
}
clientset, err := kubernetes.NewForConfig(config)
if err != nil {
log.Fatal(err)
}
metricsClient, err := metricsv.NewForConfig(config)
if err != nil {
log.Fatal(err)
}
eventBus := NewEventBus()
go startWebUI(eventBus, clientset)
for {
balanceNodes(clientset, metricsClient, eventBus)
time.Sleep(PodEvictionInterval)
}
}
func startWebUI(bus *EventBus, clientset *kubernetes.Clientset) {
mux := http.NewServeMux()
mux.Handle("/", http.FileServer(http.Dir("/web")))
mux.HandleFunc("/api/events", func(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(bus.History())
})
mux.HandleFunc("/api/stream", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/event-stream")
w.Header().Set("Cache-Control", "no-cache")
flusher, ok := w.(http.Flusher)
if !ok {
http.Error(w, "streaming unsupported", 500)
return
}
ch := bus.Subscribe()
defer bus.Unsubscribe(ch)
for {
select {
case evt := <-ch:
data, _ := json.Marshal(evt)
fmt.Fprintf(w, "data: %s\n\n", data)
flusher.Flush()
case <-r.Context().Done():
return
}
}
})
log.Println("WebUI listening on :8080")
mux.HandleFunc("/api/nodes", func(w http.ResponseWriter, r *http.Request) {
nodes, err := clientset.CoreV1().Nodes().List(context.Background(), metav1.ListOptions{})
if err != nil {
http.Error(w, "failed to list nodes", http.StatusInternalServerError)
return
}
names := []string{}
for _, n := range nodes.Items {
names = append(names, n.Name)
}
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(names)
})
mux.HandleFunc("/api/pods", func(w http.ResponseWriter, r *http.Request) {
ctx := context.Background()
pods, err := clientset.CoreV1().Pods("").List(ctx, metav1.ListOptions{})
if err != nil {
http.Error(w, "failed to list pods", http.StatusInternalServerError)
return
}
// group pods by node
podsByNode := map[string][]string{}
for _, pod := range pods.Items {
if pod.Spec.NodeName == "" {
continue
}
if _, ok := podsByNode[pod.Spec.NodeName]; !ok {
podsByNode[pod.Spec.NodeName] = []string{}
}
podsByNode[pod.Spec.NodeName] = append(podsByNode[pod.Spec.NodeName], pod.Name)
}
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(podsByNode)
})
mux.HandleFunc("/api/config", func(w http.ResponseWriter, r *http.Request) {
cfg := map[string]int64{
"animationDurationMs": PodAnimationDuration.Milliseconds(),
}
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(cfg)
})
_ = http.ListenAndServe(":8080", mux)
}
func balanceNodes(clientset *kubernetes.Clientset, metricsClient *metricsv.Clientset, bus *EventBus) {
ctx := context.Background()
// --- get node metrics ---
nodeMetricsList, err := metricsClient.MetricsV1beta1().NodeMetricses().List(ctx, metav1.ListOptions{})
if err != nil {
log.Println("Failed to get node metrics:", err)
return
}
nodeUsage := make(map[string]map[string]int64)
for _, m := range nodeMetricsList.Items {
nodeUsage[m.Name] = map[string]int64{
"cpu": m.Usage.Cpu().MilliValue(),
"mem": m.Usage.Memory().Value() / (1024 * 1024),
}
}
// --- get node capacities ---
nodes, err := clientset.CoreV1().Nodes().List(ctx, metav1.ListOptions{})
if err != nil {
log.Println("Failed to list nodes:", err)
return
}
nodeCapacity := make(map[string]map[string]int64)
for _, n := range nodes.Items {
nodeCapacity[n.Name] = map[string]int64{
"cpu": n.Status.Capacity.Cpu().MilliValue(),
"mem": n.Status.Capacity.Memory().Value() / (1024 * 1024),
}
}
// --- find overloaded and underloaded nodes ---
var overloaded, underloaded []string
for node, usage := range nodeUsage {
cpuPercent := usage["cpu"] * 100 / nodeCapacity[node]["cpu"]
memPercent := usage["mem"] * 100 / nodeCapacity[node]["mem"]
if cpuPercent > CPUOverloadThreshold || memPercent > MemoryOverloadThreshold {
overloaded = append(overloaded, node)
} else if cpuPercent < CPUUnderloadThreshold && memPercent < MemoryUnderloadThreshold {
underloaded = append(underloaded, node)
}
}
fmt.Println("Overloaded nodes:", overloaded)
fmt.Println("Underloaded nodes:", underloaded)
if len(overloaded) == 0 || len(underloaded) == 0 {
return
}
// --- move pods from overloaded to underloaded ---
for _, node := range overloaded {
pods, err := clientset.CoreV1().Pods("").List(ctx, metav1.ListOptions{
FieldSelector: fmt.Sprintf("spec.nodeName=%s", node),
})
if err != nil {
log.Println("Failed to list pods for node", node, err)
continue
}
for _, pod := range pods.Items {
if pod.Namespace == "kube-system" || isDaemonSet(&pod) {
continue
}
// Skip pods not in Running state
if pod.Status.Phase != corev1.PodRunning {
continue
}
// --- choose target before deletion ---
targetNode := pickTargetNode(underloaded, nodeUsage, nodeCapacity)
if targetNode == "" {
// fallback: just skip this pod
continue
}
fmt.Printf("Rescheduling pod %s/%s from %s to %s\n", pod.Namespace, pod.Name, node, targetNode)
// --- cordon the node ---
if err := cordonNode(clientset, node); err != nil {
log.Println("Failed to cordon node", node, err)
continue
}
// --- delete pod immediately ---
grace := int64(0)
err = clientset.CoreV1().Pods(pod.Namespace).Delete(ctx, pod.Name, metav1.DeleteOptions{
GracePeriodSeconds: &grace,
})
if err != nil {
log.Println("Failed to delete pod", pod.Name, err)
_ = uncordonNode(clientset, node)
continue
}
// --- wait for new pod from deployment ---
var ownerUID types.UID
if len(pod.OwnerReferences) > 0 {
ownerUID = pod.OwnerReferences[0].UID
}
var newPod corev1.Pod
for {
podsList, err := clientset.CoreV1().Pods(pod.Namespace).List(ctx, metav1.ListOptions{})
if err != nil {
log.Println("Failed to list pods:", err)
time.Sleep(2 * time.Second)
continue
}
found := true
for _, p := range podsList.Items {
if p.Name == pod.Name {
continue
}
for _, ref := range p.OwnerReferences {
if ref.UID == ownerUID && p.Status.Phase == corev1.PodRunning {
newPod = p
found = true
break
}
}
if found {
break
}
}
if found {
break
}
fmt.Println("Waiting for replacement pod to be Running...")
time.Sleep(2 * time.Second)
}
// --- uncordon the node now that pod has moved ---
if err := uncordonNode(clientset, node); err != nil {
log.Println("Failed to uncordon node", node, err)
}
// --- update node usage safely ---
if nodeUsage[node] != nil {
nodeUsage[node]["cpu"] -= estimatePodCPU(&pod)
nodeUsage[node]["mem"] -= estimatePodMem(&pod)
}
if nodeUsage[newPod.Spec.NodeName] == nil {
nodeUsage[newPod.Spec.NodeName] = map[string]int64{"cpu": 0, "mem": 0}
}
nodeUsage[newPod.Spec.NodeName]["cpu"] += estimatePodCPU(&pod)
nodeUsage[newPod.Spec.NodeName]["mem"] += estimatePodMem(&pod)
// --- emit event for GUI ---
bus.Emit(PodMoveEvent{
Time: time.Now(),
Namespace: pod.Namespace,
Pod: newPod.Name,
FromNode: node,
ToNode: newPod.Spec.NodeName,
Reason: "node-utilization-imbalance",
})
// only move one pod per invocation
return
}
}
}
//
// ─── HELPERS ────────────────────────────────────────────────────────────────────
//
func cordonNode(clientset *kubernetes.Clientset, nodeName string) error {
ctx := context.Background()
node, err := clientset.CoreV1().Nodes().Get(ctx, nodeName, metav1.GetOptions{})
if err != nil {
return err
}
if node.Spec.Unschedulable {
return nil
}
node.Spec.Unschedulable = true
_, err = clientset.CoreV1().Nodes().Update(ctx, node, metav1.UpdateOptions{})
return err
}
func uncordonNode(clientset *kubernetes.Clientset, nodeName string) error {
ctx := context.Background()
node, err := clientset.CoreV1().Nodes().Get(ctx, nodeName, metav1.GetOptions{})
if err != nil {
return err
}
node.Spec.Unschedulable = false
_, err = clientset.CoreV1().Nodes().Update(ctx, node, metav1.UpdateOptions{})
return err
}
func isDaemonSet(pod *corev1.Pod) bool {
for _, owner := range pod.OwnerReferences {
if owner.Kind == "DaemonSet" {
return true
}
}
return false
}
func pickTargetNode(nodes []string, usage map[string]map[string]int64, capacity map[string]map[string]int64) string {
var bestNode string
bestLoad := int64(1 << 62)
for _, n := range nodes {
cpuPercent := usage[n]["cpu"] * 100 / capacity[n]["cpu"]
memPercent := usage[n]["mem"] * 100 / capacity[n]["mem"]
load := cpuPercent + memPercent
if load < bestLoad {
bestLoad = load
bestNode = n
}
}
return bestNode
}
func estimatePodCPU(pod *corev1.Pod) int64 {
var cpu int64
for _, c := range pod.Spec.Containers {
if q, ok := c.Resources.Requests[corev1.ResourceCPU]; ok {
cpu += q.MilliValue()
}
}
return cpu
}
func estimatePodMem(pod *corev1.Pod) int64 {
var mem int64
for _, c := range pod.Spec.Containers {
if q, ok := c.Resources.Requests[corev1.ResourceMemory]; ok {
mem += q.Value() / (1024 * 1024)
}
}
return mem
}
+562
View File
@@ -0,0 +1,562 @@
package main
import (
"context"
"encoding/json"
"fmt"
"log"
"net/http"
"os"
"strconv"
"sync"
"time"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
"k8s.io/apimachinery/pkg/types"
metricsv "k8s.io/metrics/pkg/client/clientset/versioned"
)
var (
CPUOverloadThreshold int64
MemoryOverloadThreshold int64
CPUUnderloadThreshold int64
MemoryUnderloadThreshold int64
PodEvictionInterval time.Duration
PodAnimationDuration time.Duration
PodRespawnTimeout time.Duration
)
func getEnvInt64(name string, defaultVal int64) int64 {
valStr := os.Getenv(name)
if valStr == "" {
return defaultVal
}
val, err := strconv.ParseInt(valStr, 10, 64)
if err != nil {
log.Printf("Invalid %s: %s, using default %d", name, valStr, defaultVal)
return defaultVal
}
return val
}
func getEnvSecondsDuration(name string, defaultSec int64) time.Duration {
valStr := os.Getenv(name)
if valStr == "" {
return time.Duration(defaultSec) * time.Second
}
sec, err := strconv.ParseInt(valStr, 10, 64)
if err != nil {
log.Printf("Invalid %s: %s, using default %d seconds", name, valStr, defaultSec)
return time.Duration(defaultSec) * time.Second
}
return time.Duration(sec) * time.Second
}
func init() {
CPUOverloadThreshold = getEnvInt64("CPU_OVERLOAD_THRESHOLD", 80)
MemoryOverloadThreshold = getEnvInt64("MEMORY_OVERLOAD_THRESHOLD", 80)
CPUUnderloadThreshold = getEnvInt64("CPU_UNDERLOAD_THRESHOLD", 50)
MemoryUnderloadThreshold = getEnvInt64("MEMORY_UNDERLOAD_THRESHOLD", 50)
PodEvictionInterval = getEnvSecondsDuration("POD_EVICTION_INTERVAL", 30)
PodAnimationDuration = getEnvSecondsDuration("POD_ANIMATION_DURATION", 2)
PodRespawnTimeout = getEnvSecondsDuration("POD_RESPAWN_TIMEOUT", 60)
log.Println("──────────── CONFIG ────────────")
log.Printf("CPU_OVERLOAD_THRESHOLD = %d%%", CPUOverloadThreshold)
log.Printf("MEMORY_OVERLOAD_THRESHOLD = %d%%", MemoryOverloadThreshold)
log.Printf("CPU_UNDERLOAD_THRESHOLD = %d%%", CPUUnderloadThreshold)
log.Printf("MEMORY_UNDERLOAD_THRESHOLD = %d%%", MemoryUnderloadThreshold)
log.Printf("POD_EVICTION_INTERVAL = %v", PodEvictionInterval)
log.Printf("POD_ANIMATION_DURATION = %v", PodAnimationDuration)
log.Printf("POD_RESPAWN_TIMEOUT = %v", PodRespawnTimeout)
log.Println("───────────────────────────────")
}
type PodMoveEvent struct {
Time time.Time `json:"time"`
Namespace string `json:"namespace"`
Pod string `json:"pod"`
FromNode string `json:"fromNode"`
ToNode string `json:"toNode"`
Reason string `json:"reason"`
}
type EventBus struct {
mu sync.Mutex
history []PodMoveEvent
clients map[chan PodMoveEvent]struct{}
}
func NewEventBus() *EventBus {
return &EventBus{
history: make([]PodMoveEvent, 0, 100),
clients: make(map[chan PodMoveEvent]struct{}),
}
}
func (b *EventBus) Emit(evt PodMoveEvent) {
b.mu.Lock()
defer b.mu.Unlock()
if len(b.history) == 100 {
b.history = b.history[1:]
}
b.history = append(b.history, evt)
for ch := range b.clients {
select {
case ch <- evt:
default:
}
}
}
func (b *EventBus) History() []PodMoveEvent {
b.mu.Lock()
defer b.mu.Unlock()
out := make([]PodMoveEvent, len(b.history))
copy(out, b.history)
return out
}
func (b *EventBus) Subscribe() chan PodMoveEvent {
b.mu.Lock()
defer b.mu.Unlock()
ch := make(chan PodMoveEvent, 10)
b.clients[ch] = struct{}{}
return ch
}
func (b *EventBus) Unsubscribe(ch chan PodMoveEvent) {
b.mu.Lock()
defer b.mu.Unlock()
delete(b.clients, ch)
close(ch)
}
func main() {
config, err := rest.InClusterConfig()
if err != nil {
log.Fatal(err)
}
clientset, err := kubernetes.NewForConfig(config)
if err != nil {
log.Fatal(err)
}
metricsClient, err := metricsv.NewForConfig(config)
if err != nil {
log.Fatal(err)
}
eventBus := NewEventBus()
go startWebUI(eventBus, clientset)
for {
balanceNodes(clientset, metricsClient, eventBus)
time.Sleep(PodEvictionInterval)
}
}
func startWebUI(bus *EventBus, clientset *kubernetes.Clientset) {
mux := http.NewServeMux()
mux.Handle("/", http.FileServer(http.Dir("/web")))
mux.HandleFunc("/api/events", func(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(bus.History())
})
mux.HandleFunc("/api/stream", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/event-stream")
w.Header().Set("Cache-Control", "no-cache")
flusher, ok := w.(http.Flusher)
if !ok {
http.Error(w, "streaming unsupported", 500)
return
}
ch := bus.Subscribe()
defer bus.Unsubscribe(ch)
for {
select {
case evt := <-ch:
data, _ := json.Marshal(evt)
fmt.Fprintf(w, "data: %s\n\n", data)
flusher.Flush()
case <-r.Context().Done():
return
}
}
})
log.Println("WebUI listening on :8080")
mux.HandleFunc("/api/nodes", func(w http.ResponseWriter, r *http.Request) {
nodes, err := clientset.CoreV1().Nodes().List(context.Background(), metav1.ListOptions{})
if err != nil {
http.Error(w, "failed to list nodes", http.StatusInternalServerError)
return
}
names := []string{}
for _, n := range nodes.Items {
names = append(names, n.Name)
}
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(names)
})
mux.HandleFunc("/api/pods", func(w http.ResponseWriter, r *http.Request) {
ctx := context.Background()
pods, err := clientset.CoreV1().Pods("").List(ctx, metav1.ListOptions{})
if err != nil {
http.Error(w, "failed to list pods", http.StatusInternalServerError)
return
}
// group pods by node
podsByNode := map[string][]string{}
for _, pod := range pods.Items {
if pod.Spec.NodeName == "" {
continue
}
if _, ok := podsByNode[pod.Spec.NodeName]; !ok {
podsByNode[pod.Spec.NodeName] = []string{}
}
podsByNode[pod.Spec.NodeName] = append(podsByNode[pod.Spec.NodeName], pod.Name)
}
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(podsByNode)
})
mux.HandleFunc("/api/config", func(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "application/json")
cfg := map[string]interface{}{
"animationDurationMs": int64(2000), // number
"version": "1.1", // string
"clusterName": os.Getenv("CLUSTER_NAME"), // string
}
_ = json.NewEncoder(w).Encode(cfg)
})
_ = http.ListenAndServe(":8080", mux)
}
func balanceNodes(clientset *kubernetes.Clientset, metricsClient *metricsv.Clientset, bus *EventBus) {
ctx := context.Background()
// --- get node metrics ---
nodeMetricsList, err := metricsClient.MetricsV1beta1().
NodeMetricses().
List(ctx, metav1.ListOptions{})
if err != nil {
log.Println("Failed to get node metrics:", err)
return
}
nodeUsage := make(map[string]map[string]int64)
for _, m := range nodeMetricsList.Items {
nodeUsage[m.Name] = map[string]int64{
"cpu": m.Usage.Cpu().MilliValue(),
"mem": m.Usage.Memory().Value() / (1024 * 1024),
}
}
// --- get node capacities ---
nodes, err := clientset.CoreV1().
Nodes().
List(ctx, metav1.ListOptions{})
if err != nil {
log.Println("Failed to list nodes:", err)
return
}
nodeCapacity := make(map[string]map[string]int64)
for _, n := range nodes.Items {
nodeCapacity[n.Name] = map[string]int64{
"cpu": n.Status.Capacity.Cpu().MilliValue(),
"mem": n.Status.Capacity.Memory().Value() / (1024 * 1024),
}
}
// --- find overloaded and underloaded nodes ---
var overloaded, underloaded []string
for node, usage := range nodeUsage {
if nodeCapacity[node]["cpu"] == 0 {
continue
}
cpuPercent := usage["cpu"] * 100 / nodeCapacity[node]["cpu"]
if cpuPercent > CPUOverloadThreshold {
overloaded = append(overloaded, node)
} else if cpuPercent < CPUUnderloadThreshold {
underloaded = append(underloaded, node)
}
}
log.Println("Overloaded nodes:", overloaded)
log.Println("Underloaded nodes:", underloaded)
if len(overloaded) == 0 || len(underloaded) == 0 {
return
}
// --- move pods from overloaded to underloaded ---
for _, node := range overloaded {
pods, err := clientset.CoreV1().Pods("").List(ctx, metav1.ListOptions{
FieldSelector: fmt.Sprintf("spec.nodeName=%s", node),
})
if err != nil {
log.Println("Failed to list pods for node", node, err)
continue
}
for _, pod := range pods.Items {
if pod.Namespace == "kube-system" || isDaemonSet(&pod) {
continue
}
if pod.Status.Phase != corev1.PodRunning {
continue
}
if usesHostPath(&pod) {
log.Printf("Skipping pod %s/%s (uses hostPath)", pod.Namespace, pod.Name)
continue
}
targetNode := pickTargetNode(underloaded, nodeUsage, nodeCapacity)
if targetNode == "" {
continue
}
log.Printf("Rescheduling pod %s/%s from %s to %s\n",
pod.Namespace, pod.Name, node, targetNode)
// --- cordon the node ---
if err := cordonNode(clientset, node); err != nil {
log.Println("Failed to cordon node", node, err)
continue
}
log.Println("Succesfully cordoned node", node)
// --- delete pod ---
grace := int64(0)
err = clientset.CoreV1().Pods(pod.Namespace).Delete(ctx, pod.Name, metav1.DeleteOptions{
GracePeriodSeconds: &grace,
})
if err != nil {
log.Println("Failed to delete pod", pod.Name, err)
_ = uncordonNode(clientset, node)
continue
}
log.Println("Deleted pod", pod.Name)
// --- wait for replacement pod ---
var ownerUID types.UID
if len(pod.OwnerReferences) > 0 {
ownerUID = pod.OwnerReferences[0].UID
}
var newPod corev1.Pod
timeoutCtx, cancel := context.WithTimeout(ctx, PodRespawnTimeout)
ticker := time.NewTicker(2 * time.Second)
WAIT_LOOP:
for {
select {
case <-timeoutCtx.Done():
log.Println("Pod respawn timeout reached")
break WAIT_LOOP
case <-ticker.C:
podsList, err := clientset.CoreV1().
Pods(pod.Namespace).
List(ctx, metav1.ListOptions{})
if err != nil {
log.Println("Failed to list pods:", err)
continue
}
for _, p := range podsList.Items {
if p.Status.Phase != corev1.PodRunning {
continue
}
for _, ref := range p.OwnerReferences {
if ref.UID == ownerUID {
// MUST be on different node
if p.Spec.NodeName != node {
newPod = p
break WAIT_LOOP
}
}
}
}
log.Println("Waiting for replacement pod to be Running...")
}
}
ticker.Stop()
cancel()
// --- ALWAYS uncordon ---
if err := uncordonNode(clientset, node); err != nil {
log.Println("Failed to uncordon node", node, err)
}
log.Println("Succesfuly uncordoned node", node)
log.Println("About to emit PodMoveEvent")
bus.Emit(PodMoveEvent{
Time: time.Now(),
Namespace: pod.Namespace,
Pod: pod.Name,
FromNode: node,
ToNode: targetNode,
Reason: "node-utilization-imbalance",
})
// --- update node usage ---
if nodeUsage[node] != nil {
nodeUsage[node]["cpu"] -= estimatePodCPU(&pod)
nodeUsage[node]["mem"] -= estimatePodMem(&pod)
}
if nodeUsage[newPod.Spec.NodeName] == nil {
nodeUsage[newPod.Spec.NodeName] = map[string]int64{"cpu": 0, "mem": 0}
}
nodeUsage[newPod.Spec.NodeName]["cpu"] += estimatePodCPU(&pod)
nodeUsage[newPod.Spec.NodeName]["mem"] += estimatePodMem(&pod)
// only move one pod per invocation
return
}
}
}
//
// ─── HELPERS ────────────────────────────────────────────────────────────────────
//
func mustEnv(key, def string) string {
if val := os.Getenv(key); val != "" {
return val
}
return def
}
func cordonNode(clientset *kubernetes.Clientset, nodeName string) error {
ctx := context.Background()
for i := 0; i < 5; i++ { // retry up to 5 times
node, err := clientset.CoreV1().Nodes().Get(ctx, nodeName, metav1.GetOptions{})
if err != nil {
return err
}
if node.Spec.Unschedulable {
return nil // already cordoned
}
node.Spec.Unschedulable = true
_, err = clientset.CoreV1().Nodes().Update(ctx, node, metav1.UpdateOptions{})
if err == nil {
return nil
}
log.Println("Cordoning failed, retrying:", err)
time.Sleep(500 * time.Millisecond)
}
return fmt.Errorf("failed to cordon node %s after retries", nodeName)
}
func uncordonNode(clientset *kubernetes.Clientset, nodeName string) error {
ctx := context.Background()
for i := 0; i < 5; i++ {
node, err := clientset.CoreV1().Nodes().Get(ctx, nodeName, metav1.GetOptions{})
if err != nil {
return err
}
if !node.Spec.Unschedulable {
return nil // already uncordoned
}
node.Spec.Unschedulable = false
_, err = clientset.CoreV1().Nodes().Update(ctx, node, metav1.UpdateOptions{})
if err == nil {
return nil
}
log.Println("Uncordoning failed, retrying:", err)
time.Sleep(500 * time.Millisecond)
}
return fmt.Errorf("failed to uncordon node %s after retries", nodeName)
}
func isDaemonSet(pod *corev1.Pod) bool {
for _, owner := range pod.OwnerReferences {
if owner.Kind == "DaemonSet" {
return true
}
}
return false
}
func usesHostPath(pod *corev1.Pod) bool {
for _, vol := range pod.Spec.Volumes {
if vol.HostPath != nil {
return true
}
}
return false
}
func pickTargetNode(nodes []string, usage map[string]map[string]int64, capacity map[string]map[string]int64) string {
var bestNode string
bestLoad := int64(1 << 62)
for _, n := range nodes {
cpuPercent := usage[n]["cpu"] * 100 / capacity[n]["cpu"]
memPercent := usage[n]["mem"] * 100 / capacity[n]["mem"]
load := cpuPercent + memPercent
if load < bestLoad {
bestLoad = load
bestNode = n
}
}
return bestNode
}
func estimatePodCPU(pod *corev1.Pod) int64 {
var cpu int64
for _, c := range pod.Spec.Containers {
if q, ok := c.Resources.Requests[corev1.ResourceCPU]; ok {
cpu += q.MilliValue()
}
}
return cpu
}
func estimatePodMem(pod *corev1.Pod) int64 {
var mem int64
for _, c := range pod.Spec.Containers {
if q, ok := c.Resources.Requests[corev1.ResourceMemory]; ok {
mem += q.Value() / (1024 * 1024)
}
}
return mem
}
BIN
View File
Binary file not shown.
+112
View File
@@ -0,0 +1,112 @@
# Deployment for the node-balancer
apiVersion: apps/v1
kind: Deployment
metadata:
name: node-balancer
namespace: kube-system
spec:
replicas: 1
selector:
matchLabels:
app: node-balancer
template:
metadata:
labels:
app: node-balancer
spec:
nodeSelector:
node.kubernetes.io/microk8s-controlplane: microk8s-controlplane
serviceAccountName: node-balancer
containers:
- name: node-balancer
image: allardkrings/node-balancer:1.0
imagePullPolicy: Always
env:
- name: CPU_OVERLOAD_THRESHOLD
value: "15"
- name: CPU_UNDERLOAD_THRESHOLD
value: "10"
- name: MEMORY_OVERLOAD_THRESHOLD
value: "50"
- name: MEMORY_UNDERLOAD_THRESHOLD
value: "45"
- name: POD_EVICTION_INTERVAL
value: "30"
- name: POD_ANIMATION_DURATION
value: "10"
- name: POD_RESPAWN_TIMEOUT
value: "45"
- name: CLUSTER_NAME
value: "PROD"
ports:
- name: webui
containerPort: 8080
---
apiVersion: v1
kind: Service
metadata:
name: node-balancer-webui
namespace: kube-system
spec:
selector:
app: node-balancer
ports:
- name: http
protocol: TCP
port: 8080
targetPort: 8080
type: ClusterIP
---
apiVersion: traefik.io/v1alpha1
kind: IngressRoute
metadata:
name: node-balancer-tls
namespace: kube-system
spec:
entryPoints:
- websecure
routes:
- match: Host(`nodebalancer-prod.allarddcs.nl`)
kind: Rule
services:
- name: node-balancer-webui
port: 8080
tls:
certResolver: letsencrypt
---
apiVersion: v1
kind: ServiceAccount
metadata:
name: node-balancer
namespace: kube-system
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
name: node-balancer
rules:
- apiGroups: [""]
resources: ["nodes"]
verbs: ["get", "list", "watch", "update"]
- apiGroups: [""]
resources: ["pods"]
verbs: ["get", "list", "watch", "delete"]
- apiGroups: ["metrics.k8s.io"]
resources: ["nodes"]
verbs: ["get", "list", "watch"]
---
# Binding of role to account
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
name: node-balancer-binding
subjects:
- kind: ServiceAccount
name: node-balancer
namespace: kube-system
roleRef:
kind: ClusterRole
name: node-balancer
apiGroup: rbac.authorization.k8s.io
+62
View File
@@ -0,0 +1,62 @@
# Deployment for the node-balancer
apiVersion: apps/v1
kind: Deployment
metadata:
name: node-balancer
namespace: kube-system
spec:
replicas: 1
selector:
matchLabels:
app: node-balancer
template:
metadata:
labels:
app: node-balancer
spec:
serviceAccountName: node-balancer
containers:
- name: node-balancer
image: allardkrings/node-balancer:1.0
imagePullPolicy: Always
env:
- name: CPU_OVERLOAD_THRESHOLD
value: "50"
- name: CPU_UNDERLOAD_THRESHOLD
value: "10"
- name: MEMORY_OVERLOAD_THRESHOLD
value: "70"
- name: MEMORY_UNDERLOAD_THRESHOLD
value: "30"
---
apiVersion: v1
kind: ServiceAccount
metadata:
name: node-balancer
namespace: kube-system
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
name: node-balancer
rules:
- apiGroups: [""]
resources: ["nodes", "pods"]
verbs: ["get", "list", "watch", "delete"]
- apiGroups: ["metrics.k8s.io"]
resources: ["nodes"]
verbs: ["get", "list", "watch"]
---
# Binding of role to account
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
name: node-balancer-binding
subjects:
- kind: ServiceAccount
name: node-balancer
namespace: kube-system
roleRef:
kind: ClusterRole
name: node-balancer
apiGroup: rbac.authorization.k8s.io
+6
View File
@@ -0,0 +1,6 @@
microk8s kubectl delete -f node-balancer.yaml
docker build -t allardkrings/node-balancer:1.0 .
docker push allardkrings/node-balancer:1.0
microk8s kubectl apply -f node-balancer.yaml
microk8s kubectl get pod -n kube-system
microk8s kubectl logs deploy/node-balancer -n kube-system --follow
+97
View File
@@ -0,0 +1,97 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Node Balancer WebUI</title>
<style>
body { font-family: sans-serif; margin: 20px; }
svg { border:1px solid #ccc; width:100%; height:300px; background:#f9f9f9; }
.node { fill:#4CAF50; stroke:#333; stroke-width:2; }
.pod { fill:#2196F3; stroke:#000; stroke-width:1; }
.pod text { font-size:10px; fill:#fff; text-anchor:middle; dominant-baseline:middle; }
.label { font-size:14px; text-anchor:middle; }
</style>
</head>
<body>
<h2>Node Balancer</h2>
<svg id="canvas"></svg>
<script>
// SVG setup
const svg = document.getElementById("canvas");
const nodePositions = {};
const nodeY = 50;
const nodeWidth = 100;
const nodeHeight = 40;
// Fetch node names from the API
fetch("/api/nodes")
.then(res => res.json())
.then(nodeNames => {
// Draw nodes
nodeNames.forEach((name,i)=>{
const x = 50 + i*200;
nodePositions[name] = {x: x + nodeWidth/2, y: nodeY + nodeHeight/2};
const rect = document.createElementNS("http://www.w3.org/2000/svg","rect");
rect.setAttribute("x", x);
rect.setAttribute("y", nodeY);
rect.setAttribute("width", nodeWidth);
rect.setAttribute("height", nodeHeight);
rect.setAttribute("class", "node");
svg.appendChild(rect);
const label = document.createElementNS("http://www.w3.org/2000/svg","text");
label.setAttribute("x", x + nodeWidth/2);
label.setAttribute("y", nodeY + nodeHeight/2 + 25);
label.setAttribute("class","label");
label.textContent = name;
svg.appendChild(label);
});
});
// Animate a pod
function flyPod(podName, fromNode, toNode){
const g = document.createElementNS("http://www.w3.org/2000/svg","g");
const circle = document.createElementNS("http://www.w3.org/2000/svg","circle");
circle.setAttribute("r", 15);
circle.setAttribute("class","pod");
g.appendChild(circle);
const text = document.createElementNS("http://www.w3.org/2000/svg","text");
text.textContent = podName;
g.appendChild(text);
svg.appendChild(g);
let start = nodePositions[fromNode];
let end = nodePositions[toNode];
if(!start || !end) return; // safety check
let progress = 0;
const duration = 2000;
const steps = 60;
const dx = (end.x - start.x)/steps;
const dy = (end.y - start.y)/steps;
const anim = setInterval(()=>{
progress++;
const cx = start.x + dx*progress;
const cy = start.y + dy*progress;
circle.setAttribute("cx", cx);
circle.setAttribute("cy", cy);
text.setAttribute("x", cx);
text.setAttribute("y", cy);
if(progress>=steps){
clearInterval(anim);
setTimeout(()=>svg.removeChild(g),1000);
}
}, duration/steps);
}
// SSE stream
const evtSource = new EventSource("/api/stream");
evtSource.onmessage = e => {
const evt = JSON.parse(e.data);
flyPod(evt.pod, evt.fromNode, evt.toNode);
};
</script>
</body>
</html>
+268
View File
@@ -0,0 +1,268 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Node Balancer</title>
<style>
html, body {
margin: 0;
padding: 0;
min-height: 100%;
}
body { font-family: sans-serif; margin: 20px; }
svg { border:1px solid #ccc; width:100%; background:#f9f9f9; }
.node { fill:#4CAF50; stroke:#333; stroke-width:2; }
.pod { fill:#2196F3; stroke:#000; stroke-width:1; }
.label { font-size:14px; text-anchor:middle; dominant-baseline:middle; }
.pod-label { font-size:14px; text-anchor:middle; dominant-baseline:middle; fill:#fff; }
header {
display: flex;
align-items: center;
margin-bottom: 20px;
background-color: #f0f0f0; /* light gray background for the header */
padding: 10px 15px;
border-radius: 8px;
}
header .logo {
font-weight: bold;
font-size: 18px;
color: #2196F3; /* blue logo text */
margin-right: 15px;
padding: 5px 10px;
background-color: #333; /* dark background behind logo text */
color: #fff;
border-radius: 4px;
font-family: monospace;
}
header .title {
font-size: 18px;
}
header .title span {
margin-left: 10px;
color: #555;
font-weight: normal;
}
header .cluster-label {
margin-left: 20px;
color: #333;
font-weight: normal;
}
</style>
</head>
<body>
<header>
<div class="logo">allarddcs</div>
<div class="title">
Node Balancer <span id="version">v?</span>
<span class="cluster-label">Cluster: <span id="cluster-name">?</span></span>
</div>
</header>
<svg id="canvas"></svg>
<script>
const svg = document.getElementById("canvas");
const nodePositions = {};
const nodeY = 50;
const nodeWidth = 100;
const nodeHeight = 40;
let animationDuration = 2000;
// Store pod stacks per node
const podsPerNode = {};
// Fetch animation duration from server
fetch("/api/config")
.then(res => res.json())
.then(cfg => {
animationDuration = cfg.animationDurationMs;
document.getElementById("version").textContent = "v" + cfg.version;
document.getElementById("cluster-name").textContent = cfg.clusterName;
});
// Draw nodes
fetch("/api/nodes")
.then(res => res.json())
.then(nodeNames => {
nodeNames.forEach((name,i)=>{
const x = 50 + i*200;
nodePositions[name] = {x: x + nodeWidth/2, y: nodeY + nodeHeight/2};
// Node box
const rect = document.createElementNS("http://www.w3.org/2000/svg","rect");
rect.setAttribute("x", x);
rect.setAttribute("y", nodeY);
rect.setAttribute("width", nodeWidth);
rect.setAttribute("height", nodeHeight);
rect.setAttribute("class","node");
svg.appendChild(rect);
// Node label
const label = document.createElementNS("http://www.w3.org/2000/svg","text");
label.setAttribute("x", x + nodeWidth/2);
label.setAttribute("y", nodeY + nodeHeight/2);
label.setAttribute("class","label");
label.textContent = name;
svg.appendChild(label);
podsPerNode[name] = [];
});
// Fetch initial pods after nodes are drawn
fetch("/api/pods")
.then(res => res.json())
.then(podsByNode => {
for(const nodeName in podsByNode){
podsByNode[nodeName].forEach(podName => addPod(podName, nodeName));
}
});
});
// Add a pod to the stack under a node
function addPod(podName, nodeName){
if(!nodePositions[nodeName]) return;
const stack = podsPerNode[nodeName] || [];
const index = stack.length;
const x = nodePositions[nodeName].x - nodeWidth/2;
const y = nodeY + nodeHeight + index*25;
const g = document.createElementNS("http://www.w3.org/2000/svg","g");
const rect = document.createElementNS("http://www.w3.org/2000/svg","rect");
rect.setAttribute("x", x);
rect.setAttribute("y", y);
rect.setAttribute("width", nodeWidth);
rect.setAttribute("height", 20);
rect.setAttribute("class","pod");
g.appendChild(rect);
const text = document.createElementNS("http://www.w3.org/2000/svg","text");
text.setAttribute("x", x + nodeWidth/2);
text.setAttribute("y", y + 10); // vertical center
text.setAttribute("class","pod-label");
// truncate text to fit box
const maxChars = Math.floor(nodeWidth / 8); // rough estimate
text.textContent = podName.length > maxChars ? podName.substr(0, maxChars) : podName;
g.appendChild(text);
svg.appendChild(g);
stack.push(g);
podsPerNode[nodeName] = stack;
updateSVGHeight();
}
function updateSVGHeight() {
let maxY = nodeY + nodeHeight; // start with top node
for (const nodeName in podsPerNode) {
const stack = podsPerNode[nodeName];
if (!stack) continue;
if (stack.length === 0) continue;
const stackHeight = stack.length * (20 + 5) +40 ; // pod height + spacing
const bottomY = nodeY + nodeHeight + stackHeight;
if (bottomY > maxY) maxY = bottomY;
}
// optional extra padding at bottom
svg.setAttribute("height", maxY + 20);
}
// Animate pod moving from one node to another
function flyPod(podName, fromNode, toNode) {
if (!fromNode || !toNode) return;
const fromStack = podsPerNode[fromNode];
const idx = fromStack.findIndex(g => g.querySelector("text").textContent === podName);
if (idx === -1) return;
// Grab the actual pod <g> element
const g = fromStack[idx];
// Remove it from leaving stack array
fromStack.splice(idx, 1);
redrawPods(fromNode); // redraw remaining pods to close gap
// Reparent pod to SVG root so it can move freely
svg.appendChild(g);
const rect = g.querySelector("rect");
const text = g.querySelector("text");
// Get current position
const startX = parseFloat(rect.getAttribute("x"));
const startY = parseFloat(rect.getAttribute("y"));
// Calculate target position in destination stack
const endX = nodePositions[toNode].x - nodeWidth / 2;
const endY = nodeY + nodeHeight + podsPerNode[toNode].length * 25;
let progress = 0;
const steps = 60;
const dx = (endX - startX) / steps;
const dy = (endY - startY) / steps;
// Animate pod
const anim = setInterval(() => {
progress++;
rect.setAttribute("x", startX + dx * progress);
rect.setAttribute("y", startY + dy * progress);
text.setAttribute("x", startX + dx * progress + nodeWidth / 2);
text.setAttribute("y", startY + dy * progress + 10);
if (progress >= steps) {
clearInterval(anim);
// Add pod to destination stack permanently
podsPerNode[toNode].push(g);
// Ensure destination stack is redrawn correctly
redrawPods(toNode);
}
}, animationDuration / steps);
}
// redraw all pods on a node (new)
function redrawPods(nodeName){
if(!podsPerNode[nodeName]) return;
podsPerNode[nodeName].forEach((g, idx)=>{
const rect = g.querySelector("rect");
const text = g.querySelector("text");
const x = nodePositions[nodeName].x - nodeWidth/2;
const y = nodeY + nodeHeight + 20 + idx*25;
rect.setAttribute("x", x);
rect.setAttribute("y", y);
text.setAttribute("x", x + nodeWidth/2);
text.setAttribute("y", y + 10);
});
updateSVGHeight();
}
// SSE stream
const evtSource = new EventSource("/api/stream");
evtSource.onmessage = e => {
const evt = JSON.parse(e.data);
if(evt.fromNode === evt.toNode){
// same node, just redraw stack
redrawPods(evt.toNode);
return;
}
if(!evt.fromNode){ // new pod appears
addPod(evt.pod, evt.toNode);
redrawPods(evt.toNode);
} else { // pod moves
flyPod(evt.pod, evt.fromNode, evt.toNode);
}
};
</script>
</body>
</html>
+281
View File
@@ -0,0 +1,281 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Node Balancer</title>
<style>
html, body {
margin: 0;
padding: 0;
min-height: 100%;
}
body { font-family: sans-serif; margin: 20px; }
svg { border:1px solid #ccc; width:100%; background:#f9f9f9; }
.node { fill:#4CAF50; stroke:#333; stroke-width:2; }
.pod { fill:#2196F3; stroke:#000; stroke-width:1; }
.label { font-size:14px; text-anchor:middle; dominant-baseline:middle; }
.pod-label { font-size:14px; text-anchor:middle; dominant-baseline:middle; fill:#fff; }
header {
display: flex;
align-items: center;
margin-bottom: 20px;
background-color: #f0f0f0; /* light gray background for the header */
padding: 10px 15px;
border-radius: 8px;
}
header .logo {
font-weight: bold;
font-size: 18px;
color: #2196F3; /* blue logo text */
margin-right: 15px;
padding: 5px 10px;
background-color: #333; /* dark background behind logo text */
color: #fff;
border-radius: 4px;
font-family: monospace;
}
header .title {
font-size: 18px;
}
header .title span {
margin-left: 10px;
color: #555;
font-weight: normal;
}
header .cluster-label {
margin-left: 20px;
color: #333;
font-weight: normal;
}
</style>
</head>
<body>
<header>
<div class="logo">allarddcs</div>
<div class="title">
Node Balancer <span id="version">v?</span>
<span class="cluster-label">Cluster: <span id="cluster-name">?</span></span>
</div>
</header>
<svg id="canvas"></svg>
<script>
const svg = document.getElementById("canvas");
const nodePositions = {};
const nodeY = 50;
const nodeWidth = 120; // slightly wider so text fits better
const nodeHeight = 55; // taller
const podHeight = 36; // taller
const podSpacing = 6; // vertical spacing between pods
const textPaddingY = 6; // vertical padding inside pod
let animationDuration = 2000;
const podsPerNode = {};
// Fetch config
fetch("/api/config")
.then(res => res.json())
.then(cfg => {
animationDuration = cfg.animationDurationMs;
document.getElementById("version").textContent = "v" + cfg.version;
document.getElementById("cluster-name").textContent = cfg.clusterName;
});
// Draw nodes
fetch("/api/nodes")
.then(res => res.json())
.then(nodeNames => {
nodeNames.forEach((name,i)=>{
const x = 50 + i*220;
nodePositions[name] = {x: x + nodeWidth/2, y: nodeY + nodeHeight/2};
// Node box
const rect = document.createElementNS("http://www.w3.org/2000/svg","rect");
rect.setAttribute("x", x);
rect.setAttribute("y", nodeY);
rect.setAttribute("width", nodeWidth);
rect.setAttribute("height", nodeHeight);
rect.setAttribute("class","node");
svg.appendChild(rect);
// Node label
const label = document.createElementNS("http://www.w3.org/2000/svg","text");
label.setAttribute("x", x + nodeWidth/2);
label.setAttribute("y", nodeY + nodeHeight/2);
label.setAttribute("class","label");
label.setAttribute("text-anchor","middle");
label.setAttribute("dominant-baseline","middle");
label.textContent = name;
svg.appendChild(label);
podsPerNode[name] = [];
});
fetch("/api/pods")
.then(res => res.json())
.then(podsByNode => {
for(const nodeName in podsByNode){
podsByNode[nodeName].forEach(podName => addPod(podName, nodeName));
}
});
});
// Add pod
function addPod(podName, nodeName){
if(!nodePositions[nodeName]) return;
const stack = podsPerNode[nodeName] || [];
const index = stack.length;
const x = nodePositions[nodeName].x - nodeWidth/2;
const y = nodeY + nodeHeight + index*(podHeight + podSpacing);
const g = document.createElementNS("http://www.w3.org/2000/svg","g");
g.dataset.podName = podName;
const rect = document.createElementNS("http://www.w3.org/2000/svg","rect");
rect.setAttribute("x", x);
rect.setAttribute("y", y);
rect.setAttribute("width", nodeWidth);
rect.setAttribute("height", podHeight);
rect.setAttribute("class","pod");
g.appendChild(rect);
// Pod text (centered, multi-line if needed)
const text = document.createElementNS("http://www.w3.org/2000/svg","text");
text.setAttribute("class","pod-label");
text.setAttribute("text-anchor","middle");
text.setAttribute("x", x + nodeWidth/2);
if(podName.length <= 12){
text.setAttribute("y", y + podHeight/2 + textPaddingY/2);
text.setAttribute("dominant-baseline","middle");
text.textContent = podName;
} else {
const line1 = podName.substring(0,12);
const line2 = podName.substring(12);
text.setAttribute("y", y + textPaddingY + 6);
const t1 = document.createElementNS("http://www.w3.org/2000/svg","tspan");
t1.setAttribute("x", x + nodeWidth/2);
t1.textContent = line1;
const t2 = document.createElementNS("http://www.w3.org/2000/svg","tspan");
t2.setAttribute("x", x + nodeWidth/2);
t2.setAttribute("dy", "12");
t2.textContent = line2;
text.appendChild(t1);
text.appendChild(t2);
}
g.appendChild(text);
svg.appendChild(g);
stack.push(g);
podsPerNode[nodeName] = stack;
updateSVGHeight();
}
// Update SVG height
function updateSVGHeight() {
let maxY = nodeY + nodeHeight;
for(const nodeName in podsPerNode){
const stack = podsPerNode[nodeName];
if(!stack || stack.length===0) continue;
const bottomY = nodeY + nodeHeight + stack.length*(podHeight + podSpacing);
if(bottomY > maxY) maxY = bottomY;
}
svg.setAttribute("height", maxY + 20);
}
// Fly pod animation
function flyPod(podName, fromNode, toNode){
if(!fromNode || !toNode) return;
const fromStack = podsPerNode[fromNode];
const idx = fromStack.findIndex(g => g.dataset.podName===podName);
if(idx===-1) return;
const g = fromStack[idx];
fromStack.splice(idx,1);
redrawPods(fromNode);
svg.appendChild(g);
const rect = g.querySelector("rect");
const text = g.querySelector("text");
const startX = parseFloat(rect.getAttribute("x"));
const startY = parseFloat(rect.getAttribute("y"));
const endX = nodePositions[toNode].x - nodeWidth/2;
const endY = nodeY + nodeHeight + podsPerNode[toNode].length*(podHeight+podSpacing);
let progress = 0;
const steps = 60;
const dx = (endX - startX)/steps;
const dy = (endY - startY)/steps;
const anim = setInterval(()=>{
progress++;
const nx = startX + dx*progress;
const ny = startY + dy*progress;
rect.setAttribute("x", nx);
rect.setAttribute("y", ny);
text.setAttribute("x", nx + nodeWidth/2);
text.setAttribute("y", ny + podHeight/2 + textPaddingY/2);
if(progress>=steps){
clearInterval(anim);
podsPerNode[toNode].push(g);
redrawPods(toNode);
}
}, animationDuration/steps);
}
// Redraw pods on a node
function redrawPods(nodeName){
if(!podsPerNode[nodeName]) return;
podsPerNode[nodeName].forEach((g,idx)=>{
const rect = g.querySelector("rect");
const text = g.querySelector("text");
const x = nodePositions[nodeName].x - nodeWidth/2;
const y = nodeY + nodeHeight + idx*(podHeight+podSpacing);
rect.setAttribute("x", x);
rect.setAttribute("y", y);
text.setAttribute("x", x + nodeWidth/2);
text.setAttribute("y", y + podHeight/2 + textPaddingY/2);
});
updateSVGHeight();
}
// SSE stream
const evtSource = new EventSource("/api/stream");
evtSource.onmessage = e=>{
const evt = JSON.parse(e.data);
if(evt.fromNode===evt.toNode){
redrawPods(evt.toNode);
return;
}
if(!evt.fromNode){
addPod(evt.pod, evt.toNode);
redrawPods(evt.toNode);
} else {
flyPod(evt.pod, evt.fromNode, evt.toNode);
}
};
</script>
</body>
</html>
+262
View File
@@ -0,0 +1,262 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Node Balancer</title>
<style>
html, body {
margin: 0;
padding: 0;
min-height: 100%;
}
body { font-family: sans-serif; margin: 20px; }
svg { border:1px solid #ccc; width:100%; background:#f9f9f9; }
.node { fill:#4CAF50; stroke:#333; stroke-width:2; }
.pod { fill:#2196F3; stroke:#000; stroke-width:1; }
.label { font-size:14px; text-anchor:middle; dominant-baseline:middle; }
.pod-label { font-size:14px; text-anchor:middle; fill:#fff; }
header {
display: flex;
align-items: center;
margin-bottom: 20px;
background-color: #f0f0f0;
padding: 10px 15px;
border-radius: 8px;
}
header .logo {
font-weight: bold;
font-size: 18px;
color: #2196F3;
margin-right: 15px;
padding: 5px 10px;
background-color: #333;
color: #fff;
border-radius: 4px;
font-family: monospace;
}
header .title {
font-size: 18px;
}
header .title span {
margin-left: 10px;
color: #555;
font-weight: normal;
}
header .cluster-label {
margin-left: 20px;
color: #333;
font-weight: normal;
}
</style>
</head>
<body>
<header>
<div class="logo">allarddcs</div>
<div class="title">
Node Balancer <span id="version">v?</span>
<span class="cluster-label">Cluster: <span id="cluster-name">?</span></span>
</div>
</header>
<svg id="canvas"></svg>
<script>
const svg = document.getElementById("canvas");
const nodePositions = {};
const nodeY = 50;
const nodeWidth = 120; // node box width
const nodeHeight = 55; // node box height
const podHeight = 36; // pod box height
const podSpacing = 6; // vertical spacing between pods
let animationDuration = 2000;
const podsPerNode = {};
// Fetch config
fetch("/api/config")
.then(res => res.json())
.then(cfg => {
animationDuration = cfg.animationDurationMs;
document.getElementById("version").textContent = "v" + cfg.version;
document.getElementById("cluster-name").textContent = cfg.clusterName;
});
// Draw nodes
fetch("/api/nodes")
.then(res => res.json())
.then(nodeNames => {
nodeNames.forEach((name,i)=>{
const x = 50 + i*220;
nodePositions[name] = {x: x + nodeWidth/2, y: nodeY + nodeHeight/2};
// Node box
const rect = document.createElementNS("http://www.w3.org/2000/svg","rect");
rect.setAttribute("x", x);
rect.setAttribute("y", nodeY);
rect.setAttribute("width", nodeWidth);
rect.setAttribute("height", nodeHeight);
rect.setAttribute("class","node");
svg.appendChild(rect);
// Node label
const label = document.createElementNS("http://www.w3.org/2000/svg","text");
label.setAttribute("x", x + nodeWidth/2);
label.setAttribute("y", nodeY + nodeHeight/2);
label.setAttribute("class","label");
label.setAttribute("text-anchor","middle");
label.setAttribute("dominant-baseline","middle");
label.textContent = name;
svg.appendChild(label);
podsPerNode[name] = [];
});
// Fetch pods after nodes
fetch("/api/pods")
.then(res => res.json())
.then(podsByNode => {
for(const nodeName in podsByNode){
podsByNode[nodeName].forEach(podName => addPod(podName, nodeName));
}
});
});
// Add pod
function addPod(podName, nodeName){
if(!nodePositions[nodeName]) return;
const stack = podsPerNode[nodeName] || [];
const index = stack.length;
const x = nodePositions[nodeName].x - nodeWidth/2;
const y = nodeY + nodeHeight + index*(podHeight + podSpacing);
const g = document.createElementNS("http://www.w3.org/2000/svg","g");
g.dataset.podName = podName;
// Pod rectangle
const rect = document.createElementNS("http://www.w3.org/2000/svg","rect");
rect.setAttribute("x", x);
rect.setAttribute("y", y);
rect.setAttribute("width", nodeWidth);
rect.setAttribute("height", podHeight);
rect.setAttribute("class","pod");
g.appendChild(rect);
const text = document.createElementNS("http://www.w3.org/2000/svg","text");
text.setAttribute("class","pod-label");
text.setAttribute("text-anchor","middle");
text.setAttribute("x", x + nodeWidth/2);
text.setAttribute("y", y); // <-- top of pod rectangle
g.appendChild(text);
// first tspan for top padding
const tspan = document.createElementNS("http://www.w3.org/2000/svg","tspan");
tspan.setAttribute("x", x + nodeWidth/2);
tspan.setAttribute("dy", 6); // top padding inside pod
tspan.textContent = podName;
text.appendChild(tspan);
svg.appendChild(g);
stack.push(g);
podsPerNode[nodeName] = stack;
updateSVGHeight();
}
// Update SVG height
function updateSVGHeight() {
let maxY = nodeY + nodeHeight;
for(const nodeName in podsPerNode){
const stack = podsPerNode[nodeName];
if(!stack || stack.length===0) continue;
const bottomY = nodeY + nodeHeight + stack.length*(podHeight + podSpacing);
if(bottomY > maxY) maxY = bottomY;
}
svg.setAttribute("height", maxY + 20);
}
// Animate pod moving
function flyPod(podName, fromNode, toNode){
if(!fromNode || !toNode) return;
const fromStack = podsPerNode[fromNode];
const idx = fromStack.findIndex(g => g.dataset.podName===podName);
if(idx===-1) return;
const g = fromStack[idx];
fromStack.splice(idx,1);
redrawPods(fromNode);
svg.appendChild(g);
const rect = g.querySelector("rect");
const text = g.querySelector("text");
const startX = parseFloat(rect.getAttribute("x"));
const startY = parseFloat(rect.getAttribute("y"));
const endX = nodePositions[toNode].x - nodeWidth/2;
const endY = nodeY + nodeHeight + podsPerNode[toNode].length*(podHeight+podSpacing);
let progress = 0;
const steps = 60;
const dx = (endX - startX)/steps;
const dy = (endY - startY)/steps;
const anim = setInterval(()=>{
progress++;
const nx = startX + dx*progress;
const ny = startY + dy*progress;
rect.setAttribute("x", nx);
rect.setAttribute("y", ny);
text.setAttribute("x", nx + nodeWidth/2);
// text y remains managed by first tspan dy
if(progress>=steps){
clearInterval(anim);
podsPerNode[toNode].push(g);
redrawPods(toNode);
}
}, animationDuration/steps);
}
// Redraw pods on a node
function redrawPods(nodeName){
if(!podsPerNode[nodeName]) return;
podsPerNode[nodeName].forEach((g,idx)=>{
const rect = g.querySelector("rect");
const text = g.querySelector("text");
const x = nodePositions[nodeName].x - nodeWidth/2;
const y = nodeY + nodeHeight + idx*(podHeight+podSpacing);
rect.setAttribute("x", x);
rect.setAttribute("y", y);
text.setAttribute("x", x + nodeWidth/2);
// leave first tspan dy as 6 for top padding
});
updateSVGHeight();
}
// SSE stream
const evtSource = new EventSource("/api/stream");
evtSource.onmessage = e=>{
const evt = JSON.parse(e.data);
if(evt.fromNode===evt.toNode){
redrawPods(evt.toNode);
return;
}
if(!evt.fromNode){
addPod(evt.pod, evt.toNode);
redrawPods(evt.toNode);
} else {
flyPod(evt.pod, evt.fromNode, evt.toNode);
}
};
</script>
</body>
</html>
+286
View File
@@ -0,0 +1,286 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Node Balancer</title>
<style>
html, body {
margin: 0;
padding: 0;
min-height: 100%;
}
body { font-family: sans-serif; margin: 20px; }
svg { border:1px solid #ccc; width:100%; background:#f9f9f9; }
.node { fill:#4CAF50; stroke:#333; stroke-width:2; }
.pod { fill:#2196F3; stroke:#000; stroke-width:1; }
.label { font-size:14px; text-anchor:middle; dominant-baseline:middle; }
.pod-label { font-size:14px; text-anchor:middle; fill:#fff; }
header {
display: flex;
align-items: center;
margin-bottom: 20px;
background-color: #f0f0f0;
padding: 10px 15px;
border-radius: 8px;
}
header .logo {
font-weight: bold;
font-size: 18px;
color: #2196F3;
margin-right: 15px;
padding: 5px 10px;
background-color: #333;
color: #fff;
border-radius: 4px;
font-family: monospace;
}
header .title {
font-size: 18px;
}
header .title span {
margin-left: 10px;
color: #555;
font-weight: normal;
}
header .cluster-label {
margin-left: 20px;
color: #333;
font-weight: normal;
}
</style>
</head>
<body>
<header>
<div class="logo">allarddcs</div>
<div class="title">
Node Balancer <span id="version">v?</span>
<span class="cluster-label">Cluster: <span id="cluster-name">?</span></span>
</div>
</header>
<svg id="canvas"></svg>
<script>
const svg = document.getElementById("canvas");
const nodePositions = {};
const nodeY = 50;
const nodeWidth = 120;
const nodeHeight = 55;
const podHeight = 36;
const podSpacing = 6;
const textPaddingY = 6;
let animationDuration = 2000;
const podsPerNode = {};
// Fetch config
fetch("/api/config")
.then(res => res.json())
.then(cfg => {
animationDuration = cfg.animationDurationMs;
document.getElementById("version").textContent = "v" + cfg.version;
document.getElementById("cluster-name").textContent = cfg.clusterName;
});
// Draw nodes
fetch("/api/nodes")
.then(res => res.json())
.then(nodeNames => {
nodeNames.forEach((name,i)=>{
const x = 50 + i*220;
nodePositions[name] = {x: x + nodeWidth/2, y: nodeY + nodeHeight/2};
// Node box
const rect = document.createElementNS("http://www.w3.org/2000/svg","rect");
rect.setAttribute("x", x);
rect.setAttribute("y", nodeY);
rect.setAttribute("width", nodeWidth);
rect.setAttribute("height", nodeHeight);
rect.setAttribute("class","node");
svg.appendChild(rect);
// Node label
const label = document.createElementNS("http://www.w3.org/2000/svg","text");
label.setAttribute("x", x + nodeWidth/2);
label.setAttribute("y", nodeY + nodeHeight/2);
label.setAttribute("class","label");
label.setAttribute("text-anchor","middle");
label.setAttribute("dominant-baseline","middle");
label.textContent = name;
svg.appendChild(label);
podsPerNode[name] = [];
});
fetch("/api/pods")
.then(res => res.json())
.then(podsByNode => {
for(const nodeName in podsByNode){
podsByNode[nodeName].forEach(podName => addPod(podName, nodeName));
}
});
});
// Truncate podname
function truncatePodName(podName){
const parts = podName.split('-');
const hashRegex = /^[a-z0-9]+$/i;
// Remove last segment if it looks like a hash
if(parts.length > 1 && parts[parts.length - 1].match(hashRegex) && parts[parts.length - 1].length >= 5){
parts.pop();
}
// Check if the new last segment is also a hash (optional second hash)
if(parts.length > 1 && parts[parts.length - 1].match(hashRegex) && parts[parts.length - 1].length >= 5){
parts.pop();
}
return parts.join('-');
}
// Add pod
function addPod(podName, nodeName){
if(!nodePositions[nodeName]) return;
const stack = podsPerNode[nodeName] || [];
const index = stack.length;
const x = nodePositions[nodeName].x - nodeWidth/2;
const y = nodeY + nodeHeight + index*(podHeight + podSpacing);
const g = document.createElementNS("http://www.w3.org/2000/svg","g");
g.dataset.podName = podName;
const rect = document.createElementNS("http://www.w3.org/2000/svg","rect");
rect.setAttribute("x", x);
rect.setAttribute("y", y);
rect.setAttribute("width", nodeWidth);
rect.setAttribute("height", podHeight);
rect.setAttribute("class","pod");
g.appendChild(rect);
// Pod text with padding and multi-line
const text = document.createElementNS("http://www.w3.org/2000/svg","text");
text.setAttribute("class","pod-label");
text.setAttribute("text-anchor","middle");
text.setAttribute("x", x + nodeWidth/2);
text.setAttribute("y", y);
g.appendChild(text);
// Use your original truncated pod name here
const truncatedName = podName;
// Wrap in tspans for multi-line with top padding
const maxCharsPerLine = 16;
for(let i = 0; i < truncatedName.length; i += maxCharsPerLine){
const tspan = document.createElementNS("http://www.w3.org/2000/svg","tspan");
tspan.setAttribute("x", x + nodeWidth/2);
tspan.setAttribute("dy", i === 0 ? textPaddingY : 14);
tspan.textContent = truncatedName.substr(i, maxCharsPerLine);
text.appendChild(tspan);
}
svg.appendChild(g);
stack.push(g);
podsPerNode[nodeName] = stack;
updateSVGHeight();
}
// Update SVG height
function updateSVGHeight() {
let maxY = nodeY + nodeHeight;
for(const nodeName in podsPerNode){
const stack = podsPerNode[nodeName];
if(!stack || stack.length===0) continue;
const bottomY = nodeY + nodeHeight + stack.length*(podHeight + podSpacing);
if(bottomY > maxY) maxY = bottomY;
}
svg.setAttribute("height", maxY + 20);
}
// Animate pod moving
function flyPod(podName, fromNode, toNode){
if(!fromNode || !toNode) return;
const fromStack = podsPerNode[fromNode];
const idx = fromStack.findIndex(g => g.dataset.podName===podName);
if(idx===-1) return;
const g = fromStack[idx];
fromStack.splice(idx,1);
redrawPods(fromNode);
svg.appendChild(g);
const rect = g.querySelector("rect");
const text = g.querySelector("text");
const startX = parseFloat(rect.getAttribute("x"));
const startY = parseFloat(rect.getAttribute("y"));
const endX = nodePositions[toNode].x - nodeWidth/2;
const endY = nodeY + nodeHeight + podsPerNode[toNode].length*(podHeight+podSpacing);
let progress = 0;
const steps = 60;
const dx = (endX - startX)/steps;
const dy = (endY - startY)/steps;
const anim = setInterval(()=>{
progress++;
const nx = startX + dx*progress;
const ny = startY + dy*progress;
rect.setAttribute("x", nx);
rect.setAttribute("y", ny);
text.setAttribute("x", nx + nodeWidth/2);
if(progress>=steps){
clearInterval(anim);
podsPerNode[toNode].push(g);
redrawPods(toNode);
}
}, animationDuration/steps);
}
// Redraw pods on a node
function redrawPods(nodeName){
if(!podsPerNode[nodeName]) return;
podsPerNode[nodeName].forEach((g,idx)=>{
const rect = g.querySelector("rect");
const text = g.querySelector("text");
const x = nodePositions[nodeName].x - nodeWidth/2;
const y = nodeY + nodeHeight + idx*(podHeight+podSpacing);
rect.setAttribute("x", x);
rect.setAttribute("y", y);
text.setAttribute("x", x + nodeWidth/2);
text.setAttribute("y", y);
});
updateSVGHeight();
}
// SSE stream
const evtSource = new EventSource("/api/stream");
evtSource.onmessage = e=>{
const evt = JSON.parse(e.data);
if(evt.fromNode===evt.toNode){
redrawPods(evt.toNode);
return;
}
if(!evt.fromNode){
addPod(evt.pod, evt.toNode);
redrawPods(evt.toNode);
} else {
flyPod(evt.pod, evt.fromNode, evt.toNode);
}
};
</script>
</body>
</html>
+288
View File
@@ -0,0 +1,288 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Node Balancer</title>
<style>
html, body {
margin: 0;
padding: 0;
min-height: 100%;
}
body { font-family: sans-serif; margin: 20px; }
svg { border:1px solid #ccc; width:100%; background:#f9f9f9; }
.node { fill:#4CAF50; stroke:#333; stroke-width:2; }
.pod { fill:#2196F3; stroke:#000; stroke-width:1; }
.label { font-size:14px; text-anchor:middle; dominant-baseline:middle; }
.pod-label { font-size:14px; text-anchor:middle; fill:#fff; }
header {
display: flex;
align-items: center;
margin-bottom: 20px;
background-color: #f0f0f0;
padding: 10px 15px;
border-radius: 8px;
}
header .logo {
font-weight: bold;
font-size: 18px;
color: #2196F3;
margin-right: 15px;
padding: 5px 10px;
background-color: #333;
color: #fff;
border-radius: 4px;
font-family: monospace;
}
header .title {
font-size: 18px;
}
header .title span {
margin-left: 10px;
color: #555;
font-weight: normal;
}
header .cluster-label {
margin-left: 20px;
color: #333;
font-weight: normal;
}
</style>
</head>
<body>
<header>
<div class="logo">allarddcs</div>
<div class="title">
Node Balancer <span id="version">v?</span>
<span class="cluster-label">Cluster: <span id="cluster-name">?</span></span>
</div>
</header>
<svg id="canvas"></svg>
<script>
const svg = document.getElementById("canvas");
const nodePositions = {};
const nodeY = 50;
const nodeWidth = 120;
const nodeHeight = 55;
const podHeight = 36;
const podSpacing = 6;
const textPaddingY = 6;
let animationDuration = 2000;
const podsPerNode = {};
// Truncate pod names
function truncatePodName(podName){
const parts = podName.split('-');
const hashRegex = /^[a-z0-9]+$/i;
// Remove last segment if it looks like a hash
if(parts.length > 1 && parts[parts.length - 1].match(hashRegex) && parts[parts.length - 1].length >= 5){
parts.pop();
}
// Remove second last segment if it also looks like a hash
if(parts.length > 1 && parts[parts.length - 1].match(hashRegex) && parts[parts.length - 1].length >= 5){
parts.pop();
}
return parts.join('-');
}
// Fetch config
fetch("/api/config")
.then(res => res.json())
.then(cfg => {
animationDuration = cfg.animationDurationMs;
document.getElementById("version").textContent = "v" + cfg.version;
document.getElementById("cluster-name").textContent = cfg.clusterName;
});
// Draw nodes
fetch("/api/nodes")
.then(res => res.json())
.then(nodeNames => {
nodeNames.forEach((name,i)=>{
const x = 50 + i*220;
nodePositions[name] = {x: x + nodeWidth/2, y: nodeY + nodeHeight/2};
// Node box
const rect = document.createElementNS("http://www.w3.org/2000/svg","rect");
rect.setAttribute("x", x);
rect.setAttribute("y", nodeY);
rect.setAttribute("width", nodeWidth);
rect.setAttribute("height", nodeHeight);
rect.setAttribute("class","node");
svg.appendChild(rect);
// Node label
const label = document.createElementNS("http://www.w3.org/2000/svg","text");
label.setAttribute("x", x + nodeWidth/2);
label.setAttribute("y", nodeY + nodeHeight/2);
label.setAttribute("class","label");
label.setAttribute("text-anchor","middle");
label.setAttribute("dominant-baseline","middle");
label.textContent = name;
svg.appendChild(label);
podsPerNode[name] = [];
});
fetch("/api/pods")
.then(res => res.json())
.then(podsByNode => {
for(const nodeName in podsByNode){
podsByNode[nodeName].forEach(podName => addPod(podName, nodeName));
}
});
});
// Add pod
function addPod(podName, nodeName){
if(!nodePositions[nodeName]) return;
const stack = podsPerNode[nodeName] || [];
const index = stack.length;
const x = nodePositions[nodeName].x - nodeWidth/2;
const y = nodeY + nodeHeight + index*(podHeight + podSpacing);
const g = document.createElementNS("http://www.w3.org/2000/svg","g");
g.dataset.podName = podName;
const rect = document.createElementNS("http://www.w3.org/2000/svg","rect");
rect.setAttribute("x", x);
rect.setAttribute("y", y);
rect.setAttribute("width", nodeWidth);
rect.setAttribute("height", podHeight);
rect.setAttribute("class","pod");
g.appendChild(rect);
// Pod text with padding and multi-line
const text = document.createElementNS("http://www.w3.org/2000/svg","text");
text.setAttribute("class","pod-label");
text.setAttribute("text-anchor","middle");
text.setAttribute("x", x + nodeWidth/2);
text.setAttribute("y", y);
g.appendChild(text);
const truncatedName = truncatePodName(podName);
const maxCharsPerLine = 16;
for(let i = 0; i < truncatedName.length; i += maxCharsPerLine){
const tspan = document.createElementNS("http://www.w3.org/2000/svg","tspan");
tspan.setAttribute("x", x + nodeWidth/2);
// first line gets top padding equal to half the padding + half font height
tspan.setAttribute("dy", i === 0 ? textPaddingY + 10 : 14);
tspan.textContent = truncatedName.substr(i, maxCharsPerLine);
text.appendChild(tspan);
}
svg.appendChild(g);
stack.push(g);
podsPerNode[nodeName] = stack;
updateSVGHeight();
}
// Update SVG height
function updateSVGHeight() {
let maxY = nodeY + nodeHeight;
for(const nodeName in podsPerNode){
const stack = podsPerNode[nodeName];
if(!stack || stack.length===0) continue;
const bottomY = nodeY + nodeHeight + stack.length*(podHeight + podSpacing);
if(bottomY > maxY) maxY = bottomY;
}
svg.setAttribute("height", maxY + 20);
}
// Animate pod moving
function flyPod(podName, fromNode, toNode){
if(!fromNode || !toNode) return;
const fromStack = podsPerNode[fromNode];
const idx = fromStack.findIndex(g => g.dataset.podName===podName);
if(idx===-1) return;
const g = fromStack[idx];
fromStack.splice(idx,1);
redrawPods(fromNode);
svg.appendChild(g);
const rect = g.querySelector("rect");
const text = g.querySelector("text");
const startX = parseFloat(rect.getAttribute("x"));
const startY = parseFloat(rect.getAttribute("y"));
const endX = nodePositions[toNode].x - nodeWidth/2;
const endY = nodeY + nodeHeight + podsPerNode[toNode].length*(podHeight+podSpacing);
let progress = 0;
const steps = 60;
const dx = (endX - startX)/steps;
const dy = (endY - startY)/steps;
const anim = setInterval(()=>{
progress++;
const nx = startX + dx*progress;
const ny = startY + dy*progress;
rect.setAttribute("x", nx);
rect.setAttribute("y", ny);
text.setAttribute("x", nx + nodeWidth/2);
if(progress>=steps){
clearInterval(anim);
podsPerNode[toNode].push(g);
redrawPods(toNode);
}
}, animationDuration/steps);
}
// Redraw pods on a node
function redrawPods(nodeName){
if(!podsPerNode[nodeName]) return;
podsPerNode[nodeName].forEach((g,idx)=>{
const rect = g.querySelector("rect");
const text = g.querySelector("text");
const x = nodePositions[nodeName].x - nodeWidth/2;
const y = nodeY + nodeHeight + idx*(podHeight+podSpacing);
rect.setAttribute("x", x);
rect.setAttribute("y", y);
text.setAttribute("x", x + nodeWidth/2);
text.setAttribute("y", y);
});
updateSVGHeight();
}
// SSE stream
const evtSource = new EventSource("/api/stream");
evtSource.onmessage = e=>{
const evt = JSON.parse(e.data);
if(evt.fromNode===evt.toNode){
redrawPods(evt.toNode);
return;
}
if(!evt.fromNode){
addPod(evt.pod, evt.toNode);
redrawPods(evt.toNode);
} else {
flyPod(evt.pod, evt.fromNode, evt.toNode);
}
};
</script>
</body>
</html>
+328
View File
@@ -0,0 +1,328 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Node Balancer</title>
<style>
html, body {
margin: 0;
padding: 0;
min-height: 100%;
}
body { font-family: sans-serif; margin: 20px; }
svg { border:1px solid #ccc; width:100%; background:#f9f9f9; }
.node { fill:#4CAF50; stroke:#333; stroke-width:2; }
.pod { fill:#2196F3; stroke:#000; stroke-width:1; }
.label { font-size:14px; text-anchor:middle; dominant-baseline:middle; }
.pod-label { font-size:14px; text-anchor:middle; fill:#fff; }
header {
display: flex;
align-items: center;
margin-bottom: 20px;
background-color: #f0f0f0;
padding: 10px 15px;
border-radius: 8px;
}
header .logo {
font-weight: bold;
font-size: 18px;
color: #2196F3;
margin-right: 15px;
padding: 5px 10px;
background-color: #333;
color: #fff;
border-radius: 4px;
font-family: monospace;
}
header .title {
font-size: 18px;
}
header .title span {
margin-left: 10px;
color: #555;
font-weight: normal;
}
header .cluster-label {
margin-left: 20px;
color: #333;
font-weight: normal;
}
</style>
</head>
<body>
<header>
<div class="logo">allarddcs</div>
<div class="title">
Node Balancer <span id="version">v?</span>
<span class="cluster-label">Cluster: <span id="cluster-name">?</span></span>
</div>
</header>
<svg id="canvas"></svg>
<script>
const svg = document.getElementById("canvas");
const nodePositions = {};
const nodeY = 50;
const nodeWidth = 120;
const nodeHeight = 55;
const podHeight = 36;
const podSpacing = 6;
const textPaddingY = 6;
let animationDuration = 2000;
const podsPerNode = {};
// Truncate pod names (remove 1-2 trailing hashes)
function truncatePodName(podName){
const parts = podName.split('-');
const hashRegex = /^[a-z0-9]+$/i;
// Remove last segment if it looks like a hash
if(parts.length > 1 && parts[parts.length - 1].match(hashRegex) && parts[parts.length - 1].length >= 5){
parts.pop();
}
// Remove second last segment if it also looks like a hash
if(parts.length > 1 && parts[parts.length - 1].match(hashRegex) && parts[parts.length - 1].length >= 5){
parts.pop();
}
return parts.join('-');
}
// Fetch config
fetch("/api/config")
.then(res => res.json())
.then(cfg => {
animationDuration = cfg.animationDurationMs;
document.getElementById("version").textContent = "v" + cfg.version;
document.getElementById("cluster-name").textContent = cfg.clusterName;
});
// Add a node to DOM
function addNode(name, i){
const x = 50 + i*220;
nodePositions[name] = {x: x + nodeWidth/2, y: nodeY + nodeHeight/2};
// Node box
const rect = document.createElementNS("http://www.w3.org/2000/svg","rect");
rect.setAttribute("x", x);
rect.setAttribute("y", nodeY);
rect.setAttribute("width", nodeWidth);
rect.setAttribute("height", nodeHeight);
rect.setAttribute("class","node");
svg.appendChild(rect);
// Node label
const label = document.createElementNS("http://www.w3.org/2000/svg","text");
label.setAttribute("x", x + nodeWidth/2);
label.setAttribute("y", nodeY + nodeHeight/2);
label.setAttribute("class","label");
label.setAttribute("text-anchor","middle");
label.setAttribute("dominant-baseline","middle");
label.textContent = name;
svg.appendChild(label);
podsPerNode[name] = [];
}
// Remove a node from DOM
function removeNode(name){
delete nodePositions[name];
// Remove pods
if(podsPerNode[name]){
podsPerNode[name].forEach(g => g.remove());
delete podsPerNode[name];
}
// Remove node rect and label
const rects = svg.querySelectorAll("rect.node");
rects.forEach(r => {
if(r.nextSibling && r.nextSibling.textContent === name){
r.remove();
}
});
const labels = svg.querySelectorAll("text.label");
labels.forEach(t => {
if(t.textContent === name) t.remove();
});
}
function refreshNodes(){
fetch("/api/nodes")
.then(res => res.json())
.then(nodeNames => {
// Remove existing node visuals
svg.querySelectorAll("rect.node").forEach(n => n.remove());
svg.querySelectorAll("text.label").forEach(n => n.remove());
// Reset node state
for(const k in nodePositions){
delete nodePositions[k];
}
// Rebuild nodes from cluster state
nodeNames.forEach((name, i) => {
addNode(name, i);
});
});
}
// Initial node fetch
refreshNodes();
// Refresh every 5s
setInterval(refreshNodes, 5000);
// Draw pods
fetch("/api/pods")
.then(res => res.json())
.then(podsByNode => {
for(const nodeName in podsByNode){
podsByNode[nodeName].forEach(podName => addPod(podName, nodeName));
}
});
// Add a pod
function addPod(podName, nodeName){
if(!nodePositions[nodeName]) return;
const stack = podsPerNode[nodeName] || [];
const index = stack.length;
const x = nodePositions[nodeName].x - nodeWidth/2;
const y = nodeY + nodeHeight + index*(podHeight + podSpacing);
const g = document.createElementNS("http://www.w3.org/2000/svg","g");
g.dataset.podName = podName;
const rect = document.createElementNS("http://www.w3.org/2000/svg","rect");
rect.setAttribute("x", x);
rect.setAttribute("y", y);
rect.setAttribute("width", nodeWidth);
rect.setAttribute("height", podHeight);
rect.setAttribute("class","pod");
g.appendChild(rect);
// Pod text
const text = document.createElementNS("http://www.w3.org/2000/svg","text");
text.setAttribute("class","pod-label");
text.setAttribute("text-anchor","middle");
text.setAttribute("x", x + nodeWidth/2);
text.setAttribute("y", y);
g.appendChild(text);
const truncatedName = truncatePodName(podName);
const maxCharsPerLine = 16;
for(let i = 0; i < truncatedName.length; i += maxCharsPerLine){
const tspan = document.createElementNS("http://www.w3.org/2000/svg","tspan");
tspan.setAttribute("x", x + nodeWidth/2);
tspan.setAttribute("dy", i===0 ? textPaddingY + 10 : 14);
tspan.textContent = truncatedName.substr(i, maxCharsPerLine);
text.appendChild(tspan);
}
svg.appendChild(g);
stack.push(g);
podsPerNode[nodeName] = stack;
updateSVGHeight();
}
// Update SVG height
function updateSVGHeight(){
let maxY = nodeY + nodeHeight;
for(const nodeName in podsPerNode){
const stack = podsPerNode[nodeName];
if(!stack || stack.length === 0) continue;
const bottomY = nodeY + nodeHeight + stack.length*(podHeight + podSpacing);
if(bottomY > maxY) maxY = bottomY;
}
svg.setAttribute("height", maxY + 20);
}
// Animate pod move
function flyPod(podName, fromNode, toNode){
if(!fromNode || !toNode) return;
const fromStack = podsPerNode[fromNode];
const idx = fromStack.findIndex(g => g.dataset.podName === podName);
if(idx === -1) return;
const g = fromStack[idx];
fromStack.splice(idx,1);
redrawPods(fromNode);
svg.appendChild(g);
const rect = g.querySelector("rect");
const text = g.querySelector("text");
const startX = parseFloat(rect.getAttribute("x"));
const startY = parseFloat(rect.getAttribute("y"));
const endX = nodePositions[toNode].x - nodeWidth/2;
const endY = nodeY + nodeHeight + podsPerNode[toNode].length*(podHeight+podSpacing);
let progress = 0;
const steps = 60;
const dx = (endX - startX)/steps;
const dy = (endY - startY)/steps;
const anim = setInterval(()=>{
progress++;
const nx = startX + dx*progress;
const ny = startY + dy*progress;
rect.setAttribute("x", nx);
rect.setAttribute("y", ny);
text.setAttribute("x", nx + nodeWidth/2);
if(progress>=steps){
clearInterval(anim);
podsPerNode[toNode].push(g);
redrawPods(toNode);
}
}, animationDuration/steps);
}
// Redraw pods stack on node
function redrawPods(nodeName){
if(!podsPerNode[nodeName]) return;
podsPerNode[nodeName].forEach((g,idx)=>{
const rect = g.querySelector("rect");
const text = g.querySelector("text");
const x = nodePositions[nodeName].x - nodeWidth/2;
const y = nodeY + nodeHeight + idx*(podHeight+podSpacing);
rect.setAttribute("x", x);
rect.setAttribute("y", y);
text.setAttribute("x", x + nodeWidth/2);
text.setAttribute("y", y);
});
updateSVGHeight();
}
// SSE stream
const evtSource = new EventSource("/api/stream");
evtSource.onmessage = e => {
const evt = JSON.parse(e.data);
if(evt.fromNode === evt.toNode){
redrawPods(evt.toNode);
return;
}
if(!evt.fromNode){
addPod(evt.pod, evt.toNode);
redrawPods(evt.toNode);
} else {
flyPod(evt.pod, evt.fromNode, evt.toNode);
}
};
</script>
</body>
</html>
+313
View File
@@ -0,0 +1,313 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Node Balancer</title>
<style>
html, body {
margin: 0;
padding: 0;
min-height: 100%;
}
body { font-family: sans-serif; margin: 20px; }
svg { border:1px solid #ccc; width:100%; background:#f9f9f9; }
.node { fill:#4CAF50; stroke:#333; stroke-width:2; }
.pod { fill:#2196F3; stroke:#000; stroke-width:1; }
.label { font-size:14px; text-anchor:middle; dominant-baseline:middle; }
.pod-label { font-size:14px; text-anchor:middle; fill:#fff; }
header {
display: flex;
align-items: center;
margin-bottom: 20px;
background-color: #f0f0f0;
padding: 10px 15px;
border-radius: 8px;
}
header .logo {
font-weight: bold;
font-size: 18px;
color: #2196F3;
margin-right: 15px;
padding: 5px 10px;
background-color: #333;
color: #fff;
border-radius: 4px;
font-family: monospace;
}
header .title {
font-size: 18px;
}
header .title span {
margin-left: 10px;
color: #555;
font-weight: normal;
}
header .cluster-label {
margin-left: 20px;
color: #333;
font-weight: normal;
}
</style>
</head>
<body>
<header>
<div class="logo">allarddcs</div>
<div class="title">
Node Balancer <span id="version">v?</span>
<span class="cluster-label">Cluster: <span id="cluster-name">?</span></span>
</div>
</header>
<svg id="canvas"></svg>
<script>
const svg = document.getElementById("canvas");
// Node/pod layout constants
const nodePositions = {};
const nodeY = 50;
const nodeWidth = 120;
const nodeHeight = 55;
const podHeight = 36;
const podSpacing = 6;
const textPaddingY = 6;
let animationDuration = 2000;
const podsPerNode = {};
// Fetch config
fetch("/api/config")
.then(res => res.json())
.then(cfg => {
animationDuration = cfg.animationDurationMs;
document.getElementById("version").textContent = "v" + cfg.version;
document.getElementById("cluster-name").textContent = cfg.clusterName;
});
// Utility: truncate pod names
function truncatePodName(podName){
// remove trailing hash if present
const parts = podName.split("-");
if(parts.length > 2){
return parts.slice(0, parts.length-2).join("-");
}
return podName;
}
// Draw a node
function addNode(name, index){
const x = 50 + index*220;
nodePositions[name] = {x: x + nodeWidth/2, y: nodeY + nodeHeight/2};
// Node rectangle
const rect = document.createElementNS("http://www.w3.org/2000/svg","rect");
rect.setAttribute("x", x);
rect.setAttribute("y", nodeY);
rect.setAttribute("width", nodeWidth);
rect.setAttribute("height", nodeHeight);
rect.setAttribute("class","node");
svg.appendChild(rect);
// Node label
const label = document.createElementNS("http://www.w3.org/2000/svg","text");
label.setAttribute("x", x + nodeWidth/2);
label.setAttribute("y", nodeY + nodeHeight/2);
label.setAttribute("class","label");
label.setAttribute("text-anchor","middle");
label.setAttribute("dominant-baseline","middle");
label.textContent = name;
svg.appendChild(label);
podsPerNode[name] = [];
}
// Add a pod
function addPod(podName, nodeName){
if(!nodePositions[nodeName]) return;
const stack = podsPerNode[nodeName] || [];
const index = stack.length;
const x = nodePositions[nodeName].x - nodeWidth/2;
const y = nodeY + nodeHeight + index*(podHeight + podSpacing);
const g = document.createElementNS("http://www.w3.org/2000/svg","g");
g.dataset.podName = podName;
const rect = document.createElementNS("http://www.w3.org/2000/svg","rect");
rect.setAttribute("x", x);
rect.setAttribute("y", y);
rect.setAttribute("width", nodeWidth);
rect.setAttribute("height", podHeight);
rect.setAttribute("class","pod");
g.appendChild(rect);
// Pod label
const text = document.createElementNS("http://www.w3.org/2000/svg","text");
text.setAttribute("class","pod-label");
text.setAttribute("text-anchor","middle");
text.setAttribute("x", x + nodeWidth/2);
const truncated = truncatePodName(podName);
if(truncated.length <= 12){
text.setAttribute("y", y + podHeight/2 + textPaddingY/2);
text.setAttribute("dominant-baseline","middle");
text.textContent = truncated;
} else {
// split into two lines
const line1 = truncated.substring(0,12);
const line2 = truncated.substring(12);
text.setAttribute("y", y + textPaddingY + 6);
const t1 = document.createElementNS("http://www.w3.org/2000/svg","tspan");
t1.setAttribute("x", x + nodeWidth/2);
t1.textContent = line1;
const t2 = document.createElementNS("http://www.w3.org/2000/svg","tspan");
t2.setAttribute("x", x + nodeWidth/2);
t2.setAttribute("dy", "12");
t2.textContent = line2;
text.appendChild(t1);
text.appendChild(t2);
}
g.appendChild(text);
svg.appendChild(g);
stack.push(g);
podsPerNode[nodeName] = stack;
updateSVGHeight();
}
// Update SVG height
function updateSVGHeight() {
let maxY = nodeY + nodeHeight;
for(const nodeName in podsPerNode){
const stack = podsPerNode[nodeName];
if(!stack || stack.length===0) continue;
const bottomY = nodeY + nodeHeight + stack.length*(podHeight + podSpacing);
if(bottomY > maxY) maxY = bottomY;
}
svg.setAttribute("height", maxY + 20);
}
// Animate pod move
function flyPod(podName, fromNode, toNode){
if(!fromNode || !toNode) return;
const fromStack = podsPerNode[fromNode];
const idx = fromStack.findIndex(g => g.dataset.podName===podName);
if(idx===-1) return;
const g = fromStack[idx];
fromStack.splice(idx,1);
redrawPods(fromNode);
svg.appendChild(g);
const rect = g.querySelector("rect");
const text = g.querySelector("text");
const startX = parseFloat(rect.getAttribute("x"));
const startY = parseFloat(rect.getAttribute("y"));
const endX = nodePositions[toNode].x - nodeWidth/2;
const endY = nodeY + nodeHeight + podsPerNode[toNode].length*(podHeight+podSpacing);
let progress = 0;
const steps = 60;
const dx = (endX - startX)/steps;
const dy = (endY - startY)/steps;
const anim = setInterval(()=>{
progress++;
const nx = startX + dx*progress;
const ny = startY + dy*progress;
rect.setAttribute("x", nx);
rect.setAttribute("y", ny);
text.setAttribute("x", nx + nodeWidth/2);
text.setAttribute("y", ny + podHeight/2 + textPaddingY/2);
if(progress>=steps){
clearInterval(anim);
podsPerNode[toNode].push(g);
redrawPods(toNode);
}
}, animationDuration/steps);
}
// Redraw pods on a node
function redrawPods(nodeName){
if(!podsPerNode[nodeName]) return;
podsPerNode[nodeName].forEach((g,idx)=>{
const rect = g.querySelector("rect");
const text = g.querySelector("text");
const x = nodePositions[nodeName].x - nodeWidth/2;
const y = nodeY + nodeHeight + idx*(podHeight+podSpacing);
rect.setAttribute("x", x);
rect.setAttribute("y", y);
text.setAttribute("x", x + nodeWidth/2);
text.setAttribute("y", y + podHeight/2 + textPaddingY/2);
});
updateSVGHeight();
}
// Fetch authoritative cluster state and redraw
function refreshCluster(){
Promise.all([
fetch("/api/nodes").then(r=>r.json()),
fetch("/api/pods").then(r=>r.json())
]).then(([nodeNames, podsByNode])=>{
// clear SVG
while(svg.firstChild) svg.removeChild(svg.firstChild);
// reset state
for(const k in nodePositions) delete nodePositions[k];
for(const k in podsPerNode) delete podsPerNode[k];
// draw nodes
nodeNames.forEach((name,i)=>addNode(name,i));
// draw pods
for(const nodeName in podsByNode){
podsByNode[nodeName].forEach(podName=>{
addPod(podName,nodeName);
});
}
updateSVGHeight();
});
}
// SSE events
const evtSource = new EventSource("/api/stream");
evtSource.onmessage = e=>{
const evt = JSON.parse(e.data);
if(evt.fromNode && evt.toNode && evt.fromNode !== evt.toNode){
// animate first
flyPod(evt.pod, evt.fromNode, evt.toNode);
// then authoritative redraw after animation
setTimeout(refreshCluster, animationDuration);
} else {
// no animation needed
refreshCluster();
}
};
// Periodic refresh every 5s
setInterval(refreshCluster, 5000);
// Initial load
refreshCluster();
</script>
</body>
</html>
+342
View File
@@ -0,0 +1,342 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Node Balancer</title>
<style>
html, body {
margin: 0;
padding: 0;
min-height: 100%;
}
body { font-family: sans-serif; margin: 20px; }
svg { border:1px solid #ccc; width:100%; background:#f9f9f9; }
.node { fill:#4CAF50; stroke:#333; stroke-width:2; }
.pod { fill:#2196F3; stroke:#000; stroke-width:1; }
.label { font-size:14px; text-anchor:middle; dominant-baseline:middle; }
.pod-label { font-size:14px; text-anchor:middle; fill:#fff; }
header {
display: flex;
align-items: center;
margin-bottom: 20px;
background-color: #f0f0f0;
padding: 10px 15px;
border-radius: 8px;
}
header .logo {
font-weight: bold;
font-size: 18px;
color: #2196F3;
margin-right: 15px;
padding: 5px 10px;
background-color: #333;
color: #fff;
border-radius: 4px;
font-family: monospace;
}
header .title {
font-size: 18px;
}
header .title span {
margin-left: 10px;
color: #555;
font-weight: normal;
}
header .cluster-label {
margin-left: 20px;
color: #333;
font-weight: normal;
}
</style>
</head>
<body>
<header>
<div class="logo">allarddcs</div>
<div class="title">
Node Balancer <span id="version">v?</span>
<span class="cluster-label">Cluster: <span id="cluster-name">?</span></span>
</div>
</header>
<svg id="canvas"></svg>
<script>
const svg = document.getElementById("canvas");
// Node/pod layout constants
const nodePositions = {};
const nodeY = 50;
const nodeWidth = 120;
const nodeHeight = 55;
const podHeight = 36;
const podSpacing = 6;
const textPaddingY = 6;
let animationDuration = 2000;
const podsPerNode = {};
// Fetch config
fetch("/api/config")
.then(res => res.json())
.then(cfg => {
animationDuration = cfg.animationDurationMs;
document.getElementById("version").textContent = "v" + cfg.version;
document.getElementById("cluster-name").textContent = cfg.clusterName;
});
// Remove trailing k8s-style hash if present
function truncatePodName(podName){
const parts = podName.split("-");
// Helper: is this segment a k8s-style hash?
// Alphanumeric, length >= 5, not a short numeric like "0", "1", "2"…
function isHash(seg){
return /^[a-z0-9]{5,}$/.test(seg);
}
// Remove trailing hash segments until we hit a non-hash or only one segment left
while(parts.length > 1 && isHash(parts[parts.length-1])){
parts.pop();
}
return parts.join("-");
}
// Split pod name over multiple lines without breaking words
function splitPodNameLines(podName, maxCharsPerLine=12){
const words = podName.split("-");
const lines = [];
let currentLine = "";
words.forEach(word => {
if(currentLine.length === 0){
currentLine = word;
} else if((currentLine.length + 1 + word.length) <= maxCharsPerLine){
currentLine += "-" + word;
} else {
lines.push(currentLine);
currentLine = word;
}
});
if(currentLine) lines.push(currentLine);
return lines;
}
// Draw a node
function addNode(name, index){
const x = 50 + index*220;
nodePositions[name] = {x: x + nodeWidth/2, y: nodeY + nodeHeight/2};
// Node rectangle
const rect = document.createElementNS("http://www.w3.org/2000/svg","rect");
rect.setAttribute("x", x);
rect.setAttribute("y", nodeY);
rect.setAttribute("width", nodeWidth);
rect.setAttribute("height", nodeHeight);
rect.setAttribute("class","node");
svg.appendChild(rect);
// Node label
const label = document.createElementNS("http://www.w3.org/2000/svg","text");
label.setAttribute("x", x + nodeWidth/2);
label.setAttribute("y", nodeY + nodeHeight/2);
label.setAttribute("class","label");
label.setAttribute("text-anchor","middle");
label.setAttribute("dominant-baseline","middle");
label.textContent = name;
svg.appendChild(label);
podsPerNode[name] = [];
}
// Add a pod
function addPod(podName, nodeName){
if(!nodePositions[nodeName]) return;
const stack = podsPerNode[nodeName] || [];
const index = stack.length;
const x = nodePositions[nodeName].x - nodeWidth/2;
const y = nodeY + nodeHeight + index*(podHeight + podSpacing);
const g = document.createElementNS("http://www.w3.org/2000/svg","g");
g.dataset.podName = podName;
const rect = document.createElementNS("http://www.w3.org/2000/svg","rect");
rect.setAttribute("x", x);
rect.setAttribute("y", y);
rect.setAttribute("width", nodeWidth);
rect.setAttribute("height", podHeight);
rect.setAttribute("class","pod");
g.appendChild(rect);
// Pod label
const text = document.createElementNS("http://www.w3.org/2000/svg","text");
text.setAttribute("class","pod-label");
text.setAttribute("text-anchor","middle");
text.setAttribute("x", x + nodeWidth/2);
const truncated = truncatePodName(podName);
if(truncated.length <= 12){
text.setAttribute("y", y + podHeight/2 + textPaddingY/2);
text.setAttribute("dominant-baseline","middle");
text.textContent = truncated;
} else {
// split into two lines
const line1 = truncated.substring(0,12);
const line2 = truncated.substring(12);
text.setAttribute("y", y + textPaddingY + 6);
const t1 = document.createElementNS("http://www.w3.org/2000/svg","tspan");
t1.setAttribute("x", x + nodeWidth/2);
t1.textContent = line1;
const t2 = document.createElementNS("http://www.w3.org/2000/svg","tspan");
t2.setAttribute("x", x + nodeWidth/2);
t2.setAttribute("dy", "12");
t2.textContent = line2;
text.appendChild(t1);
text.appendChild(t2);
}
g.appendChild(text);
svg.appendChild(g);
stack.push(g);
podsPerNode[nodeName] = stack;
updateSVGHeight();
}
// Update SVG height
function updateSVGHeight() {
let maxY = nodeY + nodeHeight;
for(const nodeName in podsPerNode){
const stack = podsPerNode[nodeName];
if(!stack || stack.length===0) continue;
const bottomY = nodeY + nodeHeight + stack.length*(podHeight + podSpacing);
if(bottomY > maxY) maxY = bottomY;
}
svg.setAttribute("height", maxY + 20);
}
// Animate pod move
function flyPod(podName, fromNode, toNode){
if(!fromNode || !toNode) return;
const fromStack = podsPerNode[fromNode];
const idx = fromStack.findIndex(g => g.dataset.podName===podName);
if(idx===-1) return;
const g = fromStack[idx];
fromStack.splice(idx,1);
redrawPods(fromNode);
svg.appendChild(g);
const rect = g.querySelector("rect");
const text = g.querySelector("text");
const startX = parseFloat(rect.getAttribute("x"));
const startY = parseFloat(rect.getAttribute("y"));
const endX = nodePositions[toNode].x - nodeWidth/2;
const endY = nodeY + nodeHeight + podsPerNode[toNode].length*(podHeight+podSpacing);
let progress = 0;
const steps = 60;
const dx = (endX - startX)/steps;
const dy = (endY - startY)/steps;
const anim = setInterval(()=>{
progress++;
const nx = startX + dx*progress;
const ny = startY + dy*progress;
rect.setAttribute("x", nx);
rect.setAttribute("y", ny);
text.setAttribute("x", nx + nodeWidth/2);
text.setAttribute("y", ny + podHeight/2 + textPaddingY/2);
if(progress>=steps){
clearInterval(anim);
podsPerNode[toNode].push(g);
redrawPods(toNode);
}
}, animationDuration/steps);
}
// Redraw pods on a node
function redrawPods(nodeName){
if(!podsPerNode[nodeName]) return;
podsPerNode[nodeName].forEach((g,idx)=>{
const rect = g.querySelector("rect");
const text = g.querySelector("text");
const x = nodePositions[nodeName].x - nodeWidth/2;
const y = nodeY + nodeHeight + idx*(podHeight+podSpacing);
rect.setAttribute("x", x);
rect.setAttribute("y", y);
text.setAttribute("x", x + nodeWidth/2);
text.setAttribute("y", y + podHeight/2 + textPaddingY/2);
});
updateSVGHeight();
}
// Fetch authoritative cluster state and redraw
function refreshCluster(){
Promise.all([
fetch("/api/nodes").then(r=>r.json()),
fetch("/api/pods").then(r=>r.json())
]).then(([nodeNames, podsByNode])=>{
// clear SVG
while(svg.firstChild) svg.removeChild(svg.firstChild);
// reset state
for(const k in nodePositions) delete nodePositions[k];
for(const k in podsPerNode) delete podsPerNode[k];
// draw nodes
nodeNames.forEach((name,i)=>addNode(name,i));
// draw pods
for(const nodeName in podsByNode){
podsByNode[nodeName].forEach(podName=>{
addPod(podName,nodeName);
});
}
updateSVGHeight();
});
}
// SSE events
const evtSource = new EventSource("/api/stream");
evtSource.onmessage = e=>{
const evt = JSON.parse(e.data);
if(evt.fromNode && evt.toNode && evt.fromNode !== evt.toNode){
// animate first
flyPod(evt.pod, evt.fromNode, evt.toNode);
// then authoritative redraw after animation
setTimeout(refreshCluster, animationDuration);
} else {
// no animation needed
refreshCluster();
}
};
// Periodic refresh every 5s
setInterval(refreshCluster, 5000);
// Initial load
refreshCluster();
</script>
</body>
</html>
+350
View File
@@ -0,0 +1,350 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Node Balancer</title>
<style>
html, body {
margin: 0;
padding: 0;
min-height: 100%;
}
body { font-family: sans-serif; margin: 20px; }
svg { border:1px solid #ccc; width:100%; background:#f9f9f9; }
.node { fill:#4CAF50; stroke:#333; stroke-width:2; }
.pod { fill:#2196F3; stroke:#000; stroke-width:1; }
.label { font-size:14px; text-anchor:middle; dominant-baseline:middle; }
.pod-label { font-size:14px; text-anchor:middle; fill:#fff; }
header {
display: flex;
align-items: center;
margin-bottom: 20px;
background-color: #f0f0f0;
padding: 10px 15px;
border-radius: 8px;
}
header .logo {
font-weight: bold;
font-size: 18px;
color: #2196F3;
margin-right: 15px;
padding: 5px 10px;
background-color: #333;
color: #fff;
border-radius: 4px;
font-family: monospace;
}
header .title {
font-size: 18px;
}
header .title span {
margin-left: 10px;
color: #555;
font-weight: normal;
}
header .cluster-label {
margin-left: 20px;
color: #333;
font-weight: normal;
}
</style>
</head>
<body>
<header>
<div class="logo">allarddcs</div>
<div class="title">
Node Balancer <span id="version">v?</span>
<span class="cluster-label">Cluster: <span id="cluster-name">?</span></span>
</div>
</header>
<svg id="canvas"></svg>
<script>
const svg = document.getElementById("canvas");
// Node/pod layout constants
const nodePositions = {};
const nodeY = 50;
const nodeWidth = 120;
const nodeHeight = 55;
const podHeight = 36;
const podSpacing = 6;
const textPaddingY = 6;
let animationDuration = 2000;
const podsPerNode = {};
// Fetch config
fetch("/api/config")
.then(res => res.json())
.then(cfg => {
animationDuration = cfg.animationDurationMs;
document.getElementById("version").textContent = "v" + cfg.version;
document.getElementById("cluster-name").textContent = cfg.clusterName;
});
// Remove trailing k8s-style hash if present
function truncatePodName(podName) {
const parts = podName.split("-");
function isPodId(seg) {
// Pod suffix like "9tl49"
return /^[a-z0-9]{5}$/.test(seg);
}
function isReplicaSetHash(seg) {
// ReplicaSet hash typically 8–10 hex chars
return /^[a-f0-9]{8,10}$/.test(seg);
}
if (parts.length > 1 && isPodId(parts[parts.length - 1])) {
parts.pop();
}
if (parts.length > 1 && isReplicaSetHash(parts[parts.length - 1])) {
parts.pop();
}
return parts.join("-");
}
// Split pod name over multiple lines without breaking words
function splitPodNameLines(podName, maxCharsPerLine=12){
const words = podName.split("-");
const lines = [];
let currentLine = "";
words.forEach(word => {
if(currentLine.length === 0){
currentLine = word;
} else if((currentLine.length + 1 + word.length) <= maxCharsPerLine){
currentLine += "-" + word;
} else {
lines.push(currentLine);
currentLine = word;
}
});
if(currentLine) lines.push(currentLine);
return lines;
}
// Draw a node
function addNode(name, index){
const x = 50 + index*220;
nodePositions[name] = {x: x + nodeWidth/2, y: nodeY + nodeHeight/2};
// Node rectangle
const rect = document.createElementNS("http://www.w3.org/2000/svg","rect");
rect.setAttribute("x", x);
rect.setAttribute("y", nodeY);
rect.setAttribute("width", nodeWidth);
rect.setAttribute("height", nodeHeight);
rect.setAttribute("class","node");
svg.appendChild(rect);
// Node label
const label = document.createElementNS("http://www.w3.org/2000/svg","text");
label.setAttribute("x", x + nodeWidth/2);
label.setAttribute("y", nodeY + nodeHeight/2);
label.setAttribute("class","label");
label.setAttribute("text-anchor","middle");
label.setAttribute("dominant-baseline","middle");
label.textContent = name;
svg.appendChild(label);
podsPerNode[name] = [];
}
// Add a pod
function addPod(podName, nodeName){
if(!nodePositions[nodeName]) return;
const stack = podsPerNode[nodeName] || [];
const index = stack.length;
const x = nodePositions[nodeName].x - nodeWidth/2;
const y = nodeY + nodeHeight + index*(podHeight + podSpacing);
const g = document.createElementNS("http://www.w3.org/2000/svg","g");
g.dataset.podName = podName;
const rect = document.createElementNS("http://www.w3.org/2000/svg","rect");
rect.setAttribute("x", x);
rect.setAttribute("y", y);
rect.setAttribute("width", nodeWidth);
rect.setAttribute("height", podHeight);
rect.setAttribute("class","pod");
g.appendChild(rect);
// Pod label
const text = document.createElementNS("http://www.w3.org/2000/svg","text");
text.setAttribute("class","pod-label");
text.setAttribute("text-anchor","middle");
text.setAttribute("x", x + nodeWidth/2);
const truncated = truncatePodName(podName);
if(truncated.length <= 12){
text.setAttribute("y", y + podHeight/2 + textPaddingY/2);
text.setAttribute("dominant-baseline","middle");
text.textContent = truncated;
} else {
// split into two lines
const line1 = truncated.substring(0,12);
const line2 = truncated.substring(12);
text.setAttribute("y", y + textPaddingY + 6);
const t1 = document.createElementNS("http://www.w3.org/2000/svg","tspan");
t1.setAttribute("x", x + nodeWidth/2);
t1.textContent = line1;
const t2 = document.createElementNS("http://www.w3.org/2000/svg","tspan");
t2.setAttribute("x", x + nodeWidth/2);
t2.setAttribute("dy", "12");
t2.textContent = line2;
text.appendChild(t1);
text.appendChild(t2);
}
g.appendChild(text);
svg.appendChild(g);
stack.push(g);
podsPerNode[nodeName] = stack;
updateSVGHeight();
}
// Update SVG height
function updateSVGHeight() {
let maxY = nodeY + nodeHeight;
for(const nodeName in podsPerNode){
const stack = podsPerNode[nodeName];
if(!stack || stack.length===0) continue;
const bottomY = nodeY + nodeHeight + stack.length*(podHeight + podSpacing);
if(bottomY > maxY) maxY = bottomY;
}
svg.setAttribute("height", maxY + 20);
}
// Animate pod move
function flyPod(podName, fromNode, toNode){
if(!fromNode || !toNode) return;
const fromStack = podsPerNode[fromNode];
const idx = fromStack.findIndex(g => g.dataset.podName===podName);
if(idx===-1) return;
const g = fromStack[idx];
fromStack.splice(idx,1);
redrawPods(fromNode);
svg.appendChild(g);
const rect = g.querySelector("rect");
const text = g.querySelector("text");
const startX = parseFloat(rect.getAttribute("x"));
const startY = parseFloat(rect.getAttribute("y"));
const endX = nodePositions[toNode].x - nodeWidth/2;
const endY = nodeY + nodeHeight + podsPerNode[toNode].length*(podHeight+podSpacing);
let progress = 0;
const steps = 60;
const dx = (endX - startX)/steps;
const dy = (endY - startY)/steps;
const anim = setInterval(()=>{
progress++;
const nx = startX + dx*progress;
const ny = startY + dy*progress;
rect.setAttribute("x", nx);
rect.setAttribute("y", ny);
text.setAttribute("x", nx + nodeWidth/2);
text.setAttribute("y", ny + podHeight/2 + textPaddingY/2);
if(progress>=steps){
clearInterval(anim);
podsPerNode[toNode].push(g);
redrawPods(toNode);
}
}, animationDuration/steps);
}
// Redraw pods on a node
function redrawPods(nodeName){
if(!podsPerNode[nodeName]) return;
podsPerNode[nodeName].forEach((g,idx)=>{
const rect = g.querySelector("rect");
const text = g.querySelector("text");
const x = nodePositions[nodeName].x - nodeWidth/2;
const y = nodeY + nodeHeight + idx*(podHeight+podSpacing);
rect.setAttribute("x", x);
rect.setAttribute("y", y);
text.setAttribute("x", x + nodeWidth/2);
text.setAttribute("y", y + podHeight/2 + textPaddingY/2);
});
updateSVGHeight();
}
// Fetch authoritative cluster state and redraw
function refreshCluster(){
Promise.all([
fetch("/api/nodes").then(r=>r.json()),
fetch("/api/pods").then(r=>r.json())
]).then(([nodeNames, podsByNode])=>{
// clear SVG
while(svg.firstChild) svg.removeChild(svg.firstChild);
// reset state
for(const k in nodePositions) delete nodePositions[k];
for(const k in podsPerNode) delete podsPerNode[k];
// draw nodes
nodeNames.forEach((name,i)=>addNode(name,i));
// draw pods
for(const nodeName in podsByNode){
podsByNode[nodeName].forEach(podName=>{
addPod(podName,nodeName);
});
}
updateSVGHeight();
});
}
// SSE events
const evtSource = new EventSource("/api/stream");
evtSource.onmessage = e=>{
const evt = JSON.parse(e.data);
if(evt.fromNode && evt.toNode && evt.fromNode !== evt.toNode){
// animate first
flyPod(evt.pod, evt.fromNode, evt.toNode);
// then authoritative redraw after animation
setTimeout(refreshCluster, animationDuration);
} else {
// no animation needed
refreshCluster();
}
};
// Periodic refresh every 5s
setInterval(refreshCluster, 5000);
// Initial load
refreshCluster();
</script>
</body>
</html>
+152
View File
@@ -0,0 +1,152 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Node Balancer</title>
<style>
body { font-family: sans-serif; margin: 20px; }
svg { border:1px solid #ccc; width:100%; height:500px; background:#f9f9f9; }
.node { fill:#4CAF50; stroke:#333; stroke-width:2; }
.pod { fill:#2196F3; stroke:#000; stroke-width:1; }
.label { font-size:14px; text-anchor:middle; }
.pod-label { font-size:10px; text-anchor:middle; dominant-baseline:middle; fill:#fff; }
</style>
</head>
<body>
<h2>Node Balancer</h2>
<svg id="canvas"></svg>
<script>
const svg = document.getElementById("canvas");
const nodePositions = {};
const nodeY = 50;
const nodeWidth = 100;
const nodeHeight = 40;
let animationDuration = 2000;
// fetch animation duration
fetch("/api/config")
.then(res => res.json())
.then(cfg => { animationDuration = cfg.animationDurationMs; });
// fetch nodes
fetch("/api/nodes")
.then(res => res.json())
.then(nodeNames => {
nodeNames.forEach((name,i)=>{
const x = 50 + i*200;
nodePositions[name] = {x: x + nodeWidth/2, y: nodeY + nodeHeight/2};
// Node box
const rect = document.createElementNS("http://www.w3.org/2000/svg","rect");
rect.setAttribute("x", x);
rect.setAttribute("y", nodeY);
rect.setAttribute("width", nodeWidth);
rect.setAttribute("height", nodeHeight);
rect.setAttribute("class", "node");
svg.appendChild(rect);
// Node label
const label = document.createElementNS("http://www.w3.org/2000/svg","text");
label.setAttribute("x", x + nodeWidth/2);
label.setAttribute("y", nodeY + nodeHeight/2);
label.setAttribute("class","label");
label.textContent = name;
svg.appendChild(label);
});
});
fetch("/api/pods")
.then(res => res.json())
.then(podsByNode => {
for(const nodeName in podsByNode){
podsByNode[nodeName].forEach(podName => addPod(podName, nodeName));
}
});
// pod tracking per node
const podsPerNode = {};
// function to show pod vertically under node
function addPod(podName, nodeName) {
if(!nodePositions[nodeName]) return;
if(!podsPerNode[nodeName]) podsPerNode[nodeName] = [];
const podIndex = podsPerNode[nodeName].length;
const x = nodePositions[nodeName].x;
const y = nodeY + nodeHeight + 20 + podIndex*25;
const g = document.createElementNS("http://www.w3.org/2000/svg","g");
const circle = document.createElementNS("http://www.w3.org/2000/svg","circle");
circle.setAttribute("cx", x);
circle.setAttribute("cy", y);
circle.setAttribute("r", 10);
circle.setAttribute("class","pod");
g.appendChild(circle);
const text = document.createElementNS("http://www.w3.org/2000/svg","text");
text.setAttribute("x", x);
text.setAttribute("y", y);
text.setAttribute("class","pod-label");
text.textContent = podName;
g.appendChild(text);
svg.appendChild(g);
podsPerNode[nodeName].push(g);
}
// animate pod move
function movePod(podName, fromNode, toNode) {
const fromPods = podsPerNode[fromNode];
if(!fromPods) return;
// find pod element
let podG = null;
for(let i=0;i<fromPods.length;i++){
const g = fromPods[i];
const text = g.querySelector("text");
if(text && text.textContent === podName){
podG = g;
fromPods.splice(i,1); // remove from old node
break;
}
}
if(!podG) return;
// add to new node
if(!podsPerNode[toNode]) podsPerNode[toNode]=[];
podsPerNode[toNode].push(podG);
const steps = 60;
let progress=0;
const start = podG.querySelector("circle").getAttribute("cy")*1;
const end = nodeY + nodeHeight + 20 + (podsPerNode[toNode].length-1)*25;
const dx = nodePositions[toNode].x - nodePositions[fromNode].x;
const dy = end - start;
const anim = setInterval(()=>{
progress++;
const cx = nodePositions[fromNode].x + dx*progress/steps;
const cy = start + dy*progress/steps;
podG.querySelector("circle").setAttribute("cx", cx);
podG.querySelector("circle").setAttribute("cy", cy);
podG.querySelector("text").setAttribute("x", cx);
podG.querySelector("text").setAttribute("y", cy);
if(progress>=steps){
clearInterval(anim);
}
}, animationDuration/steps);
}
// SSE stream
const evtSource = new EventSource("/api/stream");
evtSource.onmessage = e => {
const evt = JSON.parse(e.data);
if(!evt.fromNode){
addPod(evt.pod, evt.toNode);
} else {
movePod(evt.pod, evt.fromNode, evt.toNode);
}
};
</script>
</body>
</html>
+329
View File
@@ -0,0 +1,329 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Node Balancer</title>
<style>
html, body {
margin: 0;
padding: 0;
min-height: 100%;
}
body { font-family: sans-serif; margin: 20px; }
svg { border:1px solid #ccc; width:100%; background:#f9f9f9; }
.node { fill:#4CAF50; stroke:#333; stroke-width:2; }
.pod { fill:#2196F3; stroke:#000; stroke-width:1; }
.label { font-size:14px; text-anchor:middle; dominant-baseline:middle; }
.pod-label { font-size:14px; text-anchor:middle; fill:#fff; }
header {
display: flex;
align-items: center;
margin-bottom: 20px;
background-color: #f0f0f0;
padding: 10px 15px;
border-radius: 8px;
}
header .logo {
font-weight: bold;
font-size: 18px;
color: #2196F3;
margin-right: 15px;
padding: 5px 10px;
background-color: #333;
color: #fff;
border-radius: 4px;
font-family: monospace;
}
header .title {
font-size: 18px;
}
header .title span {
margin-left: 10px;
color: #555;
font-weight: normal;
}
header .cluster-label {
margin-left: 20px;
color: #333;
font-weight: normal;
}
</style>
</head>
<body>
<header>
<div class="logo">allarddcs</div>
<div class="title">
Node Balancer <span id="version">v?</span>
<span class="cluster-label">Cluster: <span id="cluster-name">?</span></span>
</div>
</header>
<svg id="canvas"></svg>
<script>
const svg = document.getElementById("canvas");
// Node/pod layout constants
const nodePositions = {};
const nodeY = 50;
let nodeWidth = 120;
const nodeHeight = 55;
const podHeight = 36;
const podSpacing = 6;
const textPaddingY = 6;
let animationDuration = 2000;
const podsPerNode = {};
// Fetch config
fetch("/api/config")
.then(res => res.json())
.then(cfg => {
animationDuration = cfg.animationDurationMs;
document.getElementById("version").textContent = "v" + cfg.version;
document.getElementById("cluster-name").textContent = cfg.clusterName;
});
// Remove trailing k8s-style hash if present
function truncatePodName(podName) {
const parts = podName.split("-");
function isPodId(seg) { return /^[a-z0-9]{5}$/.test(seg); }
function isReplicaSetHash(seg) { return /^[a-f0-9]{8,10}$/.test(seg); }
if (parts.length > 1 && isPodId(parts[parts.length - 1])) parts.pop();
if (parts.length > 1 && isReplicaSetHash(parts[parts.length - 1])) parts.pop();
return parts.join("-");
}
// Split pod name into multiple lines
function splitPodNameLines(podName, maxCharsPerLine=12){
const words = podName.split("-");
const lines = [];
let currentLine = "";
words.forEach(word => {
if(currentLine.length === 0) currentLine = word;
else if((currentLine.length + 1 + word.length) <= maxCharsPerLine) currentLine += "-" + word;
else { lines.push(currentLine); currentLine = word; }
});
if(currentLine) lines.push(currentLine);
return lines;
}
// Draw a node (responsive)
function addNode(name, index, totalNodes){
const svgWidth = svg.clientWidth || window.innerWidth;
const outerPadding = 60; // distance from canvas edge
const innerMargin = 20; // breathing space inside edges
const usableWidth = svgWidth - 2 * outerPadding;
const spacing = totalNodes > 1
? usableWidth / totalNodes
: 0;
// Optional responsive node width scaling
const maxNodeWidth = 120;
const minNodeWidth = 60;
nodeWidth = Math.max(minNodeWidth, Math.min(maxNodeWidth, spacing * 0.8));
// Center nodes within their spacing slot
const centerX = outerPadding + spacing * index + spacing / 2;
const x = centerX - nodeWidth / 2;
nodePositions[name] = {
x: centerX,
y: nodeY + nodeHeight/2
};
// Node rectangle
const rect = document.createElementNS("http://www.w3.org/2000/svg","rect");
rect.setAttribute("x", x);
rect.setAttribute("y", nodeY);
rect.setAttribute("width", nodeWidth);
rect.setAttribute("height", nodeHeight);
rect.setAttribute("class","node");
svg.appendChild(rect);
// Node label
const label = document.createElementNS("http://www.w3.org/2000/svg","text");
label.setAttribute("x", centerX);
label.setAttribute("y", nodeY + nodeHeight/2);
label.setAttribute("class","label");
label.setAttribute("text-anchor","middle");
label.setAttribute("dominant-baseline","middle");
label.textContent = name;
svg.appendChild(label);
podsPerNode[name] = [];
}
// Add a pod
function addPod(podName, nodeName){
if(!nodePositions[nodeName]) return;
const stack = podsPerNode[nodeName] || [];
const index = stack.length;
const x = nodePositions[nodeName].x - nodeWidth/2;
const y = nodeY + nodeHeight + index*(podHeight + podSpacing);
const g = document.createElementNS("http://www.w3.org/2000/svg","g");
g.dataset.podName = podName;
const rect = document.createElementNS("http://www.w3.org/2000/svg","rect");
rect.setAttribute("x", x);
rect.setAttribute("y", y);
rect.setAttribute("width", nodeWidth);
rect.setAttribute("height", podHeight);
rect.setAttribute("class","pod");
g.appendChild(rect);
const text = document.createElementNS("http://www.w3.org/2000/svg","text");
text.setAttribute("class","pod-label");
text.setAttribute("text-anchor","middle");
text.setAttribute("x", x + nodeWidth/2);
const truncated = truncatePodName(podName);
if(truncated.length <= 12){
text.setAttribute("y", y + podHeight/2 + textPaddingY/2);
text.setAttribute("dominant-baseline","middle");
text.textContent = truncated;
} else {
const line1 = truncated.substring(0,12);
const line2 = truncated.substring(12);
text.setAttribute("y", y + textPaddingY + 6);
const t1 = document.createElementNS("http://www.w3.org/2000/svg","tspan");
t1.setAttribute("x", x + nodeWidth/2); t1.textContent = line1;
const t2 = document.createElementNS("http://www.w3.org/2000/svg","tspan");
t2.setAttribute("x", x + nodeWidth/2); t2.setAttribute("dy","12"); t2.textContent = line2;
text.appendChild(t1);
text.appendChild(t2);
}
g.appendChild(text);
svg.appendChild(g);
stack.push(g);
podsPerNode[nodeName] = stack;
updateSVGHeight();
}
// Update SVG height
function updateSVGHeight() {
let maxY = nodeY + nodeHeight;
for(const nodeName in podsPerNode){
const stack = podsPerNode[nodeName];
if(!stack || stack.length===0) continue;
const bottomY = nodeY + nodeHeight + stack.length*(podHeight + podSpacing);
if(bottomY > maxY) maxY = bottomY;
}
svg.setAttribute("height", maxY + 20);
}
// Animate pod move
function flyPod(podName, fromNode, toNode){
if(!fromNode || !toNode) return;
const fromStack = podsPerNode[fromNode];
const idx = fromStack.findIndex(g => g.dataset.podName===podName);
if(idx===-1) return;
const g = fromStack[idx];
fromStack.splice(idx,1);
redrawPods(fromNode);
svg.appendChild(g);
const rect = g.querySelector("rect");
const text = g.querySelector("text");
const startX = parseFloat(rect.getAttribute("x"));
const startY = parseFloat(rect.getAttribute("y"));
const endX = nodePositions[toNode].x - nodeWidth/2;
const endY = nodeY + nodeHeight + podsPerNode[toNode].length*(podHeight+podSpacing);
let progress = 0;
const steps = 60;
const dx = (endX - startX)/steps;
const dy = (endY - startY)/steps;
const anim = setInterval(()=>{
progress++;
const nx = startX + dx*progress;
const ny = startY + dy*progress;
rect.setAttribute("x", nx);
rect.setAttribute("y", ny);
text.setAttribute("x", nx + nodeWidth/2);
text.setAttribute("y", ny + podHeight/2 + textPaddingY/2);
if(progress>=steps){
clearInterval(anim);
podsPerNode[toNode].push(g);
redrawPods(toNode);
}
}, animationDuration/steps);
}
// Redraw pods on a node
function redrawPods(nodeName){
if(!podsPerNode[nodeName]) return;
podsPerNode[nodeName].forEach((g,idx)=>{
const rect = g.querySelector("rect");
const text = g.querySelector("text");
const x = nodePositions[nodeName].x - nodeWidth/2;
const y = nodeY + nodeHeight + idx*(podHeight+podSpacing);
rect.setAttribute("x", x);
rect.setAttribute("y", y);
text.setAttribute("x", x + nodeWidth/2);
text.setAttribute("y", y + podHeight/2 + textPaddingY/2);
});
updateSVGHeight();
}
// Fetch authoritative cluster state and redraw
function refreshCluster(){
Promise.all([
fetch("/api/nodes").then(r=>r.json()),
fetch("/api/pods").then(r=>r.json())
]).then(([nodeNames, podsByNode])=>{
while(svg.firstChild) svg.removeChild(svg.firstChild);
for(const k in nodePositions) delete nodePositions[k];
for(const k in podsPerNode) delete podsPerNode[k];
nodeNames.forEach((name,i)=>addNode(name,i,nodeNames.length));
for(const nodeName in podsByNode){
podsByNode[nodeName].forEach(podName=>addPod(podName,nodeName));
}
updateSVGHeight();
});
}
// SSE events
const evtSource = new EventSource("/api/stream");
evtSource.onmessage = e=>{
const evt = JSON.parse(e.data);
if(evt.fromNode && evt.toNode && evt.fromNode !== evt.toNode){
flyPod(evt.pod, evt.fromNode, evt.toNode);
setTimeout(refreshCluster, animationDuration);
} else {
refreshCluster();
}
};
// Periodic refresh every 5s
setInterval(refreshCluster, 5000);
// Responsive redraw on resize
window.addEventListener("resize", refreshCluster);
// Initial load
refreshCluster();
</script>
</body>
</html>
+196
View File
@@ -0,0 +1,196 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Node Balancer</title>
<style>
body { font-family: sans-serif; margin: 20px; }
svg { border:1px solid #ccc; width:100%; height:500px; background:#f9f9f9; }
.node { fill:#4CAF50; stroke:#333; stroke-width:2; }
.pod { fill:#2196F3; stroke:#000; stroke-width:1; }
.label { font-size:14px; text-anchor:middle; dominant-baseline:middle; }
.pod-label { font-size:14px; text-anchor:middle; dominant-baseline:middle; fill:#fff; }
</style>
</head>
<body>
<h2>Node Balancer</h2>
<svg id="canvas"></svg>
<script>
const svg = document.getElementById("canvas");
const nodePositions = {};
const nodeY = 50;
const nodeWidth = 100;
const nodeHeight = 40;
let animationDuration = 2000;
// Store pod stacks per node
const podsPerNode = {};
// Fetch animation duration from server
fetch("/api/config")
.then(res => res.json())
.then(cfg => { animationDuration = cfg.animationDurationMs; });
// Draw nodes
fetch("/api/nodes")
.then(res => res.json())
.then(nodeNames => {
nodeNames.forEach((name,i)=>{
const x = 50 + i*200;
nodePositions[name] = {x: x + nodeWidth/2, y: nodeY + nodeHeight/2};
// Node box
const rect = document.createElementNS("http://www.w3.org/2000/svg","rect");
rect.setAttribute("x", x);
rect.setAttribute("y", nodeY);
rect.setAttribute("width", nodeWidth);
rect.setAttribute("height", nodeHeight);
rect.setAttribute("class","node");
svg.appendChild(rect);
// Node label
const label = document.createElementNS("http://www.w3.org/2000/svg","text");
label.setAttribute("x", x + nodeWidth/2);
label.setAttribute("y", nodeY + nodeHeight/2);
label.setAttribute("class","label");
label.textContent = name;
svg.appendChild(label);
podsPerNode[name] = [];
});
// Fetch initial pods after nodes are drawn
fetch("/api/pods")
.then(res => res.json())
.then(podsByNode => {
for(const nodeName in podsByNode){
podsByNode[nodeName].forEach(podName => addPod(podName, nodeName));
}
});
});
// Add a pod to the stack under a node
function addPod(podName, nodeName){
if(!nodePositions[nodeName]) return;
const stack = podsPerNode[nodeName] || [];
const index = stack.length;
const x = nodePositions[nodeName].x - nodeWidth/2;
const y = nodeY + nodeHeight + index*25;
const g = document.createElementNS("http://www.w3.org/2000/svg","g");
const rect = document.createElementNS("http://www.w3.org/2000/svg","rect");
rect.setAttribute("x", x);
rect.setAttribute("y", y);
rect.setAttribute("width", nodeWidth);
rect.setAttribute("height", 20);
rect.setAttribute("class","pod");
g.appendChild(rect);
const text = document.createElementNS("http://www.w3.org/2000/svg","text");
text.setAttribute("x", x + nodeWidth/2);
text.setAttribute("y", y + 10); // vertical center
text.setAttribute("class","pod-label");
// truncate text to fit box
const maxChars = Math.floor(nodeWidth / 8); // rough estimate
text.textContent = podName.length > maxChars ? podName.substr(0, maxChars) : podName;
g.appendChild(text);
svg.appendChild(g);
stack.push(g);
podsPerNode[nodeName] = stack;
}
// Redraw the stack of pods for a node
function redrawPods(nodeName){
const stack = podsPerNode[nodeName] || [];
stack.forEach((g,i)=>{
const rect = g.querySelector("rect");
const text = g.querySelector("text");
const x = nodePositions[nodeName].x - nodeWidth/2;
const y = nodeY + nodeHeight + i*25;
rect.setAttribute("x", x);
rect.setAttribute("y", y);
text.setAttribute("x", x + nodeWidth/2);
text.setAttribute("y", y + 10);
});
}
// Animate pod moving from one node to another
function flyPod(podName, fromNode, toNode){
const g = document.createElementNS("http://www.w3.org/2000/svg","g");
// Pod rectangle
const rect = document.createElementNS("http://www.w3.org/2000/svg","rect");
rect.setAttribute("width", nodeWidth);
rect.setAttribute("height", 20);
rect.setAttribute("class","pod");
g.appendChild(rect);
// Pod text
const text = document.createElementNS("http://www.w3.org/2000/svg","text");
text.textContent = podName;
text.setAttribute("class","pod-label");
g.appendChild(text);
svg.appendChild(g);
// Remove from fromNode stack
if(fromNode && podsPerNode[fromNode]){
podsPerNode[fromNode].forEach(pg => {
const t = pg.querySelector("text");
if(t.textContent === podName){
svg.removeChild(pg); // remove visually
}
});
podsPerNode[fromNode] = podsPerNode[fromNode].filter(pg=>{
const t = pg.querySelector("text");
return t.textContent !== podName;
});
redrawPods(fromNode); // redraw remaining pods
}
// Animate movement
let start = fromNode ? nodePositions[fromNode] : nodePositions[toNode]; // start at old node or directly at target
let end = nodePositions[toNode];
if(!end) return;
let progress = 0;
const steps = 60;
const dx = (end.x - start.x)/steps;
const dy = (end.y - start.y)/steps;
const anim = setInterval(()=>{
progress++;
const x = start.x - nodeWidth/2 + dx*progress;
const y = start.y + dy*progress;
rect.setAttribute("x", x);
rect.setAttribute("y", y);
text.setAttribute("x", x + nodeWidth/2);
text.setAttribute("y", y + 10);
if(progress>=steps){
clearInterval(anim);
// remove animated g
svg.removeChild(g);
// Add pod to new node stack
addPod(podName, toNode);
}
}, animationDuration/steps);
}
// SSE stream
const evtSource = new EventSource("/api/stream");
evtSource.onmessage = e => {
const evt = JSON.parse(e.data);
if(!evt.fromNode){ // new pod appears
addPod(evt.pod, evt.toNode);
redrawPods(evt.toNode);
} else { // pod moves
flyPod(evt.pod, evt.fromNode, evt.toNode);
}
};
</script>
</body>
</html>
+201
View File
@@ -0,0 +1,201 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Node Balancer</title>
<style>
body { font-family: sans-serif; margin: 20px; }
svg { border:1px solid #ccc; width:100%; height:500px; background:#f9f9f9; }
.node { fill:#4CAF50; stroke:#333; stroke-width:2; }
.pod { fill:#2196F3; stroke:#000; stroke-width:1; }
.label { font-size:14px; text-anchor:middle; dominant-baseline:middle; }
.pod-label { font-size:14px; text-anchor:middle; dominant-baseline:middle; fill:#fff; }
</style>
</head>
<body>
<h2>Node Balancer</h2>
<svg id="canvas"></svg>
<script>
const svg = document.getElementById("canvas");
const nodePositions = {};
const nodeY = 50;
const nodeWidth = 100;
const nodeHeight = 40;
let animationDuration = 2000;
// Store pod stacks per node
const podsPerNode = {};
// Fetch animation duration from server
fetch("/api/config")
.then(res => res.json())
.then(cfg => { animationDuration = cfg.animationDurationMs; });
// Draw nodes
fetch("/api/nodes")
.then(res => res.json())
.then(nodeNames => {
nodeNames.forEach((name,i)=>{
const x = 50 + i*200;
nodePositions[name] = {x: x + nodeWidth/2, y: nodeY + nodeHeight/2};
// Node box
const rect = document.createElementNS("http://www.w3.org/2000/svg","rect");
rect.setAttribute("x", x);
rect.setAttribute("y", nodeY);
rect.setAttribute("width", nodeWidth);
rect.setAttribute("height", nodeHeight);
rect.setAttribute("class","node");
svg.appendChild(rect);
// Node label
const label = document.createElementNS("http://www.w3.org/2000/svg","text");
label.setAttribute("x", x + nodeWidth/2);
label.setAttribute("y", nodeY + nodeHeight/2);
label.setAttribute("class","label");
label.textContent = name;
svg.appendChild(label);
podsPerNode[name] = [];
});
// Fetch initial pods after nodes are drawn
fetch("/api/pods")
.then(res => res.json())
.then(podsByNode => {
for(const nodeName in podsByNode){
podsByNode[nodeName].forEach(podName => addPod(podName, nodeName));
}
});
});
// Add a pod to the stack under a node
function addPod(podName, nodeName){
if(!nodePositions[nodeName]) return;
const stack = podsPerNode[nodeName] || [];
const index = stack.length;
const x = nodePositions[nodeName].x - nodeWidth/2;
const y = nodeY + nodeHeight + index*25;
const g = document.createElementNS("http://www.w3.org/2000/svg","g");
const rect = document.createElementNS("http://www.w3.org/2000/svg","rect");
rect.setAttribute("x", x);
rect.setAttribute("y", y);
rect.setAttribute("width", nodeWidth);
rect.setAttribute("height", 20);
rect.setAttribute("class","pod");
g.appendChild(rect);
const text = document.createElementNS("http://www.w3.org/2000/svg","text");
text.setAttribute("x", x + nodeWidth/2);
text.setAttribute("y", y + 10); // vertical center
text.setAttribute("class","pod-label");
// truncate text to fit box
const maxChars = Math.floor(nodeWidth / 8); // rough estimate
text.textContent = podName.length > maxChars ? podName.substr(0, maxChars) : podName;
g.appendChild(text);
svg.appendChild(g);
stack.push(g);
podsPerNode[nodeName] = stack;
}
// Redraw the stack of pods for a node
function redrawPods(nodeName){
const stack = podsPerNode[nodeName] || [];
stack.forEach((g,i)=>{
const rect = g.querySelector("rect");
const text = g.querySelector("text");
const x = nodePositions[nodeName].x - nodeWidth/2;
const y = nodeY + nodeHeight + i*25;
rect.setAttribute("x", x);
rect.setAttribute("y", y);
text.setAttribute("x", x + nodeWidth/2);
text.setAttribute("y", y + 10);
});
}
// Animate pod moving from one node to another
function flyPod(podName, fromNode, toNode){
const g = document.createElementNS("http://www.w3.org/2000/svg","g");
// Pod rectangle
const rect = document.createElementNS("http://www.w3.org/2000/svg","rect");
rect.setAttribute("width", nodeWidth);
rect.setAttribute("height", 20);
rect.setAttribute("class","pod");
g.appendChild(rect);
// Pod text
const text = document.createElementNS("http://www.w3.org/2000/svg","text");
text.textContent = podName;
text.setAttribute("class","pod-label");
g.appendChild(text);
svg.appendChild(g);
// Remove from fromNode stack
if(fromNode && podsPerNode[fromNode]){
podsPerNode[fromNode].forEach(pg => {
const t = pg.querySelector("text");
if(t.textContent === podName){
svg.removeChild(pg); // remove visually
}
});
podsPerNode[fromNode] = podsPerNode[fromNode].filter(pg=>{
const t = pg.querySelector("text");
return t.textContent !== podName;
});
redrawPods(fromNode); // redraw remaining pods
}
// Animate movement
let start = fromNode ? nodePositions[fromNode] : nodePositions[toNode]; // start at old node or directly at target
let end = nodePositions[toNode];
if(!end) return;
let progress = 0;
const steps = 60;
const dx = (end.x - start.x)/steps;
const dy = (end.y - start.y)/steps;
const anim = setInterval(()=>{
progress++;
const x = start.x - nodeWidth/2 + dx*progress;
const y = start.y + dy*progress;
rect.setAttribute("x", x);
rect.setAttribute("y", y);
text.setAttribute("x", x + nodeWidth/2);
text.setAttribute("y", y + 10);
if(progress>=steps){
clearInterval(anim);
// remove animated g
svg.removeChild(g);
// Add pod to new node stack
addPod(podName, toNode);
}
}, animationDuration/steps);
}
// SSE stream
const evtSource = new EventSource("/api/stream");
evtSource.onmessage = e => {
const evt = JSON.parse(e.data);
if(evt.fromNode === evt.toNode){
// same node, just redraw stack
redrawPods(evt.toNode);
return;
}
if(!evt.fromNode){ // new pod appears
addPod(evt.pod, evt.toNode);
redrawPods(evt.toNode);
} else { // pod moves
flyPod(evt.pod, evt.fromNode, evt.toNode);
}
};
</script>
</body>
</html>
+193
View File
@@ -0,0 +1,193 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Node Balancer</title>
<style>
body { font-family: sans-serif; margin: 20px; }
svg { border:1px solid #ccc; width:100%; height:500px; background:#f9f9f9; }
.node { fill:#4CAF50; stroke:#333; stroke-width:2; }
.pod { fill:#2196F3; stroke:#000; stroke-width:1; }
.label { font-size:14px; text-anchor:middle; dominant-baseline:middle; }
.pod-label { font-size:14px; text-anchor:middle; dominant-baseline:middle; fill:#fff; }
</style>
</head>
<body>
<h2>Node Balancer</h2>
<svg id="canvas"></svg>
<script>
const svg = document.getElementById("canvas");
const nodePositions = {};
const nodeY = 50;
const nodeWidth = 100;
const nodeHeight = 40;
let animationDuration = 2000;
// Store pod stacks per node
const podsPerNode = {};
// Fetch animation duration from server
fetch("/api/config")
.then(res => res.json())
.then(cfg => { animationDuration = cfg.animationDurationMs; });
// Draw nodes
fetch("/api/nodes")
.then(res => res.json())
.then(nodeNames => {
nodeNames.forEach((name,i)=>{
const x = 50 + i*200;
nodePositions[name] = {x: x + nodeWidth/2, y: nodeY + nodeHeight/2};
// Node box
const rect = document.createElementNS("http://www.w3.org/2000/svg","rect");
rect.setAttribute("x", x);
rect.setAttribute("y", nodeY);
rect.setAttribute("width", nodeWidth);
rect.setAttribute("height", nodeHeight);
rect.setAttribute("class","node");
svg.appendChild(rect);
// Node label
const label = document.createElementNS("http://www.w3.org/2000/svg","text");
label.setAttribute("x", x + nodeWidth/2);
label.setAttribute("y", nodeY + nodeHeight/2);
label.setAttribute("class","label");
label.textContent = name;
svg.appendChild(label);
podsPerNode[name] = [];
});
// Fetch initial pods after nodes are drawn
fetch("/api/pods")
.then(res => res.json())
.then(podsByNode => {
for(const nodeName in podsByNode){
podsByNode[nodeName].forEach(podName => addPod(podName, nodeName));
}
});
});
// Add a pod to the stack under a node
function addPod(podName, nodeName){
if(!nodePositions[nodeName]) return;
const stack = podsPerNode[nodeName] || [];
const index = stack.length;
const x = nodePositions[nodeName].x - nodeWidth/2;
const y = nodeY + nodeHeight + index*25;
const g = document.createElementNS("http://www.w3.org/2000/svg","g");
const rect = document.createElementNS("http://www.w3.org/2000/svg","rect");
rect.setAttribute("x", x);
rect.setAttribute("y", y);
rect.setAttribute("width", nodeWidth);
rect.setAttribute("height", 20);
rect.setAttribute("class","pod");
g.appendChild(rect);
const text = document.createElementNS("http://www.w3.org/2000/svg","text");
text.setAttribute("x", x + nodeWidth/2);
text.setAttribute("y", y + 10); // vertical center
text.setAttribute("class","pod-label");
// truncate text to fit box
const maxChars = Math.floor(nodeWidth / 8); // rough estimate
text.textContent = podName.length > maxChars ? podName.substr(0, maxChars) : podName;
g.appendChild(text);
svg.appendChild(g);
stack.push(g);
podsPerNode[nodeName] = stack;
}
// Animate pod moving from one node to another
function flyPod(podName, fromNode, toNode){
// Remove pod from fromNode stack
if (fromNode && podsPerNode[fromNode]) {
podsPerNode[fromNode] = podsPerNode[fromNode].filter(g => {
const text = g.querySelector("text");
return text && text.textContent !== podName;
});
redrawPods(fromNode);
}
// Add pod to toNode stack (temporarily for animation)
const g = document.createElementNS("http://www.w3.org/2000/svg","g");
const rect = document.createElementNS("http://www.w3.org/2000/svg","rect");
rect.setAttribute("width", nodeWidth);
rect.setAttribute("height", 20);
rect.setAttribute("class","pod");
g.appendChild(rect);
const text = document.createElementNS("http://www.w3.org/2000/svg","text");
text.textContent = podName;
g.appendChild(text);
svg.appendChild(g);
let start = nodePositions[fromNode] || nodePositions[toNode];
let end = nodePositions[toNode];
if(!start || !end) return;
let progress = 0;
const steps = 60;
const dx = (end.x - start.x)/steps;
const dy = (end.y - start.y)/steps;
const anim = setInterval(()=>{
progress++;
const x = start.x - nodeWidth/2 + dx*progress;
const y = start.y + dy*progress;
rect.setAttribute("x", x);
rect.setAttribute("y", y);
text.setAttribute("x", x + nodeWidth/2);
text.setAttribute("y", y + 10);
if(progress>=steps){
clearInterval(anim);
svg.removeChild(g);
// Add the pod to the toNode stack permanently
addPod(podName, toNode);
}
}, animationDuration/steps);
}
// redraw all pods on a node (new)
function redrawPods(nodeName){
if(!podsPerNode[nodeName]) return;
podsPerNode[nodeName].forEach((g, idx)=>{
const rect = g.querySelector("rect");
const text = g.querySelector("text");
const x = nodePositions[nodeName].x - nodeWidth/2;
const y = nodeY + nodeHeight + 20 + idx*25;
rect.setAttribute("x", x);
rect.setAttribute("y", y);
text.setAttribute("x", x + nodeWidth/2);
text.setAttribute("y", y + 10);
});
}
// SSE stream
const evtSource = new EventSource("/api/stream");
evtSource.onmessage = e => {
const evt = JSON.parse(e.data);
if(evt.fromNode === evt.toNode){
// same node, just redraw stack
redrawPods(evt.toNode);
return;
}
if(!evt.fromNode){ // new pod appears
addPod(evt.pod, evt.toNode);
redrawPods(evt.toNode);
} else { // pod moves
flyPod(evt.pod, evt.fromNode, evt.toNode);
}
};
</script>
</body>
</html>
+269
View File
@@ -0,0 +1,269 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Node Balancer</title>
<style>
html, body {
margin: 0;
padding: 0;
min-height: 100%;
}
body { font-family: sans-serif; margin: 20px; }
svg { border:1px solid #ccc; width:100%; background:#f9f9f9; }
.node { fill:#4CAF50; stroke:#333; stroke-width:2; }
.pod { fill:#2196F3; stroke:#000; stroke-width:1; }
.label { font-size:14px; text-anchor:middle; dominant-baseline:middle; }
.pod-label { font-size:14px; text-anchor:middle; dominant-baseline:middle; fill:#fff; }
header {
display: flex;
align-items: center;
margin-bottom: 20px;
background-color: #f0f0f0; /* light gray background for the header */
padding: 10px 15px;
border-radius: 8px;
}
header .logo {
font-weight: bold;
font-size: 18px;
color: #2196F3; /* blue logo text */
margin-right: 15px;
padding: 5px 10px;
background-color: #333; /* dark background behind logo text */
color: #fff;
border-radius: 4px;
font-family: monospace;
}
header .title {
font-size: 18px;
}
header .title span {
margin-left: 10px;
color: #555;
font-weight: normal;
}
header .cluster-label {
margin-left: 20px;
color: #333;
font-weight: normal;
}
</style>
</head>
<body>
<header>
<div class="logo">allarddcs</div>
<div class="title">
Node Balancer <span id="version">v?</span>
<span class="cluster-label">Cluster: <span id="cluster-name">?</span></span>
</div>
</header>
<svg id="canvas"></svg>
<script>
const svg = document.getElementById("canvas");
const nodePositions = {};
const nodeY = 50;
const nodeWidth = 100;
const nodeHeight = 40;
let animationDuration = 2000;
// Store pod stacks per node
const podsPerNode = {};
// Fetch animation duration from server
fetch("/api/config")
.then(res => res.json())
.then(cfg => {
animationDuration = cfg.animationDurationMs;
document.getElementById("version").textContent = "v" + cfg.version;
document.getElementById("cluster-name").textContent = cfg.clusterName;
});
// Draw nodes
fetch("/api/nodes")
.then(res => res.json())
.then(nodeNames => {
nodeNames.forEach((name,i)=>{
const x = 50 + i*200;
nodePositions[name] = {x: x + nodeWidth/2, y: nodeY + nodeHeight/2};
// Node box
const rect = document.createElementNS("http://www.w3.org/2000/svg","rect");
rect.setAttribute("x", x);
rect.setAttribute("y", nodeY);
rect.setAttribute("width", nodeWidth);
rect.setAttribute("height", nodeHeight);
rect.setAttribute("class","node");
svg.appendChild(rect);
// Node label
const label = document.createElementNS("http://www.w3.org/2000/svg","text");
label.setAttribute("x", x + nodeWidth/2);
label.setAttribute("y", nodeY + nodeHeight/2);
label.setAttribute("class","label");
label.textContent = name;
svg.appendChild(label);
podsPerNode[name] = [];
});
// Fetch initial pods after nodes are drawn
fetch("/api/pods")
.then(res => res.json())
.then(podsByNode => {
for(const nodeName in podsByNode){
podsByNode[nodeName].forEach(podName => addPod(podName, nodeName));
}
});
});
// Add a pod to the stack under a node
function addPod(podName, nodeName){
if(!nodePositions[nodeName]) return;
const stack = podsPerNode[nodeName] || [];
const index = stack.length;
const x = nodePositions[nodeName].x - nodeWidth/2;
const y = nodeY + nodeHeight + index*25;
const g = document.createElementNS("http://www.w3.org/2000/svg","g");
const rect = document.createElementNS("http://www.w3.org/2000/svg","rect");
rect.setAttribute("x", x);
rect.setAttribute("y", y);
rect.setAttribute("width", nodeWidth);
rect.setAttribute("height", 20);
rect.setAttribute("class","pod");
g.appendChild(rect);
const text = document.createElementNS("http://www.w3.org/2000/svg","text");
text.setAttribute("x", x + nodeWidth/2);
text.setAttribute("y", y + 10); // vertical center
text.setAttribute("class","pod-label");
// truncate text to fit box
const maxChars = Math.floor(nodeWidth / 8); // rough estimate
text.textContent = podName.length > maxChars ? podName.substr(0, maxChars) : podName;
g.appendChild(text);
svg.appendChild(g);
stack.push(g);
podsPerNode[nodeName] = stack;
updateSVGHeight();
}
function updateSVGHeight() {
let maxY = nodeY + nodeHeight; // start with top node
for (const nodeName in podsPerNode) {
const stack = podsPerNode[nodeName];
if (!stack) continue;
if (stack.length === 0) continue;
const stackHeight = stack.length * (20 + 5) +40 ; // pod height + spacing
const bottomY = nodeY + nodeHeight + stackHeight;
if (bottomY > maxY) maxY = bottomY;
}
// optional extra padding at bottom
svg.setAttribute("height", maxY + 20);
}
// Animate pod moving from one node to another
function flyPod(podName, fromNode, toNode){
// Remove pod from fromNode stack
if (fromNode && podsPerNode[fromNode]) {
podsPerNode[fromNode] = podsPerNode[fromNode].filter(g => {
const text = g.querySelector("text");
return text && text.textContent !== podName;
});
redrawPods(fromNode);
}
// Add pod to toNode stack (temporarily for animation)
const g = document.createElementNS("http://www.w3.org/2000/svg","g");
const rect = document.createElementNS("http://www.w3.org/2000/svg","rect");
rect.setAttribute("width", nodeWidth);
rect.setAttribute("height", 20);
rect.setAttribute("class","pod");
g.appendChild(rect);
const text = document.createElementNS("http://www.w3.org/2000/svg","text");
text.textContent = podName;
g.appendChild(text);
svg.appendChild(g);
let start = nodePositions[fromNode] || nodePositions[toNode];
let end = nodePositions[toNode];
if(!start || !end) return;
let progress = 0;
const steps = 60;
const dx = (end.x - start.x)/steps;
const dy = (end.y - start.y)/steps;
const anim = setInterval(()=>{
progress++;
const x = start.x - nodeWidth/2 + dx*progress;
const y = start.y + dy*progress;
rect.setAttribute("x", x);
rect.setAttribute("y", y);
text.setAttribute("x", x + nodeWidth/2);
text.setAttribute("y", y + 10);
if(progress>=steps){
clearInterval(anim);
svg.removeChild(g);
// Add the pod to the toNode stack permanently
addPod(podName, toNode);
}
}, animationDuration/steps);
}
// redraw all pods on a node (new)
function redrawPods(nodeName){
if(!podsPerNode[nodeName]) return;
podsPerNode[nodeName].forEach((g, idx)=>{
const rect = g.querySelector("rect");
const text = g.querySelector("text");
const x = nodePositions[nodeName].x - nodeWidth/2;
const y = nodeY + nodeHeight + 20 + idx*25;
rect.setAttribute("x", x);
rect.setAttribute("y", y);
text.setAttribute("x", x + nodeWidth/2);
text.setAttribute("y", y + 10);
});
updateSVGHeight();
}
// SSE stream
const evtSource = new EventSource("/api/stream");
evtSource.onmessage = e => {
const evt = JSON.parse(e.data);
if(evt.fromNode === evt.toNode){
// same node, just redraw stack
redrawPods(evt.toNode);
return;
}
if(!evt.fromNode){ // new pod appears
addPod(evt.pod, evt.toNode);
redrawPods(evt.toNode);
} else { // pod moves
flyPod(evt.pod, evt.fromNode, evt.toNode);
}
};
</script>
</body>
</html>
+268
View File
@@ -0,0 +1,268 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Node Balancer</title>
<style>
html, body {
margin: 0;
padding: 0;
min-height: 100%;
}
body { font-family: sans-serif; margin: 20px; }
svg { border:1px solid #ccc; width:100%; background:#f9f9f9; }
.node { fill:#4CAF50; stroke:#333; stroke-width:2; }
.pod { fill:#2196F3; stroke:#000; stroke-width:1; }
.label { font-size:14px; text-anchor:middle; dominant-baseline:middle; }
.pod-label { font-size:14px; text-anchor:middle; dominant-baseline:middle; fill:#fff; }
header {
display: flex;
align-items: center;
margin-bottom: 20px;
background-color: #f0f0f0; /* light gray background for the header */
padding: 10px 15px;
border-radius: 8px;
}
header .logo {
font-weight: bold;
font-size: 18px;
color: #2196F3; /* blue logo text */
margin-right: 15px;
padding: 5px 10px;
background-color: #333; /* dark background behind logo text */
color: #fff;
border-radius: 4px;
font-family: monospace;
}
header .title {
font-size: 18px;
}
header .title span {
margin-left: 10px;
color: #555;
font-weight: normal;
}
header .cluster-label {
margin-left: 20px;
color: #333;
font-weight: normal;
}
</style>
</head>
<body>
<header>
<div class="logo">allarddcs</div>
<div class="title">
Node Balancer <span id="version">v?</span>
<span class="cluster-label">Cluster: <span id="cluster-name">?</span></span>
</div>
</header>
<svg id="canvas"></svg>
<script>
const svg = document.getElementById("canvas");
const nodePositions = {};
const nodeY = 50;
const nodeWidth = 100;
const nodeHeight = 40;
let animationDuration = 2000;
// Store pod stacks per node
const podsPerNode = {};
// Fetch animation duration from server
fetch("/api/config")
.then(res => res.json())
.then(cfg => {
animationDuration = cfg.animationDurationMs;
document.getElementById("version").textContent = "v" + cfg.version;
document.getElementById("cluster-name").textContent = cfg.clusterName;
});
// Draw nodes
fetch("/api/nodes")
.then(res => res.json())
.then(nodeNames => {
nodeNames.forEach((name,i)=>{
const x = 50 + i*200;
nodePositions[name] = {x: x + nodeWidth/2, y: nodeY + nodeHeight/2};
// Node box
const rect = document.createElementNS("http://www.w3.org/2000/svg","rect");
rect.setAttribute("x", x);
rect.setAttribute("y", nodeY);
rect.setAttribute("width", nodeWidth);
rect.setAttribute("height", nodeHeight);
rect.setAttribute("class","node");
svg.appendChild(rect);
// Node label
const label = document.createElementNS("http://www.w3.org/2000/svg","text");
label.setAttribute("x", x + nodeWidth/2);
label.setAttribute("y", nodeY + nodeHeight/2);
label.setAttribute("class","label");
label.textContent = name;
svg.appendChild(label);
podsPerNode[name] = [];
});
// Fetch initial pods after nodes are drawn
fetch("/api/pods")
.then(res => res.json())
.then(podsByNode => {
for(const nodeName in podsByNode){
podsByNode[nodeName].forEach(podName => addPod(podName, nodeName));
}
});
});
// Add a pod to the stack under a node
function addPod(podName, nodeName){
if(!nodePositions[nodeName]) return;
const stack = podsPerNode[nodeName] || [];
const index = stack.length;
const x = nodePositions[nodeName].x - nodeWidth/2;
const y = nodeY + nodeHeight + index*25;
const g = document.createElementNS("http://www.w3.org/2000/svg","g");
const rect = document.createElementNS("http://www.w3.org/2000/svg","rect");
rect.setAttribute("x", x);
rect.setAttribute("y", y);
rect.setAttribute("width", nodeWidth);
rect.setAttribute("height", 20);
rect.setAttribute("class","pod");
g.appendChild(rect);
const text = document.createElementNS("http://www.w3.org/2000/svg","text");
text.setAttribute("x", x + nodeWidth/2);
text.setAttribute("y", y + 10); // vertical center
text.setAttribute("class","pod-label");
// truncate text to fit box
const maxChars = Math.floor(nodeWidth / 8); // rough estimate
text.textContent = podName.length > maxChars ? podName.substr(0, maxChars) : podName;
g.appendChild(text);
svg.appendChild(g);
stack.push(g);
podsPerNode[nodeName] = stack;
updateSVGHeight();
}
function updateSVGHeight() {
let maxY = nodeY + nodeHeight; // start with top node
for (const nodeName in podsPerNode) {
const stack = podsPerNode[nodeName];
if (!stack) continue;
if (stack.length === 0) continue;
const stackHeight = stack.length * (20 + 5) +40 ; // pod height + spacing
const bottomY = nodeY + nodeHeight + stackHeight;
if (bottomY > maxY) maxY = bottomY;
}
// optional extra padding at bottom
svg.setAttribute("height", maxY + 20);
}
// Animate pod moving from one node to another
function flyPod(podName, fromNode, toNode) {
if (!fromNode || !toNode) return;
const fromStack = podsPerNode[fromNode];
const idx = fromStack.findIndex(g => g.querySelector("text").textContent === podName);
if (idx === -1) return;
// Grab the actual pod <g> element
const g = fromStack[idx];
// Remove it from leaving stack array
fromStack.splice(idx, 1);
redrawPods(fromNode); // redraw remaining pods to close gap
// Reparent pod to SVG root so it can move freely
svg.appendChild(g);
const rect = g.querySelector("rect");
const text = g.querySelector("text");
// Get current position
const startX = parseFloat(rect.getAttribute("x"));
const startY = parseFloat(rect.getAttribute("y"));
// Calculate target position in destination stack
const endX = nodePositions[toNode].x - nodeWidth / 2;
const endY = nodeY + nodeHeight + podsPerNode[toNode].length * 25;
let progress = 0;
const steps = 60;
const dx = (endX - startX) / steps;
const dy = (endY - startY) / steps;
// Animate pod
const anim = setInterval(() => {
progress++;
rect.setAttribute("x", startX + dx * progress);
rect.setAttribute("y", startY + dy * progress);
text.setAttribute("x", startX + dx * progress + nodeWidth / 2);
text.setAttribute("y", startY + dy * progress + 10);
if (progress >= steps) {
clearInterval(anim);
// Add pod to destination stack permanently
podsPerNode[toNode].push(g);
// Ensure destination stack is redrawn correctly
redrawPods(toNode);
}
}, animationDuration / steps);
}
// redraw all pods on a node (new)
function redrawPods(nodeName){
if(!podsPerNode[nodeName]) return;
podsPerNode[nodeName].forEach((g, idx)=>{
const rect = g.querySelector("rect");
const text = g.querySelector("text");
const x = nodePositions[nodeName].x - nodeWidth/2;
const y = nodeY + nodeHeight + 20 + idx*25;
rect.setAttribute("x", x);
rect.setAttribute("y", y);
text.setAttribute("x", x + nodeWidth/2);
text.setAttribute("y", y + 10);
});
updateSVGHeight();
}
// SSE stream
const evtSource = new EventSource("/api/stream");
evtSource.onmessage = e => {
const evt = JSON.parse(e.data);
if(evt.fromNode === evt.toNode){
// same node, just redraw stack
redrawPods(evt.toNode);
return;
}
if(!evt.fromNode){ // new pod appears
addPod(evt.pod, evt.toNode);
redrawPods(evt.toNode);
} else { // pod moves
flyPod(evt.pod, evt.fromNode, evt.toNode);
}
};
</script>
</body>
</html>
+201
View File
@@ -0,0 +1,201 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Node Balancer</title>
<style>
body { font-family: sans-serif; margin: 20px; }
svg { border:1px solid #ccc; width:100%; height:500px; background:#f9f9f9; }
.node { fill:#4CAF50; stroke:#333; stroke-width:2; }
.pod { fill:#2196F3; stroke:#000; stroke-width:1; }
.label { font-size:14px; text-anchor:middle; dominant-baseline:middle; }
.pod-label { font-size:14px; text-anchor:middle; dominant-baseline:middle; fill:#fff; }
</style>
</head>
<body>
<h2>Node Balancer</h2>
<svg id="canvas"></svg>
<script>
const svg = document.getElementById("canvas");
const nodePositions = {};
const nodeY = 50;
const nodeWidth = 100;
const nodeHeight = 40;
let animationDuration = 2000;
// Store pod stacks per node
const podsPerNode = {};
// Fetch animation duration from server
fetch("/api/config")
.then(res => res.json())
.then(cfg => { animationDuration = cfg.animationDurationMs; });
// Draw nodes
fetch("/api/nodes")
.then(res => res.json())
.then(nodeNames => {
nodeNames.forEach((name,i)=>{
const x = 50 + i*200;
nodePositions[name] = {x: x + nodeWidth/2, y: nodeY + nodeHeight/2};
// Node box
const rect = document.createElementNS("http://www.w3.org/2000/svg","rect");
rect.setAttribute("x", x);
rect.setAttribute("y", nodeY);
rect.setAttribute("width", nodeWidth);
rect.setAttribute("height", nodeHeight);
rect.setAttribute("class","node");
svg.appendChild(rect);
// Node label
const label = document.createElementNS("http://www.w3.org/2000/svg","text");
label.setAttribute("x", x + nodeWidth/2);
label.setAttribute("y", nodeY + nodeHeight/2);
label.setAttribute("class","label");
label.textContent = name;
svg.appendChild(label);
podsPerNode[name] = [];
});
// Fetch initial pods after nodes are drawn
fetch("/api/pods")
.then(res => res.json())
.then(podsByNode => {
for(const nodeName in podsByNode){
podsByNode[nodeName].forEach(podName => addPod(podName, nodeName));
}
});
});
// Add a pod to the stack under a node
function addPod(podName, nodeName){
if(!nodePositions[nodeName]) return;
const stack = podsPerNode[nodeName] || [];
const index = stack.length;
const x = nodePositions[nodeName].x - nodeWidth/2;
const y = nodeY + nodeHeight + index*25;
const g = document.createElementNS("http://www.w3.org/2000/svg","g");
const rect = document.createElementNS("http://www.w3.org/2000/svg","rect");
rect.setAttribute("x", x);
rect.setAttribute("y", y);
rect.setAttribute("width", nodeWidth);
rect.setAttribute("height", 20);
rect.setAttribute("class","pod");
g.appendChild(rect);
const text = document.createElementNS("http://www.w3.org/2000/svg","text");
text.setAttribute("x", x + nodeWidth/2);
text.setAttribute("y", y + 10); // vertical center
text.setAttribute("class","pod-label");
// truncate text to fit box
const maxChars = Math.floor(nodeWidth / 8); // rough estimate
text.textContent = podName.length > maxChars ? podName.substr(0, maxChars) : podName;
g.appendChild(text);
svg.appendChild(g);
stack.push(g);
podsPerNode[nodeName] = stack;
}
// Redraw the stack of pods for a node
function redrawPods(nodeName){
const stack = podsPerNode[nodeName] || [];
stack.forEach((g,i)=>{
const rect = g.querySelector("rect");
const text = g.querySelector("text");
const x = nodePositions[nodeName].x - nodeWidth/2;
const y = nodeY + nodeHeight + i*25;
rect.setAttribute("x", x);
rect.setAttribute("y", y);
text.setAttribute("x", x + nodeWidth/2);
text.setAttribute("y", y + 10);
});
}
// Animate pod moving from one node to another
function flyPod(podName, fromNode, toNode){
const g = document.createElementNS("http://www.w3.org/2000/svg","g");
// Pod rectangle
const rect = document.createElementNS("http://www.w3.org/2000/svg","rect");
rect.setAttribute("width", nodeWidth);
rect.setAttribute("height", 20);
rect.setAttribute("class","pod");
g.appendChild(rect);
// Pod text
const text = document.createElementNS("http://www.w3.org/2000/svg","text");
text.textContent = podName;
text.setAttribute("class","pod-label");
g.appendChild(text);
svg.appendChild(g);
// Remove from fromNode stack
if(fromNode && podsPerNode[fromNode]){
podsPerNode[fromNode].forEach(pg => {
const t = pg.querySelector("text");
if(t.textContent === podName){
svg.removeChild(pg); // remove visually
}
});
podsPerNode[fromNode] = podsPerNode[fromNode].filter(pg=>{
const t = pg.querySelector("text");
return t.textContent !== podName;
});
redrawPods(fromNode); // redraw remaining pods
}
// Animate movement
let start = fromNode ? nodePositions[fromNode] : nodePositions[toNode]; // start at old node or directly at target
let end = nodePositions[toNode];
if(!end) return;
let progress = 0;
const steps = 60;
const dx = (end.x - start.x)/steps;
const dy = (end.y - start.y)/steps;
const anim = setInterval(()=>{
progress++;
const x = start.x - nodeWidth/2 + dx*progress;
const y = start.y + dy*progress;
rect.setAttribute("x", x);
rect.setAttribute("y", y);
text.setAttribute("x", x + nodeWidth/2);
text.setAttribute("y", y + 10);
if(progress>=steps){
clearInterval(anim);
// remove animated g
svg.removeChild(g);
// Add pod to new node stack
addPod(podName, toNode);
}
}, animationDuration/steps);
}
// SSE stream
const evtSource = new EventSource("/api/stream");
evtSource.onmessage = e => {
const evt = JSON.parse(e.data);
if(evt.fromNode === evt.toNode){
// same node, just redraw stack
redrawPods(evt.toNode);
return;
}
if(!evt.fromNode){ // new pod appears
addPod(evt.pod, evt.toNode);
redrawPods(evt.toNode);
} else { // pod moves
flyPod(evt.pod, evt.fromNode, evt.toNode);
}
};
</script>
</body>
</html>
+260
View File
@@ -0,0 +1,260 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Node Balancer</title>
<style>
body { font-family: sans-serif; margin: 20px; }
svg { border:1px solid #ccc; width:100%; height:500px; background:#f9f9f9; }
.node { fill:#4CAF50; stroke:#333; stroke-width:2; }
.pod { fill:#2196F3; stroke:#000; stroke-width:1; }
.label { font-size:14px; text-anchor:middle; dominant-baseline:middle; }
.pod-label { font-size:14px; text-anchor:middle; dominant-baseline:middle; fill:#fff; }
header {
display: flex;
align-items: center;
margin-bottom: 20px;
background-color: #f0f0f0; /* light gray background for the header */
padding: 10px 15px;
border-radius: 8px;
}
header .logo {
font-weight: bold;
font-size: 18px;
color: #2196F3; /* blue logo text */
margin-right: 15px;
padding: 5px 10px;
background-color: #333; /* dark background behind logo text */
color: #fff;
border-radius: 4px;
font-family: monospace;
}
header .title {
font-size: 18px;
}
header .title span {
margin-left: 10px;
color: #555;
font-weight: normal;
}
header .cluster-label {
margin-left: 20px;
color: #333;
font-weight: normal;
}
</style>
</head>
<body>
<header>
<div class="logo">allarddcs</div>
<div class="title">
Node Balancer <span id="version">v?</span>
<span class="cluster-label">Cluster: <span id="cluster-name">?</span></span>
</div>
</header>
<svg id="canvas"></svg>
<script>
const svg = document.getElementById("canvas");
const nodePositions = {};
const nodeY = 50;
const nodeWidth = 100;
const nodeHeight = 40;
let animationDuration = 2000;
// Store pod stacks per node
const podsPerNode = {};
// Fetch animation duration from server
fetch("/api/config")
.then(res => res.json())
.then(cfg => {
animationDuration = cfg.animationDurationMs;
document.getElementById("version").textContent = "v" + cfg.version;
document.getElementById("cluster-name").textContent = cfg.clusterName;
});
// Draw nodes
fetch("/api/nodes")
.then(res => res.json())
.then(nodeNames => {
nodeNames.forEach((name, i) => {
const x = 50 + i*200;
// Node box
const rect = document.createElementNS("http://www.w3.org/2000/svg","rect");
rect.setAttribute("x", x);
rect.setAttribute("y", nodeY);
rect.setAttribute("width", nodeWidth);
rect.setAttribute("height", nodeHeight);
rect.setAttribute("class","node");
svg.appendChild(rect);
// Node label
const label = document.createElementNS("http://www.w3.org/2000/svg","text");
label.setAttribute("x", x + nodeWidth/2);
label.setAttribute("y", nodeY + nodeHeight/2);
label.setAttribute("class","label");
label.textContent = name;
svg.appendChild(label);
// store position and rect reference
nodePositions[name] = {
x: x + nodeWidth/2,
y: nodeY + nodeHeight/2,
rect: rect
};
podsPerNode[name] = [];
});
// Fetch initial pods after nodes are drawn
fetch("/api/pods")
.then(res => res.json())
.then(podsByNode => {
for(const nodeName in podsByNode){
podsByNode[nodeName].forEach(podName => addPod(podName, nodeName));
}
});
});
// Add a pod to the stack under a node
function addPod(podName, nodeName){
if(!nodePositions[nodeName]) return;
const stack = podsPerNode[nodeName] || [];
const index = stack.length;
const nodeRect = nodePositions[nodeName].rect;
// Update node box height first
const newHeight = nodeHeight + (index + 1)*(20 + 5); // 20 = pod height, 5 = spacing
nodeRect.setAttribute("height", newHeight);
// Pod Y now starts right below node rect
const x = nodePositions[nodeName].x - nodeWidth/2;
const y = nodeY + newHeight - (index + 1)*(20 + 5) + 5; // stack pods inside the box
const g = document.createElementNS("http://www.w3.org/2000/svg","g");
const rect = document.createElementNS("http://www.w3.org/2000/svg","rect");
rect.setAttribute("x", x);
rect.setAttribute("y", y);
rect.setAttribute("width", nodeWidth);
rect.setAttribute("height", 20);
rect.setAttribute("class","pod");
g.appendChild(rect);
const text = document.createElementNS("http://www.w3.org/2000/svg","text");
text.setAttribute("x", x + nodeWidth/2);
text.setAttribute("y", y + 10);
text.setAttribute("class","pod-label");
const maxChars = Math.floor(nodeWidth / 8);
text.textContent = podName.length > maxChars ? podName.substr(0, maxChars) : podName;
g.appendChild(text);
svg.appendChild(g);
stack.push(g);
podsPerNode[nodeName] = stack;
}
// Animate pod moving from one node to another
function flyPod(podName, fromNode, toNode){
// Remove pod from fromNode stack
if (fromNode && podsPerNode[fromNode]) {
podsPerNode[fromNode] = podsPerNode[fromNode].filter(g => {
const text = g.querySelector("text");
return text && text.textContent !== podName;
});
redrawPods(fromNode);
}
// Add pod to toNode stack (temporarily for animation)
const g = document.createElementNS("http://www.w3.org/2000/svg","g");
const rect = document.createElementNS("http://www.w3.org/2000/svg","rect");
rect.setAttribute("width", nodeWidth);
rect.setAttribute("height", 20);
rect.setAttribute("class","pod");
g.appendChild(rect);
const text = document.createElementNS("http://www.w3.org/2000/svg","text");
text.textContent = podName;
g.appendChild(text);
svg.appendChild(g);
let start = nodePositions[fromNode] || nodePositions[toNode];
let end = nodePositions[toNode];
if(!start || !end) return;
let progress = 0;
const steps = 60;
const dx = (end.x - start.x)/steps;
const dy = (end.y - start.y)/steps;
const anim = setInterval(()=>{
progress++;
const x = start.x - nodeWidth/2 + dx*progress;
const y = start.y + dy*progress;
rect.setAttribute("x", x);
rect.setAttribute("y", y);
text.setAttribute("x", x + nodeWidth/2);
text.setAttribute("y", y + 10);
if(progress>=steps){
clearInterval(anim);
svg.removeChild(g);
addPod(podName, toNode); // add permanently
}
}, animationDuration/steps);
}
// Redraw all pods on a node and adjust node box height
function redrawPods(nodeName){
if(!podsPerNode[nodeName]) return;
const stack = podsPerNode[nodeName];
const nodeRect = nodePositions[nodeName].rect;
const newHeight = nodeHeight + stack.length*(20 + 5);
nodeRect.setAttribute("height", newHeight);
stack.forEach((g, idx)=>{
const rect = g.querySelector("rect");
const text = g.querySelector("text");
const x = nodePositions[nodeName].x - nodeWidth/2;
const y = nodeY + newHeight - (stack.length - idx)*(20 + 5) + 5; // align pods inside node box
rect.setAttribute("x", x);
rect.setAttribute("y", y);
text.setAttribute("x", x + nodeWidth/2);
text.setAttribute("y", y + 10);
});
}
// SSE stream
const evtSource = new EventSource("/api/stream");
evtSource.onmessage = e => {
const evt = JSON.parse(e.data);
if(evt.fromNode === evt.toNode){
redrawPods(evt.toNode);
return;
}
if(!evt.fromNode){ // new pod appears
addPod(evt.pod, evt.toNode);
redrawPods(evt.toNode);
} else { // pod moves
flyPod(evt.pod, evt.fromNode, evt.toNode);
}
};
</script>
</body>
</html>
+362
View File
@@ -0,0 +1,362 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Node Balancer</title>
<style>
html, body {
margin: 0;
padding: 0;
min-height: 100%;
}
body { font-family: sans-serif; margin: 20px; }
svg { border:1px solid #ccc; width:100%; background:#f9f9f9; }
.node { fill:#4CAF50; stroke:#333; stroke-width:2; }
.pod { fill:#2196F3; stroke:#000; stroke-width:1; }
.label { font-size:14px; text-anchor:middle; dominant-baseline:middle; }
.pod-label { font-size:14px; text-anchor:middle; fill:#fff; }
header {
display: flex;
align-items: center;
margin-bottom: 20px;
background-color: #f0f0f0;
padding: 10px 15px;
border-radius: 8px;
}
header .logo {
font-weight: bold;
font-size: 18px;
color: #2196F3;
margin-right: 15px;
padding: 5px 10px;
background-color: #333;
color: #fff;
border-radius: 4px;
font-family: monospace;
}
header .title {
font-size: 18px;
}
header .title span {
margin-left: 10px;
color: #555;
font-weight: normal;
}
header .cluster-label {
margin-left: 20px;
color: #333;
font-weight: normal;
}
</style>
</head>
<body>
<header>
<div class="logo">allarddcs</div>
<div class="title">
Node Balancer <span id="version">v?</span>
<span class="cluster-label">Cluster: <span id="cluster-name">?</span></span>
</div>
</header>
<svg id="canvas"></svg>
<script>
const svg = document.getElementById("canvas");
// Node/pod layout constants
const nodePositions = {};
const nodeY = 50;
let nodeWidth = 120;
const nodeHeight = 55;
const podHeight = 48;
const podSpacing = 6;
const textPaddingY = 6;
let animationDuration = 2000;
const podsPerNode = {};
// Fetch config
fetch("/api/config")
.then(res => res.json())
.then(cfg => {
animationDuration = cfg.animationDurationMs;
document.getElementById("version").textContent = "v" + cfg.version;
document.getElementById("cluster-name").textContent = cfg.clusterName;
});
// Remove trailing k8s-style hash if present
function truncatePodName(podName) {
const parts = podName.split("-");
function isPodId(seg) { return /^[a-z0-9]{5}$/.test(seg); }
function isReplicaSetHash(seg) { return /^[a-f0-9]{8,10}$/.test(seg); }
if (parts.length > 1 && isPodId(parts[parts.length - 1])) parts.pop();
if (parts.length > 1 && isReplicaSetHash(parts[parts.length - 1])) parts.pop();
return parts.join("-");
}
// Split pod name into multiple lines
function splitPodNameLines(podName, maxCharsPerLine = 16) {
const parts = podName.split("-");
const lines = [];
let currentLine = "";
for (let i = 0; i < parts.length; i++) {
const part = parts[i];
const isLastPart = i === parts.length - 1;
if (currentLine.length === 0) {
currentLine = part;
continue;
}
const candidate = currentLine + "-" + part;
if (candidate.length <= maxCharsPerLine) {
currentLine = candidate;
} else {
// finalize current line with dash (since more parts follow)
lines.push(currentLine + "-");
currentLine = part;
}
}
// last line never gets trailing dash
if (currentLine.length > 0) {
lines.push(currentLine);
}
return lines;
}
// Draw a node (responsive)
function addNode(name, index, totalNodes){
const svgWidth = svg.clientWidth || window.innerWidth;
const outerPadding = 60; // distance from canvas edge
const innerMargin = 20; // breathing space inside edges
const usableWidth = svgWidth - 2 * outerPadding;
const spacing = totalNodes > 1
? usableWidth / totalNodes
: 0;
// Optional responsive node width scaling
const maxNodeWidth = 120;
const minNodeWidth = 60;
nodeWidth = Math.max(minNodeWidth, Math.min(maxNodeWidth, spacing * 0.8));
// Center nodes within their spacing slot
const centerX = outerPadding + spacing * index + spacing / 2;
const x = centerX - nodeWidth / 2;
nodePositions[name] = {
x: centerX,
y: nodeY + nodeHeight/2
};
// Node rectangle
const rect = document.createElementNS("http://www.w3.org/2000/svg","rect");
rect.setAttribute("x", x);
rect.setAttribute("y", nodeY);
rect.setAttribute("width", nodeWidth);
rect.setAttribute("height", nodeHeight);
rect.setAttribute("class","node");
svg.appendChild(rect);
// Node label
const label = document.createElementNS("http://www.w3.org/2000/svg","text");
label.setAttribute("x", centerX);
label.setAttribute("y", nodeY + nodeHeight/2);
label.setAttribute("class","label");
label.setAttribute("text-anchor","middle");
label.setAttribute("dominant-baseline","middle");
label.textContent = name;
svg.appendChild(label);
podsPerNode[name] = [];
}
// Add a pod
function addPod(podName, nodeName){
if(!nodePositions[nodeName]) return;
const stack = podsPerNode[nodeName] || [];
const index = stack.length;
const x = nodePositions[nodeName].x - nodeWidth/2;
// const y = nodeY + nodeHeight + index*(podHeight + podSpacing);
const y = nodeY + nodeHeight + podSpacing + index * (podHeight + podSpacing);
const g = document.createElementNS("http://www.w3.org/2000/svg","g");
g.dataset.podName = podName;
// Pod rectangle
const rect = document.createElementNS("http://www.w3.org/2000/svg","rect");
rect.setAttribute("x", x);
rect.setAttribute("y", y);
rect.setAttribute("width", nodeWidth);
rect.setAttribute("height", podHeight);
rect.setAttribute("class","pod");
g.appendChild(rect);
// Pod label
const text = document.createElementNS("http://www.w3.org/2000/svg","text");
text.setAttribute("class","pod-label");
text.setAttribute("text-anchor","middle");
text.setAttribute("x", x + nodeWidth/2);
const truncated = truncatePodName(podName);
const lines = splitPodNameLines(truncated, 14);
if(lines.length === 1){
// Single line: vertically centered
text.setAttribute("y", y + podHeight/2 + textPaddingY/2);
text.setAttribute("dominant-baseline","middle");
text.textContent = lines[0];
} else {
// Multi-line
const lineHeight = 12;
const totalTextHeight = lines.length * lineHeight;
// Center block vertically inside pod
const startY = y + (podHeight - totalTextHeight)/2 + lineHeight - 2;
text.setAttribute("y", startY);
lines.forEach((line, i) => {
const tspan = document.createElementNS("http://www.w3.org/2000/svg","tspan");
tspan.setAttribute("x", x + nodeWidth/2);
tspan.setAttribute("dy", i === 0 ? "0" : lineHeight);
tspan.textContent = line;
text.appendChild(tspan);
});
}
g.appendChild(text);
svg.appendChild(g);
stack.push(g);
podsPerNode[nodeName] = stack;
updateSVGHeight();
}
// Update SVG height
function updateSVGHeight() {
let maxY = nodeY + nodeHeight;
for(const nodeName in podsPerNode){
const stack = podsPerNode[nodeName];
if(!stack || stack.length===0) continue;
const bottomY = nodeY + nodeHeight + stack.length*(podHeight + podSpacing);
if(bottomY > maxY) maxY = bottomY;
}
svg.setAttribute("height", maxY + 20);
}
// Animate pod move
function flyPod(podName, fromNode, toNode){
if(!fromNode || !toNode) return;
const fromStack = podsPerNode[fromNode];
const idx = fromStack.findIndex(g => g.dataset.podName===podName);
if(idx===-1) return;
const g = fromStack[idx];
fromStack.splice(idx,1);
redrawPods(fromNode);
svg.appendChild(g);
const rect = g.querySelector("rect");
const text = g.querySelector("text");
const startX = parseFloat(rect.getAttribute("x"));
const startY = parseFloat(rect.getAttribute("y"));
const endX = nodePositions[toNode].x - nodeWidth/2;
const endY = nodeY + nodeHeight + podsPerNode[toNode].length*(podHeight+podSpacing);
let progress = 0;
const steps = 60;
const dx = (endX - startX)/steps;
const dy = (endY - startY)/steps;
const anim = setInterval(()=>{
progress++;
const nx = startX + dx*progress;
const ny = startY + dy*progress;
rect.setAttribute("x", nx);
rect.setAttribute("y", ny);
text.setAttribute("x", nx + nodeWidth/2);
text.setAttribute("y", ny + podHeight/2 + textPaddingY/2);
if(progress>=steps){
clearInterval(anim);
podsPerNode[toNode].push(g);
redrawPods(toNode);
}
}, animationDuration/steps);
}
// Redraw pods on a node
function redrawPods(nodeName){
if(!podsPerNode[nodeName]) return;
podsPerNode[nodeName].forEach((g,idx)=>{
const rect = g.querySelector("rect");
const text = g.querySelector("text");
const x = nodePositions[nodeName].x - nodeWidth/2;
const y = nodeY + nodeHeight + idx*(podHeight+podSpacing);
rect.setAttribute("x", x);
rect.setAttribute("y", y);
text.setAttribute("x", x + nodeWidth/2);
text.setAttribute("y", y + podHeight/2 + textPaddingY/2);
});
updateSVGHeight();
}
// Fetch authoritative cluster state and redraw
function refreshCluster(){
Promise.all([
fetch("/api/nodes").then(r=>r.json()),
fetch("/api/pods").then(r=>r.json())
]).then(([nodeNames, podsByNode])=>{
while(svg.firstChild) svg.removeChild(svg.firstChild);
for(const k in nodePositions) delete nodePositions[k];
for(const k in podsPerNode) delete podsPerNode[k];
nodeNames.forEach((name,i)=>addNode(name,i,nodeNames.length));
for(const nodeName in podsByNode){
podsByNode[nodeName].forEach(podName=>addPod(podName,nodeName));
}
updateSVGHeight();
});
}
// SSE events
const evtSource = new EventSource("/api/stream");
evtSource.onmessage = e=>{
const evt = JSON.parse(e.data);
if(evt.fromNode && evt.toNode && evt.fromNode !== evt.toNode){
flyPod(evt.pod, evt.fromNode, evt.toNode);
setTimeout(refreshCluster, animationDuration);
} else {
refreshCluster();
}
};
// Periodic refresh every 5s
setInterval(refreshCluster, 5000);
// Responsive redraw on resize
window.addEventListener("resize", refreshCluster);
// Initial load
refreshCluster();
</script>
</body>
</html>
+117
View File
@@ -0,0 +1,117 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Node Balancer WebUI</title>
<style>
body {
font-family: sans-serif;
margin: 20px;
}
svg {
border: 1px solid #ccc;
width: 100%;
height: 300px;
background: #f9f9f9;
}
.node {
fill: #4CAF50;
stroke: #333;
stroke-width: 2;
}
.pod {
fill: #2196F3;
stroke: #000;
stroke-width: 1;
}
.pod text {
font-size: 10px;
fill: #fff;
text-anchor: middle;
dominant-baseline: middle;
}
.label {
font-size: 14px;
text-anchor: middle;
}
</style>
</head>
<body>
<h2>Node Balancer</h2>
<svg id="canvas"></svg>
<script>
const svg = document.getElementById("canvas");
const nodeNames = ["worker-1","worker-2","worker-3"];
const nodePositions = {};
const nodeY = 50;
const nodeWidth = 100;
const nodeHeight = 40;
// draw nodes
nodeNames.forEach((name,i)=>{
const x = 50 + i*200;
nodePositions[name] = {x: x + nodeWidth/2, y: nodeY + nodeHeight/2};
const rect = document.createElementNS("http://www.w3.org/2000/svg","rect");
rect.setAttribute("x", x);
rect.setAttribute("y", nodeY);
rect.setAttribute("width", nodeWidth);
rect.setAttribute("height", nodeHeight);
rect.setAttribute("class", "node");
svg.appendChild(rect);
const label = document.createElementNS("http://www.w3.org/2000/svg","text");
label.setAttribute("x", x + nodeWidth/2);
label.setAttribute("y", nodeY + nodeHeight/2 + 25);
label.setAttribute("class","label");
label.textContent = name;
svg.appendChild(label);
});
// animate a pod
function flyPod(podName, fromNode, toNode){
const g = document.createElementNS("http://www.w3.org/2000/svg","g");
const circle = document.createElementNS("http://www.w3.org/2000/svg","circle");
circle.setAttribute("r", 15);
circle.setAttribute("class","pod");
g.appendChild(circle);
const text = document.createElementNS("http://www.w3.org/2000/svg","text");
text.textContent = podName;
g.appendChild(text);
svg.appendChild(g);
let start = nodePositions[fromNode];
let end = nodePositions[toNode];
let progress = 0;
const duration = 2000; // ms
const steps = 60;
const dx = (end.x - start.x)/steps;
const dy = (end.y - start.y)/steps;
const anim = setInterval(()=>{
progress++;
const cx = start.x + dx*progress;
const cy = start.y + dy*progress;
circle.setAttribute("cx", cx);
circle.setAttribute("cy", cy);
text.setAttribute("x", cx);
text.setAttribute("y", cy);
if(progress >= steps){
clearInterval(anim);
// leave pod at destination for a short moment then remove
setTimeout(()=>svg.removeChild(g),1000);
}
}, duration/steps);
}
// SSE stream
const evtSource = new EventSource("/api/stream");
evtSource.onmessage = e => {
const evt = JSON.parse(e.data);
flyPod(evt.pod, evt.fromNode, evt.toNode);
};
</script>
</body>
</html>