aboutsummaryrefslogtreecommitdiffstats
path: root/feature-lifecycle/src/main/java/org/onap/policy/drools/server/restful/RestLifecycleManager.java
blob: 5a534639e15524ba1dde930df101a61105e9aa6c (plain)
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
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
/*-
 * ============LICENSE_START=======================================================
 * Copyright (C) 2019-2022 AT&T Intellectual Property. All rights reserved.
 * Modifications Copyright (C) 2021 Nordix Foundation.
 * ================================================================================
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ============LICENSE_END=========================================================
 */

package org.onap.policy.drools.server.restful;

import com.worldturner.medeia.api.ValidationFailedException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import java.util.Collections;
import java.util.List;
import java.util.Properties;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.onap.policy.common.endpoints.event.comm.TopicSink;
import org.onap.policy.common.endpoints.event.comm.TopicSource;
import org.onap.policy.common.endpoints.http.server.YamlMessageBodyHandler;
import org.onap.policy.common.utils.coder.CoderException;
import org.onap.policy.common.utils.coder.StandardCoder;
import org.onap.policy.drools.lifecycle.LifecycleFeature;
import org.onap.policy.drools.lifecycle.PolicyTypeController;
import org.onap.policy.models.pdp.concepts.PdpStateChange;
import org.onap.policy.models.pdp.concepts.PdpStatistics;
import org.onap.policy.models.pdp.concepts.PdpUpdate;
import org.onap.policy.models.pdp.enums.PdpState;
import org.onap.policy.models.tosca.authorative.concepts.ToscaConceptIdentifier;
import org.onap.policy.models.tosca.authorative.concepts.ToscaPolicy;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * REST Lifecycle Manager.
 */

@Path("/policy/pdp/engine/lifecycle")
@Produces({MediaType.APPLICATION_JSON, YamlMessageBodyHandler.APPLICATION_YAML})
@Consumes({MediaType.APPLICATION_JSON, YamlMessageBodyHandler.APPLICATION_YAML})
@Api
public class RestLifecycleManager {

    private static final Logger logger = LoggerFactory.getLogger(RestLifecycleManager.class);

    private static final StandardCoder coder = new StandardCoder();

    /**
     * GET group.
     */

    @GET
    @Path("group")
    @ApiOperation(value = "Retrieves the Lifecycle group",
        notes = "Lifecycle Group", response = String.class)
    public Response group() {
        return Response.status(Response.Status.OK).entity(LifecycleFeature.getFsm().getGroup()).build();
    }

    /**
     * PUT group.
     */

    @PUT
    @Path("group/{group}")
    @ApiOperation(value = "Updates the Lifecycle group",
            notes = "Lifecycle Group", response = String.class)
    public Response updateGroup(
        @ApiParam(value = "Group", required = true) @PathParam("group") String group) {
        LifecycleFeature.getFsm().setGroup(group);
        return Response.status(Response.Status.OK).entity(LifecycleFeature.getFsm().getGroup()).build();
    }

    /**
     * GET subgroup.
     */

    @GET
    @Path("subgroup")
    @ApiOperation(value = "Retrieves the Lifecycle subgroup",
            notes = "Lifecycle Subgroup", response = String.class)
    public Response subgroup() {
        return Response.status(Response.Status.OK).entity(LifecycleFeature.getFsm().getSubGroup()).build();
    }

    /**
     * PUT subgroup.
     */

    @PUT
    @Path("subgroup/{subgroup}")
    @ApiOperation(value = "Retrieves the Lifecycle subgroup",
            notes = "Lifecycle Subgroup", response = String.class)
    public Response subgroup(
        @ApiParam(value = "Subgroup", required = true) @PathParam("subgroup") String subgroup) {
        LifecycleFeature.getFsm().setSubGroup(subgroup);
        return Response.status(Response.Status.OK).entity(LifecycleFeature.getFsm().getSubGroup()).build();
    }

    /**
     * GET properties.
     */

