-
Notifications
You must be signed in to change notification settings - Fork 97
/
FunctionAppImpl.java
457 lines (408 loc) · 18.3 KB
/
FunctionAppImpl.java
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
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
/**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*/
package com.microsoft.azure.management.appservice.implementation;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.common.io.BaseEncoding;
import com.microsoft.azure.CloudException;
import com.microsoft.azure.management.apigeneration.LangDefinition;
import com.microsoft.azure.management.appservice.AppServicePlan;
import com.microsoft.azure.management.appservice.FunctionApp;
import com.microsoft.azure.management.appservice.FunctionDeploymentSlots;
import com.microsoft.azure.management.appservice.NameValuePair;
import com.microsoft.azure.management.appservice.OperatingSystem;
import com.microsoft.azure.management.appservice.PricingTier;
import com.microsoft.azure.management.appservice.SkuDescription;
import com.microsoft.azure.management.resources.fluentcore.model.Creatable;
import com.microsoft.azure.management.resources.fluentcore.model.Indexable;
import com.microsoft.azure.management.resources.fluentcore.utils.SdkContext;
import com.microsoft.azure.management.storage.SkuName;
import com.microsoft.azure.management.storage.StorageAccount;
import com.microsoft.azure.management.storage.StorageAccountKey;
import com.microsoft.rest.LogLevel;
import com.microsoft.rest.credentials.TokenCredentials;
import okhttp3.HttpUrl;
import okhttp3.Request;
import org.joda.time.DateTime;
import retrofit2.http.Body;
import retrofit2.http.DELETE;
import retrofit2.http.GET;
import retrofit2.http.Header;
import retrofit2.http.Headers;
import retrofit2.http.POST;
import retrofit2.http.PUT;
import retrofit2.http.Path;
import retrofit2.http.Query;
import rx.Completable;
import rx.Observable;
import rx.Subscription;
import rx.functions.Action0;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* The implementation for FunctionApp.
*/
@LangDefinition(ContainerName = "/Microsoft.Azure.Management.AppService.Fluent")
class FunctionAppImpl
extends AppServiceBaseImpl<FunctionApp, FunctionAppImpl, FunctionApp.DefinitionStages.WithCreate, FunctionApp.Update>
implements
FunctionApp,
FunctionApp.Definition,
FunctionApp.DefinitionStages.NewAppServicePlanWithGroup,
FunctionApp.Update {
private Creatable<StorageAccount> storageAccountCreatable;
private StorageAccount storageAccountToSet;
private StorageAccount currentStorageAccount;
private final FunctionAppKeyService functionAppKeyService;
private final FunctionService functionService;
private final KuduClient kuduClient;
private FunctionDeploymentSlots deploymentSlots;
FunctionAppImpl(final String name, SiteInner innerObject, SiteConfigResourceInner configObject, AppServiceManager manager) {
super(name, innerObject, configObject, manager);
functionAppKeyService = manager.restClient().retrofit().create(FunctionAppKeyService.class);
HttpUrl defaultHostName = HttpUrl.parse(defaultHostName());
if (defaultHostName == null) {
defaultHostName = new HttpUrl.Builder().host(defaultHostName()).scheme("http").build();
}
functionService = manager.restClient().newBuilder()
.withBaseUrl(defaultHostName.toString())
.withCredentials(new FunctionCredentials(this))
.withLogLevel(LogLevel.BODY_AND_HEADERS)
.build()
.retrofit().create(FunctionService.class);
kuduClient = new KuduClient(this);
}
@Override
public FunctionDeploymentSlots deploymentSlots() {
if (deploymentSlots == null) {
deploymentSlots = new FunctionDeploymentSlotsImpl(this);
}
return deploymentSlots;
}
@Override
public FunctionAppImpl withNewConsumptionPlan() {
return withNewAppServicePlan(OperatingSystem.WINDOWS, new PricingTier("Dynamic", "Y1"));
}
@Override
public FunctionAppImpl withRuntimeVersion(String version) {
return withAppSetting("FUNCTIONS_EXTENSION_VERSION", version.startsWith("~") ? version : "~" + version);
}
@Override
public FunctionAppImpl withLatestRuntimeVersion() {
return withRuntimeVersion("latest");
}
@Override
Observable<Indexable> submitAppSettings() {
if (storageAccountCreatable != null && this.taskResult(storageAccountCreatable.key()) != null) {
storageAccountToSet = this.<StorageAccount>taskResult(storageAccountCreatable.key());
}
if (storageAccountToSet == null) {
return super.submitAppSettings();
} else {
return storageAccountToSet.getKeysAsync()
.flatMapIterable(new Func1<List<StorageAccountKey>, Iterable<StorageAccountKey>>() {
@Override
public Iterable<StorageAccountKey> call(List<StorageAccountKey> storageAccountKeys) {
return storageAccountKeys;
}
})
.first().flatMap(new Func1<StorageAccountKey, Observable<Indexable>>() {
@Override
public Observable<Indexable> call(StorageAccountKey storageAccountKey) {
String connectionString = String.format("DefaultEndpointsProtocol=https;AccountName=%s;AccountKey=%s",
storageAccountToSet.name(), storageAccountKey.value());
withAppSetting("AzureWebJobsStorage", connectionString);
withAppSetting("AzureWebJobsDashboard", connectionString);
withAppSetting("WEBSITE_CONTENTAZUREFILECONNECTIONSTRING", connectionString);
withAppSetting("WEBSITE_CONTENTSHARE", SdkContext.randomResourceName(name(), 32));
return FunctionAppImpl.super.submitAppSettings();
}
}).doOnCompleted(new Action0() {
@Override
public void call() {
currentStorageAccount = storageAccountToSet;
storageAccountToSet = null;
storageAccountCreatable = null;
}
});
}
}
@Override
FunctionAppImpl withNewAppServicePlan(OperatingSystem operatingSystem, PricingTier pricingTier) {
return super.withNewAppServicePlan(operatingSystem, pricingTier).autoSetAlwaysOn(pricingTier);
}
@Override
@SuppressWarnings("unchecked")
public FunctionAppImpl withExistingAppServicePlan(AppServicePlan appServicePlan) {
super.withExistingAppServicePlan(appServicePlan);
return autoSetAlwaysOn(appServicePlan.pricingTier());
}
private FunctionAppImpl autoSetAlwaysOn(PricingTier pricingTier) {
SkuDescription description = pricingTier.toSkuDescription();
if (description.tier().equalsIgnoreCase("Basic")
|| description.tier().equalsIgnoreCase("Standard")
|| description.tier().equalsIgnoreCase("Premium")) {
return withWebAppAlwaysOn(true);
} else {
return withWebAppAlwaysOn(false);
}
}
@Override
public FunctionAppImpl withNewStorageAccount(String name, SkuName sku) {
StorageAccount.DefinitionStages.WithGroup storageDefine = manager().storageManager().storageAccounts()
.define(name)
.withRegion(regionName());
if (super.creatableGroup != null && isInCreateMode()) {
storageAccountCreatable = storageDefine.withNewResourceGroup(super.creatableGroup)
.withGeneralPurposeAccountKind()
.withSku(sku);
} else {
storageAccountCreatable = storageDefine.withExistingResourceGroup(resourceGroupName())
.withGeneralPurposeAccountKind()
.withSku(sku);
}
this.addDependency(storageAccountCreatable);
return this;
}
@Override
public FunctionAppImpl withExistingStorageAccount(StorageAccount storageAccount) {
this.storageAccountToSet = storageAccount;
return this;
}
@Override
public FunctionAppImpl withDailyUsageQuota(int quota) {
inner().withDailyMemoryTimeQuota(quota);
return this;
}
@Override
public FunctionAppImpl withoutDailyUsageQuota() {
return withDailyUsageQuota(0);
}
@Override
public StorageAccount storageAccount() {
return currentStorageAccount;
}
@Override
public String getMasterKey() {
return getMasterKeyAsync().toBlocking().single();
}
@Override
public Observable<String> getMasterKeyAsync() {
return functionAppKeyService.getMasterKey(resourceGroupName(), name(), manager().subscriptionId(), "2016-08-01", manager().inner().userAgent())
.map(new Func1<Map<String, String>, String>() {
@Override
public String call(Map<String, String> stringStringMap) {
return stringStringMap.get("masterKey");
}
});
}
@Override
public Map<String, String> listFunctionKeys(String functionName) {
return listFunctionKeysAsync(functionName).toBlocking().single();
}
@Override
public Observable<Map<String, String>> listFunctionKeysAsync(final String functionName) {
return functionService.listFunctionKeys(functionName)
.map(new Func1<FunctionKeyListResult, Map<String, String>>() {
@Override
public Map<String, String> call(FunctionKeyListResult result) {
Map<String, String> keys = new HashMap<String, String>();
if (result.keys != null) {
for (NameValuePair pair : result.keys) {
keys.put(pair.name(), pair.value());
}
}
return keys;
}
});
}
@Override
public NameValuePair addFunctionKey(String functionName, String keyName, String keyValue) {
return addFunctionKeyAsync(functionName, keyName, keyValue).toBlocking().single();
}
@Override
public Observable<NameValuePair> addFunctionKeyAsync(String functionName, String keyName, String keyValue) {
if (keyValue != null) {
return functionService.addFunctionKey(functionName, keyName, new NameValuePair().withName(keyName).withValue(keyValue));
} else {
return functionService.generateFunctionKey(functionName, keyName);
}
}
@Override
public void removeFunctionKey(String functionName, String keyName) {
removeFunctionKeyAsync(functionName, keyName).toObservable().toBlocking().subscribe();
}
@Override
public Completable removeFunctionKeyAsync(String functionName, String keyName) {
return functionService.deleteFunctionKey(functionName, keyName).toCompletable();
}
@Override
public void syncTriggers() {
syncTriggersAsync().toObservable().toBlocking().subscribe();
}
@Override
public Completable syncTriggersAsync() {
return manager().inner().webApps().syncFunctionTriggersAsync(resourceGroupName(), name())
.toCompletable()
.onErrorResumeNext(new Func1<Throwable, Completable>() {
@Override
public Completable call(Throwable throwable) {
if (throwable instanceof CloudException && ((CloudException) throwable).response().code() == 200) {
return Completable.complete();
} else {
return Completable.error(throwable);
}
}
});
}
@Override
public InputStream streamApplicationLogs() {
PipedInputStreamWithCallback in = new PipedInputStreamWithCallback();
final PipedOutputStream out = new PipedOutputStream();
try {
in.connect(out);
} catch (IOException e) {
throw new RuntimeException(e);
}
final Subscription subscription = streamApplicationLogsAsync()
// Do not block current thread
.subscribeOn(Schedulers.newThread())
.subscribe(new Action1<String>() {
@Override
public void call(String s) {
try {
out.write(s.getBytes());
out.write('\n');
out.flush();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
});
in.addCallback(new Action0() {
@Override
public void call() {
subscription.unsubscribe();
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
});
return in;
}
@Override
public Observable<String> streamApplicationLogsAsync() {
return functionService.ping()
.flatMap(new Func1<Void, Observable<String>>() {
@Override
public Observable<String> call(Void aVoid) {
return kuduClient.streamApplicationLogsAsync();
}
});
}
@Override
public Completable zipDeployAsync(File zipFile) {
try {
return zipDeployAsync(new FileInputStream(zipFile));
} catch (IOException e) {
return Completable.error(e);
}
}
@Override
public void zipDeploy(File zipFile) {
zipDeployAsync(zipFile).await();
}
@Override
public Completable zipDeployAsync(InputStream zipFile) {
return kuduClient.zipDeployAsync(zipFile);
}
@Override
public void zipDeploy(InputStream zipFile) {
zipDeployAsync(zipFile).await();
}
@Override
public Observable<Indexable> createAsync() {
if (inner().serverFarmId() == null) {
withNewConsumptionPlan();
}
if (currentStorageAccount == null && storageAccountToSet == null && storageAccountCreatable == null) {
withNewStorageAccount(SdkContext.randomResourceName(name(), 20), SkuName.STANDARD_GRS);
}
return super.createAsync();
}
private interface FunctionAppKeyService {
@Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.appservice.WebApps getMasterKey" })
@GET("subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Web/sites/{name}/functions/admin/masterkey")
Observable<Map<String, String>> getMasterKey(@Path("resourceGroupName") String resourceGroupName, @Path("name") String name, @Path("subscriptionId") String subscriptionId, @Query("api-version") String apiVersion, @Header("User-Agent") String userAgent);
}
private interface FunctionService {
@Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.appservice.WebApps listFunctionKeys" })
@GET("admin/functions/{name}/keys")
Observable<FunctionKeyListResult> listFunctionKeys(@Path("name") String functionName);
@Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.appservice.WebApps addFunctionKey" })
@PUT("admin/functions/{name}/keys/{keyName}")
Observable<NameValuePair> addFunctionKey(@Path("name") String functionName, @Path("keyName") String keyName, @Body NameValuePair key);
@Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.appservice.WebApps generateFunctionKey" })
@POST("admin/functions/{name}/keys/{keyName}")
Observable<NameValuePair> generateFunctionKey(@Path("name") String functionName, @Path("keyName") String keyName);
@Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.appservice.WebApps deleteFunctionKey" })
@DELETE("admin/functions/{name}/keys/{keyName}")
Observable<Void> deleteFunctionKey(@Path("name") String functionName, @Path("keyName") String keyName);
@Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.appservice.WebApps ping" })
@POST("admin/host/ping")
Observable<Void> ping();
}
private static class FunctionKeyListResult {
@JsonProperty("keys")
private List<NameValuePair> keys;
}
private static final class FunctionCredentials extends TokenCredentials {
private String token;
private long expire;
private final FunctionAppImpl functionApp;
private FunctionCredentials(FunctionAppImpl functionApp) {
super("Bearer", null);
this.functionApp = functionApp;
}
@Override
public String getToken(Request request) {
if (token == null || expire < DateTime.now().getMillis()) {
token = functionApp.manager().inner().webApps()
.getFunctionsAdminToken(functionApp.resourceGroupName(), functionApp.name());
String jwt = new String(BaseEncoding.base64Url().decode(token.split("\\.")[1]));
Pattern pattern = Pattern.compile("\"exp\": *([0-9]+),");
Matcher matcher = pattern.matcher(jwt);
matcher.find();
expire = Long.parseLong(matcher.group(1));
}
return token;
}
}
private static class PipedInputStreamWithCallback extends PipedInputStream {
private Action0 callback;
private void addCallback(Action0 action) {
this.callback = action;
}
@Override
public void close() throws IOException {
callback.call();
super.close();
}
}
}