|
| 1 | +/* |
| 2 | + * Copyright OpenSearch Contributors |
| 3 | + * SPDX-License-Identifier: Apache-2.0 |
| 4 | + */ |
| 5 | + |
| 6 | +package org.opensearch.indexmanagement.indexstatemanagement.step.restore |
| 7 | + |
| 8 | +import org.apache.logging.log4j.LogManager |
| 9 | +import org.opensearch.ExceptionsHelper |
| 10 | +import org.opensearch.action.admin.cluster.snapshots.get.GetSnapshotsRequest |
| 11 | +import org.opensearch.action.admin.cluster.snapshots.get.GetSnapshotsResponse |
| 12 | +import org.opensearch.action.admin.cluster.snapshots.restore.RestoreSnapshotRequest |
| 13 | +import org.opensearch.action.admin.cluster.snapshots.restore.RestoreSnapshotResponse |
| 14 | +import org.opensearch.core.rest.RestStatus |
| 15 | +import org.opensearch.indexmanagement.indexstatemanagement.action.ConvertIndexToRemoteAction |
| 16 | +import org.opensearch.indexmanagement.opensearchapi.convertToMap |
| 17 | +import org.opensearch.indexmanagement.opensearchapi.suspendUntil |
| 18 | +import org.opensearch.indexmanagement.spi.indexstatemanagement.Step |
| 19 | +import org.opensearch.indexmanagement.spi.indexstatemanagement.model.ActionProperties |
| 20 | +import org.opensearch.indexmanagement.spi.indexstatemanagement.model.ManagedIndexMetaData |
| 21 | +import org.opensearch.indexmanagement.spi.indexstatemanagement.model.StepMetaData |
| 22 | +import org.opensearch.script.Script |
| 23 | +import org.opensearch.script.ScriptService |
| 24 | +import org.opensearch.script.ScriptType |
| 25 | +import org.opensearch.script.TemplateScript |
| 26 | +import org.opensearch.snapshots.SnapshotException |
| 27 | +import org.opensearch.snapshots.SnapshotState |
| 28 | +import org.opensearch.transport.RemoteTransportException |
| 29 | + |
| 30 | +class AttemptRestoreStep(private val action: ConvertIndexToRemoteAction) : Step(name) { |
| 31 | + |
| 32 | + private val logger = LogManager.getLogger(javaClass) |
| 33 | + private var stepStatus = StepStatus.STARTING |
| 34 | + private var info: Map<String, Any>? = null |
| 35 | + private var snapshotName: String? = null |
| 36 | + |
| 37 | + @Suppress("TooGenericExceptionCaught", "ComplexMethod", "ReturnCount", "LongMethod") |
| 38 | + override suspend fun execute(): Step { |
| 39 | + val context = this.context ?: return this |
| 40 | + val managedIndexMetadata = context.metadata |
| 41 | + val indexName = context.metadata.index |
| 42 | + val scriptService = context.scriptService |
| 43 | + val repository = action.repository |
| 44 | + val snapshot = action.snapshot |
| 45 | + |
| 46 | + try { |
| 47 | + val mutableInfo = mutableMapOf<String, String>() |
| 48 | + val snapshotScript = Script(ScriptType.INLINE, Script.DEFAULT_TEMPLATE_LANG, snapshot, mapOf()) |
| 49 | + val defaultSnapshotPattern = snapshot.ifBlank { indexName } |
| 50 | + val snapshotPattern = compileTemplate(snapshotScript, managedIndexMetadata, defaultSnapshotPattern, scriptService) |
| 51 | + |
| 52 | + // List snapshots matching the pattern |
| 53 | + val getSnapshotsRequest = GetSnapshotsRequest() |
| 54 | + .repository(repository) |
| 55 | + .snapshots(arrayOf("$snapshotPattern*")) |
| 56 | + .ignoreUnavailable(true) |
| 57 | + .verbose(true) |
| 58 | + |
| 59 | + val getSnapshotsResponse: GetSnapshotsResponse = context.client.admin().cluster().suspendUntil { |
| 60 | + getSnapshots(getSnapshotsRequest, it) |
| 61 | + } |
| 62 | + val snapshots = getSnapshotsResponse.snapshots |
| 63 | + if (snapshots.isNullOrEmpty()) { |
| 64 | + val message = getFailedMessage(indexName, "No snapshots found matching pattern [$snapshotPattern*]") |
| 65 | + stepStatus = StepStatus.FAILED |
| 66 | + info = mapOf("message" to message) |
| 67 | + return this |
| 68 | + } |
| 69 | + |
| 70 | + val successfulSnapshots = snapshots.filter { it.state() == SnapshotState.SUCCESS } |
| 71 | + |
| 72 | + if (successfulSnapshots.isEmpty()) { |
| 73 | + val message = getFailedMessage( |
| 74 | + indexName, |
| 75 | + "No successful snapshots found matching pattern [$snapshotPattern*]", |
| 76 | + ) |
| 77 | + stepStatus = StepStatus.FAILED |
| 78 | + info = mapOf("message" to message) |
| 79 | + return this |
| 80 | + } |
| 81 | + |
| 82 | + // Select the latest snapshot |
| 83 | + val latestSnapshotInfo = successfulSnapshots.maxByOrNull { it.endTime() }!! |
| 84 | + logger.info("Restoring snapshot info: $latestSnapshotInfo") |
| 85 | + |
| 86 | + // Use the snapshot name from the selected SnapshotInfo |
| 87 | + snapshotName = latestSnapshotInfo.snapshotId().name |
| 88 | + |
| 89 | + // Proceed with the restore operation |
| 90 | + val restoreSnapshotRequest = RestoreSnapshotRequest(repository, snapshotName) |
| 91 | + .indices(indexName) |
| 92 | + .storageType(RestoreSnapshotRequest.StorageType.REMOTE_SNAPSHOT) |
| 93 | + .renamePattern("^(.*)\$") |
| 94 | + .renameReplacement("$1_remote") |
| 95 | + .waitForCompletion(false) |
| 96 | + val response: RestoreSnapshotResponse = context.client.admin().cluster().suspendUntil { |
| 97 | + restoreSnapshot(restoreSnapshotRequest, it) |
| 98 | + } |
| 99 | + |
| 100 | + when (response.status()) { |
| 101 | + RestStatus.ACCEPTED, RestStatus.OK -> { |
| 102 | + stepStatus = StepStatus.COMPLETED |
| 103 | + mutableInfo["message"] = getSuccessMessage(indexName) |
| 104 | + } |
| 105 | + else -> { |
| 106 | + val message = getFailedMessage(indexName, "Unexpected response status: ${response.status()}") |
| 107 | + logger.warn("$message - $response") |
| 108 | + stepStatus = StepStatus.FAILED |
| 109 | + mutableInfo["message"] = message |
| 110 | + mutableInfo["cause"] = response.toString() |
| 111 | + } |
| 112 | + } |
| 113 | + info = mutableInfo.toMap() |
| 114 | + } catch (e: RemoteTransportException) { |
| 115 | + val cause = ExceptionsHelper.unwrapCause(e) |
| 116 | + if (cause is SnapshotException) { |
| 117 | + handleRestoreException(indexName, cause) |
| 118 | + } else { |
| 119 | + handleException(indexName, cause as Exception) |
| 120 | + } |
| 121 | + } catch (e: SnapshotException) { |
| 122 | + handleRestoreException(indexName, e) |
| 123 | + } catch (e: Exception) { |
| 124 | + handleException(indexName, e) |
| 125 | + } |
| 126 | + |
| 127 | + return this |
| 128 | + } |
| 129 | + |
| 130 | + private fun compileTemplate( |
| 131 | + template: Script, |
| 132 | + managedIndexMetaData: ManagedIndexMetaData, |
| 133 | + defaultValue: String, |
| 134 | + scriptService: ScriptService, |
| 135 | + ): String { |
| 136 | + val contextMap = |
| 137 | + managedIndexMetaData.convertToMap().filterKeys { key -> |
| 138 | + key in validTopContextFields |
| 139 | + } |
| 140 | + val compiledValue = |
| 141 | + scriptService.compile(template, TemplateScript.CONTEXT) |
| 142 | + .newInstance(template.params + mapOf("ctx" to contextMap)) |
| 143 | + .execute() |
| 144 | + return compiledValue.ifBlank { defaultValue } |
| 145 | + } |
| 146 | + |
| 147 | + private fun handleRestoreException(indexName: String, e: SnapshotException) { |
| 148 | + val message = getFailedRestoreMessage(indexName) |
| 149 | + logger.debug(message, e) |
| 150 | + stepStatus = StepStatus.FAILED |
| 151 | + val mutableInfo = mutableMapOf<String, Any>("message" to message) |
| 152 | + val errorMessage = e.message |
| 153 | + if (errorMessage != null) mutableInfo["cause"] = errorMessage |
| 154 | + info = mutableInfo.toMap() |
| 155 | + } |
| 156 | + |
| 157 | + private fun handleException(indexName: String, e: Exception) { |
| 158 | + val message = getFailedMessage(indexName, e.message ?: "Unknown error") |
| 159 | + logger.error(message, e) |
| 160 | + stepStatus = StepStatus.FAILED |
| 161 | + val mutableInfo = mutableMapOf<String, Any>("message" to message) |
| 162 | + val errorMessage = e.message |
| 163 | + if (errorMessage != null) mutableInfo["cause"] = errorMessage |
| 164 | + info = mutableInfo.toMap() |
| 165 | + } |
| 166 | + |
| 167 | + override fun getUpdatedManagedIndexMetadata(currentMetadata: ManagedIndexMetaData): ManagedIndexMetaData { |
| 168 | + val currentActionMetaData = currentMetadata.actionMetaData |
| 169 | + return currentMetadata.copy( |
| 170 | + actionMetaData = currentActionMetaData?.copy(actionProperties = ActionProperties(snapshotName = snapshotName)), |
| 171 | + stepMetaData = StepMetaData(name, getStepStartTime(currentMetadata).toEpochMilli(), stepStatus), |
| 172 | + transitionTo = null, |
| 173 | + info = info, |
| 174 | + ) |
| 175 | + } |
| 176 | + |
| 177 | + override fun isIdempotent(): Boolean = false |
| 178 | + |
| 179 | + companion object { |
| 180 | + val validTopContextFields = setOf("index", "indexUuid") |
| 181 | + const val name = "attempt_restore" |
| 182 | + fun getFailedMessage(index: String, cause: String) = "Failed to start restore for [index=$index], cause: $cause" |
| 183 | + fun getFailedRestoreMessage(index: String) = "Failed to start restore due to concurrent restore or snapshot in progress [index=$index]" |
| 184 | + fun getSuccessMessage(index: String) = "Successfully started restore for [index=$index]" |
| 185 | + } |
| 186 | +} |
0 commit comments