blob: d62cbde20c3d3419a49254e49b9e0cfb9e963fe0 [file] [log] [blame]
Ray Milkey140e4782015-04-24 11:25:13 -07001/*
2 * Copyright 2014-2015 Open Networking Laboratory
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.xosintegration;
17
18import java.util.Dictionary;
19import java.util.Set;
20import java.util.stream.Collectors;
21import java.util.stream.IntStream;
22
23import org.apache.felix.scr.annotations.Activate;
24import org.apache.felix.scr.annotations.Component;
25import org.apache.felix.scr.annotations.Deactivate;
26import org.apache.felix.scr.annotations.Modified;
27import org.apache.felix.scr.annotations.Property;
28import org.apache.felix.scr.annotations.Reference;
29import org.apache.felix.scr.annotations.ReferenceCardinality;
30import org.apache.felix.scr.annotations.Service;
31import org.onlab.util.Tools;
32import org.onosproject.cfg.ComponentConfigService;
33import org.onosproject.core.ApplicationId;
34import org.onosproject.core.CoreService;
35import org.osgi.service.component.ComponentContext;
36import org.slf4j.Logger;
37
38import com.eclipsesource.json.JsonArray;
39import com.eclipsesource.json.JsonObject;
40import com.sun.jersey.api.client.Client;
41import com.sun.jersey.api.client.ClientResponse;
42import com.sun.jersey.api.client.WebResource;
43import com.sun.jersey.api.client.filter.HTTPBasicAuthFilter;
44
45import static com.google.common.base.Strings.isNullOrEmpty;
46import static com.google.common.net.MediaType.JSON_UTF_8;
47import static java.net.HttpURLConnection.HTTP_CREATED;
48import static java.net.HttpURLConnection.HTTP_NO_CONTENT;
49import static java.net.HttpURLConnection.HTTP_OK;
50import static org.slf4j.LoggerFactory.getLogger;
51
52
53/**
54 * XOS interface application.
55 */
56@Component(immediate = true)
57@Service
58public class OnosXOSIntegrationManager implements VoltTenantService {
59
60 private static final String TEST_XOS_SERVER_ADDRESS = "10.254.1.22";
61 private static final int TEST_XOS_SERVER_PORT = 8000;
62 private static final String XOS_TENANT_BASE_URI = "/xoslib/volttenant/";
63
64 private final Logger log = getLogger(getClass());
65 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
66 protected CoreService coreService;
67 @Reference(cardinality = ReferenceCardinality.MANDATORY_UNARY)
68 protected ComponentConfigService cfgService;
69 @Property(name = "XOSServerAddress",
70 value = TEST_XOS_SERVER_ADDRESS,
71 label = "XOS Server address")
72 protected String xosServerAddress = TEST_XOS_SERVER_ADDRESS;
73 @Property(name = "XOSServerPort",
74 intValue = TEST_XOS_SERVER_PORT,
75 label = "XOS Server port")
76 protected int xosServerPort = TEST_XOS_SERVER_PORT;
77 private ApplicationId appId;
78
79 @Activate
80 public void activate(ComponentContext context) {
81 log.info("XOS app is starting");
82 cfgService.registerProperties(getClass());
83 appId = coreService.registerApplication("org.onosproject.xosintegration");
84 readComponentConfiguration(context);
85
86 log.info("XOS({}) started", appId.id());
87 }
88
89 @Deactivate
90 public void deactivate() {
91 cfgService.unregisterProperties(getClass(), false);
92 log.info("XOS({}) stopped", appId.id());
93 }
94
95 @Modified
96 public void modified(ComponentContext context) {
97 readComponentConfiguration(context);
98 }
99
100 /**
101 * Converts a JSON representation of a tenant into a tenant object.
102 *
103 * @param jsonTenant JSON object representing the tenant
104 * @return volt tenant object
105 */
106 private VoltTenant jsonToTenant(JsonObject jsonTenant) {
107 return VoltTenant.builder()
108 .withHumanReadableName(jsonTenant.get("humanReadableName").asString())
109 .withId(jsonTenant.get("id").asInt())
110 .withProviderService(jsonTenant.get("provider_service").asInt())
111 .withServiceSpecificId(jsonTenant.get("service_specific_id").asString())
112 .withVlanId(jsonTenant.get("vlan_id").asString())
113 .build();
114 }
115
116 /**
117 * Converts a tenant object into a JSON string.
118 *
119 * @param tenant volt tenant object to convert
120 * @return JSON string for the tenant
121 */
122 private String tenantToJson(VoltTenant tenant) {
123 return "{"
124 + "\"humanReadableName\": \"" + tenant.humanReadableName() + "\","
125 + "\"id\": \"" + tenant.id() + "\","
126 + "\"provider_service\": \"" + tenant.providerService() + "\","
127 + "\"service_specific_id\": \"" + tenant.serviceSpecificId() + "\","
128 + "\"vlan_id\": \"" + tenant.vlanId() + "\""
129 + "}";
130 }
131
132 /**
133 * Gets a client web resource builder for the base XOS REST API
134 * with no additional URI.
135 *
136 * @return web resource builder
137 */
138 private WebResource.Builder getClientBuilder() {
139 return getClientBuilder("");
140 }
141
142 /**
143 * Gets a client web resource builder for the base XOS REST API
144 * with an optional additional URI.
145 *
146 * @return web resource builder
147 */
148 private WebResource.Builder getClientBuilder(String uri) {
149 String baseUrl = "http://" + xosServerAddress + ":"
150 + Integer.toString(xosServerPort);
151 Client client = Client.create();
152 client.addFilter(new HTTPBasicAuthFilter("padmin@vicci.org", "letmein"));
153 WebResource resource = client.resource(baseUrl
154 + XOS_TENANT_BASE_URI + uri);
155 return resource.accept(JSON_UTF_8.toString())
156 .type(JSON_UTF_8.toString());
157 }
158
159 /**
160 * Performs a REST GET operation on the base XOS REST URI.
161 *
162 * @return JSON string fetched by the GET operation
163 */
164 private String getRest() {
165 return getRest("");
166 }
167
168 /**
169 * Performs a REST GET operation on the base XOS REST URI with
170 * an optional additional URI.
171 *
172 * @return JSON string fetched by the GET operation
173 */
174 private String getRest(String uri) {
175 WebResource.Builder builder = getClientBuilder(uri);
176 ClientResponse response = builder.get(ClientResponse.class);
177
178 if (response.getStatus() != HTTP_OK) {
179 log.info("REST GET request returned error code {}",
180 response.getStatus());
181 }
182 String jsonString = response.getEntity(String.class);
183 log.info("JSON read:\n{}", jsonString);
184
185 return jsonString;
186 }
187
188 /**
189 * Performs a REST POST operation of a json string on the base
190 * XOS REST URI with an optional additional URI.
191 *
192 * @param json JSON string to post
193 */
194 private void postRest(String json) {
195 WebResource.Builder builder = getClientBuilder();
196 ClientResponse response = builder.post(ClientResponse.class, json);
197
198 if (response.getStatus() != HTTP_CREATED) {
199 log.info("REST POST request returned error code {}",
200 response.getStatus());
201 }
202 }
203
204 /**
205 * Performs a REST DELETE operation on the base
206 * XOS REST URI with an optional additional URI.
207 *
208 * @param uri optional additional URI
209 */
210 private void deleteRest(String uri) {
211 WebResource.Builder builder = getClientBuilder(uri);
212 ClientResponse response = builder.delete(ClientResponse.class);
213
214 if (response.getStatus() != HTTP_NO_CONTENT) {
215 log.info("REST DELETE request returned error code {}",
216 response.getStatus());
217 }
218 }
219
220 /**
221 * Deletes the tenant with the given ID.
222 *
223 * @param tenantId ID of tenant to delete
224 */
225 private void deleteTenant(long tenantId) {
226 deleteRest(Long.toString(tenantId));
227 }
228
229 @Override
230 public Set<VoltTenant> getAllTenants() {
231 String jsonString = getRest();
232
233 JsonArray voltTenantItems = JsonArray.readFrom(jsonString);
234
235 return IntStream.range(0, voltTenantItems.size())
236 .mapToObj(index -> jsonToTenant(voltTenantItems.get(index).asObject()))
237 .collect(Collectors.toSet());
238 }
239
240 @Override
241 public void removeTenant(long id) {
242 deleteTenant(id);
243 }
244
245 @Override
246 public VoltTenant addTenant(VoltTenant newTenant) {
247 String json = tenantToJson(newTenant);
248 postRest(json);
249 return newTenant;
250 }
251
252 @Override
253 public VoltTenant getTenant(long id) {
254 String jsonString = getRest(Long.toString(id));
255 JsonObject jsonTenant = JsonObject.readFrom(jsonString);
256 if (jsonTenant.get("id") != null) {
257 return jsonToTenant(jsonTenant);
258 } else {
259 return null;
260 }
261 }
262
263 /**
264 * Extracts properties from the component configuration context.
265 *
266 * @param context the component context
267 */
268 private void readComponentConfiguration(ComponentContext context) {
269 Dictionary<?, ?> properties = context.getProperties();
270
271 String newXosServerAddress = Tools.get(properties, "XOSServerAddress");
272 if (!isNullOrEmpty(newXosServerAddress)) {
273 xosServerAddress = newXosServerAddress;
274 }
275
276 String newXosServerPortString = Tools.get(properties, "XOSServerPort");
277 if (!isNullOrEmpty(newXosServerPortString)) {
278 xosServerPort = Integer.parseInt(newXosServerPortString);
279 }
280 log.info("XOS URL is now http://{}:{}", xosServerAddress, xosServerPort);
281 }
282}
283
284