Skip to content

Instantly share code, notes, and snippets.

@sajeetharan
Last active June 18, 2019 07:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sajeetharan/06544e38bb460df5de44cbaef9b05b43 to your computer and use it in GitHub Desktop.
Save sajeetharan/06544e38bb460df5de44cbaef9b05b43 to your computer and use it in GitHub Desktop.
Cosmosdb autoscale (up/down by setting RU)
public static class Cosmosscale
{
[FunctionName("Cosmosscale")]
public static async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
ILogger log,
ExecutionContext context)
{
try
{
var config = new ConfigurationBuilder().SetBasePath(context.FunctionAppDirectory)
.AddJsonFile("local.settings.json", optional: true, reloadOnChange: true)
.AddEnvironmentVariables()
.Build();
//1) initialize the cosmosdb client
using (DocumentClient client = new DocumentClient(new Uri(config["CosmosDB_Uri"]), config["CosmosDB_appKey"]))
{
//2) Get the database self link
string selfLink = client.CreateDocumentCollectionQuery(
UriFactory.CreateDatabaseUri(config["CosmosDB_DatabaseId"]))
.Where(c => c.Id == config["CosmosDB_ContainerId"])
.AsEnumerable()
.FirstOrDefault()
.SelfLink;
//3) Get the current offer for the collection
Offer offer = client.CreateOfferQuery().Where(r => r.ResourceLink == selfLink).AsEnumerable().SingleOrDefault();
//4) Get the current throughput from the offer
int throughputCurrent = (int)offer.GetPropertyValue<JObject>("content").GetValue("offerThroughput");
log.LogInformation(string.Format("Current provisioned throughput is: {0} RU", throughputCurrent.ToString()));
//5) Get the RU increment from AppSettings and parse to an int
if (int.TryParse(config["CosmosDB_RU"], out int RUIncrement))
{
//5.a) create the new offer with the throughput increment added to the current throughput
int newThroughput = throughputCurrent + RUIncrement;
offer = new OfferV2(offer, newThroughput);
//5.b) persist the changes
await client.ReplaceOfferAsync(offer);
log.LogInformation(string.Format("New provisioned througput: {0} RU", newThroughput.ToString()));
return new OkObjectResult("The collection's throughput was changed...");
}
else
{
//5.c) if the throughputIncrement cannot be parsed return throughput not changed
return new BadRequestObjectResult("PARSE ERROR: The collection's throughput was not changed...");
}
}
}
catch (Exception e)
{
log.LogInformation(e.Message);
return new BadRequestObjectResult("ERROR: The collection's throughput was not changed...");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment