summaryrefslogtreecommitdiffstats
path: root/dcaedt_be/src/main/java/org/onap/sdc/dcae/composition/impl/BaseBusinessLogic.java
blob: 6b0ec93cbe5b8ff752bdde56c980d89c762c78d7 (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
package org.onap.sdc.dcae.composition.impl;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang.StringUtils;
import org.onap.sdc.common.onaplog.Enums.LogLevel;
import org.onap.sdc.common.onaplog.OnapLoggerDebug;
import org.onap.sdc.common.onaplog.OnapLoggerError;
import org.onap.sdc.dcae.client.ISdcClient;
import org.onap.sdc.dcae.composition.restmodels.CreateMcResponse;
import org.onap.sdc.dcae.composition.restmodels.VfcmtData;
import org.onap.sdc.dcae.composition.restmodels.sdc.*;
import org.onap.sdc.dcae.composition.util.DcaeBeConstants;
import org.onap.sdc.dcae.composition.util.SystemProperties;
import org.onap.sdc.dcae.enums.AssetType;
import org.onap.sdc.dcae.enums.LifecycleOperationType;
import org.onap.sdc.dcae.errormng.ActionStatus;
import org.onap.sdc.dcae.errormng.DcaeException;
import org.onap.sdc.dcae.errormng.ErrConfMgr;
import org.onap.sdc.dcae.errormng.ResponseFormat;
import org.onap.sdc.dcae.utils.Normalizers;
import org.onap.sdc.dcae.utils.SdcRestClientUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.util.Base64Utils;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

@Component
public class BaseBusinessLogic {

	@Autowired
	protected SystemProperties systemProperties;

    @Autowired
    protected ISdcClient sdcRestClient;

    protected static OnapLoggerError errLogger = OnapLoggerError.getInstance();
    protected static OnapLoggerDebug debugLogger = OnapLoggerDebug.getInstance();

    public ISdcClient getSdcRestClient() {
        return sdcRestClient;
    }

    public SystemProperties getSystemProperties() {
    	return systemProperties;
	}

    void setSdcRestClient(ISdcClient sdcRestClient) {
        this.sdcRestClient = sdcRestClient;
    }

    Artifact cloneArtifactToTarget(String userId, String targetId, String payload, Artifact artifactToClone, String requestId) throws JsonProcessingException {
        Artifact cloned = SdcRestClientUtils.generateDeploymentArtifact(artifactToClone.getArtifactDescription(), artifactToClone.getArtifactName(), artifactToClone.getArtifactType(), artifactToClone.getArtifactLabel(), payload.getBytes());
        return sdcRestClient.createResourceArtifact(userId, targetId, cloned, requestId);
    }

    public void cloneArtifactToTarget(String userId, String targetId, String payload, Artifact artifactToClone, Artifact artifactToOverride, String requestId) throws JsonProcessingException {
        if (null != artifactToOverride) {
            artifactToOverride.setDescription(artifactToOverride.getArtifactDescription());
            artifactToOverride.setPayloadData(Base64Utils.encodeToString(payload.getBytes()));
            sdcRestClient.updateResourceArtifact(userId, targetId, artifactToOverride, requestId);
        } else {
            cloneArtifactToTarget(userId, targetId, payload, artifactToClone, requestId);
        }
    }

    Artifact findArtifactDataByArtifactName(ResourceDetailed vfcmt, String artifactName) {
        if (null == vfcmt || null == vfcmt.getArtifacts()) {
            return null;
        }
        return vfcmt.getArtifacts().stream()
                .filter(p -> artifactName.equals(p.getArtifactName())).findAny().orElse(null);
    }

    Artifact findCdumpArtifactData(ResourceDetailed vfcmt) {
        return findArtifactDataByArtifactName(vfcmt, DcaeBeConstants.Composition.fileNames.COMPOSITION_YML);
    }

    void rollBack(String userId, ResourceDetailed newVfcmt, String requestId) {
        if (null != newVfcmt) {
            try {
                sdcRestClient.changeResourceLifecycleState(userId, newVfcmt.getUuid(), LifecycleOperationType.UNDO_CHECKOUT.getValue(), "DCAE rollback", requestId);
            } catch (Exception e) {
                errLogger.log(LogLevel.ERROR, this.getClass().getName(),"Failed rolling back Monitoring Component. ID:{}", newVfcmt.getUuid());
                debugLogger.log(LogLevel.ERROR, this.getClass().getName(),"Failed rolling back Monitoring Component:{}", e);
            }
        }
    }

    CreateMcResponse buildVfcmtAndCdumpResponse(VfcmtData vfcmt, String cdumpPayload) throws IOException {
        return new CreateMcResponse(vfcmt, new ObjectMapper().readValue(cdumpPayload, Object.class));
    }

    Artifact fetchCdump(ResourceDetailed vfcmt, String requestId) {
        Artifact cdumpArtifactData = findCdumpArtifactData(vfcmt);
        if (null != cdumpArtifactData) {
            String cdumpPayload = sdcRestClient.getResourceArtifact(vfcmt.getUuid(), cdumpArtifactData.getArtifactUUID(), requestId);
            cdumpArtifactData.setPayloadData(cdumpPayload);
        }
        return cdumpArtifactData;
    }

    String generateBlueprintFileName(String monitoringFlowType, String vfcmtName) {
        return monitoringFlowType
                .concat(".")
                .concat(Normalizers.normalizeComponentName(vfcmtName))
                .concat(".")
                .concat(DcaeBeConstants.Composition.fileNames.EVENT_PROC_BP_YAML);
    }

    ResourceInstance findVfiOnService(ServiceDetailed service, String vfiName) {
        if (null == service || null == service.getResources()) {
            return null;
        }
        return service.getResources().stream()
                .filter(p -> Normalizers.normalizeComponentInstanceName(vfiName).equals(Normalizers.normalizeComponentInstanceName(p.getResourceInstanceName()))).findAny().orElse(null);
    }

    String extractFlowTypeFromCdump(String cdump) {
        return StringUtils.substringBetween(cdump,"\"flowType\":\"","\"");
    }

    public ResourceDetailed checkinVfcmt(String userId, String uuid, String requestId) {
        return getSdcRestClient().changeResourceLifecycleState(userId, uuid, LifecycleOperationType.CHECKIN.name(), "checking in vfcmt"  + uuid, requestId);
    }
    public ResourceDetailed checkoutVfcmt(String userId, String uuid, String requestId) {
        return getSdcRestClient().changeResourceLifecycleState(userId, uuid, LifecycleOperationType.CHECKOUT.name(), null, requestId);
    }


    void checkUserIfResourceCheckedOut(String userId, Asset asset) {
        if (DcaeBeConstants.LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT == DcaeBeConstants.LifecycleStateEnum.findState(asset.getLifecycleState())) {
            String lastUpdaterUserId = asset.getLastUpdaterUserId();
            if (lastUpdaterUserId != null && !lastUpdaterUserId.equals(userId)) {
                errLogger.log(LogLevel.ERROR, this.getClass().getName(), "User conflicts. Operation not allowed for user {} on resource checked out by {}", userId, lastUpdaterUserId);
                ResponseFormat responseFormat = ErrConfMgr.INSTANCE.getResponseFormat(ActionStatus.USER_CONFLICT, null, userId, asset.getName(), lastUpdaterUserId);
                throw new DcaeException(HttpStatus.FORBIDDEN, responseFormat.getRequestError());
            }
        }
    }

    boolean isNeedToCheckOut(String lifecycleState) {
        return DcaeBeConstants.LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT != DcaeBeConstants.LifecycleStateEnum.findState(lifecycleState);
    }

    void checkVfcmtType(ResourceDetailed vfcmt) {
        if (AssetType.VFCMT != getValidAssetTypeOrNull(vfcmt.getResourceType()) || !"Template".equals(vfcmt.getCategory())) {
            ResponseFormat responseFormat = ErrConfMgr.INSTANCE.getResponseFormat(ActionStatus.RESOURCE_NOT_VFCMT_ERROR, null, vfcmt.getUuid());
            throw new DcaeException(HttpStatus.BAD_REQUEST, responseFormat.getRequestError());
        }
    }

    public AssetType getValidAssetTypeOrNull(String type) {
        try {
            return AssetType.getAssetTypeByName(type);
        } catch (IllegalArgumentException e) {
            debugLogger.log(LogLevel.ERROR, this.getClass().getName(), "invalid asset type: {}. Error: {}", type, e);
            return null;
        }
    }


	byte[] extractFile(ZipInputStream zis) throws IOException {
		byte[] buffer = new byte[1024];
		try (ByteArrayOutputStream os = new ByteArrayOutputStream()){
			int len;
			while ((len = zis.read(buffer)) > 0) {
				os.write(buffer, 0, len);
			}
			return os.toByteArray();
		}
	}
}