    @GET
    @Path("properties")
    @ApiOperation(value = "Retrieves the Lifecycle properties",
            notes = "Lifecycle Properties", response = Properties.class)
    public Response properties() {
        return Response.status(Response.Status.OK).entity(LifecycleFeature.getFsm().getProperties()).build();
    }

    /**
     * GET state.
     */

    @GET
    @Path("state")
    @ApiOperation(value = "Retrieves the Lifecycle state", notes = "Lifecycle State", response = PdpState.class)
    public Response state() {
        return Response.status(Response.Status.OK).entity(LifecycleFeature.getFsm().state()).build();
    }

    /**
     * PUT state.
     */

    @PUT
    @Path("state/{state}")
    @ApiOperation(value = "updates the Lifecycle state", notes = "Lifecycle State", response = Boolean.class)
    public Response updateState(
        @ApiParam(value = "state", required = true) @PathParam("state") String state) {

        var change = new PdpStateChange();
        change.setPdpGroup(LifecycleFeature.getFsm().getGroup());
        change.setPdpSubgroup(LifecycleFeature.getFsm().getSubGroup());
        change.setState(PdpState.valueOf(state));
        change.setName(LifecycleFeature.getFsm().getPdpName());

        return Response.status(Response.Status.OK).entity(LifecycleFeature.getFsm().stateChange(change)).build();
    }

    /**
     * GET topic source.
     */

    @GET
    @Path("topic/source")
    @ApiOperation(value = "Retrieves the Lifecycle topic source",
            notes = "Lifecycle Topic Source", response = TopicSource.class)
    public Response source() {
        return Response.status(Response.Status.OK).entity(LifecycleFeature.getFsm().getSource()).build();
    }

    /**
     * GET topic sink.
     */

    @GET
    @Path("topic/sink")
    @ApiOperation(value = "Retrieves the Lifecycle topic sink",
            notes = "Lifecycle Topic Sink", response = TopicSink.class)
    public Response sink() {
        return Response.status(Response.Status.OK).entity(LifecycleFeature.getFsm().getClient()).build();
    }

    /**
     * GET status interval.
     */

    @GET
    @Path("status/interval")
    @ApiOperation(value = "Retrieves the Lifecycle Status Timer Interval in seconds",
            notes = "Lifecycle Status Timer Interval in seconds", response = Long.class)
    public Response updateStatusTimer() {
        return Response.status(Response.Status.OK).entity(LifecycleFeature.getFsm().getStatusTimerSeconds()).build();
    }

    /**
     * PUT timeout.
     */

    @PUT
    @Path("status/interval/{timeout}")
    @ApiOperation(value = "Updates the Lifecycle Status Timer Interval in seconds",
            notes = "Lifecycle Status Timer Interval in seconds", response = Long.class)
    public Response statusTimer(
            @ApiParam(value = "timeout", required = true) @PathParam("timeout") Long timeout) {
        LifecycleFeature.getFsm().setStatusTimerSeconds(timeout);
        return Response.status(Response.Status.OK).entity(LifecycleFeature.getFsm().getStatusTimerSeconds()).build();
    }

    /**
     * GET policy types.
     */

    @GET
    @Path("policyTypes")
    @ApiOperation(value = "List of supported policy types",
            notes = "Lifecycle Policy Types", responseContainer = "List")
    public Response policyTypes() {
        return Response.status(Response.Status.OK)
                       .entity(LifecycleFeature.getFsm().getPolicyTypesMap().keySet())
                       .build();
    }

    /**
     * GET controllers.
     */

