-
Notifications
You must be signed in to change notification settings - Fork 52
/
api_tasks.go
85 lines (74 loc) · 2.65 KB
/
api_tasks.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
// Copyright (c) 2021 Canonical Ltd
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License version 3 as
// published by the Free Software Foundation.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package daemon
import (
"errors"
"net/http"
"os"
"github.com/canonical/pebble/internals/logger"
"github.com/canonical/pebble/internals/overlord/state"
)
func v1GetTaskWebsocket(c *Command, req *http.Request, _ *UserState) Response {
vars := muxVars(req)
taskID := vars["task-id"]
websocketID := vars["websocket-id"]
st := c.d.overlord.State()
st.Lock()
defer st.Unlock()
task := st.Task(taskID)
if task == nil {
// These errors are logged as well, because when a client is
// connecting to a websocket they may only see the error
// "bad handshake".
logger.Noticef("Websocket: cannot find task with id %q", taskID)
return statusNotFound("cannot find task with id %q", taskID)
}
var connect websocketConnectFunc
switch task.Kind() {
case "exec":
commandMgr := c.d.overlord.CommandManager()
connect = commandMgr.Connect
default:
logger.Noticef("Websocket %s: %q tasks do not have websockets", task.ID(), task.Kind())
return statusBadRequest("%q tasks do not have websockets", task.Kind())
}
return websocketResponse{
task: task,
websocketID: websocketID,
connect: connect,
}
}
type websocketConnectFunc func(r *http.Request, w http.ResponseWriter, task *state.Task, websocketID string) error
type websocketResponse struct {
task *state.Task
websocketID string
connect websocketConnectFunc
}
func (wr websocketResponse) ServeHTTP(w http.ResponseWriter, r *http.Request) {
err := wr.connect(r, w, wr.task, wr.websocketID)
if errors.Is(err, os.ErrNotExist) {
logger.Noticef("Websocket %s: cannot find websocket with id %q", wr.task.ID(), wr.websocketID)
rsp := statusNotFound("cannot find websocket with id %q", wr.websocketID)
rsp.ServeHTTP(w, r)
return
}
if err != nil {
logger.Noticef("Websocket %s: cannot connect to websocket %q: %v", wr.task.ID(), wr.websocketID, err)
rsp := statusInternalError("cannot connect to websocket %q: %v", wr.websocketID, err)
rsp.ServeHTTP(w, r)
return
}
// In the success case, Connect takes over the connection and upgrades to
// the websocket protocol.
}