aboutsummaryrefslogtreecommitdiffstats
path: root/catalog-model/src/main/java/org/openecomp/sdc/be/model/operations/impl/ArtifactOperation.java
blob: 102e896c3873a677243c3a1bc64419ae83d7d831 (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
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
/*-
 * ============LICENSE_START=======================================================
 * SDC
 * ================================================================================
 * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
 * ================================================================================
 * 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.openecomp.sdc.be.model.operations.impl;

import org.janusgraph.core.JanusGraph;
import org.janusgraph.core.JanusGraphVertex;
import fj.data.Either;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.apache.tinkerpop.gremlin.structure.Direction;
import org.apache.tinkerpop.gremlin.structure.Edge;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.openecomp.sdc.be.config.BeEcompErrorManager;
import org.openecomp.sdc.be.config.BeEcompErrorManager.ErrorSeverity;
import org.openecomp.sdc.be.dao.graph.GraphElementFactory;
import org.openecomp.sdc.be.dao.graph.datatype.GraphEdge;
import org.openecomp.sdc.be.dao.graph.datatype.GraphElementTypeEnum;
import org.openecomp.sdc.be.dao.graph.datatype.GraphRelation;
import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus;
import org.openecomp.sdc.be.dao.neo4j.GraphEdgeLabels;
import org.openecomp.sdc.be.dao.neo4j.GraphEdgePropertiesDictionary;
import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary;
import org.openecomp.sdc.be.dao.janusgraph.JanusGraphGenericDao;
import org.openecomp.sdc.be.datatypes.elements.ArtifactDataDefinition;
import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
import org.openecomp.sdc.be.model.ArtifactDefinition;
import org.openecomp.sdc.be.model.HeatParameterDefinition;
import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
import org.openecomp.sdc.be.resources.data.ArtifactData;
import org.openecomp.sdc.be.resources.data.HeatParameterData;
import org.openecomp.sdc.be.resources.data.HeatParameterValueData;
import org.openecomp.sdc.be.resources.data.UniqueIdData;
import org.openecomp.sdc.common.api.ArtifactTypeEnum;
import org.openecomp.sdc.common.log.api.ILogConfiguration;
import org.openecomp.sdc.common.log.wrappers.Logger;
import org.slf4j.MDC;
import org.springframework.stereotype.Component;

import java.util.*;

@Component("artifact-operation")
public class ArtifactOperation {

    private static final String THE_RETURNED_ARTIFACT_DEFINTION_IS = "The returned ArtifactDefintion is {}";

	@javax.annotation.Resource
    private JanusGraphGenericDao janusGraphGenericDao;

    @javax.annotation.Resource
    private HeatParametersOperation heatParametersOperation;

    @javax.annotation.Resource
    private GroupOperation groupOperation;
    @javax.annotation.Resource
    private GroupInstanceOperation groupInstanceOperation;

    private static final Logger log = Logger.getLogger(ArtifactOperation.class.getName());

    public ArtifactOperation() {
        super();
    }

    public Either<ArtifactDefinition, StorageOperationStatus> addArifactToComponent(ArtifactDefinition artifactInfo, String parentId, NodeTypeEnum type, boolean failIfExist, boolean inTransaction) {

        Either<ArtifactData, StorageOperationStatus> status = addArtifactToGraph(artifactInfo, parentId, type, failIfExist);

        if (status.isRight()) {
            if (!inTransaction) {
                janusGraphGenericDao.rollback();
            }
            log.debug("Failed to add artifact {} to {} {}", artifactInfo.getArtifactName(), type , parentId);
            return Either.right(status.right().value());
        } else {
            if (!inTransaction) {
                janusGraphGenericDao.commit();
            }
            ArtifactData artifactData = status.left().value();

            ArtifactDefinition artifactDefResult = convertArtifactDataToArtifactDefinition(artifactData);

            log.debug(THE_RETURNED_ARTIFACT_DEFINTION_IS, artifactDefResult);
            return Either.left(artifactDefResult);
        }

    }

    private Either<ArtifactData, StorageOperationStatus> addArtifactToGraph(ArtifactDefinition artifactInfo, String id, NodeTypeEnum type, boolean failIfexist) {

        if (artifactInfo.getUniqueId() == null || artifactInfo.getUniqueId().isEmpty()) {
            String uniqueId = UniqueIdBuilder.buildPropertyUniqueId(id, artifactInfo.getArtifactLabel());
            artifactInfo.setUniqueId(uniqueId);
        }

        if (!validateParentType(type)) {
            return Either.right(StorageOperationStatus.GENERAL_ERROR);
        }

        ArtifactData artifactData = new ArtifactData(artifactInfo);

        Either<ArtifactData, JanusGraphOperationStatus> existArtifact = janusGraphGenericDao
            .getNode(artifactData.getUniqueIdKey(), artifactData.getUniqueId(), ArtifactData.class);
        if (existArtifact.isRight()) {
            if (existArtifact.right().value().equals(JanusGraphOperationStatus.NOT_FOUND)) {
                // create new node
                log.debug("Before adding artifact to graph {}" , artifactData);
                if (artifactData.getArtifactDataDefinition().getArtifactUUID() == null || artifactData.getArtifactDataDefinition().getArtifactUUID().isEmpty())
                    updateUUID(artifactData.getArtifactDataDefinition(), null, artifactData.getArtifactDataDefinition().getArtifactVersion());
                Either<ArtifactData, JanusGraphOperationStatus> createNodeResult = janusGraphGenericDao
                    .createNode(artifactData, ArtifactData.class);
                log.debug("After adding artifact to graph {}", artifactData);

                if (createNodeResult.isRight()) {
                    JanusGraphOperationStatus operationStatus = createNodeResult.right().value();
                    log.debug("Failed to add artifact {} to graph. status is {}", artifactData.getArtifactDataDefinition().getArtifactName(), operationStatus);
                    BeEcompErrorManager.getInstance().logBeFailedCreateNodeError("Add artifact", artifactData.getArtifactDataDefinition().getArtifactName(), String.valueOf(operationStatus));
                    return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(operationStatus));
                }
                artifactData = createNodeResult.left().value();

                // add heat parameters
                if (artifactInfo.getHeatParameters() != null && !artifactInfo.getHeatParameters().isEmpty() && !artifactInfo.getArtifactType().equals(ArtifactTypeEnum.HEAT_ENV.getType())) {
                    StorageOperationStatus addPropertiesStatus = heatParametersOperation.addPropertiesToGraph(artifactInfo.getListHeatParameters(), artifactData.getUniqueId().toString(), NodeTypeEnum.ArtifactRef);
                    if (addPropertiesStatus != StorageOperationStatus.OK) {
                        log.debug("Failed to create heat parameters on graph for artifact {}", artifactInfo.getArtifactName());
                        return Either.right(addPropertiesStatus);
                    }
                }

            } else {
                log.debug("Failed to check existance of artifact in graph for id {}", artifactData.getUniqueId());
                return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(existArtifact.right().value()));
            }
        } else if (failIfexist) {
            log.debug("Artifact {} already exist", artifactData.getUniqueId());
            return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(
                JanusGraphOperationStatus.ALREADY_EXIST));
        } else {
            artifactData = existArtifact.left().value();
        }

        UniqueIdData parent = new UniqueIdData(type, id);

        // save logical artifact ref name on edge as property
        Map<String, Object> properties = new HashMap<>();
        properties.put(GraphEdgePropertiesDictionary.NAME.getProperty(), artifactInfo.getArtifactLabel());
        if (artifactInfo.getArtifactGroupType() != null)
            properties.put(GraphEdgePropertiesDictionary.GROUP_TYPE.getProperty(), artifactInfo.getArtifactGroupType().getType());
        Either<GraphRelation, JanusGraphOperationStatus> relation = janusGraphGenericDao
            .createRelation(parent, artifactData, GraphEdgeLabels.ARTIFACT_REF, properties);
        if (relation.isRight()) {
            log.debug("Failed to create relation in graph fro id {} to new artifact", id);
            return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(relation.right().value()));
        }

        return Either.left(artifactData);
    }

    private boolean validateParentType(NodeTypeEnum type) {
        boolean isValid = false;
        switch (type) {
        case Resource:
        case InterfaceOperation:
        case Service:
        case ResourceInstance:
            isValid = true;
            break;
        default:
            log.debug("Not supported node type for artifact relation : {} ", type);
        }
        return isValid;
    }


    protected ArtifactDefinition convertArtifactDataToArtifactDefinition(ArtifactData artifactDefResult) {
        log.debug("The object returned after create property is {}" ,artifactDefResult);

        ArtifactDefinition propertyDefResult = new ArtifactDefinition(artifactDefResult.getArtifactDataDefinition());
        List<HeatParameterDefinition> parameters = new ArrayList<>();
        StorageOperationStatus heatParametersOfNode = heatParametersOperation.getHeatParametersOfNode(NodeTypeEnum.ArtifactRef, artifactDefResult.getUniqueId().toString(), parameters);
        if ((heatParametersOfNode.equals(StorageOperationStatus.OK)) && !parameters.isEmpty()) {
            propertyDefResult.setListHeatParameters(parameters);
        }
        return propertyDefResult;
    }

    public Either<ArtifactDefinition, StorageOperationStatus> updateArifactOnResource(ArtifactDefinition artifactInfo, String id, String artifactId, NodeTypeEnum type, boolean inTransaction) {
        Either<ArtifactData, StorageOperationStatus> status = updateArtifactOnGraph(artifactInfo, artifactId, type, id);

        if (status.isRight()) {
            if (!inTransaction) {
                janusGraphGenericDao.rollback();
            }
            log.debug("Failed to update artifact {} of {} {}. status is {}", artifactId, type.getName(), id, status.right().value());
            BeEcompErrorManager.getInstance().logBeFailedUpdateNodeError("Update Artifact", artifactId, String.valueOf(status.right().value()));
            return Either.right(status.right().value());
        } else {
            if (!inTransaction) {
                janusGraphGenericDao.commit();
            }
            ArtifactData artifactData = status.left().value();

            ArtifactDefinition artifactDefResult = convertArtifactDataToArtifactDefinition(artifactData);
            log.debug(THE_RETURNED_ARTIFACT_DEFINTION_IS, artifactDefResult);
            return Either.left(artifactDefResult);
        }
    }

    public Either<ArtifactDefinition, StorageOperationStatus> removeArifactFromResource(String id, String artifactId, NodeTypeEnum type, boolean deleteMandatoryArtifact, boolean inTransaction) {
        Either<ArtifactData, StorageOperationStatus> status = removeArtifactOnGraph(id, artifactId, type, deleteMandatoryArtifact);

        if (status.isRight()) {
            if (!inTransaction) {
                janusGraphGenericDao.rollback();
            }
            log.debug("Failed to delete artifact {} of resource {}", artifactId, id);

            BeEcompErrorManager.getInstance().logBeFailedDeleteNodeError("Delete Artifact", artifactId, String.valueOf(status.right().value()));
            return Either.right(status.right().value());
        } else {
            if (!inTransaction) {
                janusGraphGenericDao.commit();
            }
            ArtifactData artifactData = status.left().value();

            ArtifactDefinition artifactDefResult = convertArtifactDataToArtifactDefinition(artifactData);
            log.debug(THE_RETURNED_ARTIFACT_DEFINTION_IS , artifactDefResult);
            return Either.left(artifactDefResult);
        }
    }

    @SuppressWarnings("null")
    private Either<ArtifactData, StorageOperationStatus> updateArtifactOnGraph(ArtifactDefinition artifactInfo, String artifactId, NodeTypeEnum type, String id) {

        Either<JanusGraph, JanusGraphOperationStatus> graph = janusGraphGenericDao.getGraph();
        if (graph.isRight()) {
            return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(graph.right().value()));
        }

        JanusGraph tGraph = graph.left().value();

        @SuppressWarnings("unchecked")
        Iterable<JanusGraphVertex> verticesArtifact = tGraph.query().has(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ArtifactRef), artifactId).vertices();
        Iterator<JanusGraphVertex> iterator = verticesArtifact.iterator();
        if (!iterator.hasNext()) {
            log.debug("No artifact node for id = {}", artifactId);
            return Either.right(StorageOperationStatus.NOT_FOUND);
        }
        JanusGraphVertex artifactV = iterator.next();

        Iterator<Edge> iterEdge = artifactV.edges(Direction.IN, GraphEdgeLabels.ARTIFACT_REF.getProperty());

        int edgeCount = 0;
        Edge edgeFromTo = null;
        while (iterEdge.hasNext()) {
            Edge edge = iterEdge.next();
            Vertex vertexFrom = edge.outVertex();
            String vertexId = vertexFrom.value(UniqueIdBuilder.getKeyByNodeType(type));
            if (id.equals(vertexId)) {
                edgeFromTo = edge;
            }
            ++edgeCount;
        }

        if (isNeedUpdateHeatTime(artifactInfo)) {
            artifactInfo.setHeatParamsUpdateDate(System.currentTimeMillis());
        }

        ArtifactData artifactData = new ArtifactData(artifactInfo);
        if (edgeFromTo == null) {
            log.debug("No relation between artifact  = {} and node with id = {}", artifactId, id);
            return Either.right(StorageOperationStatus.GENERAL_ERROR);
        }

        Either<Boolean, StorageOperationStatus> setRelevantHeatParamIdRes = null;
        if (edgeCount > 1) {
            // need to remove relation, create new node
            log.debug("artifactRef have more connection. Need to clone node");
            log.debug("remove edge {}", edgeFromTo);
            edgeFromTo.remove();
            // update resource id in new artifact node
            String uniqueId = UniqueIdBuilder.buildPropertyUniqueId(id, artifactInfo.getArtifactLabel());
            artifactInfo.setUniqueId(uniqueId);
            // update UUID and artifact version
            String oldChecksum = artifactV.valueOrNull(
                janusGraphGenericDao.getGraph().left().value().getPropertyKey(GraphPropertiesDictionary.ARTIFACT_CHECKSUM.getProperty()));
            String oldVersion = artifactV.valueOrNull(
                janusGraphGenericDao.getGraph().left().value().getPropertyKey(GraphPropertiesDictionary.ARTIFACT_VERSION.getProperty()));
            updateUUID(artifactInfo, oldChecksum, oldVersion);
            log.debug("try to create new artifact ref node for id {}", uniqueId);
            Either<ArtifactData, StorageOperationStatus> addedArtifactRes = addArtifactToGraph(artifactInfo, id, type, true);

            if (addedArtifactRes.isLeft()) {
                // remove all relations between groups to the old artifact
                // add relation between the same groups to the new artifact
                StorageOperationStatus reassociateGroupsFromArtifact = groupOperation.dissociateAndAssociateGroupsFromArtifact(id, type, artifactId, addedArtifactRes.left().value(), true);
                if (reassociateGroupsFromArtifact != StorageOperationStatus.OK) {
                    BeEcompErrorManager.getInstance().logInternalFlowError("UpdateArtifact", "Failed to reassociate groups to the new artifact", ErrorSeverity.ERROR);
                    return Either.right(reassociateGroupsFromArtifact);
                }

                StorageOperationStatus reassociateGroupInstancesFromArtifact = groupInstanceOperation.dissociateAndAssociateGroupsInstanceFromArtifact(id, type, artifactId, addedArtifactRes.left().value());
                if (reassociateGroupInstancesFromArtifact != StorageOperationStatus.OK) {
                    BeEcompErrorManager.getInstance().logInternalFlowError("UpdateArtifact", "Failed to reassociate group instances to the new artifact", ErrorSeverity.ERROR);
                    return Either.right(reassociateGroupsFromArtifact);
                }

                // If artifact is heat env
                if (artifactInfo.getArtifactType().equals(ArtifactTypeEnum.HEAT_ENV.getType())) {
                    ArtifactData addedArtifact = addedArtifactRes.left().value();
                    String newArtifactUniqueId = addedArtifact.getUniqueId();
                    Either<HeatParameterValueData, StorageOperationStatus> updateResult = null;

                    setRelevantHeatParamIdRes = setRelevantHeatParamId(artifactV, artifactInfo);
                    if (setRelevantHeatParamIdRes.isRight()) {
                        log.error("Failed to set relevant id to heat parameters for heat env artifact {}. Status is {}", artifactInfo.getUniqueId(), setRelevantHeatParamIdRes.right().value());
                        return Either.right(setRelevantHeatParamIdRes.right().value());
                    }
                    for (HeatParameterDefinition heatEnvParam : artifactInfo.getListHeatParameters()) {
                        updateResult = heatParametersOperation.updateHeatParameterValue(heatEnvParam, newArtifactUniqueId, id, artifactInfo.getArtifactLabel());
                        if (updateResult.isRight()) {
                            log.error("Failed to update heat parameter {}. Status is {}", heatEnvParam.getName(), updateResult.right().value());
                            return Either.right(updateResult.right().value());
                        }
                    }

                    Iterator<Edge> iterEdgeGeneratedFrom = artifactV.edges(Direction.OUT, GraphEdgeLabels.GENERATED_FROM.getProperty());

                    if (!iterEdgeGeneratedFrom.hasNext()) {
                        log.error("No heat artifact node for id = {}", artifactId);
                        return Either.right(StorageOperationStatus.NOT_FOUND);
                    }
                    Edge edgeToHeat = iterEdgeGeneratedFrom.next();
                    Vertex vertexIn = edgeToHeat.inVertex();
                    String generatedFromArtifactId = vertexIn.value(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ArtifactRef));
                    UniqueIdData generatedFromArtifactNode = new UniqueIdData(NodeTypeEnum.ArtifactRef, generatedFromArtifactId);
                    Either<GraphRelation, JanusGraphOperationStatus> createRelationToGeneratedFromArtifactRes = janusGraphGenericDao
                        .createRelation(addedArtifact, generatedFromArtifactNode, GraphEdgeLabels.GENERATED_FROM, null);
                    if (createRelationToGeneratedFromArtifactRes.isRight()) {
                        log.error("Failed to create relation from heat_env {} to heat {}", addedArtifact.getUniqueId(), generatedFromArtifactNode);
                        return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(createRelationToGeneratedFromArtifactRes.right().value()));
                    }
                }
            }
            return addedArtifactRes;

        } else {
            if (edgeCount == 1) {
                String oldChecksum = artifactV.valueOrNull(
                    janusGraphGenericDao.getGraph().left().value().getPropertyKey(GraphPropertiesDictionary.ARTIFACT_CHECKSUM.getProperty()));
                String oldVersion = artifactV.valueOrNull(
                    janusGraphGenericDao.getGraph().left().value().getPropertyKey(GraphPropertiesDictionary.ARTIFACT_VERSION.getProperty()));
                updateUUID(artifactInfo, oldChecksum, oldVersion);
                // update exist
                Either<ArtifactData, JanusGraphOperationStatus> updatedArtifact = janusGraphGenericDao
                    .updateNode(artifactData, ArtifactData.class);
                if (updatedArtifact.isRight()) {
                    log.debug("failed to update artifact node for id {}", artifactData.getUniqueId());
                    return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(updatedArtifact.right().value()));
                }

                if (artifactInfo.getArtifactType().equals(ArtifactTypeEnum.HEAT_ENV.getType())) {
                    Either<HeatParameterValueData, StorageOperationStatus> updateResult = null;
                    String artifactUniqueId = artifactInfo.getUniqueId();
                    setRelevantHeatParamIdRes = setRelevantHeatParamId(artifactV, artifactInfo);
                    if (setRelevantHeatParamIdRes.isRight()) {
                        log.error("Failed to set relevant id to heat parameters for heat env artifact {}. Status is {}", artifactInfo.getUniqueId(), setRelevantHeatParamIdRes.right().value());
                        return Either.right(setRelevantHeatParamIdRes.right().value());
                    }
                    for (HeatParameterDefinition heatEnvParam : artifactInfo.getListHeatParameters()) {
                        updateResult = heatParametersOperation.updateHeatParameterValue(heatEnvParam, artifactUniqueId, id, artifactInfo.getArtifactLabel());
                        if (updateResult.isRight()) {
                            log.error("Failed to update heat parameter {}. Status is {}", heatEnvParam.getName(), updateResult.right().value());
                            return Either.right(updateResult.right().value());
                        }
                    }
                } else {
                    if (artifactData.getArtifactDataDefinition().getArtifactChecksum() == null) {
                        // update heat parameters only if it is not heat env
                        if (artifactInfo.getGeneratedFromId() == null) {
                            StorageOperationStatus operationStatus = heatParametersOperation.updateHeatParameters(artifactInfo.getListHeatParameters());
                            if (operationStatus != StorageOperationStatus.OK) {
                                return Either.right(operationStatus);
                            }
                        }
                    } else {
                        Either<List<HeatParameterDefinition>, StorageOperationStatus> deleteParameters = heatParametersOperation.deleteAllHeatParametersAssociatedToNode(NodeTypeEnum.ArtifactRef, artifactInfo.getUniqueId());
                        if (deleteParameters.isRight()) {
                            log.debug("failed to update heat parameters for artifact id {}", artifactData.getUniqueId());
                            return Either.right(StorageOperationStatus.GENERAL_ERROR);
                        }

                        StorageOperationStatus addParameters = heatParametersOperation.addPropertiesToGraph(artifactInfo.getListHeatParameters(), artifactId, NodeTypeEnum.ArtifactRef);
                        if (!addParameters.equals(StorageOperationStatus.OK)) {
                            log.debug("failed to update heat parameters for artifact id {}", artifactData.getUniqueId());
                            return Either.right(StorageOperationStatus.GENERAL_ERROR);
                        }

                    }
                }

                return Either.left(updatedArtifact.left().value());
            } else {
                log.debug("No relevent edges for artifact = {}", artifactId);
                return Either.right(StorageOperationStatus.GENERAL_ERROR);
            }
        }
    }

    private boolean isNeedUpdateHeatTime(ArtifactDefinition artifactInfo) {
        if (artifactInfo.getArtifactType().equals(ArtifactTypeEnum.HEAT.getType()) || artifactInfo.getArtifactType().equals(ArtifactTypeEnum.HEAT_NET.getType()) || artifactInfo.getArtifactType().equals(ArtifactTypeEnum.HEAT_VOL.getType())) {
            return true;
        }
        return false;
    }

    private Either<Boolean, StorageOperationStatus> setRelevantHeatParamId(JanusGraphVertex artifactV, ArtifactDefinition artifactInfo) {

        Map<String, String> heatParametersHM = new HashMap<>();

        Iterator<Edge> iterHeat = artifactV.edges(Direction.OUT, GraphEdgeLabels.GENERATED_FROM.getProperty());
        if (!iterHeat.hasNext()) {
            log.debug("No edges with label GENERATED_FROM for the node {}" , artifactInfo.getUniqueId());
            return Either.right(StorageOperationStatus.NOT_FOUND);
        }
        Edge heat = iterHeat.next();
        Vertex heatVertex = heat.inVertex();
        String heatUniqueId = (String) heatVertex.value(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ArtifactRef));

        Either<List<ImmutablePair<HeatParameterData, GraphEdge>>, JanusGraphOperationStatus> getHeatParametersRes = janusGraphGenericDao
            .getChildrenNodes(GraphPropertiesDictionary.UNIQUE_ID.getProperty(), heatUniqueId, GraphEdgeLabels.HEAT_PARAMETER,
                NodeTypeEnum.HeatParameter, HeatParameterData.class);
        if (getHeatParametersRes.isRight()) {
            log.debug("No heat parameters for heat artifact {}", heatUniqueId);
            return Either.right(StorageOperationStatus.NOT_FOUND);
        }
        List<ImmutablePair<HeatParameterData, GraphEdge>> heatParameters = getHeatParametersRes.left().value();
        if (heatParameters == null) {
            log.debug("No heat parameters for heat artifact {}", heatUniqueId);
            return Either.right(StorageOperationStatus.NOT_FOUND);
        }
        for (ImmutablePair<HeatParameterData, GraphEdge> heatParamEdge : heatParameters) {
            HeatParameterData heatParam = heatParamEdge.getLeft();
            heatParametersHM.put(heatParam.getName(), (String) heatParam.getUniqueId());
        }
        String curName = null;
        for (HeatParameterDefinition heatEnvParam : artifactInfo.getListHeatParameters()) {
            curName = heatEnvParam.getName();
            if (heatParametersHM.containsKey(curName)) {
                heatEnvParam.setUniqueId(heatParametersHM.get(curName));
            }
        }
        return Either.left(true);
    }

    private Either<ArtifactData, StorageOperationStatus> removeArtifactOnGraph(String id, String artifactId, NodeTypeEnum type, boolean deleteMandatoryArtifact) {
        Either<JanusGraph, StorageOperationStatus> graph = janusGraphGenericDao.getGraph()
                .right()
                .map(DaoStatusConverter::convertJanusGraphStatusToStorageStatus);
        if (graph.isRight()) {
            return Either.right(graph.right().value());
        }

        JanusGraph tGraph = graph.left().value();
        Either<ArtifactData, StorageOperationStatus> artifactData = janusGraphGenericDao
            .getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ArtifactRef), artifactId, ArtifactData.class)
                .right()
                .map(DaoStatusConverter::convertJanusGraphStatusToStorageStatus);
        if (artifactData.isRight()) {
            log.debug("Failed to retrieve  artifact for id = {}", artifactId);
            return Either.right(artifactData.right().value());
        }
        ArtifactDataDefinition artifactDefinition = artifactData.left().value().getArtifactDataDefinition();
        boolean isMandatory = false;
        if ((artifactDefinition.getMandatory() || artifactDefinition.getServiceApi()) && !deleteMandatoryArtifact) {
            isMandatory = true;
        }

        @SuppressWarnings("unchecked")
        Iterable<JanusGraphVertex> verticesArtifact = tGraph.query().has(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ArtifactRef), artifactId).vertices();
        Iterator<JanusGraphVertex> iterator = verticesArtifact.iterator();
        if (!iterator.hasNext()) {
            log.debug("No artifact node for id = {}", artifactId);
            return Either.right(StorageOperationStatus.NOT_FOUND);
        }
        Vertex artifactV = iterator.next();
        Iterator<Edge> iterEdge = artifactV.edges(Direction.IN, GraphEdgeLabels.ARTIFACT_REF.getProperty());
        int edgeCount = 0;
        Edge edgeFromTo = null;
        while (iterEdge.hasNext()) {
            Edge edge = iterEdge.next();
            Vertex vertexFrom = edge.outVertex();
            String vertexId = vertexFrom.value(UniqueIdBuilder.getKeyByNodeType(type));
            if (id.equals(vertexId)) {
                edgeFromTo = edge;
            }
            ++edgeCount;
        }
        if (edgeFromTo == null) {
            log.debug("No relation between artifact  = {} and node with id = {}", artifactId, id);
            return Either.right(StorageOperationStatus.GENERAL_ERROR);
        }

        // need to remove relation from resource/interface

        log.debug("remove edge {}", edgeFromTo);
        if (!isMandatory || (isMandatory && edgeCount > 1)) {
            edgeFromTo.remove();
        }

        // delete edges from all groups under the component id which related to
        // this artifact.
        // Also in case it is a mandatory artifact.
        Either<List<GraphRelation>, StorageOperationStatus> dissociateAllGroups = groupOperation.dissociateAllGroupsFromArtifactOnGraph(id, type, artifactId);
        if (dissociateAllGroups.isRight()) {
            StorageOperationStatus status = dissociateAllGroups.right().value();
            if (status != StorageOperationStatus.NOT_FOUND && status != StorageOperationStatus.OK) {
                return Either.right(status);
            }
        }

        if (edgeCount == 1) {
            // remove artifactRef node
            log.debug("Remove artifactRef node from graph");
            Either<List<HeatParameterDefinition>, StorageOperationStatus> deleteStatus = heatParametersOperation.deleteAllHeatParametersAssociatedToNode(NodeTypeEnum.ArtifactRef, artifactId);
            if (deleteStatus.isRight()) {
                log.error("failed to delete heat parameters of artifact {}", artifactId);
                return Either.right(StorageOperationStatus.GENERAL_ERROR);
            }

            StorageOperationStatus deleteValuesStatus = heatParametersOperation.deleteAllHeatValuesAssociatedToNode(NodeTypeEnum.ArtifactRef, artifactId);
            if (!deleteValuesStatus.equals(StorageOperationStatus.OK)) {
                log.error("failed to delete heat values of artifact {}", artifactId);
                return Either.right(StorageOperationStatus.GENERAL_ERROR);
            }
            if (!isMandatory) {
                artifactV.remove();
            }
        } else {
            log.debug("artifactRef have more connection. ArtifactRef node will not be removed ");
        }

        return Either.left(artifactData.left().value());

    }

    /**
     *
     * @param parentId
     * @param parentType
     * @param inTransaction
     * @return
     */
    public Either<Map<String, ArtifactDefinition>, StorageOperationStatus> getArtifacts(String parentId, NodeTypeEnum parentType, boolean inTransaction) {
        Either<Map<String, ArtifactDefinition>, StorageOperationStatus> result = null;
        try {
            Either<JanusGraph, JanusGraphOperationStatus> graph = janusGraphGenericDao.getGraph();
            if (graph.isRight()) {
                log.debug("Failed to work with graph {}", graph.right().value());
                return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(graph.right().value()));
            }
            JanusGraph tGraph = graph.left().value();
            @SuppressWarnings("unchecked")
            Iterable<JanusGraphVertex> vertices = tGraph.query().has(UniqueIdBuilder.getKeyByNodeType(parentType), parentId).vertices();
            if (vertices == null) {
                log.debug("No nodes for type {}  for id = {}", parentType, parentId);
                result = Either.right(StorageOperationStatus.NOT_FOUND);
                return result;
            }
            Iterator<JanusGraphVertex> iterator = vertices.iterator();

            Map<String, ArtifactDefinition> artifactMap = new HashMap<>();
            while (iterator.hasNext()) {
                Vertex vertex = iterator.next();
                Iterator<Edge> iteratorEdge = vertex.edges(Direction.OUT, GraphEdgeLabels.ARTIFACT_REF.getProperty());

                if (iteratorEdge != null) {

                    while (iteratorEdge.hasNext()) {
                        Edge edge = iteratorEdge.next();

                        Vertex artifactV = edge.inVertex();

                        Map<String, Object> properties = this.janusGraphGenericDao.getProperties(artifactV);
                        ArtifactData artifact = GraphElementFactory.createElement(NodeTypeEnum.ArtifactRef.getName(), GraphElementTypeEnum.Node, properties, ArtifactData.class);
                        if (artifact != null) {

                            ArtifactDefinition artifactDefinition = new ArtifactDefinition(artifact.getArtifactDataDefinition());
                            Iterator<Edge> edgesGeneratedFrom = artifactV.edges(Direction.OUT, GraphEdgeLabels.GENERATED_FROM.getProperty());
                            if (edgesGeneratedFrom != null && edgesGeneratedFrom.hasNext()) {
                                JanusGraphVertex inVertex = (JanusGraphVertex) edgesGeneratedFrom.next().inVertex();
                                String artifactIdGeneratedFrom = (String) janusGraphGenericDao
                                    .getProperty(inVertex, GraphPropertiesDictionary.UNIQUE_ID.getProperty());
                                artifactDefinition.setGeneratedFromId(artifactIdGeneratedFrom);
                            }
                            List<HeatParameterDefinition> heatParams = new ArrayList<>();
                            StorageOperationStatus heatParametersStatus = heatParametersOperation.getHeatParametersOfNode(NodeTypeEnum.ArtifactRef, artifactDefinition.getUniqueId(), heatParams);
                            if (!heatParametersStatus.equals(StorageOperationStatus.OK)) {
                                log.debug("failed to get heat parameters for node {}  {}", parentType.getName(), parentId);
                                return Either.right(heatParametersStatus);
                            }
                            if (!heatParams.isEmpty()) {
                                artifactDefinition.setListHeatParameters(heatParams);
                            }
                            artifactMap.put(artifactDefinition.getArtifactLabel(), artifactDefinition);
                            log.debug("Artifact was added to list {}", artifact.getUniqueId());
                        }
                    }
                }
            }
            result = Either.left(artifactMap);
            return result;
        } finally {
            if (!inTransaction) {
                if (result == null || result.isRight()) {
                    this.janusGraphGenericDao.rollback();
                } else {
                    this.janusGraphGenericDao.commit();
                }

            }
        }

    }

    private void updateUUID(ArtifactDataDefinition artifactData, String oldChecksum, String oldVesrion) {
        if (oldVesrion == null || oldVesrion.isEmpty())
            oldVesrion = "0";

        String currentChecksum = artifactData.getArtifactChecksum();
        if (oldChecksum == null || oldChecksum.isEmpty()) {
            if (currentChecksum != null) {
                generateUUID(artifactData, oldVesrion);
            }
        } else if ((currentChecksum != null && !currentChecksum.isEmpty()) && !oldChecksum.equals(currentChecksum)) {
            generateUUID(artifactData, oldVesrion);
        }

    }

    private void generateUUID(ArtifactDataDefinition artifactData, String oldVesrion) {

        UUID uuid = UUID.randomUUID();
        artifactData.setArtifactUUID(uuid.toString());
        MDC.put(ILogConfiguration.MDC_SERVICE_INSTANCE_ID, uuid.toString());
        updateVersionAndDate(artifactData, oldVesrion);
    }

    private void updateVersionAndDate(ArtifactDataDefinition artifactData, String oldVesrion) {
        long time = System.currentTimeMillis();
        artifactData.setPayloadUpdateDate(time);
        int newVersion = new Integer(oldVesrion).intValue();
        newVersion++;
        artifactData.setArtifactVersion(String.valueOf(newVersion));
    }

}