fun readInstanceMetadata()

in plugin-azure-common/src/main/kotlin/jetbrains/buildServer/clouds/azure/AzureMetadata.kt [21:52]


    fun readInstanceMetadata(): Metadata {
        val requestConfig = RequestConfig.custom()
                .setConnectTimeout(PING_CONNECTION_TIMEOUT_MS)
                .build()

        HttpClients.custom()
                .useSystemProperties()
                .setDefaultRequestConfig(requestConfig)
                .build().use {
                    for (i in 1..PING_MAX_TRIES) {
                        val response = try {
                            it.execute(HttpGet(INSTANCE_METADATA_URL).apply {
                                addHeader("Metadata", "true")
                            })
                        } catch (ignored: SocketTimeoutException) {
                            // Ignore logging timeouts which is the expected failure mode in non Azure environments.
                            continue
                        } catch (e: Exception) {
                            throw IOException("Failed to connect to $INSTANCE_METADATA_URL: ${e.message}")
                        }

                        val statusCode = response.statusLine.statusCode
                        if (statusCode == 200) {
                            return deserializeInstanceMetadata(EntityUtils.toString(response.entity))
                        } else {
                            throw IOException("Failed to connect to $INSTANCE_METADATA_URL: HTTP $statusCode")
                        }
                    }
                }

        throw IOException("Unable to connect to $INSTANCE_METADATA_URL in $PING_MAX_TRIES attempts")
    }