Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to execute command in a pod (kubernetes) using API?

I'm trying to execute command in a contianer (in a Kubernetes POD on GKE with kubernetes 1.1.2).

Reading documentation I understood that I can use GET or POST query to open websocket connection on API endpoint to execute command. When I use GET, it does not work completly, returns error. When I try to use POST, something like that could work probably (but it's not):

curl 'https://admin:xxx@IP/api/v1/namespaces/default/pods/hello-whue1/exec?stdout=1&stderr=1&command=ls' -H "Connection: upgrade" -k -X POST -H 'Upgrade: websocket'

repsponse for that is

unable to upgrade: missing upgrade headers in request: http.Header{"User-Agent":[]string{"curl/7.44.0"}, "Content-Length":[]string{"0"}, "Accept":[]string{"*/*"}, "Authorization":[]string{"Basic xxx=="}, "Connection":[]string{"upgrade"}, "Upgrade":[]string{"websocket"}}

Looks like that should be enough to upgrade post request and start using websocket streams, right? What I'm missing?

I was also pointed that opening websocket with POST is probably violation of websocket protocol (only GET should work?).

Also

like image 833
spinus Avatar asked Dec 19 '15 17:12

spinus


2 Answers

You'll probably have the best time using the Kubernetes client library, which is the same code the Kubectl uses, but if for some reason that isn't an option, than my best suggestion is to look through the client library's code for executing remote commands and seeing what headers it sets.

like image 67
Alex Robinson Avatar answered Sep 22 '22 07:09

Alex Robinson


Use websocket client it's work.

In my local kuberenetes cluster, the connection metadata like this:

ApiServer = "172.21.1.11:8080"
Namespace = "default"
PodName = "my-nginx-3855515330-l1uqk"
ContainerName = "my-nginx"
Commands = "/bin/bash"

the connect url:

"ws://172.21.1.11:8080/api/v1/namespaces/default/pods/my-nginx-3855515330-l1uqk/exec?container=my-nginx&stdin=1&stdout=1&stderr=1&tty=1&command=%2Fbin%2Fbash"

On maxos, a wsclient CLI tool: wscat, you can use it as a test tool:

enter image description here

You can access the websocket example: "https://github.com/lth2015/container-terminal"

like image 41
litanhua Avatar answered Sep 20 '22 07:09

litanhua