|
| 1 | +// Copyright 2020 New Relic, Inc. All rights reserved. |
| 2 | +// SPDX-License-Identifier: Apache-2.0 |
| 3 | + |
| 4 | +using System; |
| 5 | +using System.Collections.Concurrent; |
| 6 | +using System.Collections.Generic; |
| 7 | +using System.Collections.ObjectModel; |
| 8 | +using System.Threading.Tasks; |
| 9 | +using NewRelic.Agent.Api; |
| 10 | +using NewRelic.Agent.Api.Experimental; |
| 11 | +using NewRelic.Agent.Extensions.Parsing; |
| 12 | +using NewRelic.Agent.Extensions.Providers.Wrapper; |
| 13 | +using NewRelic.Agent.Extensions.SystemExtensions; |
| 14 | +using NewRelic.Reflection; |
| 15 | + |
| 16 | +namespace NewRelic.Agent.Extensions.Helpers |
| 17 | +{ |
| 18 | + public abstract class SearchRequestWrapperBase |
| 19 | + { |
| 20 | + private Func<object, bool> _successGetter; |
| 21 | + private Func<object, object> _exceptionGetter; |
| 22 | + private Func<object, Uri> _uriGetter; |
| 23 | + |
| 24 | + protected ConcurrentDictionary<Type, Func<object, object>> GetRequestResponseFromGeneric = new ConcurrentDictionary<Type, Func<object, object>>(); |
| 25 | + |
| 26 | + public abstract DatastoreVendor Vendor { get; } |
| 27 | + |
| 28 | + protected ISegment BuildSegment(int requestParamsIndex, InstrumentedMethodCall instrumentedMethodCall, ITransaction transaction) |
| 29 | + { |
| 30 | + var path = (string)instrumentedMethodCall.MethodCall.MethodArguments[1]; |
| 31 | + var request = instrumentedMethodCall.MethodCall.MethodArguments[0].ToString(); |
| 32 | + var requestParams = instrumentedMethodCall.MethodCall.MethodArguments[requestParamsIndex]; |
| 33 | + var splitPath = path.Trim('/').Split('/'); |
| 34 | + |
| 35 | + var operation = (requestParams == null) ? GetOperationFromPath(request, splitPath) : GetOperationFromRequestParams(requestParams); |
| 36 | + |
| 37 | + var model = splitPath[0]; // For Elastic/OpenSearch model is the index name. This is often the first component of the request path, but not always. |
| 38 | + if ((model.Length == 0) || (model[0] == '_')) // Per Elastic/OpenSearch docs, index names aren't allowed to start with an underscore, and the first component of the path can be an operation name in some cases, e.g. "_bulk" or "_msearch" |
| 39 | + { |
| 40 | + model = "Unknown"; |
| 41 | + } |
| 42 | + |
| 43 | + var transactionExperimental = transaction.GetExperimentalApi(); |
| 44 | + var datastoreSegmentData = transactionExperimental.CreateDatastoreSegmentData(new ParsedSqlStatement(Vendor, model, operation), new ConnectionInfo(string.Empty, string.Empty, string.Empty), string.Empty, null); |
| 45 | + var segment = transactionExperimental.StartSegment(instrumentedMethodCall.MethodCall); |
| 46 | + segment.GetExperimentalApi().SetSegmentData(datastoreSegmentData).MakeLeaf(); |
| 47 | + |
| 48 | + return segment; |
| 49 | + } |
| 50 | + |
| 51 | + protected void TryProcessResponse(IAgent agent, ITransaction transaction, object response, ISegment segment, Func<object, object> apiCallDetailsGetter) |
| 52 | + { |
| 53 | + try |
| 54 | + { |
| 55 | + if (response == null || segment == null) |
| 56 | + { |
| 57 | + return; |
| 58 | + } |
| 59 | + var apiCallDetails = apiCallDetailsGetter.Invoke(response); |
| 60 | + var uri = GetUriFromApiCallDetails(apiCallDetails); |
| 61 | + SetUriOnDatastoreSegment(segment, uri); |
| 62 | + ReportError(transaction, apiCallDetails); |
| 63 | + |
| 64 | + segment.End(); |
| 65 | + } |
| 66 | + catch (Exception ex) |
| 67 | + { |
| 68 | + agent.HandleWrapperException(ex); |
| 69 | + } |
| 70 | + } |
| 71 | + |
| 72 | + private void ReportError(ITransaction transaction, object apiCallDetails) |
| 73 | + { |
| 74 | + var exceptionGetter = _exceptionGetter ??= GetExceptionGetterFromApiCallDetails(apiCallDetails); |
| 75 | + var ex = exceptionGetter(apiCallDetails); |
| 76 | + |
| 77 | + if ((ex != null) && (ex is Exception exception)) |
| 78 | + { |
| 79 | + transaction.NoticeError(exception); |
| 80 | + return; |
| 81 | + } |
| 82 | + |
| 83 | + // If an error can be caught by the library before the request is made, it doesn't throw an exception, or |
| 84 | + // set any kind of error object. The best we can do is check if it was successful, and use the ToString() |
| 85 | + // override to get a summary of what happened |
| 86 | + var successGetter = _successGetter ??= GetSuccessGetterFromApiCallDetails(apiCallDetails); |
| 87 | + var success = successGetter(apiCallDetails); |
| 88 | + |
| 89 | + if (!success) |
| 90 | + { |
| 91 | + transaction.NoticeError(new Exception(apiCallDetails.ToString())); |
| 92 | + } |
| 93 | + } |
| 94 | + |
| 95 | + private Uri GetUriFromApiCallDetails(object apiCallDetails) |
| 96 | + { |
| 97 | + var UriGetter = _uriGetter ??= GetUriGetterFromApiCallDetails(apiCallDetails); |
| 98 | + var uri = UriGetter.Invoke(apiCallDetails); |
| 99 | + |
| 100 | + return uri; |
| 101 | + } |
| 102 | + |
| 103 | + private static Func<object, Uri> GetUriGetterFromApiCallDetails(object apiCallDetails) |
| 104 | + { |
| 105 | + var typeOfApiCall = apiCallDetails.GetType(); |
| 106 | + var responseAssemblyName = apiCallDetails.GetType().Assembly.FullName; |
| 107 | + |
| 108 | + return VisibilityBypasser.Instance.GeneratePropertyAccessor<Uri>(responseAssemblyName, typeOfApiCall.FullName, "Uri"); |
| 109 | + } |
| 110 | + |
| 111 | + private static Func<object, Exception> GetExceptionGetterFromApiCallDetails(object apiCallDetails) |
| 112 | + { |
| 113 | + var typeOfApiCall = apiCallDetails.GetType(); |
| 114 | + var responseAssemblyName = apiCallDetails.GetType().Assembly.FullName; |
| 115 | + |
| 116 | + return VisibilityBypasser.Instance.GeneratePropertyAccessor<Exception>(responseAssemblyName, typeOfApiCall.FullName, "OriginalException"); |
| 117 | + } |
| 118 | + |
| 119 | + private static Func<object, bool> GetSuccessGetterFromApiCallDetails(object apiCallDetails) |
| 120 | + { |
| 121 | + var typeOfApiCall = apiCallDetails.GetType(); |
| 122 | + var responseAssemblyName = apiCallDetails.GetType().Assembly.FullName; |
| 123 | + |
| 124 | + // "Success" might be better, but it isn't available on all libraries |
| 125 | + return VisibilityBypasser.Instance.GeneratePropertyAccessor<bool>(responseAssemblyName, typeOfApiCall.FullName, "SuccessOrKnownError"); |
| 126 | + } |
| 127 | + |
| 128 | + // Some request types are defined by the HTTP request |
| 129 | + private static ReadOnlyDictionary<string, string> RequestMap = new ReadOnlyDictionary<string, string>(new Dictionary<string, string> |
| 130 | + { |
| 131 | + { "PUT|_doc", "Index" }, |
| 132 | + { "POST|_doc", "Index" }, |
| 133 | + { "GET|_doc", "Get" }, |
| 134 | + { "HEAD|_doc", "Get" }, |
| 135 | + { "DELETE|_doc", "Delete" }, |
| 136 | + }); |
| 137 | + |
| 138 | + // Some request types use abbreviations |
| 139 | + private static ReadOnlyDictionary<string, string> RenameMap = new ReadOnlyDictionary<string, string>(new Dictionary<string, string> |
| 140 | + { |
| 141 | + { "_mget", "MultiGet" }, |
| 142 | + { "_termvectors", "TermVectors" }, |
| 143 | + { "_msearch", "MultiSearch" }, |
| 144 | + { "_mtermvectors", "MultiTermVectors" }, |
| 145 | + { "_field_caps", "FieldCapabilities" }, |
| 146 | + }); |
| 147 | + |
| 148 | + // Some request types have a subtype |
| 149 | + private static ReadOnlyDictionary<string, string> SubTypeMap = new ReadOnlyDictionary<string, string>(new Dictionary<string, string> |
| 150 | + { |
| 151 | + { "_search|template", "SearchTemplate" }, |
| 152 | + { "_msearch|template", "MultiSearchTemplate" }, |
| 153 | + { "_render|template", "RenderSearchTemplate" }, |
| 154 | + { "_search|scroll", "Scroll" }, |
| 155 | + }); |
| 156 | + |
| 157 | + // Some request types depend on the type, subtype, and HTTP request |
| 158 | + private static ReadOnlyDictionary<string, string> FullRequestTypeMap = new ReadOnlyDictionary<string, string>(new Dictionary<string, string> |
| 159 | + { |
| 160 | + { "DELETE|_search|scroll", "ClearScroll" }, |
| 161 | + }); |
| 162 | + |
| 163 | + private static void ParsePath(string[] splitPath, out string api, out string subType) |
| 164 | + { |
| 165 | + // Some examples of different structures: |
| 166 | + // GET /my-index/_count?q=user:foo => API = "_count" |
| 167 | + // GET /my-index/_search => API = "_search" |
| 168 | + // PUT /my-index-000001 => API = "" |
| 169 | + // GET /_search/scroll => API = "_search", subType = "scroll" |
| 170 | + |
| 171 | + api = ""; |
| 172 | + subType = ""; |
| 173 | + bool foundApi = false; |
| 174 | + foreach (var path in splitPath) |
| 175 | + { |
| 176 | + if (string.IsNullOrEmpty(path)) |
| 177 | + { |
| 178 | + continue; |
| 179 | + } |
| 180 | + // Sub-api is directly after the API |
| 181 | + if (foundApi) |
| 182 | + { |
| 183 | + subType = path.Split('?')[0]; |
| 184 | + break; |
| 185 | + } |
| 186 | + else if (path[0] == '_') |
| 187 | + { |
| 188 | + // The API starts with an underscore and may have parameters |
| 189 | + api = path.Split('?')[0]; |
| 190 | + foundApi = true; |
| 191 | + } |
| 192 | + } |
| 193 | + } |
| 194 | + |
| 195 | + private static string GetOperationFromPath(string request, string[] splitPath) |
| 196 | + { |
| 197 | + ParsePath(splitPath, out string api, out string subType); |
| 198 | + |
| 199 | + // Since different operations are determined by different combinations of the path, combine the different |
| 200 | + // elements into a single string with a separator, so we can do a faster dictionary lookup |
| 201 | + string operation; |
| 202 | + string apiWithSub = api + "|" + subType; |
| 203 | + string apiWithRequest = request + "|" + api; |
| 204 | + string fullApi = apiWithRequest + "|" + subType; |
| 205 | + |
| 206 | + // Check from most-specific to least-specific special cases. Most will fall through to the default handler. |
| 207 | + if (FullRequestTypeMap.TryGetValue(fullApi, out operation)) |
| 208 | + { |
| 209 | + return operation; |
| 210 | + } |
| 211 | + if (SubTypeMap.TryGetValue(apiWithSub, out operation)) |
| 212 | + { |
| 213 | + return operation; |
| 214 | + } |
| 215 | + if (RequestMap.TryGetValue(apiWithRequest, out operation)) |
| 216 | + { |
| 217 | + return operation; |
| 218 | + } |
| 219 | + if (RenameMap.TryGetValue(api, out operation)) |
| 220 | + { |
| 221 | + return operation; |
| 222 | + } |
| 223 | + |
| 224 | + // Many request types are named exactly for their API call, like _search, _create, _search_shards |
| 225 | + return api.CapitalizeEachWord('_'); |
| 226 | + } |
| 227 | + |
| 228 | + protected static string GetOperationFromRequestParams(object requestParams) |
| 229 | + { |
| 230 | + if (requestParams == null) |
| 231 | + { |
| 232 | + // Params will be null when the low-level client is used, fall back to a generic operation name |
| 233 | + return "Query"; |
| 234 | + } |
| 235 | + var typeOfRequestParams = requestParams.GetType(); |
| 236 | + |
| 237 | + var requestParamsTypeName = typeOfRequestParams.Name; // IndexRequestParameters, SearchRequestParameters, etc |
| 238 | + return requestParamsTypeName.Remove(requestParamsTypeName.Length - "RequestParameters".Length); |
| 239 | + } |
| 240 | + |
| 241 | + private static void SetUriOnDatastoreSegment(ISegment segment, Uri uri) |
| 242 | + { |
| 243 | + var segmentExperimentalApi = segment.GetExperimentalApi(); |
| 244 | + var data = segmentExperimentalApi.SegmentData as IDatastoreSegmentData; |
| 245 | + data.SetConnectionInfo(new ConnectionInfo(uri.Host, uri.Port, string.Empty)); |
| 246 | + segmentExperimentalApi.SetSegmentData(data); |
| 247 | + } |
| 248 | + |
| 249 | + protected static bool ValidTaskResponse(Task response) |
| 250 | + { |
| 251 | + return response?.Status == TaskStatus.RanToCompletion; |
| 252 | + } |
| 253 | + } |
| 254 | +} |
0 commit comments