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 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266
|
// -*- Mode: Go; indent-tabs-mode: t -*-
/*
* Copyright (C) 2015-2020 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 (
"encoding/json"
"errors"
"fmt"
"net/http"
"sort"
"strings"
"github.com/snapcore/snapd/interfaces"
"github.com/snapcore/snapd/overlord/auth"
"github.com/snapcore/snapd/overlord/ifacestate"
"github.com/snapcore/snapd/overlord/snapstate"
"github.com/snapcore/snapd/overlord/state"
"github.com/snapcore/snapd/overlord/swfeats"
)
var (
interfacesCmd = &Command{
Path: "/v2/interfaces",
GET: interfacesConnectionsMultiplexer,
POST: changeInterfaces,
Actions: []string{"connect", "disconnect"},
ReadAccess: openAccess{},
WriteAccess: authenticatedAccess{Polkit: polkitActionManageInterfaces},
}
)
var (
connectSnapChangeKind = swfeats.RegisterChangeKind("connect-snap")
disconnectSnapChangeKind = swfeats.RegisterChangeKind("disconnect-snap")
)
// interfacesConnectionsMultiplexer multiplexes to either legacy (connection) or modern behavior (interfaces).
func interfacesConnectionsMultiplexer(c *Command, r *http.Request, user *auth.UserState) Response {
query := r.URL.Query()
qselect := query.Get("select")
if qselect == "" {
return getLegacyConnections(c, r, user)
} else {
return getInterfaces(c, r, user)
}
}
func getInterfaces(c *Command, r *http.Request, user *auth.UserState) Response {
// Collect query options from request arguments.
q := r.URL.Query()
pselect := q.Get("select")
if pselect != "all" && pselect != "connected" {
return BadRequest("unsupported select qualifier")
}
var names []string // Interface names
namesStr := q.Get("names")
if namesStr != "" {
names = strings.Split(namesStr, ",")
}
opts := &interfaces.InfoOptions{
Names: names,
Doc: q.Get("doc") == "true",
Plugs: q.Get("plugs") == "true",
Slots: q.Get("slots") == "true",
Connected: pselect == "connected",
}
// Query the interface repository (this returns []*interface.Info).
infos := c.d.overlord.InterfaceManager().Repository().Info(opts)
infoJSONs := make([]*interfaceJSON, 0, len(infos))
for _, info := range infos {
// Convert interfaces.Info into interfaceJSON
plugs := make([]*plugJSON, 0, len(info.Plugs))
for _, plug := range info.Plugs {
plugs = append(plugs, &plugJSON{
Snap: plug.Snap.InstanceName(),
Name: plug.Name,
Attrs: plug.Attrs,
Label: plug.Label,
})
}
slots := make([]*slotJSON, 0, len(info.Slots))
for _, slot := range info.Slots {
slots = append(slots, &slotJSON{
Snap: slot.Snap.InstanceName(),
Name: slot.Name,
Attrs: slot.Attrs,
Label: slot.Label,
})
}
infoJSONs = append(infoJSONs, &interfaceJSON{
Name: info.Name,
Summary: info.Summary,
DocURL: info.DocURL,
Plugs: plugs,
Slots: slots,
})
}
return SyncResponse(infoJSONs)
}
func getLegacyConnections(c *Command, r *http.Request, user *auth.UserState) Response {
connsjson, err := collectConnections(c.d.overlord.InterfaceManager(), collectFilter{})
if err != nil {
return InternalError("collecting connection information failed: %v", err)
}
legacyconnsjson := legacyConnectionsJSON{
Plugs: connsjson.Plugs,
Slots: connsjson.Slots,
}
return SyncResponse(legacyconnsjson)
}
// changeInterfaces controls the interfaces system.
// Plugs can be connected to and disconnected from slots.
func changeInterfaces(c *Command, r *http.Request, user *auth.UserState) Response {
var a interfaceAction
decoder := json.NewDecoder(r.Body)
if err := decoder.Decode(&a); err != nil {
return BadRequest("cannot decode request body into an interface action: %v", err)
}
if a.Action == "" {
return BadRequest("interface action not specified")
}
if len(a.Plugs) > 1 || len(a.Slots) > 1 {
return NotImplemented("many-to-many operations are not implemented")
}
if a.Action != "connect" && a.Action != "disconnect" {
return BadRequest("unsupported interface action: %q", a.Action)
}
if len(a.Plugs) == 0 || len(a.Slots) == 0 {
return BadRequest("at least one plug and slot is required")
}
var summary string
var err error
var tasksets []*state.TaskSet
var affected []string
st := c.d.overlord.State()
st.Lock()
defer st.Unlock()
checkInstalled := func(snapName string) error {
// empty snap name is fine, ResolveConnect/ResolveDisconnect handles it.
if snapName == "" {
return nil
}
var snapst snapstate.SnapState
err := snapstate.Get(st, snapName, &snapst)
if (err == nil && !snapst.IsInstalled()) || errors.Is(err, state.ErrNoState) {
return fmt.Errorf("snap %q is not installed", snapName)
}
if err == nil {
return nil
}
return fmt.Errorf("internal error: cannot get state of snap %q: %v", snapName, err)
}
for i := range a.Plugs {
a.Plugs[i].Snap = ifacestate.RemapSnapFromRequest(a.Plugs[i].Snap)
if err := checkInstalled(a.Plugs[i].Snap); err != nil {
return errToResponse(err, nil, BadRequest, "%v")
}
}
for i := range a.Slots {
a.Slots[i].Snap = ifacestate.RemapSnapFromRequest(a.Slots[i].Snap)
if err := checkInstalled(a.Slots[i].Snap); err != nil {
return errToResponse(err, nil, BadRequest, "%v")
}
}
var changeKind string
switch a.Action {
case "connect":
var connRef *interfaces.ConnRef
repo := c.d.overlord.InterfaceManager().Repository()
connRef, err = repo.ResolveConnect(a.Plugs[0].Snap, a.Plugs[0].Name, a.Slots[0].Snap, a.Slots[0].Name)
if err == nil {
var ts *state.TaskSet
affected = snapNamesFromConns([]*interfaces.ConnRef{connRef})
summary = fmt.Sprintf("Connect %s:%s to %s:%s", connRef.PlugRef.Snap, connRef.PlugRef.Name, connRef.SlotRef.Snap, connRef.SlotRef.Name)
ts, err = ifacestate.Connect(st, connRef.PlugRef.Snap, connRef.PlugRef.Name, connRef.SlotRef.Snap, connRef.SlotRef.Name)
if _, ok := err.(*ifacestate.ErrAlreadyConnected); ok {
change := newChange(st, connectSnapChangeKind, summary, nil, affected)
change.SetStatus(state.DoneStatus)
return AsyncResponse(nil, change.ID())
}
tasksets = append(tasksets, ts)
}
changeKind = connectSnapChangeKind
case "disconnect":
var conns []*interfaces.ConnRef
summary = fmt.Sprintf("Disconnect %s:%s from %s:%s", a.Plugs[0].Snap, a.Plugs[0].Name, a.Slots[0].Snap, a.Slots[0].Name)
conns, err = c.d.overlord.InterfaceManager().ResolveDisconnect(a.Plugs[0].Snap, a.Plugs[0].Name, a.Slots[0].Snap, a.Slots[0].Name, a.Forget)
if err == nil {
if len(conns) == 0 {
return InterfacesUnchanged("nothing to do")
}
repo := c.d.overlord.InterfaceManager().Repository()
for _, connRef := range conns {
var ts *state.TaskSet
var conn *interfaces.Connection
if a.Forget {
ts, err = ifacestate.Forget(st, repo, connRef)
} else {
conn, err = repo.Connection(connRef)
if err != nil {
break
}
ts, err = ifacestate.Disconnect(st, conn)
if err != nil {
break
}
}
if err != nil {
break
}
ts.JoinLane(st.NewLane())
tasksets = append(tasksets, ts)
}
affected = snapNamesFromConns(conns)
}
changeKind = disconnectSnapChangeKind
}
if err != nil {
return errToResponse(err, nil, BadRequest, "%v")
}
change := newChange(st, changeKind, summary, tasksets, affected)
st.EnsureBefore(0)
return AsyncResponse(nil, change.ID())
}
func snapNamesFromConns(conns []*interfaces.ConnRef) []string {
m := make(map[string]bool)
for _, conn := range conns {
m[conn.PlugRef.Snap] = true
m[conn.SlotRef.Snap] = true
}
l := make([]string, 0, len(m))
for name := range m {
l = append(l, name)
}
sort.Strings(l)
return l
}
|