    @GET
    @Path("policyTypes/{policyType}/{policyTypeVersion}")
    @ApiOperation(value = "Entities associated with a policy type",
            notes = "Lifecycle policy Types", response = PolicyTypeController.class)
    public Response policyType(
        @ApiParam(value = "Policy Type", required = true)
            @PathParam("policyType") String policyType,
        @ApiParam(value = "Policy Type Version", required = true)
            @PathParam("policyTypeVersion") String policyTypeVersion) {
        PolicyTypeController typeController =
            LifecycleFeature.getFsm().getPolicyTypesMap()
                    .get(new ToscaConceptIdentifier(policyType, policyTypeVersion));
        if (typeController == null) {
            return Response.status(Response.Status.NOT_FOUND).build();
        }

        return Response.status(Response.Status.OK)
                       .entity(typeController)
                       .build();
    }

    /**
     * GET policies.
     */

    @GET
    @Path("policies")
    @ApiOperation(value = "List of policies", responseContainer = "List")
    public Response policies() {
        return Response.status(Response.Status.OK)
                       .entity(LifecycleFeature.getFsm().getPoliciesMap().keySet())
                       .build();

    }

    /**
     * POST a Policy.
     */

    @POST
    @Path("policies")
    @ApiOperation(value = "Deploy a policy", response = Boolean.class)
    public Response deployTrackedPolicy(
            @ApiParam(value = "Tosca Policy", required = true) String policy) {

        var toscaPolicy = getToscaPolicy(policy);
        if (toscaPolicy == null) {
            return Response.status(Response.Status.NOT_ACCEPTABLE).build();
        }

        var typeController = getPolicyTypeController(toscaPolicy);
        if (typeController == null) {
            return Response.status(Response.Status.NOT_FOUND).build();
        }

        boolean updateResult = LifecycleFeature.getFsm().update(getDeployPolicyUpdate(List.of(toscaPolicy)));
        return Response.status((updateResult ? Response.Status.OK : Response.Status.NOT_ACCEPTABLE))
                       .entity(updateResult)
                       .build();
    }

    /**
     * GET a policy.
     */

    @GET
    @Path("policies/{policyName}/{policyVersion}")
    @ApiOperation(value = "Retrieves a policy", response = ToscaPolicy.class)
    public Response policy(
            @ApiParam(value = "Policy Name", required = true) @PathParam("policyName") String policyName,
            @ApiParam(value = "Policy Version", required = true) @PathParam("policyVersion") String policyVersion) {

        ToscaPolicy policy;
        try {
            policy =
                LifecycleFeature.getFsm().getPoliciesMap().get(new ToscaConceptIdentifier(policyName, policyVersion));
        } catch (RuntimeException r) {
            logger.debug("policy {}:{} has not been found", policyName, policyVersion, r);
            return Response.status(Response.Status.NOT_FOUND).build();
        }

        if (policy == null) {
            return Response.status(Response.Status.NOT_FOUND).build();
        }

        return Response.status(Response.Status.OK).entity(policy).build();
    }

    /**
     * DELETE a policy.
     */

    @DELETE
    @Path("policies/{policyName}/{policyVersion}")
    @ApiOperation(value = "Deletes a Lifecycle tracked policy", response = Boolean.class)
    public Response undeployPolicy(
            @ApiParam(value = "Policy", required = true) @PathParam("policyName") String policyName,
            @ApiParam(value = "Policy Version", required = true) @PathParam("policyVersion") String policyVersion) {

        ToscaPolicy policy;
        try {
            policy =
                LifecycleFeature.getFsm().getPoliciesMap().get(new ToscaConceptIdentifier(policyName, policyVersion));
        } catch (RuntimeException r) {
            logger.debug("policy {}:{} has not been found", policyName, policyVersion, r);
            return Response.status(Response.Status.NOT_FOUND).build();
        }

        if (policy == null) {
            return Response.status(Response.Status.NOT_FOUND).build();
        }

        return Response.status(Response.Status.OK)
                       .entity(LifecycleFeature.getFsm().update(getUndeployPolicyUpdate(List.of(policy))))
                       .build();
    }

    /**
     * List of policies individual Operations supported.
     */

