Skip to content
This repository was archived by the owner on Feb 23, 2024. It is now read-only.

Commit 1454e02

Browse files
committed
refactor extractor classes for all types except api
1 parent 898d127 commit 1454e02

File tree

9 files changed

+339
-353
lines changed

9 files changed

+339
-353
lines changed

src/APIM_ARMTemplate/apimtemplate/Commands/Extract.cs

Lines changed: 21 additions & 266 deletions
Large diffs are not rendered by default.

src/APIM_ARMTemplate/apimtemplate/Extractor/EntityExtractors/APIExtractor.cs

Lines changed: 0 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -56,24 +56,6 @@ public async Task<string> GetAPIVersionSet(string ApiManagementName, string Reso
5656

5757
return await CallApiManagement(azToken, requestUrl);
5858
}
59-
public async Task<string> GetProducts(string ApiManagementName, string ResourceGroupName)
60-
{
61-
(string azToken, string azSubId) = await auth.GetAccessToken();
62-
63-
string requestUrl = string.Format("{0}/subscriptions/{1}/resourceGroups/{2}/providers/Microsoft.ApiManagement/service/{3}/products?api-version={4}",
64-
baseUrl, azSubId, ResourceGroupName, ApiManagementName, GlobalConstants.APIVersion);
65-
66-
return await CallApiManagement(azToken, requestUrl);
67-
}
68-
public async Task<string> GetProductDetails(string ApiManagementName, string ResourceGroupName, string ProductName)
69-
{
70-
(string azToken, string azSubId) = await auth.GetAccessToken();
71-
72-
string requestUrl = string.Format("{0}/subscriptions/{1}/resourceGroups/{2}/providers/Microsoft.ApiManagement/service/{3}/products/{4}?api-version={5}",
73-
baseUrl, azSubId, ResourceGroupName, ApiManagementName, ProductName, GlobalConstants.APIVersion);
74-
75-
return await CallApiManagement(azToken, requestUrl);
76-
}
7759
public async Task<string> GetAPIs(string ApiManagementName, string ResourceGroupName)
7860
{
7961
(string azToken, string azSubId) = await auth.GetAccessToken();
Lines changed: 46 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,15 @@
1-
using System.Net.Http;
2-
using System.Net.Http.Headers;
3-
using System.Threading.Tasks;
1+
using System.Threading.Tasks;
42
using Microsoft.Azure.Management.ApiManagement.ArmTemplates.Common;
3+
using System.Collections.Generic;
4+
using Newtonsoft.Json.Linq;
5+
using Newtonsoft.Json;
6+
using System.Linq;
7+
using System;
58

69
namespace Microsoft.Azure.Management.ApiManagement.ArmTemplates.Extract
710
{
8-
public class AuthorizationServerExtractor
11+
public class AuthorizationServerExtractor: EntityExtractor
912
{
10-
static string baseUrl = "https://management.azure.com";
11-
internal Authentication auth = new Authentication();
12-
1313
public async Task<string> GetAuthorizationServers(string ApiManagementName, string ResourceGroupName)
1414
{
1515
(string azToken, string azSubId) = await auth.GetAccessToken();
@@ -30,22 +30,50 @@ public async Task<string> GetAuthorizationServer(string ApiManagementName, strin
3030
return await CallApiManagement(azToken, requestUrl);
3131
}
3232

33-
private static async Task<string> CallApiManagement(string azToken, string requestUrl)
33+
public async Task<Template> GenerateAuthorizationServersARMTemplate(string apimname, string resourceGroup, string singleApiName, List<TemplateResource> armTemplateResources)
3434
{
35-
using (HttpClient httpClient = new HttpClient())
36-
{
37-
var request = new HttpRequestMessage(HttpMethod.Get, requestUrl);
35+
Console.WriteLine("------------------------------------------");
36+
Console.WriteLine("Getting authorization servers from service");
37+
Template armTemplate = GenerateEmptyTemplateWithParameters();
38+
39+
List<TemplateResource> templateResources = new List<TemplateResource>();
3840

39-
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", azToken);
41+
// isolate api resources in the case of a single api extraction, as they may reference authorization servers
42+
var apiResources = armTemplateResources.Where(resource => resource.type == ResourceTypeConstants.API);
4043

41-
HttpResponseMessage response = await httpClient.SendAsync(request);
44+
string authorizationServers = await GetAuthorizationServers(apimname, resourceGroup);
45+
JObject oAuthorizationServers = JObject.Parse(authorizationServers);
46+
47+
foreach (var item in oAuthorizationServers["value"])
48+
{
49+
string authorizationServerName = ((JValue)item["name"]).Value.ToString();
50+
string authorizationServer = await GetAuthorizationServer(apimname, resourceGroup, authorizationServerName);
4251

43-
response.EnsureSuccessStatusCode();
44-
string responseBody = await response.Content.ReadAsStringAsync();
45-
return responseBody;
52+
AuthorizationServerTemplateResource authorizationServerTemplateResource = JsonConvert.DeserializeObject<AuthorizationServerTemplateResource>(authorizationServer);
53+
authorizationServerTemplateResource.name = $"[concat(parameters('ApimServiceName'), '/{authorizationServerName}')]";
54+
authorizationServerTemplateResource.apiVersion = "2018-06-01-preview";
55+
56+
// only extract the authorization server if this is a full extraction, or in the case of a single api, if it is referenced by one of the api's authentication settings
57+
bool isReferencedByAPI = false;
58+
foreach (APITemplateResource apiResource in apiResources)
59+
{
60+
if (apiResource.properties.authenticationSettings != null &&
61+
apiResource.properties.authenticationSettings.oAuth2 != null &&
62+
apiResource.properties.authenticationSettings.oAuth2.authorizationServerId != null &&
63+
apiResource.properties.authenticationSettings.oAuth2.authorizationServerId.Contains(authorizationServerName))
64+
{
65+
isReferencedByAPI = true;
66+
}
67+
}
68+
if (singleApiName == null || isReferencedByAPI)
69+
{
70+
Console.WriteLine("'{0}' Authorization Server found", authorizationServerName);
71+
templateResources.Add(authorizationServerTemplateResource);
72+
}
4673
}
74+
75+
armTemplate.resources = templateResources.ToArray();
76+
return armTemplate;
4777
}
4878
}
49-
50-
5179
}
Lines changed: 58 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,15 @@
1-
using System.Net.Http;
2-
using System.Net.Http.Headers;
3-
using System.Threading.Tasks;
1+
using System.Threading.Tasks;
42
using Microsoft.Azure.Management.ApiManagement.ArmTemplates.Common;
3+
using System.Collections.Generic;
4+
using Newtonsoft.Json.Linq;
5+
using System.Linq;
6+
using Newtonsoft.Json;
7+
using System;
58

69
namespace Microsoft.Azure.Management.ApiManagement.ArmTemplates.Extract
710
{
8-
public class BackendExtractor
11+
public class BackendExtractor : EntityExtractor
912
{
10-
static string baseUrl = "https://management.azure.com";
11-
internal Authentication auth = new Authentication();
12-
1313
public async Task<string> GetBackends(string ApiManagementName, string ResourceGroupName)
1414
{
1515
(string azToken, string azSubId) = await auth.GetAccessToken();
@@ -30,22 +30,63 @@ public async Task<string> GetBackend(string ApiManagementName, string ResourceGr
3030
return await CallApiManagement(azToken, requestUrl);
3131
}
3232

33-
private static async Task<string> CallApiManagement(string azToken, string requestUrl)
33+
public async Task<Template> GenerateBackendsARMTemplate(string apimname, string resourceGroup, string singleApiName, List<TemplateResource> armTemplateResources)
3434
{
35-
using (HttpClient httpClient = new HttpClient())
35+
Console.WriteLine("------------------------------------------");
36+
Console.WriteLine("Getting backends from service");
37+
Template armTemplate = GenerateEmptyTemplateWithParameters();
38+
39+
List<TemplateResource> templateResources = new List<TemplateResource>();
40+
41+
// isolate api and operation policy resources in the case of a single api extraction, as they may reference backends
42+
var policyResources = armTemplateResources.Where(resource => (resource.type == ResourceTypeConstants.APIPolicy || resource.type == ResourceTypeConstants.APIOperationPolicy));
43+
44+
string backends = await GetBackends(apimname, resourceGroup);
45+
JObject oBackends = JObject.Parse(backends);
46+
47+
foreach (var item in oBackends["value"])
3648
{
37-
var request = new HttpRequestMessage(HttpMethod.Get, requestUrl);
49+
string backendName = ((JValue)item["name"]).Value.ToString();
50+
string backend = await GetBackend(apimname, resourceGroup, backendName);
3851

39-
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", azToken);
52+
BackendTemplateResource backendTemplateResource = JsonConvert.DeserializeObject<BackendTemplateResource>(backend);
53+
backendTemplateResource.name = $"[concat(parameters('ApimServiceName'), '/{backendName}')]";
54+
backendTemplateResource.apiVersion = "2018-06-01-preview";
4055

41-
HttpResponseMessage response = await httpClient.SendAsync(request);
56+
// extract all the backends in both cases for the time being
57+
Console.WriteLine("'{0}' Backend found", backendName);
58+
templateResources.Add(backendTemplateResource);
4259

43-
response.EnsureSuccessStatusCode();
44-
string responseBody = await response.Content.ReadAsStringAsync();
45-
return responseBody;
60+
// only extract the backend if this is a full extraction, or in the case of a single api, if it is referenced by one of the policies
61+
//if (singleApiName == null)
62+
//{
63+
// // if the user is extracting all apis, extract all the backends
64+
// Console.WriteLine("'{0}' Backend found", backendName);
65+
// templateResources.Add(backendTemplateResource);
66+
//}
67+
//else
68+
//{
69+
// bool isReferencedInPolicy = false;
70+
// foreach (PolicyTemplateResource policyTemplateResource in policyResources)
71+
// {
72+
// // the backend is used in a policy if the xml contains a set-backend-service policy, which will reference the backend's url or id
73+
// string policyContent = policyTemplateResource.properties.policyContent;
74+
// if (policyContent.Contains(backendName) || policyContent.Contains(backendTemplateResource.properties.url) || policyContent.Contains(backendTemplateResource.properties.resourceId))
75+
// {
76+
// isReferencedInPolicy = true;
77+
// }
78+
// }
79+
// if (isReferencedInPolicy == true)
80+
// {
81+
// // backend was used in policy, extract it
82+
// Console.WriteLine("'{0}' Backend found", backendName);
83+
// templateResources.Add(backendTemplateResource);
84+
// }
85+
//}
4686
}
87+
88+
armTemplate.resources = templateResources.ToArray();
89+
return armTemplate;
4790
}
4891
}
49-
50-
5192
}
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
using System.Net.Http;
2+
using System.Net.Http.Headers;
3+
using System.Threading.Tasks;
4+
using Microsoft.Azure.Management.ApiManagement.ArmTemplates.Common;
5+
using System.Collections.Generic;
6+
using Microsoft.Azure.Management.ApiManagement.ArmTemplates.Create;
7+
8+
namespace Microsoft.Azure.Management.ApiManagement.ArmTemplates.Extract
9+
{
10+
public class EntityExtractor
11+
{
12+
public string baseUrl = "https://management.azure.com";
13+
internal Authentication auth = new Authentication();
14+
15+
public static async Task<string> CallApiManagement(string azToken, string requestUrl)
16+
{
17+
using (HttpClient httpClient = new HttpClient())
18+
{
19+
var request = new HttpRequestMessage(HttpMethod.Get, requestUrl);
20+
21+
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", azToken);
22+
23+
HttpResponseMessage response = await httpClient.SendAsync(request);
24+
25+
response.EnsureSuccessStatusCode();
26+
string responseBody = await response.Content.ReadAsStringAsync();
27+
return responseBody;
28+
}
29+
}
30+
31+
public Template GenerateEmptyTemplateWithParameters()
32+
{
33+
TemplateCreator templateCreator = new TemplateCreator();
34+
Template armTemplate = templateCreator.CreateEmptyTemplate();
35+
armTemplate.parameters = new Dictionary<string, TemplateParameterProperties> { { "ApimServiceName", new TemplateParameterProperties() { type = "string" } } };
36+
return armTemplate;
37+
}
38+
}
39+
}
Lines changed: 61 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,15 @@
11
using System;
2-
using System.Net.Http;
3-
using System.Net.Http.Headers;
42
using System.Threading.Tasks;
53
using Microsoft.Azure.Management.ApiManagement.ArmTemplates.Common;
4+
using System.Collections.Generic;
5+
using Newtonsoft.Json.Linq;
6+
using Newtonsoft.Json;
7+
using System.Linq;
68

79
namespace Microsoft.Azure.Management.ApiManagement.ArmTemplates.Extract
810
{
9-
class LoggerExtractor
11+
public class LoggerExtractor: EntityExtractor
1012
{
11-
static string baseUrl = "https://management.azure.com";
12-
internal Authentication auth = new Authentication();
13-
1413
public async Task<string> GetLoggers(string ApiManagementName, string ResourceGroupName)
1514
{
1615
(string azToken, string azSubId) = await auth.GetAccessToken();
@@ -31,20 +30,67 @@ public async Task<string> GetLogger(string ApiManagementName, string ResourceGro
3130
return await CallApiManagement(azToken, requestUrl);
3231
}
3332

34-
private static async Task<string> CallApiManagement(string azToken, string requestUrl)
33+
public async Task<Template> GenerateLoggerTemplate(string apimname, string resourceGroup, string singleApiName, List<TemplateResource> armTemplateResources)
3534
{
36-
using (HttpClient httpClient = new HttpClient())
37-
{
38-
var request = new HttpRequestMessage(HttpMethod.Get, requestUrl);
35+
Console.WriteLine("------------------------------------------");
36+
Console.WriteLine("Getting loggers from service");
37+
Template armTemplate = GenerateEmptyTemplateWithParameters();
38+
39+
// isolate product api associations in the case of a single api extraction
40+
var diagnosticResources = armTemplateResources.Where(resource => resource.type == ResourceTypeConstants.APIDiagnostic);
41+
var policyResources = armTemplateResources.Where(resource => (resource.type == ResourceTypeConstants.APIPolicy || resource.type == ResourceTypeConstants.APIOperationPolicy));
3942

40-
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", azToken);
43+
List<TemplateResource> templateResources = new List<TemplateResource>();
4144

42-
HttpResponseMessage response = await httpClient.SendAsync(request);
45+
string loggers = await GetLoggers(apimname, resourceGroup);
46+
JObject oLoggers = JObject.Parse(loggers);
47+
foreach (var extractedLogger in oLoggers["value"])
48+
{
49+
string loggerName = ((JValue)extractedLogger["name"]).Value.ToString();
50+
51+
string fullLoggerResource = await GetLogger(apimname, resourceGroup, loggerName);
52+
LoggerTemplateResource loggerResource = JsonConvert.DeserializeObject<LoggerTemplateResource>(fullLoggerResource);
53+
loggerResource.name = $"[concat(parameters('ApimServiceName'), '/{loggerName}')]";
54+
loggerResource.type = ResourceTypeConstants.Logger;
55+
loggerResource.apiVersion = "2018-06-01-preview";
56+
loggerResource.scale = null;
4357

44-
response.EnsureSuccessStatusCode();
45-
string responseBody = await response.Content.ReadAsStringAsync();
46-
return responseBody;
58+
if (singleApiName == null)
59+
{
60+
// if the user is extracting all apis, extract all the loggers
61+
Console.WriteLine("'{0}' Logger found", loggerName);
62+
templateResources.Add(loggerResource);
63+
}
64+
else
65+
{
66+
// if the user is extracting a single api, extract the loggers referenced by its diagnostics and api policies
67+
bool isReferencedInPolicy = false;
68+
bool isReferencedInDiagnostic = false;
69+
foreach (PolicyTemplateResource policyTemplateResource in policyResources)
70+
{
71+
if (policyTemplateResource.properties.policyContent.Contains(loggerName))
72+
{
73+
isReferencedInPolicy = true;
74+
}
75+
}
76+
foreach (DiagnosticTemplateResource diagnosticTemplateResource in diagnosticResources)
77+
{
78+
if (diagnosticTemplateResource.properties.loggerId.Contains(loggerName))
79+
{
80+
isReferencedInPolicy = true;
81+
}
82+
}
83+
if (isReferencedInPolicy == true || isReferencedInDiagnostic == true)
84+
{
85+
// logger was used in policy or diagnostic, extract it
86+
Console.WriteLine("'{0}' Logger found", loggerName);
87+
templateResources.Add(loggerResource);
88+
}
89+
};
4790
}
91+
92+
armTemplate.resources = templateResources.ToArray();
93+
return armTemplate;
4894
}
4995
}
5096
}

0 commit comments

Comments
 (0)