blob: afcdfbd16a3f20629ae6f5ffbc34324e3f2c277b [file] [log] [blame]
Laszlo Pappda059e72017-10-23 11:39:31 +01001/*
2 * Copyright 2017-present Open Networking Foundation
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16package org.onosproject.powermanagement;
17
18import org.onosproject.net.Device;
19import org.onosproject.net.Direction;
20import org.onosproject.net.PortNumber;
21import org.onosproject.net.behaviour.PowerConfig;
22import org.onosproject.net.device.DeviceService;
23import org.onosproject.rest.AbstractWebResource;
24
25import static org.onosproject.net.DeviceId.deviceId;
26
27import com.fasterxml.jackson.databind.JsonNode;
28import com.fasterxml.jackson.databind.ObjectMapper;
29import com.fasterxml.jackson.databind.node.ArrayNode;
30import com.fasterxml.jackson.databind.node.ObjectNode;
31
32import com.google.common.collect.HashMultimap;
33import com.google.common.collect.Multimap;
34import com.google.common.collect.Range;
35import static com.google.common.base.Preconditions.checkNotNull;
36
37import javax.ws.rs.Consumes;
38import javax.ws.rs.GET;
39import javax.ws.rs.PUT;
40import javax.ws.rs.Path;
41import javax.ws.rs.PathParam;
42import javax.ws.rs.Produces;
43import javax.ws.rs.QueryParam;
44import javax.ws.rs.core.MediaType;
45import javax.ws.rs.core.Response;
46
47import java.io.IOException;
48import java.io.InputStream;
49
50import java.util.Iterator;
51import java.util.Map;
52import java.util.Map.Entry;
53
54import org.slf4j.Logger;
55import static org.slf4j.LoggerFactory.getLogger;
56
57/**
58 * Manage inventory of infrastructure devices with Power Config behaviour.
59 */
60@Path("devices")
61public class PowerConfigWebResource extends AbstractWebResource {
62
63 private static final String JSON_INVALID = "Invalid json input";
64 private static final String DEVICE_NOT_FOUND = "Device is not found";
65 private static final String POWERCONFIG_UNSUPPORTED = "Power Config is not supported";
66 private static final String DIRECTION_UNSUPPORTED = "Direction is not supported";
67
68 private static final String DEVICES = "powerConfigDevices";
69 private static final String PORTS = "ports";
70 private static final String DEVICE_ID = "deviceId";
71 private static final String DEVICE_IDS = "powerConfigDeviceIds";
72 private static final String POWERCONFIG_SUPPORTED = "powerConfigSupported";
73 private static final String DIRECTION = "direction";
74 private static final String PORT_ID = "portId";
75 private static final String TARGET_POWER = "targetPower";
76 private static final String CURRENT_POWER = "currentPower";
77 private static final String INPUT_POWER_RANGE = "inputPowerRange";
78 private static final String TARGET_POWER_RANGE = "targetPowerRange";
79
80 private final ObjectMapper mapper = new ObjectMapper();
81
82 private static final Logger log = getLogger(PowerConfigWebResource.class);
83
84 /**
85 * Gets all power config devices.
86 * Returns array of all discovered power config devices.
87 *
88 * @return 200 OK with a collection of devices
89 * @onos.rsModel PowerConfigDevicesGet
90 */
91 @GET
92 @Produces(MediaType.APPLICATION_JSON)
93 public Response getDevices() {
94 ObjectNode root = mapper().createObjectNode();
95 ArrayNode deviceIdsNode = root.putArray(DEVICE_IDS);
96
97 Iterable<Device> devices = get(DeviceService.class).getDevices();
98 if (devices != null) {
99 for (Device d : devices) {
100 if (getPowerConfig(d.id().toString()) != null) {
101 deviceIdsNode.add(d.id().toString());
102 }
103 }
104 }
105
106 return ok(root).build();
107 }
108
109 /**
110 * Applies the target power for the specified device.
111 *
112 * @param stream JSON representation of device, port, component and target
113 * power info
114 * @return status of the request - CREATED if the JSON is correct,
115 * BAD_REQUEST if the JSON is invalid
116 * @onos.rsModel PowerConfigPut
117 */
118 @PUT
119 @Consumes(MediaType.APPLICATION_JSON)
120 public Response setTargetPower(InputStream stream) {
121 try {
122 ObjectNode jsonTree = (ObjectNode) mapper().readTree(stream);
123 decode(jsonTree);
124 return Response.ok().build();
125 } catch (IOException e) {
126 throw new IllegalArgumentException(e);
127 }
128 }
129
130 /**
131 * Gets the details of a power config device.
132 * Returns the details of the specified power config device.
133 *
134 * @param id device identifier
135 * @return 200 OK with a device
136 * @onos.rsModel PowerConfigDeviceGet
137 */
138 @GET
139 @Path("{id}")
140 @Produces(MediaType.APPLICATION_JSON)
141 public Response getDevice(@PathParam("id") String id) {
142 ObjectNode result = mapper.createObjectNode();
143 result.put(POWERCONFIG_SUPPORTED, (getPowerConfig(id) != null) ? true : false);
144 return ok(result).build();
145 }
146
147 private PowerConfig<Object> getPowerConfig(String id) {
148 Device device = get(DeviceService.class).getDevice(deviceId(id));
149 if (device == null) {
150 throw new IllegalArgumentException(DEVICE_NOT_FOUND);
151 }
152 if (device.is(PowerConfig.class)) {
153 return device.as(PowerConfig.class);
154 }
155 return null;
156 }
157
158 /**
159 * Gets the ports of a power config device.
160 * Returns the details of the specified power config device ports.
161 *
162 * @onos.rsModel PowerConfigDeviceGetPorts
163 * @param id device identifier
164 * @param direction port direction
165 * @param channel port channel
166 * @return 200 OK with a collection of ports of the given device
167 */
168 @GET
169 @Path("{id}/ports")
170 @Produces(MediaType.APPLICATION_JSON)
171 public Response getDevicePorts(@PathParam("id") String id,
172 @QueryParam("direction") String direction,
173 @QueryParam("channel") String channel) {
174 PowerConfig<Object> powerConfig = getPowerConfig(id);
175 if (powerConfig == null) {
176 throw new IllegalArgumentException(POWERCONFIG_UNSUPPORTED);
177 }
178 if (direction == null && channel == null) {
179 direction = "ALL";
180 // TODO: Fallback to all channels?
181 }
182 ObjectNode result = encode(powerConfig, direction, channel);
183 return ok(result).build();
184 }
185
186 private ObjectNode encode(PowerConfig<Object> powerConfig, String direction, String channel) {
187 checkNotNull(powerConfig, "PowerConfig cannot be null");
188 ObjectNode powerConfigPorts = mapper.createObjectNode();
189 Multimap<PortNumber, Object> portsMap = HashMultimap.create();
190
191 if (direction != null) {
192 for (PortNumber port : powerConfig.getPorts(direction)) {
193 portsMap.put(port, Direction.valueOf(direction.toUpperCase()));
194 }
195 }
196
197 if (channel != null) {
198 for (PortNumber port : powerConfig.getPorts(channel)) {
199 // TODO: channel to be handled
200 portsMap.put(port, channel);
201 }
202 }
203
204 for (Map.Entry<PortNumber, Object> entry : portsMap.entries()) {
205 PortNumber port = entry.getKey();
206 ObjectNode powerConfigComponents = mapper.createObjectNode();
207 for (Object component : portsMap.get(port)) {
208 // TODO: channel to be handled
209 String componentName = "unknown";
210 if (component instanceof Direction) {
211 componentName = component.toString();
212 }
213 ObjectNode powerConfigNode = mapper.createObjectNode()
214 .put(CURRENT_POWER, powerConfig.currentPower(port, component).orElse(0L))
215 .put(TARGET_POWER, powerConfig.getTargetPower(port, component).orElse(0L))
216 .put(INPUT_POWER_RANGE, powerConfig.getInputPowerRange(port,
217 component).orElse(Range.closed(0L, 0L)).toString())
218 .put(TARGET_POWER_RANGE, powerConfig.getTargetPowerRange(port,
219 component).orElse(Range.closed(0L, 0L)).toString());
220 powerConfigComponents.set(componentName, powerConfigNode);
221 }
222 powerConfigPorts.set(port.toString(), powerConfigComponents);
223 }
224
225 ObjectNode result = mapper.createObjectNode();
226 result.set("powerConfigPorts", powerConfigPorts);
227 return result;
228 }
229
230 public void decode(ObjectNode json) {
231 if (json == null || !json.isObject()) {
232 throw new IllegalArgumentException(JSON_INVALID);
233 }
234
235 JsonNode devicesNode = json.get(DEVICES);
236 if (!devicesNode.isObject()) {
237 throw new IllegalArgumentException(JSON_INVALID);
238 }
239
240 Iterator<Entry<String, JsonNode>> deviceEntries = devicesNode.fields();
241 while (deviceEntries.hasNext()) {
242 Entry<String, JsonNode> deviceEntryNext = deviceEntries.next();
243 String deviceId = deviceEntryNext.getKey();
244 PowerConfig<Object> powerConfig = getPowerConfig(deviceId);
245 JsonNode portsNode = deviceEntryNext.getValue();
246 if (!portsNode.isObject()) {
247 throw new IllegalArgumentException(JSON_INVALID);
248 }
249
250 Iterator<Entry<String, JsonNode>> portEntries = portsNode.fields();
251 while (portEntries.hasNext()) {
252 Entry<String, JsonNode> portEntryNext = portEntries.next();
253 PortNumber portNumber = PortNumber.portNumber(portEntryNext.getKey());
254 JsonNode componentsNode = portEntryNext.getValue();
255 Iterator<Entry<String, JsonNode>> componentEntries = componentsNode.fields();
256 while (componentEntries.hasNext()) {
257 Direction direction = null;
258 Entry<String, JsonNode> componentEntryNext = componentEntries.next();
259 try {
260 direction = Direction.valueOf(componentEntryNext.getKey().toUpperCase());
261 } catch (IllegalArgumentException e) {
262 // TODO: Handle other components
263 }
264
265 JsonNode powerNode = componentEntryNext.getValue();
266 if (!powerNode.isObject()) {
267 throw new IllegalArgumentException(JSON_INVALID);
268 }
269 Long targetPower = powerNode.get(TARGET_POWER).asLong();
270 if (direction != null) {
271 powerConfig.setTargetPower(portNumber, direction, targetPower);
272 }
273 }
274 }
275 }
276 }
277}