    @GET
    @Path("policies/operations")
    @ApiOperation(value = "Gets Policy Operations", responseContainer = "List")
    public Response policiesOperations() {
        return Response.status(Response.Status.OK).entity(List.of("deployment", "undeployment", "validation")).build();
    }

    /**
     * POST a deployment operation on a policy.
     */

    @POST
    @Path("policies/operations/deployment")
    @ApiOperation(value = "Deploys a policy", notes = "Deploys a policy", response = Boolean.class)
    public Response deployOperation(@ApiParam(value = "Tosca Policy", required = true) String policy) {
        return deployUndeployOperation(policy, true);
    }

    /**
     * POST an undeployment operation on a policy.
     */

    @POST
    @Path("policies/operations/undeployment")
    @ApiOperation(value = "Undeploys a policy", response = Boolean.class)
    public Response undeployOperation(@ApiParam(value = "Tosca Policy", required = true) String policy) {
        return deployUndeployOperation(policy, false);
    }

    /**
     * POST a policy for validation.
     */

    @POST
    @Path("policies/operations/validation")
    @ApiOperation(value = "Validates a policy", responseContainer = "List")
    public Response validateOperation(@ApiParam(value = "Tosca Policy", required = true) String policy) {
        var toscaPolicy = getToscaPolicy(policy);
        if (toscaPolicy == null) {
            return Response.status(Response.Status.NOT_ACCEPTABLE).build();
        }

        try {
            LifecycleFeature.getFsm().getDomainMaker().conformance(toscaPolicy);
        } catch (ValidationFailedException v) {
            logger.trace("policy {} validation errors: {}", toscaPolicy, v.getMessage(), v);
            return Response.status(Response.Status.NOT_ACCEPTABLE).entity(v.getFailures()).build();
        }

        return Response.status(Response.Status.OK).entity(Collections.emptyList()).build();
    }

    /**
     * Get current counts.
     */

    @GET
    @Path("statistics")
    @ApiOperation(value = "Gets Policy Statistics", response = PdpStatistics.class)
    public Response stats() {
        return Response.status(Response.Status.OK).entity(LifecycleFeature.getFsm().statisticsPayload()).build();
    }

    private Response deployUndeployOperation(String policy, boolean deploy) {
        var toscaPolicy = getToscaPolicy(policy);
        if (toscaPolicy == null) {
            return Response.status(Response.Status.NOT_ACCEPTABLE).build();
        }

        var typeController = getPolicyTypeController(toscaPolicy);
        if (typeController == null) {
            return Response.status(Response.Status.NOT_FOUND).build();
        }

        return Response.status(Response.Status.OK)
                       .entity((deploy) ? typeController.deploy(toscaPolicy) : typeController.undeploy(toscaPolicy))
                       .build();
    }

    private ToscaPolicy getToscaPolicy(String policy) {
        try {
            return coder.decode(policy, ToscaPolicy.class);
        } catch (CoderException | RuntimeException e) {
            return null;
        }
    }

    private PolicyTypeController getPolicyTypeController(ToscaPolicy policy) {
        return LifecycleFeature.getFsm().getPolicyTypesMap().get(policy.getTypeIdentifier());
    }

    private PdpUpdate getPolicyUpdate() {
        var update = new PdpUpdate();
        update.setName(LifecycleFeature.getFsm().getPdpName());
        update.setPdpGroup(LifecycleFeature.getFsm().getGroup());
        update.setPdpSubgroup(LifecycleFeature.getFsm().getSubGroup());
        return update;
    }

    private PdpUpdate getDeployPolicyUpdate(List<ToscaPolicy> policies) {
        PdpUpdate update = getPolicyUpdate();
        update.setPoliciesToBeDeployed(policies);
        return update;
    }

    private PdpUpdate getUndeployPolicyUpdate(List<ToscaPolicy> policies) {
        PdpUpdate update = getPolicyUpdate();
        update.setPoliciesToBeUndeployed(LifecycleFeature.fsm.getPolicyIds(policies));
        return update;
    }

}