content
stringlengths
0
14.9M
filename
stringlengths
44
136
#' Azure Active Directory object #' #' Base class representing an Azure Active Directory object in Microsoft Graph. #' #' @docType class #' @section Fields: #' - `token`: The token used to authenticate with the Graph host. #' - `tenant`: The Azure Active Directory tenant for this object. #' - `type`: The type of object: user, group, application or service principal. #' - `properties`: The object properties. #' @section Methods: #' - `new(...)`: Initialize a new directory object. Do not call this directly; see 'Initialization' below. #' - `delete(confirm=TRUE)`: Delete an object. By default, ask for confirmation first. #' - `update(...)`: Update the object information in Azure Active Directory. #' - `do_operation(...)`: Carry out an arbitrary operation on the object. #' - `sync_fields()`: Synchronise the R object with the data in Azure Active Directory. #' - `list_group_memberships(security_only=FALSE, filter=NULL, n=Inf)`: Return the IDs of all groups this object is a member of. If `security_only` is TRUE, only security group IDs are returned. #' - `list_object_memberships(security_only=FALSE, filter=NULL, n=Inf)`: Return the IDs of all groups, administrative units and directory roles this object is a member of. #' #' @section Initialization: #' Objects of this class should not be created directly. Instead, create an object of the appropriate subclass: [az_app], [az_service_principal], [az_user], [az_group]. #' #' @section List methods: #' All `list_*` methods have `filter` and `n` arguments to limit the number of results. The former should be an [OData expression](https://learn.microsoft.com/en-us/graph/query-parameters#filter-parameter) as a string to filter the result set on. The latter should be a number setting the maximum number of (filtered) results to return. The default values are `filter=NULL` and `n=Inf`. If `n=NULL`, the `ms_graph_pager` iterator object is returned instead to allow manual iteration over the results. #' #' Support in the underlying Graph API for OData queries is patchy. Not all endpoints that return lists of objects support filtering, and if they do, they may not allow all of the defined operators. If your filtering expression results in an error, you can carry out the operation without filtering and then filter the results on the client side. #' @seealso #' [ms_graph], [az_app], [az_service_principal], [az_user], [az_group] #' #' [Microsoft Graph overview](https://learn.microsoft.com/en-us/graph/overview), #' [REST API reference](https://learn.microsoft.com/en-us/graph/api/overview?view=graph-rest-1.0) #' #' @format An R6 object of class `az_object`, inheriting from `ms_object`. #' @export az_object <- R6::R6Class("az_object", inherit=ms_object, public=list( list_object_memberships=function(security_only=FALSE, filter=NULL, n=Inf) { if(!is.null(filter)) stop("This method doesn't support filtering", call.=FALSE) body <- list(securityEnabledOnly=security_only) pager <- self$get_list_pager(self$do_operation("getMemberObjects", body=body, http_verb="POST"), generate_objects=FALSE) unlist(extract_list_values(pager, n)) }, list_group_memberships=function(security_only=FALSE, filter=NULL, n=Inf) { if(!is.null(filter)) stop("This method doesn't support filtering", call.=FALSE) body <- list(securityEnabledOnly=security_only) pager <- self$get_list_pager(self$do_operation("getMemberGroups", body=body, http_verb="POST"), generate_objects=FALSE) unlist(extract_list_values(pager, n)) }, print=function(...) { cat("<Azure Active Directory object '", self$properties$displayName, "'>\n", sep="") cat(" directory id:", self$properties$id, "\n") cat("---\n") cat(format_public_methods(self)) invisible(self) } ))
/scratch/gouwar.j/cran-all/cranData/AzureGraph/R/az_object.R
#' Service principal in Azure Active Directory #' #' Class representing an AAD service principal. #' #' @docType class #' @section Fields: #' - `token`: The token used to authenticate with the Graph host. #' - `tenant`: The Azure Active Directory tenant for this service principal. #' - `type`: always "service principal" for a service principal object. #' - `properties`: The service principal properties. #' @section Methods: #' - `new(...)`: Initialize a new service principal object. Do not call this directly; see 'Initialization' below. #' - `delete(confirm=TRUE)`: Delete a service principal. By default, ask for confirmation first. #' - `update(...)`: Update the service principal information in Azure Active Directory. #' - `do_operation(...)`: Carry out an arbitrary operation on the service principal. #' - `sync_fields()`: Synchronise the R object with the service principal data in Azure Active Directory. #' #' @section Initialization: #' Creating new objects of this class should be done via the `create_service_principal` and `get_service_principal` methods of the [ms_graph] and [az_app] classes. Calling the `new()` method for this class only constructs the R object; it does not call the Microsoft Graph API to create the actual service principal. #' #' @seealso #' [ms_graph], [az_app], [az_object] #' #' [Azure Microsoft Graph overview](https://learn.microsoft.com/en-us/graph/overview), #' [REST API reference](https://learn.microsoft.com/en-us/graph/api/overview?view=graph-rest-1.0) #' #' @format An R6 object of class `az_service_principal`, inheriting from `az_object`. #' @export az_service_principal <- R6::R6Class("az_service_principal", inherit=az_object, public=list( initialize=function(token, tenant=NULL, properties=NULL) { self$type <- "service principal" private$api_type <- "servicePrincipals" super$initialize(token, tenant, properties) }, print=function(...) { cat("<Graph service principal '", self$properties$displayName, "'>\n", sep="") cat(" app id:", self$properties$appId, "\n") cat(" directory id:", self$properties$id, "\n") cat(" app tenant:", self$properties$appOwnerOrganizationId, "\n") cat("---\n") cat(format_public_methods(self)) invisible(self) } ))
/scratch/gouwar.j/cran-all/cranData/AzureGraph/R/az_svc_principal.R
#' User in Azure Active Directory #' #' Class representing an AAD user account. #' #' @docType class #' @section Fields: #' - `token`: The token used to authenticate with the Graph host. #' - `tenant`: The Azure Active Directory tenant for this user. #' - `type`: always "user" for a user object. #' - `properties`: The user properties. #' @section Methods: #' - `new(...)`: Initialize a new user object. Do not call this directly; see 'Initialization' below. #' - `delete(confirm=TRUE)`: Delete a user account. By default, ask for confirmation first. #' - `update(...)`: Update the user information in Azure Active Directory. #' - `do_operation(...)`: Carry out an arbitrary operation on the user account. #' - `sync_fields()`: Synchronise the R object with the app data in Azure Active Directory. #' - `list_direct_memberships(filter=NULL, n=Inf)`: List the groups and directory roles this user is a direct member of. #' - `list_owned_objects(type=c("user", "group", "application", "servicePrincipal"), filter=NULL, n=Inf)`: List directory objects (groups/apps/service principals) owned by this user. Specify the `type` argument to limit the result to specific object type(s). #' - `list_created_objects(type=c("user", "group", "application", "servicePrincipal"), filter=NULL, n=Inf)`: List directory objects (groups/apps/service principals) created by this user. Specify the `type` argument to limit the result to specific object type(s). #' - `list_owned_devices(filter=NULL, n=Inf)`: List the devices owned by this user. #' - `list_registered_devices(filter=NULL, n=Inf)`: List the devices registered by this user. #' - `reset_password(password=NULL, force_password_change=TRUE)`: Resets a user password. By default the new password will be randomly generated, and must be changed at next login. #' #' @section Initialization: #' Creating new objects of this class should be done via the `create_user` and `get_user` methods of the [ms_graph] and [az_app] classes. Calling the `new()` method for this class only constructs the R object; it does not call the Microsoft Graph API to create the actual user account. #' #' @section List methods: #' All `list_*` methods have `filter` and `n` arguments to limit the number of results. The former should be an [OData expression](https://learn.microsoft.com/en-us/graph/query-parameters#filter-parameter) as a string to filter the result set on. The latter should be a number setting the maximum number of (filtered) results to return. The default values are `filter=NULL` and `n=Inf`. If `n=NULL`, the `ms_graph_pager` iterator object is returned instead to allow manual iteration over the results. #' #' Support in the underlying Graph API for OData queries is patchy. Not all endpoints that return lists of objects support filtering, and if they do, they may not allow all of the defined operators. If your filtering expression results in an error, you can carry out the operation without filtering and then filter the results on the client side. #' @seealso #' [ms_graph], [az_app], [az_group], [az_device], [az_object] #' #' [Microsoft Graph overview](https://learn.microsoft.com/en-us/graph/overview), #' [REST API reference](https://learn.microsoft.com/en-us/graph/api/overview?view=graph-rest-1.0) #' #' @examples #' \dontrun{ #' #' gr <- get_graph_login() #' #' # my user account #' gr$get_user() #' #' # another user account #' usr <- gr$get_user("[email protected]") #' #' grps <- usr$list_direct_memberships() #' head(grps) #' #' # owned objects #' usr$list_owned_objects() #' #' # owned apps and service principals #' usr$list_owned_objects(type=c("application", "servicePrincipal")) #' #' # first 5 objects #' usr$list_owned_objects(n=5) #' #' # get the pager object #' pager <- usr$list_owned_objects(n=NULL) #' pager$value #' #' } #' @format An R6 object of class `az_user`, inheriting from `az_object`. #' @export az_user <- R6::R6Class("az_user", inherit=az_object, public=list( password=NULL, initialize=function(token, tenant=NULL, properties=NULL, password=NULL) { self$type <- "user" private$api_type <- "users" self$password <- password super$initialize(token, tenant, properties) }, reset_password=function(password=NULL, force_password_change=TRUE) { if(is.null(password)) password <- openssl::base64_encode(openssl::rand_bytes(40)) properties <- modifyList(properties, list( passwordProfile=list( password=password, forceChangePasswordNextSignIn=force_password_change, forceChangePasswordNextSignInWithMfa=FALSE ) )) self$do_operation(body=properties, encode="json", http_verb="PATCH") self$properties <- self$do_operation() self$password <- password password }, list_owned_objects=function(type=c("user", "group", "application", "servicePrincipal"), filter=NULL, n=Inf) { opts <- list(`$filter`=filter, `$count`=if(!is.null(filter)) "true") hdrs <- if(!is.null(filter)) httr::add_headers(consistencyLevel="eventual") pager <- self$get_list_pager(self$do_operation("ownedObjects", options=opts, hdrs), type_filter=type) extract_list_values(pager, n) }, list_created_objects=function(type=c("user", "group", "application", "servicePrincipal"), filter=NULL, n=Inf) { opts <- list(`$filter`=filter, `$count`=if(!is.null(filter)) "true") hdrs <- if(!is.null(filter)) httr::add_headers(consistencyLevel="eventual") pager <- self$get_list_pager(self$do_operation("createdObjects", options=opts, hdrs), type_filter=type) extract_list_values(pager, n) }, list_owned_devices=function(filter=NULL, n=Inf) { opts <- list(`$filter`=filter, `$count`=if(!is.null(filter)) "true") hdrs <- if(!is.null(filter)) httr::add_headers(consistencyLevel="eventual") pager <- self$get_list_pager(self$do_operation("ownedDevices", options=opts, hdrs)) extract_list_values(pager, n) }, list_direct_memberships=function(filter=NULL, n=Inf) { opts <- list(`$filter`=filter, `$count`=if(!is.null(filter)) "true") hdrs <- if(!is.null(filter)) httr::add_headers(consistencyLevel="eventual") pager <- self$get_list_pager(self$do_operation("memberOf", options=opts, hdrs)) extract_list_values(pager, n) }, print=function(...) { cat("<Graph user account '", self$properties$displayName, "'>\n", sep="") cat(" principal name:", self$properties$userPrincipalName, "\n") cat(" email:", self$properties$mail, "\n") cat(" directory id:", self$properties$id, "\n") cat("---\n") cat(format_public_methods(self)) invisible(self) } ))
/scratch/gouwar.j/cran-all/cranData/AzureGraph/R/az_user.R
#' Microsoft Graph request #' #' Class representing a request to the Microsoft Graph API. Currently this is used only in building a batch call. #' #' @docType class #' @section Methods: #' - `new(...)`: Initialize a new request object with the given parameters. See 'Details' below. #' - `batchify()`: Generate a list object suitable for incorporating into a call to the batch endpoint. #' @section Details: #' The `initialize()` method takes the following arguments, representing the components of a HTTPS request: #' - `op`: The path of the HTTPS URL, eg `/me/drives`. #' - `body`: The body of the HTTPS request, if it is a PUT, POST or PATCH. #' - `options`: A list containing the query parameters for the URL. #' - `headers`: Any optional HTTP headers for the request. #' - `encode`: If a request body is present, how it should be encoded when sending it to the endpoint. The default is `json`, meaning it will be sent as JSON text; an alternative is `raw`, for binary data. #' - `http_verb`: One of "GET" (the default), "DELETE", "PUT", "POST", "HEAD", or "PATCH". #' #' This class is currently used only for building batch calls. Future versions of AzureGraph may be refactored to use it in general API calls as well. #' @seealso #' [call_batch_endpoint] #' #' [Microsoft Graph overview](https://learn.microsoft.com/en-us/graph/overview), #' [Batch endpoint documentation](https://learn.microsoft.com/en-us/graph/json-batching) #' #' @examples #' graph_request$new("me") #' #' # a new email message in Outlook #' graph_request$new("me/messages", #' body=list( #' body=list( #' content="Hello from R", #' content_type="text" #' ), #' subject="Hello", #' toRecipients="[email protected]" #' ), #' http_verb="POST" #' ) #' @format An R6 object of class `graph_request`. #' @export graph_request <- R6::R6Class("graph_request", public=list( method=NULL, op=NULL, options=list(), headers=list(), body=NULL, encode=NULL, initialize=function(op, body=NULL, options=list(), headers=list(), encode="json", http_verb=c("GET", "DELETE", "PUT", "POST", "HEAD", "PATCH")) { self$op <- op self$method <- match.arg(http_verb) self$options <- options self$headers <- headers self$body <- body self$encode <- encode }, batchify=function() { url <- httr::parse_url("foo://bar") # dummy scheme and host url$path <- self$op url$query <- self$options url <- httr::build_url(url) req <- list( id=NULL, method=self$method, url=substr(url, 10, nchar(url)) ) hdrs <- self$headers if(!is_empty(self$body)) { hdrs$`Content-Type` <- if(self$encode == "json") "application/json" else if(self$encode == "raw") "application/octet-stream" else self$encode } if(!is_empty(hdrs)) req$headers <- hdrs if(!is_empty(self$body)) req$body <- self$body req }, print=function(...) { path <- httr::parse_url(self$op) path$query <- self$options path <- sub("^://", "", httr::build_url(path)) cat("<Microsoft Graph request object>\n") cat(" path:", self$method, path, "\n") invisible(self) } )) #' Call the Graph API batch endpoint #' #' @param token An Azure OAuth token, of class [AzureToken]. #' @param requests A list of [graph_request] objects, representing individual requests to the Graph API. #' @param depends_on An optional named vector, or TRUE. See below. #' @param api_version The API version to use, which will form part of the URL sent to the host. #' #' @details #' Use this function to combine multiple requests into a single HTTPS call. This can save significant network latency. #' #' The `depends_on` argument specifies the dependencies that may exist between requests. The default is to treat the requests as independent, which allows them to be executed in parallel. If `depends_on` is TRUE, each request is specified as depending on the immediately preceding request. Otherwise, this should be a named vector or list that gives the dependency or dependencies for each request. #' #' There are 2 restrictions on `depends_on`: #' - If one request has a dependency, then all requests must have dependencies specified #' - A request can only depend on previous requests in the list, not on later ones. #' #' A request list that has dependencies will be executed serially. #' #' @return #' A list containing the responses to each request. Each item has components `id` and `status` at a minimum. It may also contain `headers` and `body`, depending on the specifics of the request. #' @seealso #' [graph_request], [call_graph_endpoint] #' #' [Microsoft Graph overview](https://learn.microsoft.com/en-us/graph/overview), #' [Batch endpoint documentation](https://learn.microsoft.com/en-us/graph/json-batching) #' #' [OData documentation on batch requests](https://docs.oasis-open.org/odata/odata-json-format/v4.01/odata-json-format-v4.01.html#sec_BatchRequestsandResponses) #' #' @examples #' \dontrun{ #' #' req1 <- graph_request$new("me") #' #' # a new email message in Outlook #' req_create <- graph_request$new("me/messages", #' body=list( #' body=list( #' content="Hello from R", #' content_type="text" #' ), #' subject="Hello", #' toRecipients="[email protected]" #' ), #' http_verb="POST" #' ) #' #' # messages in drafts #' req_get <- graph_request$new("me/mailFolders/drafts/messages") #' #' # requests are dependent: 2nd list of drafts will include just-created message #' call_batch_endpoint(token, list(req_get, req_create, req_get), depends_on=TRUE) #' #' # alternate way: enumerate all requests #' call_batch_endpoint(token, list(req_get, req_create, req_get), depends_on=c("2"=1, "3"=2)) #' #' } #' @export call_batch_endpoint <- function(token, requests=list(), depends_on=NULL, api_version=getOption("azure_graph_api_version")) { if(is_empty(requests)) return(invisible(NULL)) for(req in requests) if(!inherits(req, "graph_request")) stop("Must supply a list of request objects", call.=FALSE) if(length(requests) > 20) stop("Maximum of 20 requests per batch job", call.=FALSE) ids <- as.character(seq_along(requests)) # populate the batch request body reqlst <- lapply(requests, function(req) req$batchify()) for(i in seq_along(reqlst)) reqlst[[i]]$id <- as.character(i) # insert depends_on if required if(isTRUE(depends_on)) { for(i in seq_along(requests)[-1]) reqlst[[i]]$dependsOn <- I(as.character(i - 1)) } else if(!is_empty(depends_on)) { names_depends <- names(depends_on) if(is.null(names_depends) || any(names_depends == "")) stop("'depends_on' should be TRUE or a named vector identifying dependencies") for(i in seq_along(depends_on)) { id <- as.numeric(names_depends)[i] reqlst[[id]]$dependsOn <- I(as.character(depends_on[[i]])) } } reslst <- call_graph_endpoint(token, "$batch", body=list(requests=reqlst), http_verb="POST", api_version=api_version)$responses reslst <- reslst[order(sapply(reslst, `[[`, "id"))] err_msgs <- lapply(reslst, function(res) { if(res$status >= 300) error_message(res$body) else NULL }) errs <- !sapply(err_msgs, is.null) if(any(errs)) stop("Graph batch job encountered errors on requests ", paste(which(errs), collapse=", "), "\nMessages:\n", paste(unlist(err_msgs[errs]), collapse="\n"), call.=FALSE) reslst }
/scratch/gouwar.j/cran-all/cranData/AzureGraph/R/batch.R
#' Call the Microsoft Graph REST API #' #' @param token An Azure OAuth token, of class [AzureToken]. #' @param operation The operation to perform, which will form part of the URL path. #' @param options A named list giving the URL query parameters. #' @param api_version The API version to use, which will form part of the URL sent to the host. #' @param url A complete URL to send to the host. #' @param http_verb The HTTP verb as a string, one of `GET`, `PUT`, `POST`, `DELETE`, `HEAD` or `PATCH`. #' @param http_status_handler How to handle in R the HTTP status code of a response. `"stop"`, `"warn"` or `"message"` will call the appropriate handlers in httr, while `"pass"` ignores the status code. #' @param simplify Whether to turn arrays of objects in the JSON response into data frames. Set this to `TRUE` if you are expecting the endpoint to return tabular data and you want a tabular result, as opposed to a list of objects. #' @param auto_refresh Whether to refresh/renew the OAuth token if it is no longer valid. #' @param body The body of the request, for `PUT`/`POST`/`PATCH`. #' @param encode The encoding (really content-type) for the request body. The default value "json" means to serialize a list body into a JSON object. If you pass an already-serialized JSON object as the body, set `encode` to "raw". #' @param ... Other arguments passed to lower-level code, ultimately to the appropriate functions in httr. #' #' @details #' These functions form the low-level interface between R and Microsoft Graph. `call_graph_endpoint` forms a URL from its arguments and passes it to `call_graph_url`. #' #' If `simplify` is `TRUE`, `call_graph_url` will exploit the ability of `jsonlite::fromJSON` to convert arrays of objects into R data frames. This can be useful for REST calls that return tabular data. However, it can also cause problems for _paged_ lists, where each page will be turned into a separate data frame; as the individual objects may not have the same fields, the resulting data frames will also have differing columns. This will cause base R's `rbind` to fail when binding the pages together. When processing paged lists, AzureGraph will use `vctrs::vec_rbind` instead of `rbind` when the vctrs package is available; `vec_rbind` does not have this problem. For safety, you should only set `simplify=TRUE` when vctrs is installed. #' #' @return #' If `http_status_handler` is one of `"stop"`, `"warn"` or `"message"`, the status code of the response is checked. If an error is not thrown, the parsed content of the response is returned with the status code attached as the "status" attribute. #' #' If `http_status_handler` is `"pass"`, the entire response is returned without modification. #' #' @seealso #' [httr::GET], [httr::PUT], [httr::POST], [httr::DELETE], [httr::stop_for_status], [httr::content] #' @rdname call_graph #' @export call_graph_endpoint <- function(token, operation, ..., options=list(), api_version=getOption("azure_graph_api_version")) { url <- find_resource_host(token) url$path <- construct_path(api_version, operation) url$path <- encode_hash(url$path) url$query <- options call_graph_url(token, url, ...) } #' @rdname call_graph #' @export call_graph_url <- function(token, url, ..., body=NULL, encode="json", http_verb=c("GET", "DELETE", "PUT", "POST", "HEAD", "PATCH"), http_status_handler=c("stop", "warn", "message", "pass"), simplify=FALSE, auto_refresh=TRUE) { # if content-type is json, serialize it manually to ensure proper handling of nulls if(encode == "json" && !is_empty(body)) { null <- vapply(body, is.null, logical(1)) body <- jsonlite::toJSON(body[!null], auto_unbox=TRUE, digits=22, null="null") encode <- "raw" } # do actual API call, checking for throttling (max 10 retries) for(i in 1:10) { headers <- process_headers(token, url, auto_refresh) res <- httr::VERB(match.arg(http_verb), url, headers, ..., body=body, encode=encode) if(httr::status_code(res) == 429) { delay <- httr::headers(res)$`Retry-After` Sys.sleep(if(!is.null(delay)) as.numeric(delay) else i^1.5) } else break } process_response(res, match.arg(http_status_handler), simplify) } process_headers <- function(token, host, auto_refresh) { # if token has expired, renew it if(auto_refresh && !token$validate()) { message("Access token has expired or is no longer valid; refreshing") token$refresh() } creds <- token$credentials host <- httr::parse_url(host)$hostname headers <- c( Host=host, Authorization=paste(creds$token_type, creds$access_token), `Content-Type`="application/json" ) httr::add_headers(.headers=headers) } process_response <- function(response, handler, simplify) { if(handler != "pass") { cont <- httr::content(response, simplifyVector=simplify) handler <- get(paste0(handler, "_for_status"), getNamespace("httr")) handler(response, paste0("complete operation. Message:\n", sub("\\.$", "", error_message(cont)))) if(is.null(cont)) cont <- list() attr(cont, "status") <- httr::status_code(response) cont } else response } # provide complete error messages from Resource Manager/Microsoft Graph/etc error_message <- function(cont) { # kiboze through possible message locations msg <- if(is.character(cont)) cont # else if(inherits(cont, "xml_node")) # Graph # paste(xml2::xml_text(xml2::xml_children(cont)), collapse=": ") else if(is.list(cont)) { if(is.character(cont$message)) cont$message else if(is.list(cont$error) && is.character(cont$error$message)) cont$error$message else if(is.list(cont$odata.error)) # Graph OData cont$odata.error$message$value } else "" paste0(strwrap(msg), collapse="\n") } # handle different behaviour of file_path on Windows/Linux wrt trailing / construct_path <- function(...) { sub("/$", "", file.path(..., fsep="/")) } # paths containing hash need to be encoded encode_hash <- function(x) { gsub("#", "%23", x, fixed = TRUE) } # display confirmation prompt, return TRUE/FALSE (no NA) get_confirmation <- function(msg, default=TRUE) { ok <- if(getRversion() < numeric_version("3.5.0")) { msg <- paste(msg, if(default) "(Yes/no/cancel) " else "(yes/No/cancel) ") yn <- readline(msg) if(nchar(yn) == 0) default else tolower(substr(yn, 1, 1)) == "y" } else utils::askYesNo(msg, default) isTRUE(ok) } find_resource_host <- function(token) { if(is_azure_v2_token(token)) { # search the vector of scopes for the actual resource URL url <- list() i <- 1 while(is.null(url$scheme) && i <= length(token$scope)) { url <- httr::parse_url(token$scope[i]) i <- i + 1 } } else url <- httr::parse_url(token$resource) # v1 token is the easy case if(is.null(url$scheme)) stop("Could not find Graph host URL", call.=FALSE) url$path <- NULL url }
/scratch/gouwar.j/cran-all/cranData/AzureGraph/R/call_graph.R
#' Format a Microsoft Graph or Azure object #' #' Miscellaneous functions for printing Microsoft Graph and Azure R6 objects #' #' @param env An R6 object's environment for printing. #' @param exclude Objects in `env` to exclude from the printout. #' #' @details #' These are utilities to aid in printing R6 objects created by this package or its descendants. They are not meant to be called by the user. #' #' @rdname format #' @export format_public_fields <- function(env, exclude=character(0)) { objnames <- ls(env) std_fields <- c("token") objnames <- setdiff(objnames, c(exclude, std_fields)) maxwidth <- as.integer(0.8 * getOption("width")) objconts <- sapply(objnames, function(n) { x <- get(n, env) deparsed <- if(is_empty(x) || is.function(x)) # don't print empty fields return(NULL) else if(is.list(x)) paste0("list(", paste(names(x), collapse=", "), ")") else if(is.vector(x)) { x <- paste0(x, collapse=", ") if(nchar(x) > maxwidth - nchar(n) - 10) x <- paste0(substr(x, 1, maxwidth - nchar(n) - 10), " ...") x } else deparse(x)[[1]] paste0(strwrap(paste0(n, ": ", deparsed), width=maxwidth, indent=2, exdent=4), collapse="\n") }, simplify=FALSE) empty <- sapply(objconts, is.null) objconts <- objconts[!empty] # print etag at the bottom, not the top if("etag" %in% names(objconts)) objconts <- c(objconts[-which(names(objconts) == "etag")], objconts["etag"]) paste0(paste0(objconts, collapse="\n"), "\n---\n") } #' @rdname format #' @export format_public_methods <- function(env) { objnames <- ls(env) std_methods <- c("clone", "print", "initialize") objnames <- setdiff(objnames, std_methods) is_method <- sapply(objnames, function(obj) is.function(.subset2(env, obj))) maxwidth <- as.integer(0.8 * getOption("width")) objnames <- strwrap(paste(objnames[is_method], collapse=", "), width=maxwidth, indent=4, exdent=4) paste0(" Methods:\n", paste0(objnames, collapse="\n"), "\n") }
/scratch/gouwar.j/cran-all/cranData/AzureGraph/R/format.R
#' Login to Azure Active Directory Graph #' #' @param tenant The Azure Active Directory tenant for which to obtain a login client. Can be a name ("myaadtenant"), a fully qualified domain name ("myaadtenant.onmicrosoft.com" or "mycompanyname.com"), or a GUID. The default is to login via the "common" tenant, which will infer your actual tenant from your credentials. #' @param app The client/app ID to use to authenticate with Azure Active Directory. The default is to login interactively using the Azure CLI cross-platform app, but you can supply your own app credentials as well. #' @param password If `auth_type == "client_credentials"`, the app secret; if `auth_type == "resource_owner"`, your account password. #' @param username If `auth_type == "resource_owner"`, your username. #' @param certificate If `auth_type == "client_credentials", a certificate to authenticate with. This is a more secure alternative to using an app secret. #' @param auth_type The OAuth authentication method to use, one of "client_credentials", "authorization_code", "device_code" or "resource_owner". If `NULL`, this is chosen based on the presence of the `username` and `password` arguments. #' @param version The Azure Active Directory version to use for authenticating. #' @param host Your Microsoft Graph host. Defaults to `https://graph.microsoft.com/`. Change this if you are using a government or private cloud. #' @param aad_host Azure Active Directory host for authentication. Defaults to `https://login.microsoftonline.com/`. Change this if you are using a government or private cloud. #' @param scopes The Microsoft Graph scopes (permissions) to obtain for this Graph login. For `create_graph_login`, this is used only for `version=2`. For `get_graph_login`, set this to NA to require an AAD v1.0 token. #' @param config_file Optionally, a JSON file containing any of the arguments listed above. Arguments supplied in this file take priority over those supplied on the command line. You can also use the output from the Azure CLI `az ad sp create-for-rbac` command. #' @param token Optionally, an OAuth 2.0 token, of class [AzureAuth::AzureToken]. This allows you to reuse the authentication details for an existing session. If supplied, all other arguments to `create_graph_login` will be ignored. #' @param refresh For `get_graph_login`, whether to refresh the authentication token on loading the client. #' @param selection For `get_graph_login`, if you have multiple logins for a given tenant, which one to use. This can be a number, or the input MD5 hash of the token used for the login. If not supplied, `get_graph_login` will print a menu and ask you to choose a login. #' @param confirm For `delete_graph_login`, whether to ask for confirmation before deleting. #' @param ... Other arguments passed to `ms_graph$new()`. #' #' @details #' `create_graph_login` creates a login client to authenticate with Microsoft Graph, using the supplied arguments. The authentication token is obtained using [get_azure_token], which automatically caches and reuses tokens for subsequent sessions. #' #' For interactive use, you would normally _not_ supply the `username` and `password` arguments. Omitting them will prompt `create_graph_login` to authenticate you with AAD using your browser, which is the recommended method. If you don't have a browser available to your R session, for example if you're using RStudio Server or Azure Databricks, you can specify `auth_type="device_code`". #' #' For non-interactive use, for example if you're calling AzureGraph in a deployment pipeline, the recommended authentication method is via client credentials. For this method, you supply _only_ the `password` argument, which should contain the client secret for your app registration. You must also specify your own app registration ID, in the `app` argument. #' #' The AzureAuth package has a [vignette](https://cran.r-project.org/package=AzureAuth/vignettes/scenarios.html) that goes into more detail on these authentication scenarios. #' #' `get_graph_login` returns a previously created login client. If there are multiple existing clients, you can specify which client to return via the `selection`, `app`, `scopes` and `auth_type` arguments. If you don't specify which one to return, it will pop up a menu and ask you to choose one. #' #' One difference between `create_graph_login` and `get_graph_login` is the former will delete any previously saved credentials that match the arguments it was given. You can use this to force AzureGraph to remove obsolete tokens that may be lying around. #' #' @return #' For `get_graph_login` and `create_graph_login`, an object of class `ms_graph`, representing the login client. For `list_graph_logins`, a (possibly nested) list of such objects. #' #' If the AzureR data directory for saving credentials does not exist, `get_graph_login` will throw an error. #' #' @seealso #' [ms_graph], [AzureAuth::get_azure_token] for more details on authentication methods #' #' [AzureAuth vignette on authentication scenarios](https://cran.r-project.org/package=AzureAuth/vignettes/scenarios.html) #' #' [Microsoft Graph overview](https://learn.microsoft.com/en-us/graph/overview), #' [REST API reference](https://learn.microsoft.com/en-us/graph/api/overview?view=graph-rest-1.0) #' #' @examples #' \dontrun{ #' #' # without any arguments, this will create a client using your AAD organisational account #' az <- create_graph_login() #' #' # retrieve the login in subsequent sessions #' az <- get_graph_login() #' #' # this will create an Microsoft Graph client for the tenant 'mytenant.onmicrosoft.com', #' # using the client_credentials method #' az <- create_graph_login("mytenant", app="{app_id}", password="{password}") #' #' # you can also login using credentials in a json file #' az <- create_graph_login(config_file="~/creds.json") #' #' # creating and obtaining a login with specific scopes #' create_graph_login("mytenant", scopes=c("User.Read", "Files.ReadWrite.All")) #' get_graph_login("mytenant", scopes=c("User.Read", "Files.ReadWrite.All")) #' #' # to use your personal account, set the tenant to one of the following #' create_graph_login("9188040d-6c67-4c5b-b112-36a304b66dad") #' create_graph_login("consumers") # requires AzureAuth 1.3.0 #' #' } #' @rdname graph_login #' @export create_graph_login <- function(tenant="common", app=NULL, password=NULL, username=NULL, certificate=NULL, auth_type=NULL, version=2, host="https://graph.microsoft.com/", aad_host="https://login.microsoftonline.com/", scopes=".default", config_file=NULL, token=NULL, ...) { if(!is_azure_token(token)) { if(!is.null(config_file)) { conf <- jsonlite::fromJSON(config_file) call <- as.list(match.call())[-1] call$config_file <- call$token <- NULL call <- lapply(modifyList(call, conf), function(x) eval.parent(x)) return(do.call(create_graph_login, call)) } tenant <- normalize_tenant(tenant) app <- if(is.null(app)) { if(tenant %in% c("consumers", "9188040d-6c67-4c5b-b112-36a304b66dad")) .azurer_graph_app_id else .az_cli_app_id } else normalize_guid(app) if(version == 2) host <- c(paste0(host, scopes), "openid", "offline_access") token_args <- list(resource=host, tenant=tenant, app=app, password=password, username=username, certificate=certificate, auth_type=auth_type, aad_host=aad_host, version=version, ...) hash <- do.call(token_hash, token_args) tokenfile <- file.path(AzureR_dir(), hash) if(file.exists(tokenfile)) { message("Deleting existing Azure Active Directory token for this set of credentials") file.remove(tokenfile) } message("Creating Microsoft Graph login for ", format_tenant(tenant)) token <- do.call(get_azure_token, token_args) } else tenant <- token$tenant client <- ms_graph$new(token=token) # save login info for future sessions graph_logins <- load_graph_logins() graph_logins[[tenant]] <- sort(unique(c(graph_logins[[tenant]], client$token$hash()))) save_graph_logins(graph_logins) client } #' @rdname graph_login #' @export get_graph_login <- function(tenant="common", selection=NULL, app=NULL, scopes=NULL, auth_type=NULL, refresh=TRUE) { if(!dir.exists(AzureR_dir())) stop("AzureR data directory does not exist; cannot load saved logins") tenant <- normalize_tenant(tenant) graph_logins <- load_graph_logins() this_login <- graph_logins[[tenant]] if(is_empty(this_login)) { msg <- paste0("No Microsoft Graph logins found for ", format_tenant(tenant), ";\nuse create_graph_login() to create one") stop(msg, call.=FALSE) } message("Loading Microsoft Graph login for ", format_tenant(tenant)) # do we need to choose which login client to use? have_selection <- !is.null(selection) have_auth_spec <- any(!is.null(app), !is.null(scopes), !is.null(auth_type)) token <- if(length(this_login) > 1 || have_selection || have_auth_spec) choose_token(this_login, selection, app, scopes, auth_type) else load_azure_token(this_login) if(is.null(token)) return(NULL) client <- ms_graph$new(token=token) if(refresh) client$token$refresh() client } #' @rdname graph_login #' @export delete_graph_login <- function(tenant="common", confirm=TRUE) { if(!dir.exists(AzureR_dir())) { warning("AzureR data directory does not exist; no logins to delete") return(invisible(NULL)) } tenant <- normalize_tenant(tenant) if(confirm && interactive()) { msg <- paste0("Do you really want to delete the Microsoft Graph login(s) for ", format_tenant(tenant), "?") if(!get_confirmation(msg, FALSE)) return(invisible(NULL)) } graph_logins <- load_graph_logins() graph_logins[[tenant]] <- NULL save_graph_logins(graph_logins) invisible(NULL) } #' @rdname graph_login #' @export list_graph_logins <- function() { graph_logins <- load_graph_logins() logins <- sapply(graph_logins, function(tenant) { sapply(tenant, function(hash) ms_graph$new(token=load_azure_token(hash)), simplify=FALSE) }, simplify=FALSE) logins } load_graph_logins <- function() { file <- file.path(AzureR_dir(), "graph_logins.json") if(!file.exists(file)) return(named_list()) jsonlite::fromJSON(file) } save_graph_logins <- function(logins) { if(!dir.exists(AzureR_dir())) { message("AzureR data directory does not exist; login credentials not saved") return(invisible(NULL)) } if(is_empty(logins)) names(logins) <- character(0) file <- file.path(AzureR_dir(), "graph_logins.json") writeLines(jsonlite::toJSON(logins, auto_unbox=TRUE, pretty=TRUE), file) invisible(NULL) } format_tenant <- function(tenant) { if(tenant == "common") "default tenant" else paste0("tenant '", tenant, "'") } # algorithm for choosing a token: # if given a hash, choose it (error if no match) # otherwise if given a number, use it (error if out of bounds) # otherwise if given any of app|scopes|auth_type, use those (error if no match, ask if multiple matches) # otherwise ask choose_token <- function(hashes, selection, app, scopes, auth_type) { if(is.character(selection)) { if(!(selection %in% hashes)) stop("Token with selected hash not found", call.=FALSE) return(load_azure_token(selection)) } if(is.numeric(selection)) { if(selection <= 0 || selection > length(hashes)) stop("Invalid numeric selection", call.=FALSE) return(load_azure_token(hashes[selection])) } tokens <- lapply(hashes, load_azure_token) ok <- rep(TRUE, length(tokens)) # filter down list of tokens based on auth criteria if(!is.null(app) || !is.null(scopes) || !is.null(auth_type)) { if(!is.null(scopes)) scopes <- tolower(scopes) # look for matching token for(i in seq_along(hashes)) { app_match <- scope_match <- auth_match <- TRUE if(!is.null(app) && tokens[[i]]$client$client_id != app) app_match <- FALSE if(!is.null(scopes)) { # AAD v1.0 tokens do not have scopes if(is.null(tokens[[i]]$scope)) scope_match <- is.na(scopes) else { tok_scopes <- tolower(basename(grep("^.+://", tokens[[i]]$scope, value=TRUE))) if(!setequal(scopes, tok_scopes)) scope_match <- FALSE } } if(!is.null(auth_type) && tokens[[i]]$auth_type != auth_type) auth_match <- FALSE if(!app_match || !scope_match || !auth_match) ok[i] <- FALSE } } tokens <- tokens[ok] if(length(tokens) == 0) stop("No tokens found with selected authentication parameters", call.=FALSE) else if(length(tokens) == 1) return(tokens[[1]]) # bring up a menu tenant <- tokens[[1]]$tenant choices <- sapply(tokens, function(token) { app <- token$client$client_id scopes <- if(!is.null(token$scope)) paste(tolower(basename(grep("^.+://", token$scope, value=TRUE))), collapse=" ") else "<NA>" paste0("App ID: ", app, "\n Scopes: ", scopes, "\n Authentication method: ", token$auth_type, "\n MD5 Hash: ", token$hash()) }) msg <- paste0("Choose a Microsoft Graph login for ", format_tenant(tenant)) selection <- utils::menu(choices, title=msg) if(selection == 0) invisible(NULL) else tokens[[selection]] }
/scratch/gouwar.j/cran-all/cranData/AzureGraph/R/graph_login.R
#' Informational functions #' #' These functions return whether the object is of the corresponding class. #' #' @param object An R object. #' #' @return #' A boolean. #' @rdname info #' @export is_app <- function(object) { R6::is.R6(object) && inherits(object, "az_app") } #' @rdname info #' @export is_service_principal <- function(object) { R6::is.R6(object) && inherits(object, "az_service_principal") } #' @rdname info #' @export is_user <- function(object) { R6::is.R6(object) && inherits(object, "az_user") } #' @rdname info #' @export is_group <- function(object) { R6::is.R6(object) && inherits(object, "az_group") } #' @rdname info #' @export is_directory_role <- function(object) { R6::is.R6(object) && inherits(object, "az_directory_role") } #' @rdname info #' @export is_aad_object <- function(object) { R6::is.R6(object) && inherits(object, "az_object") } #' @rdname info #' @export is_msgraph_object <- function(object) { R6::is.R6(object) && inherits(object, "ms_object") }
/scratch/gouwar.j/cran-all/cranData/AzureGraph/R/is.R
#' Microsoft Graph #' #' Base class for interacting with Microsoft Graph API. #' #' @docType class #' @section Methods: #' - `new(tenant, app, ...)`: Initialize a new Microsoft Graph connection with the given credentials. See 'Authentication' for more details. #' - `create_app(name, ..., add_password=TRUE, password_name=NULL, password_duration=2, certificate=NULL, create_service_principal=TRUE)`: Creates a new app registration in Azure Active Directory. See 'App creation' below. #' - `get_app(app_id, object_id)`: Retrieves an existing app registration, via either its app ID or object ID. #' - `list_apps(filter=NULL, n=Inf)`: Lists the app registrations in the current tenant. #' - `delete_app(app_id, object_id, confirm=TRUE)`: Deletes an existing app registration. Any associated service principal will also be deleted. #' - `create_service_principal(app_id, ...)`: Creates a service principal for a app registration. #' - `get_service_principal()`: Retrieves an existing service principal. #' - `list_service_principals(filter=NULL, n=Inf)`: Lists the service principals in the current tenant. #' - `delete_service_principal()`: Deletes an existing service principal. #' - `create_user(name, email, enabled=TRUE, ..., password=NULL, force_password_change=TRUE)`: Creates a new user account. By default this will be a work account (not social or local) in the current tenant, and will have a randomly generated password that must be changed at next login. #' - `get_user(user_id, email, name)`: Retrieves an existing user account. You can supply either the user ID, email address, or display name. The default is to return the logged-in user. #' - `list_users(filter=NULL, n=Inf)`: Lists the users in the current tenant. #' - `delete_user(user_id, email, name, confirm=TRUE)`: Deletes a user account. #' - `create_group(name, email, ...)`: Creates a new group. Note that only security groups can be created via the Microsoft Graph API. #' - `get_group(group_id, name)`: Retrieves an existing group. #' - `list_groups(filter=NULL, n=Inf)`: Lists the groups in the current tenant. #' - `delete_group(group_id, name, confirm=TRUE)`: Deletes a group. #' - `call_graph_endpoint(op="", ...)`: Calls the Microsoft Graph API using this object's token and tenant as authentication arguments. See [call_graph_endpoint]. #' - `call_batch_endpoint(requests=list(), ...)`: Calls the batch endpoint with a list of individual requests. See [call_batch_endpoint]. #' - `get_aad_object(id)`: Retrieves an arbitrary Azure Active Directory object by ID. #' #' @section Authentication: #' The recommended way to authenticate with Microsoft Graph is via the [create_graph_login] function, which creates a new instance of this class. #' #' To authenticate with the `ms_graph` class directly, provide the following arguments to the `new` method: #' - `tenant`: Your tenant ID. This can be a name ("myaadtenant"), a fully qualified domain name ("myaadtenant.onmicrosoft.com" or "mycompanyname.com"), or a GUID. #' - `app`: The client/app ID to use to authenticate with Azure Active Directory. The default is to login interactively using the Azure CLI cross-platform app, but it's recommended to supply your own app credentials if possible. #' - `password`: if `auth_type == "client_credentials"`, the app secret; if `auth_type == "resource_owner"`, your account password. #' - `username`: if `auth_type == "resource_owner"`, your username. #' - `certificate`: If `auth_type == "client_credentials", a certificate to authenticate with. This is a more secure alternative to using an app secret. #' - `auth_type`: The OAuth authentication method to use, one of "client_credentials", "authorization_code", "device_code" or "resource_owner". See [get_azure_token] for how the default method is chosen, along with some caveats. #' - `version`: The Azure Active Directory (AAD) version to use for authenticating. #' - `host`: your Microsoft Graph host. Defaults to `https://graph.microsoft.com/`. #' - `aad_host`: Azure Active Directory host for authentication. Defaults to `https://login.microsoftonline.com/`. Change this if you are using a government or private cloud. #' - `scopes`: The Microsoft Graph scopes (permissions) to obtain for this Graph login. Only for `version=2`. #' - `token`: Optionally, an OAuth 2.0 token, of class [AzureAuth::AzureToken]. This allows you to reuse the authentication details for an existing session. If supplied, all other arguments will be ignored. #' #' @section App creation: #' The `create_app` method creates a new app registration. By default, a new app will have a randomly generated strong password with duration of 2 years. To skip assigning a password, set the `add_password` argument to FALSE. #' #' The `certificate` argument allows authenticating via a certificate instead of a password. This should be a character string containing the certificate public key (aka the CER file). Alternatively it can be an list, or an object of class `AzureKeyVault::stored_cert` representing a certificate stored in an Azure Key Vault. See the examples below. #' #' A new app will also have a service principal created for it by default. To disable this, set `create_service_principal=FALSE`. #' #' @section List methods: #' All `list_*` methods have `filter` and `n` arguments to limit the number of results. The former should be an [OData expression](https://learn.microsoft.com/en-us/graph/query-parameters#filter-parameter) as a string to filter the result set on. The latter should be a number setting the maximum number of (filtered) results to return. The default values are `filter=NULL` and `n=Inf`. If `n=NULL`, the `ms_graph_pager` iterator object is returned instead to allow manual iteration over the results. #' #' Support in the underlying Graph API for OData queries is patchy. Not all endpoints that return lists of objects support filtering, and if they do, they may not allow all of the defined operators. If your filtering expression results in an error, you can carry out the operation without filtering and then filter the results on the client side. #' #' @seealso #' [create_graph_login], [get_graph_login] #' #' [Microsoft Graph overview](https://learn.microsoft.com/en-us/graph/overview), #' [REST API reference](https://learn.microsoft.com/en-us/graph/api/overview?view=graph-rest-1.0) #' #' @examples #' \dontrun{ #' #' # start a new Graph session #' gr <- ms_graph$new(tenant="myaadtenant.onmicrosoft.com") #' #' # authenticate with credentials in a file #' gr <- ms_graph$new(config_file="creds.json") #' #' # authenticate with device code #' gr <- ms_graph$new(tenant="myaadtenant.onmicrosoft.com", app="app_id", auth_type="device_code") #' #' # retrieve an app registration #' gr$get_app(app_id="myappid") #' #' # create a new app and associated service principal, set password duration to 10 years #' app <- gr$create_app("mynewapp", password_duration=10) #' #' # delete the app #' gr$delete_app(app_id=app$properties$appId) #' # ... but better to call the object's delete method directly #' app$delete() #' #' # create an app with authentication via a certificate #' cert <- readLines("mycert.cer") #' gr$create_app("mycertapp", password=FALSE, certificate=cert) #' #' # retrieving your own user details (assuming interactive authentication) #' gr$get_user() #' #' # retrieving another user's details #' gr$get_user("[email protected]") #' gr$get_user(email="[email protected]") #' gr$get_user(name="Hong Ooi") #' #' # get an AAD object (a group) #' id <- gr$get_user()$list_group_memberships()[1] #' gr$get_aad_object(id) #' #' # list the users in the tenant #' gr$list_users() #' #' # list (guest) users with a 'gmail.com' email address #' gr$list_users(filter="endsWith(mail,'gmail.com')") #' #' # list Microsoft 365 groups #' gr$list_groups(filter="groupTypes/any(c:c eq 'Unified')") #' #' } #' @format An R6 object of class `ms_graph`. #' @export ms_graph <- R6::R6Class("ms_graph", public=list( host=NULL, tenant=NULL, token=NULL, # authenticate and get subscriptions initialize=function(tenant="common", app=.az_cli_app_id, password=NULL, username=NULL, certificate=NULL, auth_type=NULL, version=2, host="https://graph.microsoft.com/", aad_host="https://login.microsoftonline.com/", scopes=".default", token=NULL, ...) { if(is_azure_token(token)) { self$host <- httr::build_url(find_resource_host(token)) self$tenant <- token$tenant self$token <- token return(NULL) } self$host <- host self$tenant <- normalize_tenant(tenant) app <- normalize_guid(app) if(version == 2) host <- c(paste0(host, scopes), "openid", "offline_access") self$token <- get_azure_token(resource=host, tenant=self$tenant, app=app, password=password, username=username, certificate=certificate, auth_type=auth_type, aad_host=aad_host, version=version, ...) NULL }, create_app=function(name, ..., add_password=TRUE, password_name=NULL, password_duration=2, certificate=NULL, create_service_principal=TRUE) { properties <- list(displayName=name, ...) if(!is_empty(certificate)) { key <- read_cert(certificate) properties <- modifyList(properties, list( keyCredentials=list(list( key=key, type="AsymmetricX509Cert", usage="verify" )) )) } res <- az_app$new( self$token, self$tenant, self$call_graph_endpoint("applications", body=properties, encode="json", http_verb="POST") ) if(create_service_principal) res$create_service_principal() if(add_password) res$add_password(password_name, password_duration) res }, get_app=function(app_id=NULL, object_id=NULL) { if(!is.null(app_id)) { op <- sprintf("applications?$filter=appId+eq+'%s'", app_id) az_app$new(self$token, self$tenant, self$call_graph_endpoint(op)$value[[1]]) } else if(!is.null(object_id)) { op <- file.path("applications", object_id) az_app$new(self$token, self$tenant, self$call_graph_endpoint(op)) } else stop("Must supply either app ID or object (directory) ID") }, delete_app=function(app_id=NULL, object_id=NULL, confirm=TRUE) { self$get_app(app_id, object_id)$delete(confirm=confirm) }, list_apps=function(filter=NULL, n=Inf) { opts <- list(`$filter`=filter, `$count`=if(!is.null(filter)) "true") hdrs <- if(!is.null(filter)) httr::add_headers(consistencyLevel="eventual") pager <- ms_graph_pager$new(self$token, self$call_graph_endpoint("applications", options=opts, hdrs)) extract_list_values(pager, n) }, create_service_principal=function(app_id, ...) { self$get_app(app_id)$create_service_principal(...) }, get_service_principal=function(app_id=NULL, object_id=NULL) { if(!is.null(app_id) && is_guid(app_id)) { op <- sprintf("servicePrincipals?$filter=appId+eq+'%s'", app_id) az_service_principal$new(self$token, self$tenant, self$call_graph_endpoint(op)$value[[1]]) } else if(!is.null(object_id) && is_guid(object_id)) { op <- file.path("servicePrincipals", object_id) az_service_principal$new(self$token, self$tenant, self$call_graph_endpoint(op)) } else stop("Must supply either app ID or object (directory) ID") }, delete_service_principal=function(app_id=NULL, object_id=NULL, confirm=TRUE) { self$get_service_principal(app_id, object_id)$delete(confirm=confirm) }, list_service_principals=function(filter=NULL, n=Inf) { opts <- list(`$filter`=filter, `$count`=if(!is.null(filter)) "true") hdrs <- if(!is.null(filter)) httr::add_headers(consistencyLevel="eventual") pager <- ms_graph_pager$new(self$token, self$call_graph_endpoint("servicePrincipals", options=opts, hdrs)) extract_list_values(pager, n) }, create_user=function(name, email, enabled=TRUE, ..., password=NULL, force_password_change=TRUE) { properties <- list( displayName=name, mail=email, userPrincipalName=email, mailNickname=email, accountEnabled=enabled ) properties <- modifyList(properties, list(...)) if(is.null(password)) password <- openssl::base64_encode(openssl::rand_bytes(40)) properties <- modifyList(properties, list( passwordProfile=list( password=password, forceChangePasswordNextSignIn=force_password_change, forceChangePasswordNextSignInWithMfa=FALSE ) )) az_user$new( self$token, self$tenant, self$call_graph_endpoint("users", body=properties, encode="json", http_verb="POST"), password ) }, get_user=function(user_id=NULL, name=NULL, email=NULL) { has_id <- !is.null(user_id) has_name <- !is.null(name) has_email <- !is.null(email) if(has_id + has_email + has_name > 1) stop("Supply one of user ID, email or display name", call.=FALSE) if(has_email || has_name) { filter <- if(has_email) sprintf("mail eq '%s'", email) else sprintf("displayName eq '%s'", name) users <- self$list_users(filter=filter) if(length(users) != 1) stop("Invalid user email or name", call.=FALSE) return(users[[1]]) } op <- if(!has_id) "me" else file.path("users", curl::curl_escape(user_id)) az_user$new(self$token, self$tenant, self$call_graph_endpoint(op)) }, delete_user=function(user_id=NULL, name=NULL, email=NULL, confirm=TRUE) { self$get_user(user_id, email, name)$delete(confirm=confirm) }, list_users=function(filter=NULL, n=Inf) { opts <- list(`$filter`=filter, `$count`=if(!is.null(filter)) "true") hdrs <- if(!is.null(filter)) httr::add_headers(consistencyLevel="eventual") pager <- ms_graph_pager$new(self$token, self$call_graph_endpoint("users", options=opts, hdrs)) extract_list_values(pager, n) }, create_group=function(name, email, ...) { properties <- list( displayName=name, mailEnabled=FALSE, mailNickname=email, securityEnabled=TRUE ) az_group$new( self$token, self$tenant, self$call_graph_endpoint("groups", body=properties, encode="json", http_verb="POST") ) }, get_group=function(group_id=NULL, name=NULL) { has_id <- !is.null(group_id) has_name <- !is.null(name) if(has_id + has_name != 1) stop("Supply one of group ID or display name", call.=FALSE) if(has_name) { filter <- sprintf("displayName eq '%s'", name) grps <- self$list_groups(filter=filter) if(length(grps) != 1) stop("Invalid group name", call.=FALSE) return(grps[[1]]) } op <- file.path("groups", group_id) az_group$new(self$token, self$tenant, self$call_graph_endpoint(op)) }, delete_group=function(group_id=NULL, name=NULL, confirm=TRUE) { self$get_group(group_id, name)$delete(confirm=confirm) }, list_groups=function(filter=NULL, n=Inf) { opts <- list(`$filter`=filter, `$count`=if(!is.null(filter)) "true") hdrs <- if(!is.null(filter)) httr::add_headers(consistencyLevel="eventual") pager <- ms_graph_pager$new(self$token, self$call_graph_endpoint("groups", options=opts, hdrs)) extract_list_values(pager, n) }, call_graph_endpoint=function(op="", ...) { call_graph_endpoint(self$token, op, ...) }, call_batch_endpoint=function(requests=list(), ...) { call_batch_endpoint(self$token, requests, ...) }, get_aad_object=function(id) { res <- self$call_graph_endpoint(file.path("directoryObjects", id)) gen <- find_class_generator(res, type_filter=NULL) gen$new(self$token, self$tenant, res) }, print=function(...) { cat("<Microsoft Graph client>\n") cat("<Authentication>\n") fmt_token <- gsub("\n ", "\n ", format_auth_header(self$token)) cat(" ", fmt_token) cat("---\n") cat(format_public_methods(self)) invisible(self) } )) assert_one_arg <- function(..., msg) { arglst <- list(...) nulls <- sapply(arglst, is.null) if(sum(!nulls) != 1) stop(msg, call.=FALSE) }
/scratch/gouwar.j/cran-all/cranData/AzureGraph/R/ms_graph.R
#' Pager object for Graph list results #' #' Class representing an _iterator_ for a set of paged query results. #' #' @docType class #' @section Fields: #' - `token`: The token used to authenticate with the Graph host. #' - `output`: What the pager should yield on each iteration, either "data.frame","list" or "object". See 'Value' below. #' @section Methods: #' - `new(...)`: Initialize a new user object. See 'Initialization' below. #' - `has_data()`: Returns TRUE if there are pages remaining in the iterator, or FALSE otherwise. #' @section Active bindings: #' - `value`: The returned value on each iteration of the pager. #' #' @section Initialization: #' The recommended way to create objects of this class is via the `ms_object$get_list_pager()` method, but it can also be initialized directly. The arguments to the `new()` method are: #' - `token`: The token used to authenticate with the Graph host. #' - `first_page`: A list containing the first page of results, generally from a call to `call_graph_endpoint()` or the `do_operation()` method of an AzureGraph R6 object. #' - `next_link_name,value_name`: The names of the components of `first_page` containing the link to the next page, and the set of values for the page respectively. The default values are `@odata.nextLink` and `value`. #' - `generate_objects`: Whether the iterator should return a list containing the parsed JSON for the page values, or convert it into a list of R6 objects. See 'Value' below. #' - `type_filter`: Any extra arguments required to initialise the returned objects. Only used if `generate_objects` is TRUE. #' - `default_generator`: The default generator object to use when converting a list of properties into an R6 object, if the class can't be detected. Defaults to `ms_object`. Only used if `generate_objects` is TRUE. #' - `...`: Any extra arguments required to initialise the returned objects. Only used if `generate_objects` is TRUE. #' #' @section Value: #' The `value` active binding returns the page values for each iteration of the pager. This can take one of 3 forms, based on the initial format of the first page and the `generate_objects` argument. #' #' If the first page of results is a data frame (each item has been converted into a row), then the pager will return results as data frames. In this case, the `output` field is automatically set to "data.frame" and the `generate_objects` initialization argument is ignored. Usually this will be the case when the results are meant to represent external data, eg items in a SharePoint list. #' #' If the first page of results is a list, the `generate_objects` argument sets whether to convert the items in each page into R6 objects defined by the AzureGraph class framework. If `generate_objects` is TRUE, the `output` field is set to "object", and if `generate_objects` is FALSE, the `output` field is set to "list". #' #' @seealso #' [ms_object], [extract_list_values] #' #' [Microsoft Graph overview](https://learn.microsoft.com/en-us/graph/overview), #' [Paging documentation](https://learn.microsoft.com/en-us/graph/paging) #' #' @examples #' \dontrun{ #' #' # list direct memberships #' firstpage <- call_graph_endpoint(token, "me/memberOf") #' #' pager <- ms_graph_pager$new(token, firstpage) #' pager$has_data() #' pager$value #' #' # once all the pages have been returned #' isFALSE(pager$has_data()) #' is.null(pager$value) #' #' # returning items, 1 per page, as raw lists of properties #' firstpage <- call_graph_endpoint(token, "me/memberOf", options=list(`$top`=1)) #' pager <- ms_graph_pager$new(token, firstpage, generate_objects=FALSE) #' lst <- NULL #' while(pager$has_data()) #' lst <- c(lst, pager$value) #' #' # returning items as a data frame #' firstdf <- call_graph_endpoint(token, "me/memberOf", options=list(`$top`=1), #' simplify=TRUE) #' pager <- ms_graph_pager$new(token, firstdf) #' df <- NULL #' while(pager$has_data()) #' df <- vctrs::vec_rbin(df, pager$value) #' #' } #' @format An R6 object of class `ms_graph_pager`. #' @export ms_graph_pager <- R6::R6Class("ms_graph_pager", public=list( token=NULL, output=NULL, initialize=function(token, first_page, next_link_name="@odata.nextLink", value_name="value", generate_objects=TRUE, type_filter=NULL, default_generator=ms_object, ...) { self$token <- token private$value_name <- value_name private$next_link_name <- next_link_name private$type_filter <- type_filter private$default_generator <- default_generator private$init_args <- list(...) self$output <- if(is.data.frame(first_page$value)) "data.frame" else if(generate_objects) "object" else "list" private$next_link <- first_page[[next_link_name]] private$next_value <- first_page[[value_name]] }, has_data=function() { !is.null(private$next_value) }, print=function(...) { cat("<Graph pager object>\n", sep="") cat(" output:", self$output, "\n") cat(" has data:", self$has_data(), "\n") invisible(self) } ), active=list( value=function() { val <- private$next_value private$next_value <- if(!is.null(private$next_link)) { page <- call_graph_url(self$token, private$next_link, simplify=(self$output == "data.frame")) private$next_link <- page[[private$next_link_name]] page[[private$value_name]] } else NULL if(self$output == "object") private$make_objects(val) else val } ), private=list( next_link_name=NULL, value_name=NULL, next_link=NULL, next_value=NULL, type_filter=NULL, default_generator=NULL, init_args=NULL, make_objects=function(page) { if(is_empty(page)) return(list()) page <- lapply(page, function(obj) { class_gen <- find_class_generator(obj, private$type_filter, private$default_generator) if(is.null(class_gen)) NULL else do.call(class_gen$new, c(list(self$token, self$tenant, obj), private$init_args)) }) page[!sapply(page, is.null)] } )) #' Get the list of values from a Graph pager object #' #' @param pager An object of class `ms_graph_pager`, which is an iterator for a list of paged query results. #' @param n The number of items from the list to return. Note this is _not_ the number of _pages_ (each page will usually contain multiple items). The default value of `Inf` extracts all the values from the list, leaving the pager empty. If this is NULL, the pager itself is returned. #' #' @details #' This is a convenience function to perform the common task of extracting all or some of the items from a paged response. #' #' @return #' If `n` is `Inf` or a number, the items from the paged query results. The format of the returned value depends on the pager settings. This will either be a nested list containing the properties for each of the items; a list of R6 objects; or a data frame. If the pager is empty, an error is thrown. #' #' If `n` is NULL, the pager itself is returned. #' #' @seealso #' [ms_graph_pager], [ms_object], [call_graph_endpoint] #' #' @examples #' \dontrun{ #' #' firstpage <- call_graph_endpoint(token, "me/memberOf") #' pager <- ms_graph_pager$new(token, firstpage) #' extract_list_values(pager) #' #' # trying to extract values a 2nd time will fail #' try(extract_list_values(pager)) #' #' } #' @export extract_list_values <- function(pager, n=Inf) { if(is.null(n)) return(pager) if(!pager$has_data()) stop("Pager is empty", call.=FALSE) bind_fn <- if(pager$output != "data.frame") base::c else if(requireNamespace("vctrs", quietly=TRUE)) vctrs::vec_rbind else base::rbind res <- NULL while(pager$has_data() && NROW(res) < n) # not nrow() res <- bind_fn(res, pager$value) if(NROW(res) > n) utils::head(res, n) else res }
/scratch/gouwar.j/cran-all/cranData/AzureGraph/R/ms_graph_pager.R
#' Microsoft Graph object #' #' Base class representing a object in Microsoft Graph. All other Graph object classes ultimately inherit from this class. #' #' @docType class #' @section Fields: #' - `token`: The token used to authenticate with the Graph host. #' - `tenant`: The Azure Active Directory tenant for this object. #' - `type`: The type of object, in a human-readable format. #' - `properties`: The object properties, as obtained from the Graph host. #' @section Methods: #' - `new(...)`: Initialize a new directory object. Do not call this directly; see 'Initialization' below. #' - `delete(confirm=TRUE)`: Delete an object. By default, ask for confirmation first. #' - `update(...)`: Update the object information in Azure Active Directory. #' - `do_operation(...)`: Carry out an arbitrary operation on the object. #' - `sync_fields()`: Synchronise the R object with the data in Azure Active Directory. #' - `get_list_pager(...)`: Returns a pager object, which is an _iterator_ for a set of paged query results. See 'Paged results' below. #' #' @section Initialization: #' Objects of this class should not be created directly. Instead, create an object of the appropriate subclass. #' #' @section List methods: #' All `list_*` methods have `filter` and `n` arguments to limit the number of results. The former should be an [OData expression](https://learn.microsoft.com/en-us/graph/query-parameters#filter-parameter) as a string to filter the result set on. The latter should be a number setting the maximum number of (filtered) results to return. The default values are `filter=NULL` and `n=Inf`. If `n=NULL`, the `ms_graph_pager` iterator object is returned instead to allow manual iteration over the results. #' #' Support in the underlying Graph API for OData queries is patchy. Not all endpoints that return lists of objects support filtering, and if they do, they may not allow all of the defined operators. If your filtering expression results in an error, you can carry out the operation without filtering and then filter the results on the client side. #' #' @section Paged results: #' Microsoft Graph returns lists in pages, with each page containing a subset of objects and a link to the next page. AzureGraph provides an iterator-based API that lets you access each page individually, or collect them all into a single object. #' #' To create a new pager object, call the `get_list_pager()` method with the following arguments: #' - `lst`: A list containing the first page of results, generally from a call to the `do_operation()` method. #' - `next_link_name,value_name`: The names of the components of `first_page` containing the link to the next page, and the set of values for the page respectively. The default values are `@odata.nextLink` and `value`. #' - `generate_objects`: Whether the iterator should return a list containing the parsed JSON for the page values, or convert it into a list of R6 objects. #' - `type_filter`: Any extra arguments required to initialise the returned objects. Only used if `generate_objects` is TRUE. #' - `default_generator`: The default generator object to use when converting a list of properties into an R6 object, if the class can't be detected. Defaults to `ms_object`. Only used if `generate_objects` is TRUE. #' - `...`: Any extra arguments required to initialise the returned objects. Only used if `generate_objects` is TRUE. #' #' This returns an object of class [ms_graph_pager], which is an _iterator_ for the set of paged results. Each call to the object's `value` active binding yields the next page. When all pages have been returned, `value` contains NULL. #' #' The format of the returned values can take one of 3 forms, based on the initial format of the first page and the `generate_objects` argument. #' #' If the first page of results is a data frame (each item has been converted into a row), then the pager will return results as data frames. In this case, the `output` field is automatically set to "data.frame" and the `generate_objects` initialization argument is ignored. Usually this will be the case when the results are meant to represent external data, eg items in a SharePoint list. #' #' If the first page of results is a list, the `generate_objects` argument sets whether to convert the items in each page into R6 objects defined by the AzureGraph class framework. If `generate_objects` is TRUE, the `output` field is set to "object", and if `generate_objects` is FALSE, the `output` field is set to "list". #' #' You can also call the `extract_list_values()` function to get all or some of the values from a pager, without having to manually combine the pages together. #' #' @section Deprecated methods: #' The following methods are private and **deprecated**, and form the older AzureGraph API for accessing paged results. They will eventually be removed. #' - `get_paged_list(lst, next_link_name, value_name, simplify, n)`: This method reconstructs the list, given the first page. #' - `init_list_objects(lst, type_filter, default_generator, ...)`: `get_paged_list` returns a raw list, the result of parsing the JSON response from the Graph host. This method converts the list into actual R6 objects. #' #' @seealso #' [ms_graph], [az_object], [ms_graph_pager], [extract_list_values] #' #' [Microsoft Graph overview](https://learn.microsoft.com/en-us/graph/overview), #' [REST API reference](https://learn.microsoft.com/en-us/graph/api/overview?view=graph-rest-1.0) #' #' @format An R6 object of class `ms_object`. #' @export ms_object <- R6::R6Class("ms_object", public=list( token=NULL, tenant=NULL, # user-readable object type type=NULL, # object data from server properties=NULL, initialize=function(token, tenant=NULL, properties=NULL) { self$token <- token self$tenant <- tenant self$properties <- properties }, update=function(...) { self$do_operation(body=list(...), encode="json", http_verb="PATCH") self$properties <- self$do_operation() self }, sync_fields=function() { self$properties <- self$do_operation() invisible(self) }, delete=function(confirm=TRUE) { if(confirm && interactive()) { name <- self$properties$displayName if(is.null(name)) name <- self$properties$name if(is.null(name)) name <- self$properties$id msg <- sprintf("Do you really want to delete the %s '%s'?", self$type, name) if(!get_confirmation(msg, FALSE)) return(invisible(NULL)) } self$do_operation(http_verb="DELETE") invisible(NULL) }, do_operation=function(op="", ...) { op <- construct_path(private$api_type, self$properties$id, op) call_graph_endpoint(self$token, op, ...) }, get_list_pager=function(lst, next_link_name="@odata.nextLink", value_name="value", generate_objects=TRUE, type_filter=NULL, default_generator=ms_object, ...) { ms_graph_pager$new(self$token, lst, next_link_name, value_name, generate_objects, type_filter, default_generator, ...) }, print=function(...) { cat("<Graph directory object '", self$properties$displayName, "'>\n", sep="") cat(" directory id:", self$properties$id, "\n") cat("---\n") cat(format_public_methods(self)) invisible(self) } ), private=list( # object type as it appears in REST API path api_type=NULL, get_paged_list=function(lst, next_link_name="@odata.nextLink", value_name="value", simplify=FALSE, n=Inf) { bind_fn <- if(requireNamespace("vctrs", quietly=TRUE)) vctrs::vec_rbind else base::rbind res <- lst[[value_name]] if(n <= 0) n <- Inf while(!is_empty(lst[[next_link_name]]) && NROW(res) < n) { lst <- call_graph_url(self$token, lst[[next_link_name]], simplify=simplify) res <- if(simplify) bind_fn(res, lst[[value_name]]) # base::rbind assumes all objects have the exact same fields else c(res, lst[[value_name]]) } if(n < NROW(res)) { if(inherits(res, "data.frame")) res[seq_len(n), ] else res[seq_len(n)] } else res }, init_list_objects=function(lst, type_filter=NULL, default_generator=ms_object, ...) { lst <- lapply(lst, function(obj) { class_gen <- find_class_generator(obj, type_filter, default_generator) if(is.null(class_gen)) NULL else class_gen$new(self$token, self$tenant, obj, ...) }) lst[!sapply(lst, is.null)] } ))
/scratch/gouwar.j/cran-all/cranData/AzureGraph/R/ms_object.R
# get certificate details to add to an app read_cert <- function(cert) { UseMethod("read_cert") } read_cert.character <- function(cert) { if(file.exists(cert)) read_cert_file(cert) else paste0(cert, collapse="") } read_cert.raw <- function(cert) { openssl::base64_encode(cert) } read_cert.rawConnection <- function(cert) { openssl::base64_encode(rawConnectionValue(cert)) } # AzureKeyVault::stored_cert read_cert.stored_cert <- function(cert) { cert$cer } # openssl::cert read_cert.cert <- function(cert) { openssl::base64_encode(cert) } read_cert_file <- function(file) { ext <- tolower(tools::file_ext(file)) if(ext == "pem") { pem <- openssl::read_cert(file) openssl::base64_encode(pem) } else if(ext %in% c("p12", "pfx")) { pfx <- openssl::read_p12(file) pfx$cert } else stop("Unsupported file extension: ", ext, call.=FALSE) }
/scratch/gouwar.j/cran-all/cranData/AzureGraph/R/read_cert.R
#' Miscellaneous utility functions #' #' @param lst A named list of objects. #' @param name_fields The components of the objects in `lst`, to be used as names. #' @param x For `is_empty`, An R object. #' @details #' `named_list` extracts from each object in `lst`, the components named by `name_fields`. It then constructs names for `lst` from these components, separated by a `"/"`. #' #' @return #' For `named_list`, the list that was passed in but with names. An empty input results in a _named list_ output: a list of length 0, with a `names` attribute. #' #' For `is_empty`, whether the length of the object is zero (this includes the special case of `NULL`). #' #' @rdname utils #' @export named_list <- function(lst=NULL, name_fields="name") { if(is_empty(lst)) return(structure(list(), names=character(0))) lst_names <- sapply(name_fields, function(n) sapply(lst, `[[`, n)) if(length(name_fields) > 1) { dim(lst_names) <- c(length(lst_names) / length(name_fields), length(name_fields)) lst_names <- apply(lst_names, 1, function(nn) paste(nn, collapse="/")) } names(lst) <- lst_names dups <- duplicated(tolower(names(lst))) if(any(dups)) { duped_names <- names(lst)[dups] warning("Some names are duplicated: ", paste(unique(duped_names), collapse=" "), call.=FALSE) } lst } #' @rdname utils #' @export is_empty <- function(x) { length(x) == 0 }
/scratch/gouwar.j/cran-all/cranData/AzureGraph/R/utils.R
#' Extensible registry of Microsoft Graph classes that AzureGraph supports #' #' @param name The name of the Graph class, eg "user", "servicePrincipal", etc. #' @param R6_generator An R6 class generator corresponding to this Graph class. #' @param check_function A boolean function that checks if a list of properties is for an object of this class. #' @details #' As written, AzureGraph knows about a subset of all the object classes contained in Microsoft Graph. These are mostly the classes originating from Azure Active Directory: users, groups, app registrations, service principals and registered devices. #' #' You can extend AzureGraph by writing your own R6 class that inherits from `ms_object`. If so, you should also _register_ your class by calling `register_graph_class` and providing the generator object, along with a check function. The latter should accept a list of object properties (as obtained from the Graph REST API), and return TRUE/FALSE based on whether the object is of your class. #' #' @return #' An invisible vector of registered class names. #' @examples #' \dontrun{ #' #' # built-in 'az_user' class, for an AAD user object #' register_graph_class("user", az_user, #' function(props) !is.null(props$userPrincipalName)) #' #' } #' @export register_graph_class <- function(name, R6_generator, check_function) { if(!R6::is.R6Class(R6_generator)) stop("R6_generator should be an R6 class generator object", call.=FALSE) if(!is.function(check_function)) stop("check_function should be a function") .graph_classes[[name]] <- list( generator=R6_generator, check=check_function ) invisible(ls(.graph_classes)) } .graph_classes <- new.env() # classes supplied by AzureGraph register_graph_class("user", az_user, function(props) !is.null(props$userPrincipalName)) register_graph_class("group", az_group, function(props) !is.null(props$groupTypes)) register_graph_class("application", az_app, function(props) !is.null(props$appId) && is.null(props$servicePrincipalType)) register_graph_class("servicePrincipal", az_service_principal, function(props) !is.null(props$appId) && !is.null(props$servicePrincipalType)) register_graph_class("device", az_device, function(props) !is.null(props$publishingState)) register_graph_class("directoryRole", az_directory_role, function(props) !is.null(props$roleTemplateId)) #' Find the R6 class for a Graph object #' #' @param props A list of object properties, generally the result of a Graph API call. #' @param type_filter An optional vector of types by which to filter the result. #' @param default_generator The default class generator to use, if a match couldn't be found. #' @details #' This function maps Graph objects to AzureGraph classes. #' @return #' An R6 class generator for the appropriate AzureGraph class. If no matching R6 class could be found, the default generator is returned. If `type_filter` is provided, but the matching R6 class isn't in the filter, NULL is returned. #' @export find_class_generator <- function(props, type_filter=NULL, default_generator=ms_object) { # use ODATA metadata if available if(!is.null(props$`@odata.type`)) { type <- sub("^#microsoft.graph.", "", props$`@odata.type`) if(!(type %in% ls(.graph_classes))) type <- NA } else # check for each known type in turn { type <- NA for(n in ls(.graph_classes)) { if(.graph_classes[[n]]$check(props)) { type <- n break } } } # here, 'type' will be one of the known types or NA for unknown # always return the default class if unknown, even if a type filter is provided if(is.na(type)) return(default_generator) if(is.null(type_filter) || type %in% type_filter) .graph_classes[[type]]$generator else NULL }
/scratch/gouwar.j/cran-all/cranData/AzureGraph/R/zzz_class_directory.R
--- title: "Authentication basics" author: Hong Ooi output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Authentication} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{utf8} --- There are a number of ways to authenticate to the Microsoft Graph API with AzureGraph. This vignette goes through the most common scenarios. ## Interactive authentication This is the scenario where you're using R interactively, such as in your local desktop or laptop, or in a hosted RStudio Server, Jupyter notebook or ssh session. The first time you authenticate with AzureGraph, you run `create_graph_login()`: ```r # on first use library(AzureGraph) gr <- create_graph_login() ``` Notice that you _don't_ enter your username and password. AzureGraph will attempt to detect which authentication flow to use, based on your session details. In most cases, it will bring up the Azure Active Directory (AAD) login page in your browser, which is where you enter your user credentials. This is also known as the "authorization code" flow. There are some complications to be aware of: - If you are running R in a hosted session, trying to start a browser will usually fail. In this case, specify the device code authentication flow, with the `auth_type` argument: ```r gr <- create_graph_login(auth_type="device_code") ``` - If you have a personal account that is also a guest in an organisational tenant, you may have to specify your tenant explicitly: ```r gr <- create_graph_login(tenant="yourtenant") ``` - By default, AzureGraph identifies itself using the Azure CLI app registration ID. This is meant for working with the AAD part of the Graph API, so it has permissions which are relevant for this purpose. If you are using Graph for other purposes (eg to interact with Microsoft 365 services), you'll need to supply your own app ID that has the correct permissions. On the client side, you supply the app ID via the `app` argument; see later for creating the app registration on the server side. ```r gr <- create_graph_login(app="yourappid") ``` All of the above arguments can be combined, eg this will authenticate using the device code flow, with an explicit tenant name, and a custom app ID: ```r gr <- create_graph_login(tenant="yourtenant", app="yourappid", auth_type="device_code") ``` If needed, you can also supply other arguments that will be passed to `AzureAuth::get_azure_token()`. Having created the login, in subsequent sessions you run `get_graph_login()`. This will load your previous authentication details, saving you from having to login again. If you specified the tenant in the `create_graph_login()` call, you'll also need to specify it for `get_graph_login()`; the other arguments don't have to be repeated. ```r gr <- get_graph_login() # if you specified the tenant in create_graph_login gr <- get_graph_login(tenant="yourtenant") ``` ## Non-interactive authentication This is the scenario where you want to use AzureGraph as part of an automated script or unattended session, for example in a deployment pipeline. The appropriate authentication flow in this case is the client credentials flow. For this scenario, you must have a custom app ID and client secret. On the client side, these are supplied in the `app` and `password` arguments; see later for creating the app registration on the server side. You must also specify your tenant as AAD won't be able to detect it from a user's credentials. ```r gr <- create_graph_login(tenant="yourtenant", app="yourccappid", password="client_secret") ``` In the non-interactive scenario, you don't use `get_graph_login()`; instead, you simply call `create_graph_login()` as part of your script. ## Creating a custom app registration This part is meant mostly for Azure tenant administrators, or users who have the appropriate rights to create AAD app registrations. You can create a new app registration using any of the usual methods. For example to create an app registration in the Azure Portal (`https://portal.azure.com/`), click on "Azure Active Directory" in the menu bar down the left, go to "App registrations" and click on "New registration". Name the app something suitable, eg "AzureGraph custom app". - If you want your users to be able to login with the authorization code flow, you must add a **public client/native redirect URI** of `http://localhost:1410`. This is appropriate if your users will be running R on their local PCs, with an Internet browser available. - If you want your users to be able to login with the device code flow, you must **enable the "Allow public client flows" setting** for your app. In the Portal, you can find this setting in the "Authentication" pane once the app registration is complete. This is appropriate if your users are running R in a remote session. - If the app is meant for non-interactive use, you must give the app a **client secret**, which is much the same as a password (and should similarly be kept secure). In the Portal, you can set this in the "Certificates and Secrets" pane for your app registration. Once the app registration has been created, note the app ID and, if applicable, the client secret. The latter can't be viewed after app creation, so make sure you note its value now. It's also possible to authenticate with a **client certificate (public key)**, but this is more complex and we won't go into it here. For more details, see the [Azure Active Directory documentation](https://learn.microsoft.com/en-au/azure/active-directory/develop/v2-oauth2-client-creds-grant-flow) and the [AzureAuth intro vignette](https://cran.r-project.org/package=AzureAuth/vignettes/token.html). ### Set the app permissions For your app to be useful, you must give it the appropriate permisssions for the Microsoft Graph API. You can set this by going to the "API permissions" pane for your app registration, then clicking on "Add a permission". Choose the Microsoft Graph API, and then enable the permissions that you need. - For interactive use, make sure that you enable the _delegated_ permissions. These apply when a logged-in user is present. [See the documentation](https://learn.microsoft.com/en-us/graph/auth/auth-concepts#microsoft-graph-permissions) for how permissions and user roles interact; essentially, if a user wants to use AzureGraph to do an action, they must have the correct role _and_ the app registration must have the correct permission. - It's highly recommended to enable the "offline_access" permission for an interactive app, as this is necessary to obtain refresh tokens. Without these, a user must reauthenticate each time their access token expires, which by default is after one hour. - For non-interactive use, enable the _application_ permissions. These are more powerful since there is no user role that can moderate what AzureGraph can do, so assign application permissions with caution.
/scratch/gouwar.j/cran-all/cranData/AzureGraph/inst/doc/auth.Rmd
--- title: "Batching and paging" author: Hong Ooi output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Batching and Paging} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{utf8} --- This vignette describes a couple of special interfaces that are available in Microsoft Graph, and how to use them in AzureGraph. ## Batching The batch API allows you to combine multiple requests into a single batch call, potentially resulting in significant performance improvements. If all the requests are independent, they can be executed in parallel, so that they only take the same time as a single request. If the requests depend on each other, they must be executed serially, but even in this case you benefit by not having to make multiple HTTP requests with the associated network overhead. For example, let's say you want to get the object information for all the Azure Active Directory groups, directory roles and admin units you're a member of. The `az_object$list_object_memberships()` method returns the IDs for these objects, but to get the remaining object properties, you have to call the `directoryObjects` API endpoint for each individual ID. Rather than making separate calls for every ID, let's combine them into a single batch request. ```r gr <- get_graph_login() me <- gr$get_user() # get the AAD object IDs obj_ids <- me$list_object_memberships(security_only=FALSE) ``` AzureGraph represents a single request with the `graph_request` R6 class. To create a new request object, call `graph_request$new()` with the following arguments: - `op`: The operation to carry out, eg `/me/drives`. - `body`: The body of the HTTPS request, if it is a PUT, POST or PATCH. - `options`: A list containing the query parameters for the URL, for example OData parameters. - `headers`: Any optional HTTP headers for the request. - `encode`: If a request body is present, how it should be encoded when sending it to the endpoint. The default is `json`, meaning it will be sent as JSON text; an alternative is `raw`, for binary data. - `http_verb`: One of "GET" (the default), "DELETE", "PUT", "POST", "HEAD", or "PATCH". For this example, only `op` is required. ```r obj_reqs <- lapply(obj_ids, function(id) { op <- file.path("directoryObjects", id) graph_request$new(op) }) ``` To make a request to the batch endpoint, use the `call_batch_endpoint()` function, or the `ms_graph$call_batch_endpoint()` method. This takes as arguments a list of individual requests, as well as an optional named vector of dependencies. The result of the call is a list of the responses from the requests; each response will have components named `id` and `status`, and usually `body` as well. In this case, there are no dependencies between the individual requests, so the code is very simple. Simply use the `call_batch_endpoint()` method with the request list; then run the `find_class_generator()` function to get the appropriate class generator for each list of object properties, and instantiate a new object. ```r objs <- gr$call_batch_endpoint(obj_reqs) lapply(objs, function(obj) { cls <- find_class_generator(obj) cls$new(gr$token, gr$tenant, obj$body) }) ``` ## Paging Some Microsoft Graph calls return multiple results. In AzureGraph, these calls are generally those represented by methods starting with `list_*`, eg the `list_object_memberships` method used previously. Graph handles result sets by breaking them into _pages_, with each page containing several results. The built-in AzureGraph methods will generally handle paging automatically, without you needing to be aware of the details. If necessary however, you can also carry out a paged request and handle the results manually. The starting point for a paged request is a regular Graph call to an endpoint that returns a paged response. For example, let's take the `memberOf` endpoint, which returns the groups of which a user is a member. Calling this endpoint returns the first page of results, along with a link to the next page. ```r res <- me$do_operation("memberOf") ``` Once you have the first page, you can use that to instantiate a new object of class `ms_graph_pager`. This is an _iterator_ object: each time you access data from it, you retrieve a new page of results. If you have used other programming languages such as Python, Java or C#, the concept of iterators should be familiar. If you're a user of the foreach package, you'll also have used iterators: foreach depends on the iterators package, which implements the same concept using S3 classes. The easiest way to instantiate a new pager object is via the `get_list_pager()` method. Once instantiated, you access the `value` active binding to retrieve each page of results, starting from the first page. ```r pager <- me$get_list_pager(res) pager$value # [[1]] # <Security group 'secgroup'> # directory id: cd806a5f-9d19-426c-b34b-3a3ec662ecf2 # description: test security group # --- # Methods: # delete, do_operation, get_list_pager, list_group_memberships, # list_members, list_object_memberships, list_owners, sync_fields, # update # [[2]] # <Azure Active Directory role 'Global Administrator'> # directory id: df643f93-3d9d-497f-8f2e-9cfd4c275e41 # description: Can manage all aspects of Azure AD and Microsoft services that use Azure # AD identities. # --- # Methods: # delete, do_operation, get_list_pager, list_group_memberships, # list_members, list_object_memberships, sync_fields, update ``` Once there are no more pages, calling `value` returns an empty result. ```r pager$value # list() ``` By default, as shown above, the pager object will create new AzureGraph R6 objects from the properties for each item in the results. You can customise the output in the following ways: - If the first page of results consists of a data frame, rather than a list of items, the pager will continue to output data frames. This is most useful when the results are meant to represent external, tabular data, eg items in a SharePoint list or files in a OneDrive folder. Some AzureGraph methods will automatically request data frame output; if you want this from a manual REST API call, specify `simplify=TRUE` in the `do_operation()` call. - You can suppress the conversion of the item properties into an R6 object by specifying `generate_objects=FALSE` in the `get_list_pager()` call. In this case, the pager will return raw lists. AzureGraph also provides the `extract_list_values()` function to perform the common task of getting all or some of the values from a paged result set. Rather than reading `pager$value` repeatedly until there is no data left, you can simply call: ```r extract_list_values(pager) ``` To restrict the output to only the first N items, call `extract_list_values(pager, n=N)`. However, note that the result set from a paged query usually isn't ordered in any way, so the items you get will be arbitrary.
/scratch/gouwar.j/cran-all/cranData/AzureGraph/inst/doc/batching_paging.Rmd
--- title: "Extending AzureGraph" author: Hong Ooi output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Extending} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{utf8} --- As written, AzureGraph provides support for Microsoft Graph objects derived from Azure Active Directory (AAD): users, groups, app registrations and service principals. This vignette describes how to extend it to support other services. ## Extend the `ms_object` base class AzureGraph provides the `ms_object` class to represent a generic object in Graph. You can extend this to support specific services by adding custom methods and fields. For example, the [Microsoft365R](https://github.com/Azure/Microsoft365R) package extends AzureGraph to support SharePoint Online sites and OneDrive filesystems (both personal and business). This is the `ms_site` class from that package, which represents a SharePoint site. To save space, the actual code in the new methods has been elided. ```r ms_site <- R6::R6Class("ms_site", inherit=ms_object, public=list( initialize=function(token, tenant=NULL, properties=NULL) { self$type <- "site" private$api_type <- "sites" super$initialize(token, tenant, properties) }, list_drives=function() {}, # ... get_drive=function(drive_id=NULL) {}, # ... list_subsites=function() {}, # ... get_list=function(list_name=NULL, list_id=NULL) {}, # ... print=function(...) { cat("<Sharepoint site '", self$properties$displayName, "'>\n", sep="") cat(" directory id:", self$properties$id, "\n") cat(" web link:", self$properties$webUrl, "\n") cat(" description:", self$properties$description, "\n") cat("---\n") cat(format_public_methods(self)) invisible(self) } )) ``` Note the following: - The `initialize()` method of your class should take 3 arguments: the OAuth2 token for authenticating with Graph, the name of the AAD tenant, and the list of properties for this object as obtained from the Graph endpoint. It should set 2 fields: `self$type` contains a human-readable name for this type of object, and `private$api_type` contains the object type as it appears in the URL of a Graph API request. It should then call the superclass method to complete the initialisation. `initialize()` itself should not contact the Graph endpoint; it should merely create and populate the R6 object given the response from a previous request. - The `print()` method is optional and should display any properties that can help identify this object to a human reader. You can read the code of the existing classes such as `az_user`, `az_app` etc to see how to call the API. The `do_operation()` method should suffice for any regular communication with the Graph endpoint. ## Register the class with `register_graph_class` Having defined your new class, call `register_graph_class` so that AzureGraph becomes aware of it and can automatically use it to populate object lists. If you are writing a new package, the `register_graph_class` call should go in your package's `.onLoad` startup function. For example, registering the `ms_site` SharePoint class looks like this. ```r .onLoad <- function(libname, pkgname) { register_graph_class("site", ms_site, function(props) grepl("sharepoint", props$id, fixed=TRUE)) # ... other startup code ... } ``` `register_graph_class` takes 3 arguments: - The name of the object class, as it appears in the [Microsoft Graph online documentation](https://learn.microsoft.com/en-us/graph/api/overview?view=graph-rest-1.0). - The R6 class generator object, as defined in the previous section. - A check function which takes a list of properties (as returned by the Graph API) and returns TRUE/FALSE based on whether the properties are for an object of your class. This is necessary as some Graph calls that return lists of objects do not always include explicit metadata indicating the type of each object, hence the type must be inferred from the properties. ## Add getter and setter methods Finally, so that people can use the same workflow with your class as with AzureGraph-supplied classes, you can add getter and setter methods to `ms_graph` and any other classes for which it's appropriate. Again, if you're writing a package, this should happen in the `.onLoad` function. In the case of `ms_site`, it's appropriate to add a getter method not just to `ms_graph`, but also the `ms_group` class. This is because SharePoint sites have associated user groups, hence it's useful to be able to retrieve a site given the object for a group. The relevant code in the `.onLoad` function looks like this (slightly simplified): ```r .onLoad <- function(libname, pkgname) { # ... ms_graph$set("public", "get_sharepoint_site", overwrite=TRUE, function(site_url=NULL, site_id=NULL) { op <- if(is.null(site_url) && !is.null(site_id)) file.path("sites", site_id) else if(!is.null(site_url) && is.null(site_id)) { site_url <- httr::parse_url(site_url) file.path("sites", paste0(site_url$hostname, ":"), site_url$path) } else stop("Must supply either site ID or URL") ms_site$new(self$token, self$tenant, self$call_graph_endpoint(op)) }) az_group$set("public", "get_sharepoint_site", overwrite=TRUE, function() { res <- self$do_operation("sites/root") ms_site$new(self$token, self$tenant, res) }) # ... } ``` Once this is done, the object for a SharePoint site can be instantiated as follows: ```r library(AzureGraph) library(Microsoft365R) gr <- get_graph_login() # directly from the Graph client mysite1 <- gr$get_sharepoint_site("https://mytenant.sharepoint.com/sites/my-site-name") # or via a group mygroup <- gr$get_group("my-group-guid") mysite2 <- mygroup$get_sharepoint_site() ```
/scratch/gouwar.j/cran-all/cranData/AzureGraph/inst/doc/extend.Rmd
--- title: "Introduction to AzureGraph" author: Hong Ooi output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Introduction} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{utf8} --- [Microsoft Graph](https://learn.microsoft.com/en-us/graph/overview) is a comprehensive framework for accessing data in various online Microsoft services, including Azure Active Directory (AAD), Office 365, OneDrive, Teams, and more. AzureGraph is a simple R6-based interface to the Graph REST API, and is the companion package to [AzureRMR](https://github.com/Azure/AzureRMR) and [AzureAuth](https://github.com/Azure/AzureAuth). Currently, AzureGraph aims to provide an R interface only to the AAD part, with a view to supporting R interoperability with Azure: registered apps and service principals, users and groups. However, it can be extended to support other services; for more information, see the "Extending AzureGraph" vignette. ## Authentication The first time you authenticate with a given Azure Active Directory tenant, you call `create_graph_login()` and supply your credentials. AzureGraph will prompt you for permission to create a special data directory in which to cache the obtained authentication token and AD Graph login. Once this information is saved on your machine, it can be retrieved in subsequent R sessions with `get_graph_login()`. Your credentials will be automatically refreshed so you don't have to reauthenticate. ```r library(AzureGraph) # authenticate with AAD # - on first login, call create_graph_login() # - on subsequent logins, call get_graph_login() gr <- create_graph_login() ``` See the "Authentication basics" vignette for more details on how to authenticate with AzureGraph. ## Users and groups The basic classes for interacting with user accounts and groups are `az_user` and `az_group`. To instantiate these, call the `get_user` and `get_group` methods of the login client object. You can also list the users and groups with the `list_users` and `list_groups` methods. ```r # account of the logged-in user (if you authenticated via the default method) me <- gr$get_user() # alternative: supply a GUID, name or email address me2 <- gr$get_user(email="[email protected]") # lists of users and groups (may be large!) gr$list_users() gr$list_groups() # IDs of my groups head(me$list_group_memberships()) #> [1] "98326d14-365a-4257-b0f1-5c3ce3104f75" "b21e5600-8ac5-407b-8774-396168150210" #> [3] "be42ef66-5c13-48cb-be5c-21e563e333ed" "dd58be5a-1eac-47bd-ab78-08a452a08ea0" #> [5] "4c2bfcfe-5012-4136-ab33-f10389f2075c" "a45fbdbe-c365-4478-9366-f6f517027a22" # a specific group (grp <- gr$get_group("82d27e38-026b-4e5d-ba1a-a0f5a21a2e85")) #> <Graph group 'AIlyCATs'> #> directory id: 82d27e38-026b-4e5d-ba1a-a0f5a21a2e85 #> description: ADS AP on Microsoft Teams. #> - Instant communication. #> - Share files/links/codes/... #> - Have fun. :) ``` The actual properties of an object are stored as a list in the `properties` field: ```r # properties of a user account names(me$properties) #> [1] "@odata.context" "id" "deletedDateTime" #> [4] "accountEnabled" "ageGroup" "businessPhones" #> [7] "city" "createdDateTime" "companyName" #> [10] "consentProvidedForMinor" "country" "department" #> [13] "displayName" "employeeId" "faxNumber" #> ... me$properties$companyName #> [1] "MICROSOFT PTY LIMITED" # properties of a group names(grp$properties) #> [1] "@odata.context" "id" "deletedDateTime" #> [4] "classification" "createdDateTime" "description" #> [7] "displayName" "expirationDateTime" "groupTypes" #> [10] "mail" "mailEnabled" "mailNickname" #> [13] "membershipRule" "membershipRuleProcessingState" "onPremisesLastSyncDateTime" #> ... ``` You can apply a filter to the `list_users` and `list_groups` methods, to cut down on the number of results. The filter should be a supported [OData expression](https://learn.microsoft.com/en-us/graph/query-parameters#filter-parameter). For example, this will filter the list of users down to your own account: ```r # get my own name my_name <- me$properties$displayName gr$list_users(filter=sprintf("displayName eq '%s'", my_name)) ``` You can also view any directory objects that you own and/or created, via the `list_owned_objects` and `list_registered_objects` methods of the user object. These accept a `type` argument to filter the list of objects by the specified type(s). ```r me$list_owned_objects(type="application") #> [[1]] #> <Graph registered app 'AzureRapp'> #> app id: 5af7bc65-8834-4ee6-90df-e7271a12cc62 #> directory id: 132ce21b-ebb9-4e75-aa04-ad9155bb921f #> domain: microsoft.onmicrosoft.com me$list_owned_objects(type="group") #> [[1]] #> <Graph group 'AIlyCATs'> #> directory id: 82d27e38-026b-4e5d-ba1a-a0f5a21a2e85 #> description: ADS AP on Microsoft Teams. #> - Instant communication. #> - Share files/links/codes/... #> - Have fun. :) #> #> [[2]] #> <Graph group 'ANZ Data Science and AI V-Team'> #> directory id: 4e237eed-5f9b-4abd-830b-9322cb472b66 #> description: ANZ Data Science V-Team #> #> ... ``` ## Registered apps and service principals To get the details for a registered app, use the `get_app` or `create_app` methods of the login client object. These return an object of class `az_app`. The first method retrieves an existing app, while the second creates a new app. ```r # an existing app gr$get_app("5af7bc65-8834-4ee6-90df-e7271a12cc62") #> <Graph registered app 'AzureRapp'> #> app id: 5af7bc65-8834-4ee6-90df-e7271a12cc62 #> directory id: 132ce21b-ebb9-4e75-aa04-ad9155bb921f #> domain: microsoft.onmicrosoft.com # create a new app (appnew <- gr$create_app("AzureRnewapp")) #> <Graph registered app 'AzureRnewapp'> #> app id: 1751d755-71b1-40e7-9f81-526d636c1029 #> directory id: be11df41-d9f1-45a0-b460-58a30daaf8a9 #> domain: microsoft.onmicrosoft.com ``` By default, creating a new app will also generate a strong password with a duration of two years, and create a corresponding service principal in your AAD tenant. You can retrieve this with the `get_service_principal` method, which returns an object of class `az_service_principal`. ```r appnew$get_service_principal() #> <Graph service principal 'AzureRnewapp'> #> app id: 1751d755-71b1-40e7-9f81-526d636c1029 #> directory id: 7dcc9602-2325-4912-a32e-03e262ffd240 #> app tenant: 72f988bf-86f1-41af-91ab-2d7cd011db47 # or directly from the login client (supply the app ID in this case) gr$get_service_principal("1751d755-71b1-40e7-9f81-526d636c1029") #> <Graph service principal 'AzureRnewapp'> #> app id: 1751d755-71b1-40e7-9f81-526d636c1029 #> directory id: 7dcc9602-2325-4912-a32e-03e262ffd240 #> app tenant: 72f988bf-86f1-41af-91ab-2d7cd011db47 ``` To update an app, call its `update` method. For example, use this to set a redirect URL or change its permissions. Consult the Microsoft Graph documentation for what properties you can update. ```r #' # set a public redirect URL newapp$update(publicClient=list(redirectUris=I("http://localhost:1410"))) ``` One app property you _cannot_ change with `update` is its password. As a security measure, app passwords are auto-generated on the server, rather than being specified manually. To manage an app's password, call the `add_password` and `remove_password` methods. ```r #' # add a password newapp$add_password() #' remove a password pwd_id <- newapp$properties$passwordCredentials[[1]]$keyId newapp$remove_password(pwd_id) ``` Similarly, to manage an app's certificate for authentication, call the `add_certificate` and `remove_certificate` methods. ```r #' add a certificate: #' can be specified as a filename, openssl::cert object, AzureKeyVault::stored_cert object, #' or raw or character vector newapp$add_certificate("cert.pem") #' remove a certificate cert_id <- newapp$properties$keyCredentials[[1]]$keyId newapp$remove_certificate(cert_id) ``` ## Common methods The classes described above inherit from the `az_object` class, which represents an arbitrary object in Azure Active Directory. This has the following methods: - `list_group_memberships()`: Return the IDs of all groups this object is a member of. - `list_object_memberships()`: Return the IDs of all groups, administrative units and directory roles this object is a member of. In turn, the `az_object` class inherits from `ms_object`, which is a base class to represent any object (not just an AAD object) in Microsoft Graph. This has the following methods: - `delete(confirm=TRUE)`: Delete an object. By default, ask for confirmation first. - `update(...)`: Update the object information in Azure Active Directory (mentioned above when updating an app). - `do_operation(...)`: Carry out an arbitrary operation on the object. - `sync_fields()`: Synchronise the R object with the data in Azure Active Directory. - `get_list_pager()`: Returns a pager object for iterating through the items in a list of results. See the "Batching and paging" vignette for more information on this topic. In particular, the `do_operation` method allows you to call the Graph REST endpoint directly. This means that even if AzureGraph doesn't support the operation you want to perform, you can do it manually. For example, if you want to retrieve information on your OneDrive: ```r # get my OneDrive me$do_operation("drive") # list the files in my OneDrive root folder me$do_operation("drive/root/children") ``` ## See also See the following links on Microsoft Docs for more information. - [Microsoft Graph](https://learn.microsoft.com/en-us/graph/overview) - [Graph REST API (beta)](https://learn.microsoft.com/en-us/graph/api/overview?view=graph-rest-beta)
/scratch/gouwar.j/cran-all/cranData/AzureGraph/inst/doc/intro.Rmd
--- title: "Authentication basics" author: Hong Ooi output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Authentication} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{utf8} --- There are a number of ways to authenticate to the Microsoft Graph API with AzureGraph. This vignette goes through the most common scenarios. ## Interactive authentication This is the scenario where you're using R interactively, such as in your local desktop or laptop, or in a hosted RStudio Server, Jupyter notebook or ssh session. The first time you authenticate with AzureGraph, you run `create_graph_login()`: ```r # on first use library(AzureGraph) gr <- create_graph_login() ``` Notice that you _don't_ enter your username and password. AzureGraph will attempt to detect which authentication flow to use, based on your session details. In most cases, it will bring up the Azure Active Directory (AAD) login page in your browser, which is where you enter your user credentials. This is also known as the "authorization code" flow. There are some complications to be aware of: - If you are running R in a hosted session, trying to start a browser will usually fail. In this case, specify the device code authentication flow, with the `auth_type` argument: ```r gr <- create_graph_login(auth_type="device_code") ``` - If you have a personal account that is also a guest in an organisational tenant, you may have to specify your tenant explicitly: ```r gr <- create_graph_login(tenant="yourtenant") ``` - By default, AzureGraph identifies itself using the Azure CLI app registration ID. This is meant for working with the AAD part of the Graph API, so it has permissions which are relevant for this purpose. If you are using Graph for other purposes (eg to interact with Microsoft 365 services), you'll need to supply your own app ID that has the correct permissions. On the client side, you supply the app ID via the `app` argument; see later for creating the app registration on the server side. ```r gr <- create_graph_login(app="yourappid") ``` All of the above arguments can be combined, eg this will authenticate using the device code flow, with an explicit tenant name, and a custom app ID: ```r gr <- create_graph_login(tenant="yourtenant", app="yourappid", auth_type="device_code") ``` If needed, you can also supply other arguments that will be passed to `AzureAuth::get_azure_token()`. Having created the login, in subsequent sessions you run `get_graph_login()`. This will load your previous authentication details, saving you from having to login again. If you specified the tenant in the `create_graph_login()` call, you'll also need to specify it for `get_graph_login()`; the other arguments don't have to be repeated. ```r gr <- get_graph_login() # if you specified the tenant in create_graph_login gr <- get_graph_login(tenant="yourtenant") ``` ## Non-interactive authentication This is the scenario where you want to use AzureGraph as part of an automated script or unattended session, for example in a deployment pipeline. The appropriate authentication flow in this case is the client credentials flow. For this scenario, you must have a custom app ID and client secret. On the client side, these are supplied in the `app` and `password` arguments; see later for creating the app registration on the server side. You must also specify your tenant as AAD won't be able to detect it from a user's credentials. ```r gr <- create_graph_login(tenant="yourtenant", app="yourccappid", password="client_secret") ``` In the non-interactive scenario, you don't use `get_graph_login()`; instead, you simply call `create_graph_login()` as part of your script. ## Creating a custom app registration This part is meant mostly for Azure tenant administrators, or users who have the appropriate rights to create AAD app registrations. You can create a new app registration using any of the usual methods. For example to create an app registration in the Azure Portal (`https://portal.azure.com/`), click on "Azure Active Directory" in the menu bar down the left, go to "App registrations" and click on "New registration". Name the app something suitable, eg "AzureGraph custom app". - If you want your users to be able to login with the authorization code flow, you must add a **public client/native redirect URI** of `http://localhost:1410`. This is appropriate if your users will be running R on their local PCs, with an Internet browser available. - If you want your users to be able to login with the device code flow, you must **enable the "Allow public client flows" setting** for your app. In the Portal, you can find this setting in the "Authentication" pane once the app registration is complete. This is appropriate if your users are running R in a remote session. - If the app is meant for non-interactive use, you must give the app a **client secret**, which is much the same as a password (and should similarly be kept secure). In the Portal, you can set this in the "Certificates and Secrets" pane for your app registration. Once the app registration has been created, note the app ID and, if applicable, the client secret. The latter can't be viewed after app creation, so make sure you note its value now. It's also possible to authenticate with a **client certificate (public key)**, but this is more complex and we won't go into it here. For more details, see the [Azure Active Directory documentation](https://learn.microsoft.com/en-au/azure/active-directory/develop/v2-oauth2-client-creds-grant-flow) and the [AzureAuth intro vignette](https://cran.r-project.org/package=AzureAuth/vignettes/token.html). ### Set the app permissions For your app to be useful, you must give it the appropriate permisssions for the Microsoft Graph API. You can set this by going to the "API permissions" pane for your app registration, then clicking on "Add a permission". Choose the Microsoft Graph API, and then enable the permissions that you need. - For interactive use, make sure that you enable the _delegated_ permissions. These apply when a logged-in user is present. [See the documentation](https://learn.microsoft.com/en-us/graph/auth/auth-concepts#microsoft-graph-permissions) for how permissions and user roles interact; essentially, if a user wants to use AzureGraph to do an action, they must have the correct role _and_ the app registration must have the correct permission. - It's highly recommended to enable the "offline_access" permission for an interactive app, as this is necessary to obtain refresh tokens. Without these, a user must reauthenticate each time their access token expires, which by default is after one hour. - For non-interactive use, enable the _application_ permissions. These are more powerful since there is no user role that can moderate what AzureGraph can do, so assign application permissions with caution.
/scratch/gouwar.j/cran-all/cranData/AzureGraph/vignettes/auth.Rmd
--- title: "Batching and paging" author: Hong Ooi output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Batching and Paging} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{utf8} --- This vignette describes a couple of special interfaces that are available in Microsoft Graph, and how to use them in AzureGraph. ## Batching The batch API allows you to combine multiple requests into a single batch call, potentially resulting in significant performance improvements. If all the requests are independent, they can be executed in parallel, so that they only take the same time as a single request. If the requests depend on each other, they must be executed serially, but even in this case you benefit by not having to make multiple HTTP requests with the associated network overhead. For example, let's say you want to get the object information for all the Azure Active Directory groups, directory roles and admin units you're a member of. The `az_object$list_object_memberships()` method returns the IDs for these objects, but to get the remaining object properties, you have to call the `directoryObjects` API endpoint for each individual ID. Rather than making separate calls for every ID, let's combine them into a single batch request. ```r gr <- get_graph_login() me <- gr$get_user() # get the AAD object IDs obj_ids <- me$list_object_memberships(security_only=FALSE) ``` AzureGraph represents a single request with the `graph_request` R6 class. To create a new request object, call `graph_request$new()` with the following arguments: - `op`: The operation to carry out, eg `/me/drives`. - `body`: The body of the HTTPS request, if it is a PUT, POST or PATCH. - `options`: A list containing the query parameters for the URL, for example OData parameters. - `headers`: Any optional HTTP headers for the request. - `encode`: If a request body is present, how it should be encoded when sending it to the endpoint. The default is `json`, meaning it will be sent as JSON text; an alternative is `raw`, for binary data. - `http_verb`: One of "GET" (the default), "DELETE", "PUT", "POST", "HEAD", or "PATCH". For this example, only `op` is required. ```r obj_reqs <- lapply(obj_ids, function(id) { op <- file.path("directoryObjects", id) graph_request$new(op) }) ``` To make a request to the batch endpoint, use the `call_batch_endpoint()` function, or the `ms_graph$call_batch_endpoint()` method. This takes as arguments a list of individual requests, as well as an optional named vector of dependencies. The result of the call is a list of the responses from the requests; each response will have components named `id` and `status`, and usually `body` as well. In this case, there are no dependencies between the individual requests, so the code is very simple. Simply use the `call_batch_endpoint()` method with the request list; then run the `find_class_generator()` function to get the appropriate class generator for each list of object properties, and instantiate a new object. ```r objs <- gr$call_batch_endpoint(obj_reqs) lapply(objs, function(obj) { cls <- find_class_generator(obj) cls$new(gr$token, gr$tenant, obj$body) }) ``` ## Paging Some Microsoft Graph calls return multiple results. In AzureGraph, these calls are generally those represented by methods starting with `list_*`, eg the `list_object_memberships` method used previously. Graph handles result sets by breaking them into _pages_, with each page containing several results. The built-in AzureGraph methods will generally handle paging automatically, without you needing to be aware of the details. If necessary however, you can also carry out a paged request and handle the results manually. The starting point for a paged request is a regular Graph call to an endpoint that returns a paged response. For example, let's take the `memberOf` endpoint, which returns the groups of which a user is a member. Calling this endpoint returns the first page of results, along with a link to the next page. ```r res <- me$do_operation("memberOf") ``` Once you have the first page, you can use that to instantiate a new object of class `ms_graph_pager`. This is an _iterator_ object: each time you access data from it, you retrieve a new page of results. If you have used other programming languages such as Python, Java or C#, the concept of iterators should be familiar. If you're a user of the foreach package, you'll also have used iterators: foreach depends on the iterators package, which implements the same concept using S3 classes. The easiest way to instantiate a new pager object is via the `get_list_pager()` method. Once instantiated, you access the `value` active binding to retrieve each page of results, starting from the first page. ```r pager <- me$get_list_pager(res) pager$value # [[1]] # <Security group 'secgroup'> # directory id: cd806a5f-9d19-426c-b34b-3a3ec662ecf2 # description: test security group # --- # Methods: # delete, do_operation, get_list_pager, list_group_memberships, # list_members, list_object_memberships, list_owners, sync_fields, # update # [[2]] # <Azure Active Directory role 'Global Administrator'> # directory id: df643f93-3d9d-497f-8f2e-9cfd4c275e41 # description: Can manage all aspects of Azure AD and Microsoft services that use Azure # AD identities. # --- # Methods: # delete, do_operation, get_list_pager, list_group_memberships, # list_members, list_object_memberships, sync_fields, update ``` Once there are no more pages, calling `value` returns an empty result. ```r pager$value # list() ``` By default, as shown above, the pager object will create new AzureGraph R6 objects from the properties for each item in the results. You can customise the output in the following ways: - If the first page of results consists of a data frame, rather than a list of items, the pager will continue to output data frames. This is most useful when the results are meant to represent external, tabular data, eg items in a SharePoint list or files in a OneDrive folder. Some AzureGraph methods will automatically request data frame output; if you want this from a manual REST API call, specify `simplify=TRUE` in the `do_operation()` call. - You can suppress the conversion of the item properties into an R6 object by specifying `generate_objects=FALSE` in the `get_list_pager()` call. In this case, the pager will return raw lists. AzureGraph also provides the `extract_list_values()` function to perform the common task of getting all or some of the values from a paged result set. Rather than reading `pager$value` repeatedly until there is no data left, you can simply call: ```r extract_list_values(pager) ``` To restrict the output to only the first N items, call `extract_list_values(pager, n=N)`. However, note that the result set from a paged query usually isn't ordered in any way, so the items you get will be arbitrary.
/scratch/gouwar.j/cran-all/cranData/AzureGraph/vignettes/batching_paging.Rmd
--- title: "Extending AzureGraph" author: Hong Ooi output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Extending} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{utf8} --- As written, AzureGraph provides support for Microsoft Graph objects derived from Azure Active Directory (AAD): users, groups, app registrations and service principals. This vignette describes how to extend it to support other services. ## Extend the `ms_object` base class AzureGraph provides the `ms_object` class to represent a generic object in Graph. You can extend this to support specific services by adding custom methods and fields. For example, the [Microsoft365R](https://github.com/Azure/Microsoft365R) package extends AzureGraph to support SharePoint Online sites and OneDrive filesystems (both personal and business). This is the `ms_site` class from that package, which represents a SharePoint site. To save space, the actual code in the new methods has been elided. ```r ms_site <- R6::R6Class("ms_site", inherit=ms_object, public=list( initialize=function(token, tenant=NULL, properties=NULL) { self$type <- "site" private$api_type <- "sites" super$initialize(token, tenant, properties) }, list_drives=function() {}, # ... get_drive=function(drive_id=NULL) {}, # ... list_subsites=function() {}, # ... get_list=function(list_name=NULL, list_id=NULL) {}, # ... print=function(...) { cat("<Sharepoint site '", self$properties$displayName, "'>\n", sep="") cat(" directory id:", self$properties$id, "\n") cat(" web link:", self$properties$webUrl, "\n") cat(" description:", self$properties$description, "\n") cat("---\n") cat(format_public_methods(self)) invisible(self) } )) ``` Note the following: - The `initialize()` method of your class should take 3 arguments: the OAuth2 token for authenticating with Graph, the name of the AAD tenant, and the list of properties for this object as obtained from the Graph endpoint. It should set 2 fields: `self$type` contains a human-readable name for this type of object, and `private$api_type` contains the object type as it appears in the URL of a Graph API request. It should then call the superclass method to complete the initialisation. `initialize()` itself should not contact the Graph endpoint; it should merely create and populate the R6 object given the response from a previous request. - The `print()` method is optional and should display any properties that can help identify this object to a human reader. You can read the code of the existing classes such as `az_user`, `az_app` etc to see how to call the API. The `do_operation()` method should suffice for any regular communication with the Graph endpoint. ## Register the class with `register_graph_class` Having defined your new class, call `register_graph_class` so that AzureGraph becomes aware of it and can automatically use it to populate object lists. If you are writing a new package, the `register_graph_class` call should go in your package's `.onLoad` startup function. For example, registering the `ms_site` SharePoint class looks like this. ```r .onLoad <- function(libname, pkgname) { register_graph_class("site", ms_site, function(props) grepl("sharepoint", props$id, fixed=TRUE)) # ... other startup code ... } ``` `register_graph_class` takes 3 arguments: - The name of the object class, as it appears in the [Microsoft Graph online documentation](https://learn.microsoft.com/en-us/graph/api/overview?view=graph-rest-1.0). - The R6 class generator object, as defined in the previous section. - A check function which takes a list of properties (as returned by the Graph API) and returns TRUE/FALSE based on whether the properties are for an object of your class. This is necessary as some Graph calls that return lists of objects do not always include explicit metadata indicating the type of each object, hence the type must be inferred from the properties. ## Add getter and setter methods Finally, so that people can use the same workflow with your class as with AzureGraph-supplied classes, you can add getter and setter methods to `ms_graph` and any other classes for which it's appropriate. Again, if you're writing a package, this should happen in the `.onLoad` function. In the case of `ms_site`, it's appropriate to add a getter method not just to `ms_graph`, but also the `ms_group` class. This is because SharePoint sites have associated user groups, hence it's useful to be able to retrieve a site given the object for a group. The relevant code in the `.onLoad` function looks like this (slightly simplified): ```r .onLoad <- function(libname, pkgname) { # ... ms_graph$set("public", "get_sharepoint_site", overwrite=TRUE, function(site_url=NULL, site_id=NULL) { op <- if(is.null(site_url) && !is.null(site_id)) file.path("sites", site_id) else if(!is.null(site_url) && is.null(site_id)) { site_url <- httr::parse_url(site_url) file.path("sites", paste0(site_url$hostname, ":"), site_url$path) } else stop("Must supply either site ID or URL") ms_site$new(self$token, self$tenant, self$call_graph_endpoint(op)) }) az_group$set("public", "get_sharepoint_site", overwrite=TRUE, function() { res <- self$do_operation("sites/root") ms_site$new(self$token, self$tenant, res) }) # ... } ``` Once this is done, the object for a SharePoint site can be instantiated as follows: ```r library(AzureGraph) library(Microsoft365R) gr <- get_graph_login() # directly from the Graph client mysite1 <- gr$get_sharepoint_site("https://mytenant.sharepoint.com/sites/my-site-name") # or via a group mygroup <- gr$get_group("my-group-guid") mysite2 <- mygroup$get_sharepoint_site() ```
/scratch/gouwar.j/cran-all/cranData/AzureGraph/vignettes/extend.Rmd
--- title: "Introduction to AzureGraph" author: Hong Ooi output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Introduction} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{utf8} --- [Microsoft Graph](https://learn.microsoft.com/en-us/graph/overview) is a comprehensive framework for accessing data in various online Microsoft services, including Azure Active Directory (AAD), Office 365, OneDrive, Teams, and more. AzureGraph is a simple R6-based interface to the Graph REST API, and is the companion package to [AzureRMR](https://github.com/Azure/AzureRMR) and [AzureAuth](https://github.com/Azure/AzureAuth). Currently, AzureGraph aims to provide an R interface only to the AAD part, with a view to supporting R interoperability with Azure: registered apps and service principals, users and groups. However, it can be extended to support other services; for more information, see the "Extending AzureGraph" vignette. ## Authentication The first time you authenticate with a given Azure Active Directory tenant, you call `create_graph_login()` and supply your credentials. AzureGraph will prompt you for permission to create a special data directory in which to cache the obtained authentication token and AD Graph login. Once this information is saved on your machine, it can be retrieved in subsequent R sessions with `get_graph_login()`. Your credentials will be automatically refreshed so you don't have to reauthenticate. ```r library(AzureGraph) # authenticate with AAD # - on first login, call create_graph_login() # - on subsequent logins, call get_graph_login() gr <- create_graph_login() ``` See the "Authentication basics" vignette for more details on how to authenticate with AzureGraph. ## Users and groups The basic classes for interacting with user accounts and groups are `az_user` and `az_group`. To instantiate these, call the `get_user` and `get_group` methods of the login client object. You can also list the users and groups with the `list_users` and `list_groups` methods. ```r # account of the logged-in user (if you authenticated via the default method) me <- gr$get_user() # alternative: supply a GUID, name or email address me2 <- gr$get_user(email="[email protected]") # lists of users and groups (may be large!) gr$list_users() gr$list_groups() # IDs of my groups head(me$list_group_memberships()) #> [1] "98326d14-365a-4257-b0f1-5c3ce3104f75" "b21e5600-8ac5-407b-8774-396168150210" #> [3] "be42ef66-5c13-48cb-be5c-21e563e333ed" "dd58be5a-1eac-47bd-ab78-08a452a08ea0" #> [5] "4c2bfcfe-5012-4136-ab33-f10389f2075c" "a45fbdbe-c365-4478-9366-f6f517027a22" # a specific group (grp <- gr$get_group("82d27e38-026b-4e5d-ba1a-a0f5a21a2e85")) #> <Graph group 'AIlyCATs'> #> directory id: 82d27e38-026b-4e5d-ba1a-a0f5a21a2e85 #> description: ADS AP on Microsoft Teams. #> - Instant communication. #> - Share files/links/codes/... #> - Have fun. :) ``` The actual properties of an object are stored as a list in the `properties` field: ```r # properties of a user account names(me$properties) #> [1] "@odata.context" "id" "deletedDateTime" #> [4] "accountEnabled" "ageGroup" "businessPhones" #> [7] "city" "createdDateTime" "companyName" #> [10] "consentProvidedForMinor" "country" "department" #> [13] "displayName" "employeeId" "faxNumber" #> ... me$properties$companyName #> [1] "MICROSOFT PTY LIMITED" # properties of a group names(grp$properties) #> [1] "@odata.context" "id" "deletedDateTime" #> [4] "classification" "createdDateTime" "description" #> [7] "displayName" "expirationDateTime" "groupTypes" #> [10] "mail" "mailEnabled" "mailNickname" #> [13] "membershipRule" "membershipRuleProcessingState" "onPremisesLastSyncDateTime" #> ... ``` You can apply a filter to the `list_users` and `list_groups` methods, to cut down on the number of results. The filter should be a supported [OData expression](https://learn.microsoft.com/en-us/graph/query-parameters#filter-parameter). For example, this will filter the list of users down to your own account: ```r # get my own name my_name <- me$properties$displayName gr$list_users(filter=sprintf("displayName eq '%s'", my_name)) ``` You can also view any directory objects that you own and/or created, via the `list_owned_objects` and `list_registered_objects` methods of the user object. These accept a `type` argument to filter the list of objects by the specified type(s). ```r me$list_owned_objects(type="application") #> [[1]] #> <Graph registered app 'AzureRapp'> #> app id: 5af7bc65-8834-4ee6-90df-e7271a12cc62 #> directory id: 132ce21b-ebb9-4e75-aa04-ad9155bb921f #> domain: microsoft.onmicrosoft.com me$list_owned_objects(type="group") #> [[1]] #> <Graph group 'AIlyCATs'> #> directory id: 82d27e38-026b-4e5d-ba1a-a0f5a21a2e85 #> description: ADS AP on Microsoft Teams. #> - Instant communication. #> - Share files/links/codes/... #> - Have fun. :) #> #> [[2]] #> <Graph group 'ANZ Data Science and AI V-Team'> #> directory id: 4e237eed-5f9b-4abd-830b-9322cb472b66 #> description: ANZ Data Science V-Team #> #> ... ``` ## Registered apps and service principals To get the details for a registered app, use the `get_app` or `create_app` methods of the login client object. These return an object of class `az_app`. The first method retrieves an existing app, while the second creates a new app. ```r # an existing app gr$get_app("5af7bc65-8834-4ee6-90df-e7271a12cc62") #> <Graph registered app 'AzureRapp'> #> app id: 5af7bc65-8834-4ee6-90df-e7271a12cc62 #> directory id: 132ce21b-ebb9-4e75-aa04-ad9155bb921f #> domain: microsoft.onmicrosoft.com # create a new app (appnew <- gr$create_app("AzureRnewapp")) #> <Graph registered app 'AzureRnewapp'> #> app id: 1751d755-71b1-40e7-9f81-526d636c1029 #> directory id: be11df41-d9f1-45a0-b460-58a30daaf8a9 #> domain: microsoft.onmicrosoft.com ``` By default, creating a new app will also generate a strong password with a duration of two years, and create a corresponding service principal in your AAD tenant. You can retrieve this with the `get_service_principal` method, which returns an object of class `az_service_principal`. ```r appnew$get_service_principal() #> <Graph service principal 'AzureRnewapp'> #> app id: 1751d755-71b1-40e7-9f81-526d636c1029 #> directory id: 7dcc9602-2325-4912-a32e-03e262ffd240 #> app tenant: 72f988bf-86f1-41af-91ab-2d7cd011db47 # or directly from the login client (supply the app ID in this case) gr$get_service_principal("1751d755-71b1-40e7-9f81-526d636c1029") #> <Graph service principal 'AzureRnewapp'> #> app id: 1751d755-71b1-40e7-9f81-526d636c1029 #> directory id: 7dcc9602-2325-4912-a32e-03e262ffd240 #> app tenant: 72f988bf-86f1-41af-91ab-2d7cd011db47 ``` To update an app, call its `update` method. For example, use this to set a redirect URL or change its permissions. Consult the Microsoft Graph documentation for what properties you can update. ```r #' # set a public redirect URL newapp$update(publicClient=list(redirectUris=I("http://localhost:1410"))) ``` One app property you _cannot_ change with `update` is its password. As a security measure, app passwords are auto-generated on the server, rather than being specified manually. To manage an app's password, call the `add_password` and `remove_password` methods. ```r #' # add a password newapp$add_password() #' remove a password pwd_id <- newapp$properties$passwordCredentials[[1]]$keyId newapp$remove_password(pwd_id) ``` Similarly, to manage an app's certificate for authentication, call the `add_certificate` and `remove_certificate` methods. ```r #' add a certificate: #' can be specified as a filename, openssl::cert object, AzureKeyVault::stored_cert object, #' or raw or character vector newapp$add_certificate("cert.pem") #' remove a certificate cert_id <- newapp$properties$keyCredentials[[1]]$keyId newapp$remove_certificate(cert_id) ``` ## Common methods The classes described above inherit from the `az_object` class, which represents an arbitrary object in Azure Active Directory. This has the following methods: - `list_group_memberships()`: Return the IDs of all groups this object is a member of. - `list_object_memberships()`: Return the IDs of all groups, administrative units and directory roles this object is a member of. In turn, the `az_object` class inherits from `ms_object`, which is a base class to represent any object (not just an AAD object) in Microsoft Graph. This has the following methods: - `delete(confirm=TRUE)`: Delete an object. By default, ask for confirmation first. - `update(...)`: Update the object information in Azure Active Directory (mentioned above when updating an app). - `do_operation(...)`: Carry out an arbitrary operation on the object. - `sync_fields()`: Synchronise the R object with the data in Azure Active Directory. - `get_list_pager()`: Returns a pager object for iterating through the items in a list of results. See the "Batching and paging" vignette for more information on this topic. In particular, the `do_operation` method allows you to call the Graph REST endpoint directly. This means that even if AzureGraph doesn't support the operation you want to perform, you can do it manually. For example, if you want to retrieve information on your OneDrive: ```r # get my OneDrive me$do_operation("drive") # list the files in my OneDrive root folder me$do_operation("drive/root/children") ``` ## See also See the following links on Microsoft Docs for more information. - [Microsoft Graph](https://learn.microsoft.com/en-us/graph/overview) - [Graph REST API (beta)](https://learn.microsoft.com/en-us/graph/api/overview?view=graph-rest-beta)
/scratch/gouwar.j/cran-all/cranData/AzureGraph/vignettes/intro.Rmd
#' @import AzureRMR #' @import AzureGraph NULL utils::globalVariables(c("self", "private", "super", "get_paged_list")) .az_cli_app_id <- "04b07795-8ddb-461a-bbee-02f9e1bf7b46" .onLoad <- function(libname, pkgname) { options(azure_keyvault_api_version="7.2") add_methods() }
/scratch/gouwar.j/cran-all/cranData/AzureKeyVault/R/AzureKeyVault.R
# documentation is separate from implementation because roxygen still doesn't know how to handle R6 #' Create Azure key vault #' #' Method for the [AzureRMR::az_resource_group] class. #' #' @rdname create_key_vault #' @name create_key_vault #' @aliases create_key_vault #' @section Usage: #' ``` #' create_key_vault(name, location = self$location, initial_access = default_access(), #' sku = "Standard", ..., wait = TRUE) #' ``` #' @section Arguments: #' - `name`: The name of the key vault. #' - `location`: The location/region in which to create the account. Defaults to the resource group location. #' - `initial_access`: The user or service principals that will have access to the vault. This should be a list of objects of type `[vault_access_policy]`, created by the function of the same name. The default is to grant access to the logged-in user or service principal of the current Resource Manager client. #' - `sku`: The sku for the vault. Set this to "Premium" to enable the use of hardware security modules (HSMs). #' - `allow_vm_access`: Whether to allow Azure virtual machines to retrieve certificates from the vault. #' - `allow_arm_access`: Whether to allow Azure Resource Manager to retrieve secrets from the vault for template deployment purposes. #' - `allow_disk_encryption_access`: Whether to allow Azure Disk Encryption to retrieve secrets and keys from the vault. #' - `soft_delete`: Whether soft-deletion should be enabled for this vault. Soft-deletion is a feature which protects both the vault itself and its contents from accidental/malicious deletion; see below. #' - `purge_protection`: Whether purge protection is enabled. If this is TRUE and soft-deletion is enabled for the vault, manual purges are not allowed. Has no effect if `soft_delete=FALSE`. #' - `...`: Other named arguments to pass to the [az_key_vault] initialization function. #' - `wait`: Whether to wait for the resource creation to complete before returning. #' #' @section Details: #' This method deploys a new key vault resource, with parameters given by the arguments. A key vault is a secure facility for storing and managing encryption keys, certificates, storage account keys, and generic secrets. #' #' A new key vault will have access granted to the user or service principal used to sign in to the Azure Resource Manager client. To manage access policies after creation, use the `add_principal`, `list_principals` and `remove_principal` methods of the key vault object. #' #' Key Vault's soft delete feature allows recovery of the deleted vaults and vault objects, known as soft-delete. Specifically, it addresses the following scenarios: #' - Support for recoverable deletion of a key vault #' - Support for recoverable deletion of key vault objects (keys, secrets, certificates) #' #' With this feature, the delete operation on a key vault or key vault object is a soft-delete, effectively holding the resources for a given retention period (90 days), while giving the appearance that the object is deleted. The service further provides a mechanism for recovering the deleted object, essentially undoing the deletion. #' #' Soft-deleted vaults can be purged (permanently removed) by calling the `purge_key_vault` method for the resource group or subscription classes. The purge protection optional feature provides an additional layer of protection by forbidding manual purges; when this is on, a vault or an object in deleted state cannot be purged until the retention period of 90 days has passed. #' #' To see what soft-deleted key vaults exist, call the `list_deleted_key_vaults` method. To recover a soft-deleted key vault, call the `create_key_vault` method from the vault's original resource group, with the vault name. To purge (permanently delete) it, call the `purge_key_vault` method. #' #' @section Value: #' An object of class `az_key_vault` representing the created key vault. #' #' @seealso #' [get_key_vault], [delete_key_vault], [purge_key_vault], [az_key_vault], [vault_access_policy] #' #' [Azure Key Vault documentation](https://docs.microsoft.com/en-us/azure/key-vault/), #' [Azure Key Vault API reference](https://docs.microsoft.com/en-us/rest/api/keyvault) #' #' @examples #' \dontrun{ #' #' rg <- AzureRMR::get_azure_login()$ #' get_subscription("subscription_id")$ #' get_resource_group("rgname") #' #' # create a new key vault #' rg$create_key_vault("mykeyvault") #' #' # create a new key vault, and grant access to a service principal #' gr <- AzureGraph::get_graph_login() #' svc <- gr$get_service_principal("app_id") #' rg$create_key_vault("mykeyvault", #' initial_access=list(vault_access_policy(svc, tenant=NULL))) #' #' } NULL #' Get existing Azure Key Vault #' #' Methods for the [AzureRMR::az_resource_group] class. #' #' @rdname get_key_vault #' @name get_key_vault #' @aliases get_key_vault list_key_vaults #' #' @section Usage: #' ``` #' get_key_vault(name) #' list_key_vaults() #' ``` #' @section Arguments: #' - `name`: For `get_key_vault()`, the name of the key vault. #' #' @section Value: #' For `get_key_vault()`, an object of class `az_key_vault` representing the vault. #' #' For `list_key_vaults()`, a list of such objects. #' #' @seealso #' [create_key_vault], [delete_key_vault], [az_key_vault] #' #' [Azure Key Vault documentation](https://docs.microsoft.com/en-us/azure/key-vault/), #' [Azure Key Vault API reference](https://docs.microsoft.com/en-us/rest/api/keyvault) #' #' @examples #' \dontrun{ #' #' rg <- AzureRMR::get_azure_login()$ #' get_subscription("subscription_id")$ #' get_resource_group("rgname") #' #' rg$list_key_vaults() #' #' rg$get_key_vault("mykeyvault") #' #' } NULL #' Delete an Azure Key Vault #' #' Method for the [AzureRMR::az_resource_group] class. #' #' @rdname delete_key_vault #' @name delete_key_vault #' @aliases delete_key_vault #' #' @section Usage: #' ``` #' delete_key_vault(name, confirm=TRUE, wait=FALSE, purge=FALSE) #' ``` #' @section Arguments: #' - `name`: The name of the key vault. #' - `confirm`: Whether to ask for confirmation before deleting. #' - `wait`: Whether to wait until the deletion is complete. Note that `purge=TRUE` will set `wait=TRUE` as well. #' - `purge`: For a vault with the soft-deletion feature enabled, whether to purge it as well (hard delete). Has no effect if the vault does not have soft-deletion enabled. #' @details #' Deleting a key vault that has soft-deletion enabled does not permanently remove it. Instead the resource is held for a given retention period (90 days), during which it can be recovered, essentially undoing the deletion. #' #' To see what soft-deleted key vaults exist, call the `list_deleted_key_vaults` method. To recover a soft-deleted key vault, call the `create_key_vault` method from the vault's original resource group, with the vault name. To purge (permanently delete) it, call the `purge_key_vault` method. #' #' @section Value: #' NULL on successful deletion. #' #' @seealso #' [create_key_vault], [get_key_vault], [purge_key_vault], [list_deleted_key_vaults], [az_key_vault], #' #' [Azure Key Vault documentation](https://docs.microsoft.com/en-us/azure/key-vault/), #' [Azure Key Vault API reference](https://docs.microsoft.com/en-us/rest/api/keyvault) #' #' @examples #' \dontrun{ #' #' rg <- AzureRMR::get_azure_login()$ #' get_subscription("subscription_id")$ #' get_resource_group("rgname") #' #' # assuming the vault has soft-delete enabled #' rg$delete_key_vault("mykeyvault", purge=FALSE) #' #' # recovering a soft-deleted key vault #' rg$create_key_vault("mykeyvault") #' #' # deleting it for good #' rg$delete_key_vault("mykeyvault", purge=FALSE) #' #' } NULL #' Purge a deleted Azure Key Vault #' #' Method for the [AzureRMR::az_subscription] and [AzureRMR::az_resource_group] classes. #' #' @rdname purge_key_vault #' @name purge_key_vault #' @aliases purge_key_vault #' #' @section Usage: #' ``` #' purge_key_vault(name, location, confirm=TRUE) #' ``` #' @section Arguments: #' - `name`,`location`: The name and location of the key vault. #' - `confirm`: Whether to ask for confirmation before permanently deleting the vault. #' @details #' This method permanently deletes a soft-deleted key vault. Note that it will fail if the vault has purge protection enabled. #' #' @section Value: #' NULL on successful purging. #' #' @seealso #' [create_key_vault], [get_key_vault], [delete_key_vault], [list_deleted_key_vaults], [az_key_vault], #' #' [Azure Key Vault documentation](https://docs.microsoft.com/en-us/azure/key-vault/), #' [Azure Key Vault API reference](https://docs.microsoft.com/en-us/rest/api/keyvault) #' #' @examples #' \dontrun{ #' #' rg <- AzureRMR::get_azure_login()$ #' get_subscription("subscription_id")$ #' get_resource_group("rgname") #' #' # assuming the vault has soft-delete enabled, and is in the same location as its RG #' rg$delete_key_vault("mykeyvault") #' rg$purge_key_vault("mykeyvault", rg$location) #' #' } NULL #' List soft-deleted Key Vaults #' #' Method for the [AzureRMR::az_subscription] class. #' #' @rdname list_deleted_key_vaults #' @name list_deleted_key_vaults #' @aliases list_deleted_key_vaults #' #' @section Usage: #' ``` #' list_deleted_key_vaults() #' ``` #' @section Value: #' This method returns a data frame with the following columns: #' - `name`: The name of the deleted key vault. #' - `location`: The location (region) of the vault. #' - `deletion_date`: When the vault was soft-deleted. #' - `purge_date`: When the vault is scheduled to be purged (permanently deleted). #' - `protected`: Whether the vault has purge protection enabled. If TRUE, manual attempts to purge it will fail. #' #' @seealso #' [create_key_vault], [get_key_vault], [delete_key_vault], [purge_key_vault], [az_key_vault], #' #' [Azure Key Vault documentation](https://docs.microsoft.com/en-us/azure/key-vault/), #' [Azure Key Vault API reference](https://docs.microsoft.com/en-us/rest/api/keyvault) NULL add_methods <- function() { ## extending AzureRMR classes az_resource_group$set("public", "create_key_vault", overwrite=TRUE, function(name, location=self$location, initial_access=default_access(), sku="Standard", allow_vm_access=FALSE, allow_arm_access=FALSE, allow_disk_encryption_access=FALSE, soft_delete=TRUE, purge_protection=FALSE, ..., wait=TRUE) { creds <- AzureAuth::decode_jwt(self$token$credentials$access_token) tenant <- creds$payload$tid default_access <- function() { principal <- creds$payload$oid list(vault_access_policy(principal, tenant, "all", "all", "all", "all")) } props <- utils::modifyList( list( tenantId=tenant, accessPolicies=lapply(initial_access, function(x) { if(is.null(x$tenantId)) x$tenantId <- tenant unclass(x) }), enableSoftDelete=soft_delete, enabledForDeployment=allow_vm_access, enabledForTemplateDeployment=allow_arm_access, enabledForDiskEncryption=allow_disk_encryption_access, sku=list(family="A", name=sku) ), list(...) ) # only set this if TRUE; API doesn't allow setting it to FALSE if(purge_protection && soft_delete) props$enablePurgeProtection <- TRUE AzureKeyVault::az_key_vault$new(self$token, self$subscription, self$name, type="Microsoft.KeyVault/vaults", name=name, location=location, properties=props, wait=wait) }) az_resource_group$set("public", "get_key_vault", overwrite=TRUE, function(name) { AzureKeyVault::az_key_vault$new(self$token, self$subscription, self$name, type="Microsoft.KeyVault/vaults", name=name) }) az_resource_group$set("public", "delete_key_vault", overwrite=TRUE, function(name, confirm=TRUE, wait=FALSE, purge=FALSE) { self$get_key_vault(name)$delete(confirm=confirm, wait=wait, purge=purge) }) az_resource_group$set("public", "purge_key_vault", overwrite=TRUE, function(name, location, confirm=TRUE) { sub <- az_subscription$new(self$token, self$subscription) sub$purge_key_vault(name, location, confirm) }) az_resource_group$set("public", "list_key_vaults", overwrite=TRUE, function() { api_version <- az_subscription$ new(self$token, self$subscription)$ get_provider_api_version("Microsoft.KeyVault", "vaults") lst <- private$rg_op("providers/Microsoft.KeyVault/vaults", api_version=api_version) res <- lst$value while(!is_empty(lst$nextLink)) { lst <- call_azure_url(self$token, lst$nextLink) res <- c(res, lst$value) } named_list(lapply(res, function(parms) AzureKeyVault::az_key_vault$new(self$token, self$subscription, deployed_properties=parms))) }) az_subscription$set("public", "purge_key_vault", overwrite=TRUE, function(name, location, confirm=TRUE) { if(interactive() && confirm) { msg <- sprintf("Do you really want to purge the key vault '%s'?", name) ok <- if(getRversion() < numeric_version("3.5.0")) { msg <- paste(msg, "(yes/No/cancel) ") yn <- readline(msg) if (nchar(yn) == 0) FALSE else tolower(substr(yn, 1, 1)) == "y" } else utils::askYesNo(msg, FALSE) if(!ok) return(invisible(NULL)) } api_version <- self$get_provider_api_version("Microsoft.KeyVault", "deletedVaults") op <- file.path("providers/Microsoft.KeyVault/locations", location, "deletedVaults", name, "purge") self$do_operation(op, api_version=api_version, http_verb="POST") invisible(NULL) }) az_subscription$set("public", "list_deleted_key_vaults", overwrite=TRUE, function() { as_datetime <- function(x) { as.POSIXct(x, format="%Y-%m-%dT%H:%M:%S", tz="GMT") } api_version <- self$get_provider_api_version("Microsoft.KeyVault", "deletedVaults") res <- self$do_operation("providers/Microsoft.KeyVault/deletedVaults", api_version=api_version) lst <- get_paged_list(res, self$token) do.call(rbind, lapply(lst, function(x) { data.frame( name=x$name, location=x$properties$location, deletion_date=as_datetime(x$properties$deletionDate), purge_date=as_datetime(x$properties$scheduledPurgeDate), protected=isTRUE(x$properties$purgeProtectionEnabled), stringsAsFactors=FALSE ) })) }) }
/scratch/gouwar.j/cran-all/cranData/AzureKeyVault/R/add_methods.R
#' Key vault resource class #' #' Class representing a key vault, exposing methods for working with it. #' #' @docType class #' @section Methods: #' The following methods are available, in addition to those provided by the [AzureRMR::az_resource] class: #' - `new(...)`: Initialize a new key vault object. See 'Initialization'. #' - `add_principal(principal, ...)`: Add an access policy for a user or service principal. See 'Access policies' below. #' - `get_principal(principal)`: Retrieve an access policy for a user or service principal. #' - `remove_principal(principal)`: Remove access for a user or service principal. #' - `get_endpoint()`: Return the vault endpoint. See 'Endpoint' below. #' #' @section Initialization: #' Initializing a new object of this class can either retrieve an existing key vault, or create a new vault on the host. The recommended way to initialize an object is via the `get_key_vault`, `create_key_vault` or `list_key_vaults` methods of the [az_resource_group] class, which handle the details automatically. #' #' @section Access policies: #' Client access to a key vault is governed by its access policies, which are set on a per-principal basis. Each principal (user or service) can have different permissions granted, for keys, secrets, certificates, and storage accounts. #' #' To grant access, use the `add_principal` method. This has signature #' #' ``` #' add_principal(principal, tenant = NULL, #' key_permissions = "all", #' secret_permissions = "all", #' certificate_permissions = "all", #' storage_permissions = "all") #'``` #' The `principal` can be a GUID, an object of class `vault_access_policy`, or a user, app or service principal object from the AzureGraph package. Note that the app ID of a registered app is not the same as the ID of its service principal. #' #' The tenant must be a GUID; if this is NULL, it will be taken from the tenant of the key vault resource. #' #' Here are the possible permissions for keys, secrets, certificates, and storage accounts. The permission "all" means to grant all permissions. #' - Keys: "get", "list", "update", "create", "import", "delete", "recover", "backup", "restore", "decrypt", "encrypt", "unwrapkey", "wrapkey", "verify", "sign", "purge" #' - Secrets: "get", "list", "set", "delete", "recover", "backup", "restore", "purge" #' - Certificates: "get", "list", "update", "create", "import", "delete", "recover", "backup", "restore", "managecontacts", "manageissuers", "getissuers", "listissuers", "setissuers", "deleteissuers", "purge" #' - Storage accounts: "get", "list", "update", "set", "delete", "recover", "backup", "restore", "regeneratekey", "getsas", "listsas", "setsas", "deletesas", "purge" #' #' To revoke access, use the `remove_principal` method. To view the current access policy, use `get_principal` or `list_principals`. #' #' @section Endpoint: #' The client-side interaction with a key vault is via its _endpoint_, which is usually at the URL `https://[vaultname].vault.azure.net`. The `get_endpoint` method returns an R6 object of class `key_vault`, which represents the endpoint. Authenticating with the endpoint is done via an OAuth token; the necessary credentials are taken from the current Resource Manager client in use, or you can supply your own. #' #' ``` #' get_endpoint(tenant = self$token$tenant, #' app = self$token$client$client_id, #' password = self$token$client$client_secret, ...) #'``` #' To access the key vault independently of Resource Manager (for example if you are a user without admin or owner access to the vault resource), use the [key_vault] function. #' #' @seealso #' [vault_access_policy], [key_vault] #' [create_key_vault], [get_key_vault], [delete_key_vault], #' [AzureGraph::get_graph_login], [AzureGraph::az_user], [AzureGraph::az_app], [AzureGraph::az_service_principal] #' #' [Azure Key Vault documentation](https://docs.microsoft.com/en-us/azure/key-vault/), #' [Azure Key Vault API reference](https://docs.microsoft.com/en-us/rest/api/keyvault) #' #' @examples #' \dontrun{ #' #' # recommended way of retrieving a resource: via a resource group object #' kv <- resgroup$get_key_vault("mykeyvault") #' #' # list principals that have access to the vault #' kv$list_principals() #' #' # grant a user full access (the default) #' usr <- AzureGraph::get_graph_login()$ #' get_user("[email protected]") #' kv$add_principal(usr) #' #' # grant a service principal read access to keys and secrets only #' svc <- AzureGraph::get_graph_login()$ #' get_service_principal(app_id="app_id") #' kv$add_principal(svc, #' key_permissions=c("get", "list"), #' secret_permissions=c("get", "list"), #' certificate_permissions=NULL, #' storage_permissions=NULL) # #' # alternatively, supply a vault_access_policy with the listed permissions #' pol <- vault_access_policy(svc, #' key_permissions=c("get", "list"), #' secret_permissions=c("get", "list"), #' certificate_permissions=NULL, #' storage_permissions=NULL) #' kv$add_principal(pol) #' #' # revoke access #' kv$remove_access(svc) #' #' # get the endpoint object #' vault <- kv$get_endpoint() #' #' } #' @export az_key_vault <- R6::R6Class("az_key_vault", inherit=AzureRMR::az_resource, public=list( add_principal=function(principal, tenant=NULL, key_permissions="all", secret_permissions="all", certificate_permissions="all", storage_permissions="all") { if(!inherits(principal, "vault_access_policy")) principal <- vault_access_policy( principal, tenant, key_permissions, secret_permissions, certificate_permissions, storage_permissions ) # un-nullify tenant ID using tenant of resource if(is.null(principal$tenantId)) principal$tenantId <- self$properties$tenantId props <- list(accessPolicies=list(unclass(principal))) self$do_operation("accessPolicies/add", body=list(properties=props), encode="json", http_verb="PUT") self$sync_fields() invisible(self) }, get_principal=function(principal) { principal <- find_principal(principal) pols <- self$properties$accessPolicies i <- sapply(pols, function(obj) obj$objectId == principal) if(!any(i)) stop("No access policy for principal '", principal, "'", call.=FALSE) pol <- pols[[which(i)]] vault_access_policy(pol$objectId, pol$tenantId, pol$permissions$keys, pol$permissions$secrets, pol$permissions$certificates, pol$permissions$storage) }, remove_principal=function(principal) { pol <- self$get_principal(principal) props <- list(accessPolicies=list(unclass(pol))) self$do_operation("accessPolicies/remove", body=list(properties=props), encode="json", http_verb="PUT") self$sync_fields() invisible(self) }, list_principals=function() { lapply(self$properties$accessPolicies, function(pol) vault_access_policy(pol$objectId, pol$tenantId, pol$permissions$keys, pol$permissions$secrets, pol$permissions$certificates, pol$permissions$storage) ) }, get_endpoint=function(tenant=self$token$tenant, app=self$token$client$client_id, password=self$token$client$client_secret, ...) { url <- self$properties$vaultUri key_vault(url=url, tenant=tenant, app=app, password=password, ...) }, delete=function(confirm=TRUE, wait=FALSE, purge=FALSE) { if(purge) wait <- TRUE super$delete(confirm, wait) if(purge && isTRUE(self$properties$enableSoftDelete)) { sub <- az_subscription$new(self$token, self$subscription) sub$purge_key_vault(self$name, self$location, confirm) } invisible(NULL) } )) #' Specify a key vault access policy #' #' @param principal The user or service principal for this access policy. Can be a GUID, or a user, app or service principal object from the AzureGraph package. #' @param tenant The tenant of the principal. #' @param key_permissions The permissions to grant for working with keys. #' @param secret_permissions The permissions to grant for working with secrets. #' @param certificate_permissions The permissions to grant for working with certificates. #' @param storage_permissions The permissions to grant for working with storage accounts. #' #' @details #' Client access to a key vault is governed by its access policies, which are set on a per-principal basis. Each principal (user or service) can have different permissions granted, for keys, secrets, certificates, and storage accounts. #' #' Here are the possible permissions. The permission "all" means to grant all permissions. #' - Keys: "get", "list", "update", "create", "import", "delete", "recover", "backup", "restore", "decrypt", "encrypt", "unwrapkey", "wrapkey", "verify", "sign", "purge" #' - Secrets: "get", "list", "set", "delete", "recover", "backup", "restore", "purge" #' - Certificates: "get", "list", "update", "create", "import", "delete", "recover", "backup", "restore", "managecontacts", "manageissuers", "getissuers", "listissuers", "setissuers", "deleteissuers", "purge" #' - Storage accounts: "get", "list", "update", "set", "delete", "recover", "backup", "restore", "regeneratekey", "getsas", "listsas", "setsas", "deletesas", "purge" #' #' @return #' An object of class `vault_access_policy`, suitable for creating a key vault resource. #' #' @seealso #' [create_key_vault], [az_key_vault] #' #' [Azure Key Vault documentation](https://docs.microsoft.com/en-us/azure/key-vault/), #' [Azure Key Vault API reference](https://docs.microsoft.com/en-us/rest/api/keyvault) #' #' @examples #' \dontrun{ #' #' # default is to grant full access #' vault_access_policy("user_id") #' #' # use AzureGraph to specify a user via their email address rather than a GUID #' usr <- AzureGraph::get_graph_login()$get_user("[email protected]") #' vault_access_policy(usr) #' #' # grant a service principal read access to keys and secrets only #' svc <- AzureGraph::get_graph_login()$ #' get_service_principal(app_id="app_id") #' vault_access_policy(svc, #' key_permissions=c("get", "list"), #' secret_permissions=c("get", "list"), #' certificate_permissions=NULL, #' storage_permissions=NULL) #' #' } #' @export vault_access_policy <- function(principal, tenant=NULL, key_permissions="all", secret_permissions="all", certificate_permissions="all", storage_permissions="all") { principal <- find_principal(principal) key_permissions <- verify_key_permissions(key_permissions) secret_permissions <- verify_secret_permissions(secret_permissions) certificate_permissions <- verify_certificate_permissions(certificate_permissions) storage_permissions <- verify_storage_permissions(storage_permissions) obj <- list( tenantId=tenant, objectId=principal, permissions=list( keys=I(key_permissions), secrets=I(secret_permissions), certificates=I(certificate_permissions), storage=I(storage_permissions) ) ) class(obj) <- "vault_access_policy" obj } #' @export print.vault_access_policy <- function(x, ...) { cat("Tenant:", if(is.null(x$tenantId)) "<default>" else x$tenantId, "\n") cat("Principal:", x$objectId, "\n") cat("Key permissions:\n") cat(strwrap(paste(x$permissions$keys, collapse=", "), indent=4, exdent=4), sep="\n") cat("Secret permissions:\n") cat(strwrap(paste(x$permissions$secrets, collapse=", "), indent=4, exdent=4), sep="\n") cat("Certificate permissions:\n") cat(strwrap(paste(x$permissions$certificates, collapse=", "), indent=4, exdent=4), sep="\n") cat("Storage account permissions:\n") cat(strwrap(paste(x$permissions$storage, collapse=", "), indent=4, exdent=4), sep="\n") cat("\n") invisible(x) } find_principal <- function(principal) { if(is_user(principal) || is_service_principal(principal)) principal$properties$id else if(is_app(principal)) principal$get_service_principal()$properties$id else if(inherits(principal, "vault_access_policy")) principal$objectId else if(!is_guid(principal)) stop("Must supply a valid principal ID or object", call.=FALSE) else AzureAuth::normalize_guid(principal) } verify_key_permissions <- function(perms) { key_perms <- c("get", "list", "update", "create", "import", "delete", "recover", "backup", "restore", "decrypt", "encrypt", "unwrapkey", "wrapkey", "verify", "sign", "purge") verify_permissions(perms, key_perms) } verify_secret_permissions <- function(perms) { secret_perms <- c("get", "list", "set", "delete", "recover", "backup", "restore", "purge") verify_permissions(perms, secret_perms) } verify_certificate_permissions <- function(perms) { certificate_perms <- c("get", "list", "update", "create", "import", "delete", "recover", "backup", "restore", "managecontacts", "manageissuers", "getissuers", "listissuers", "setissuers", "deleteissuers", "purge") verify_permissions(perms, certificate_perms) } verify_storage_permissions <- function(perms) { storage_perms <- c("backup", "delete", "deletesas", "get", "getsas", "list", "listsas", "purge", "recover", "regeneratekey", "restore", "set", "setsas", "update") verify_permissions(perms, storage_perms) } verify_permissions <- function(perms, all_perms) { perms <- tolower(unlist(perms)) if(length(perms) == 1 && perms == "all") return(all_perms) else if(!all(perms %in% all_perms)) stop("Invalid permissions") perms }
/scratch/gouwar.j/cran-all/cranData/AzureKeyVault/R/az_vault.R
#' Certificates in Key Vault #' #' This class represents the collection of certificates stored in a vault. It provides methods for managing certificates, including creating, importing and deleting certificates, and doing backups and restores. For operations with a specific certificate, see [certificate]. #' #' @docType class #' #' @section Methods: #' This class provides the following methods: #' ``` #' create(name, subject, x509=cert_x509_properties(), issuer=cert_issuer_properties(), #' key=cert_key_properties(), format=c("pem", "pkcs12"), #' expiry_action=cert_expiry_action(), #' attributes=vault_object_attrs(), #' ..., wait=TRUE) #' import(name, value, pwd=NULL, #' attributes=vault_object_attrs(), #' ..., wait=TRUE) #' get(name) #' delete(name, confirm=TRUE) #' list() #' backup(name) #' restore(backup) #' get_contacts() #' set_contacts(email) #' add_issuer(issuer, provider, credentials=NULL, details=NULL) #' remove_issuer(issuer) #' get_issuer(issuer) #' list_issuers() #' ``` #' @section Arguments: #' - `name`: The name of the certificate. #' - `subject`: For `create`, The subject or X.500 distinguished name for the certificate. #' - `x509`: Other X.509 properties for the certificate, such as the domain name(s) and validity period. A convenient way to provide this is via the [cert_x509_properties] helper function. #' - `issuer`: Issuer properties for the certificate. A convenient way to provide this is via the [cert_issuer_properties] helper function. The default is to specify a self-signed certificate. #' - `key`: Key properties for the certificate. A convenient way to provide this is via the [cert_key_properties] helper function. #' - `format`: The format to store the certificate in. Can be either PEM or PFX, aka PKCS#12. This also determines the format in which the certificate will be exported (see [certificate]). #' - `expiry_action`: What Key Vault should do when the certificate is about to expire. A convenient way to provide this is via the [cert_expiry_action] helper function. #' - `attributes`: Optional attributes for the secret. A convenient way to provide this is via the [vault_object_attrs] helper function. #' - `value`: For `import`, the certificate to import. This can be the name of a PFX file, or a raw vector with the contents of the file. #' - `pwd`: For `import`, the password if the imported certificate is password-protected. #' - `...`: For `create` and `import`, other named arguments which will be treated as tags. #' - `wait`: For `create` and `import`, whether to wait until the certificate has been created before returning. If FALSE, you can check on the status of the certificate via the returned object's `sync` method. #' - `backup`: For `restore`, a string representing the backup blob for a key. #' - `email`: For `set_contacts`, the email addresses of the contacts. #' - `issuer`: For the issuer methods, the name by which to refer to an issuer. #' - `provider`: For `add_issuer`, the provider name as a string. #' - `credentials`: For `add_issuer`, the credentials for the issuer, if required. Should be a list containing the components `account_id` and `password`. #' - `details`: For `add_issuer`, the organisation details, if required. See the [Azure docs](https://docs.microsoft.com/en-us/rest/api/keyvault/setcertificateissuer/setcertificateissuer#administratordetails) for more information. #' #' @section Value: #' For `get`, `create` and `import`, an object of class `stored_certificate`, representing the certificate itself. #' #' For `list`, a vector of key names. #' #' For `add_issuer` and `get_issuer`, an object representing an issuer. For `list_issuers`, a vector of issuer names. #' #' For `backup`, a string representing the backup blob for a certificate. If the certificate has multiple versions, the blob will contain all versions. #' #' @seealso #' [certificate], [cert_key_properties], [cert_x509_properties], [cert_issuer_properties], [vault_object_attrs] #' #' [Azure Key Vault documentation](https://docs.microsoft.com/en-us/azure/key-vault/), #' [Azure Key Vault API reference](https://docs.microsoft.com/en-us/rest/api/keyvault) #' #' @examples #' \dontrun{ #' #' vault <- key_vault("mykeyvault") #' #' vault$certificates$create("mynewcert", "CN=mydomain.com") #' vault$certificates$list() #' vault$certificates$get("mynewcert") #' #' # specifying some domain names #' vault$certificates$create("mynewcert", "CN=mydomain.com", #' x509=cert_x509_properties(dns_names=c("mydomain.com", "otherdomain.com"))) #' #' # specifying a validity period of 2 years (24 months) #' vault$certificates$create("mynewcert", "CN=mydomain.com", #' x509=cert_x509_properties(validity_months=24)) #' #' # setting management tags #' vault$certificates$create("mynewcert", "CN=mydomain.com", tag1="a value", othertag="another value") #' #' # importing a cert from a PFX file #' vault$certificates$import("importedcert", "mycert.pfx") #' #' # backup and restore a cert #' bak <- vault$certificates$backup("mynewcert") #' vault$certificates$delete("mynewcert", confirm=FALSE) #' vault$certificates$restore(bak) #' #' # set a contact #' vault$certificates$set_contacts("[email protected]") #' vault$certificates$get_contacts() #' #' # add an issuer and then obtain a cert #' # this can take a long time, so set wait=FALSE to return immediately #' vault$certificates$add_issuer("newissuer", provider="OneCert") #' vault$certificates$create("issuedcert", "CN=mydomain.com", #' issuer=cert_issuer_properties("newissuer"), #' wait=FALSE) #' #' } #' @name certificates #' @aliases certificates certs #' @rdname certificates NULL vault_certificates <- R6::R6Class("vault_certificates", public=list( token=NULL, url=NULL, initialize=function(token, url) { self$token <- token self$url <- url }, create=function(name, subject, x509=cert_x509_properties(), issuer=cert_issuer_properties(), key=cert_key_properties(), format=c("pem", "pfx"), expiry_action=cert_expiry_action(), attributes=vault_object_attrs(), ..., wait=TRUE) { format <- if(match.arg(format) == "pem") "application/x-pem-file" else "application/x-pkcs12" policy <- list( issuer=issuer, key_props=key, secret_props=list(contentType=format), x509_props=c(subject=subject, x509), lifetime_actions=expiry_action, attributes=attributes ) body <- list(policy=policy, attributes=attributes, tags=list(...)) op <- construct_path(name, "create") self$do_operation(op, body=body, encode="json", http_verb="POST") cert <- self$get(name) if(!wait) message("Certificate creation started. Call the sync() method to update status.") else while(is.null(cert$cer)) { Sys.sleep(5) cert <- self$get(name) } cert }, get=function(name, version=NULL) { op <- construct_path(name, version) stored_cert$new(self$token, self$url, name, version, self$do_operation(op)) }, delete=function(name, confirm=TRUE) { if(delete_confirmed(confirm, name, "certificate")) invisible(self$do_operation(name, http_verb="DELETE")) }, list=function() { sapply(get_vault_paged_list(self$do_operation(), self$token), function(props) basename(props$id)) }, backup=function(name) { self$do_operation(construct_path(name, "backup"), http_verb="POST")$value }, restore=function(name, backup) { stopifnot(is.character(backup)) self$do_operation("restore", body=list(value=backup), encode="json", http_verb="POST") }, import=function(name, value, pwd=NULL, attributes=vault_object_attrs(), ..., wait=TRUE) { if(is.character(value) && length(value) == 1 && file.exists(value)) value <- readBin(value, "raw", file.info(value)$size) body <- list(value=value, pwd=pwd, attributes=attributes, tags=list(...)) self$do_operation(construct_path(name, "import"), body=body, encode="json", http_verb="POST") cert <- self$get(name) if(!wait) message("Certificate creation started. Call the sync() method to update status.") else while(is.null(cert$cer)) { Sys.sleep(5) cert <- self$get(name) } cert }, get_contacts=function() { self$do_operation("contacts") }, set_contacts=function(email) { df <- data.frame(email=email, stringsAsFactors=FALSE) self$do_operation("contacts", body=list(contacts=df), encode="json", http_verb="PUT") }, delete_contacts=function() { invisible(self$do_operation("contacts", http_verb="DELETE")) }, add_issuer=function(issuer, provider, credentials=NULL, details=NULL) { op <- construct_path("issuers", issuer) body <- list(provider=provider, credentials=credentials, org_details=details) self$do_operation(op, body=body, encode="json", http_verb="PUT") }, get_issuer=function(issuer) { op <- construct_path("issuers", issuer) self$do_operation(op) }, remove_issuer=function(issuer) { op <- construct_path("issuers", issuer) invisible(self$do_operation(op, http_verb="DELETE")) }, list_issuers=function() { sapply(self$do_operation("issuers")$value, function(x) basename(x$id)) }, do_operation=function(op="", ..., options=list()) { url <- self$url url$path <- construct_path("certificates", op) url$query <- options call_vault_url(self$token, url, ...) }, print=function(...) { url <- self$url url$path <- "certificates" cat("<key vault endpoint '", httr::build_url(url), "'>\n", sep="") invisible(self) } ))
/scratch/gouwar.j/cran-all/cranData/AzureKeyVault/R/certificates.R
#' Encryption keys in Key Vault #' #' This class represents the collection of encryption keys stored in a vault. It provides methods for managing keys, including creating, importing and deleting keys, and doing backups and restores. For operations with a specific key, see [key]. #' #' @docType class #' #' @section Methods: #' This class provides the following methods: #' ``` #' create(name, type=c("RSA", "EC"), hardware=FALSE, #' ec_curve=NULL, rsa_key_size=NULL, key_ops=NULL, #' attributes=vault_object_attrs(), ...) #' import(name, key, hardware=FALSE, #' attributes=vault_object_attrs(), ...) #' get(name) #' delete(name, confirm=TRUE) #' list(include_managed=FALSE) #' backup(name) #' restore(backup) #' ``` #' @section Arguments: #' - `name`: The name of the key. #' - `type`: For `create`, the type of key to create: RSA or elliptic curve (EC). Note that for keys backing a certificate, only RSA is allowed. #' - `hardware`: For `create`, Whether to use a hardware key or software key. The former requires a premium key vault. #' - `ec_curve`: For an EC key, the type of elliptic curve. #' - `rsa_key_size`: For an RSA key, the key size, either 2048, 3072 or 4096. #' - `key_ops`: A character vector of operations that the key supports. The possible operations are "encrypt", "decrypt", "sign", "verify", "wrapkey" and "unwrapkey". See [key] for more information. #' - `attributes`: Optional attributes for the key, such as the expiry date and activation date. A convenient way to provide this is via the [vault_object_attrs] helper function. #' - `key`: For `import`, the key to import. This can be the name of a PEM file, a JSON web key (JWK) string, or a key object generated by the openssl package. See the examples below. #' - `hardware`: For `import`, whether to import this key as a hardware key (HSM). Only supported for a premium key vault. #' - `...`: For `create` and `import`, other named arguments which will be treated as tags. #' - `include_managed`: For `list`, whether to include keys that were created by Key Vault to support a managed certificate. #' - `backup`: For `restore`, a string representing the backup blob for a key. #' #' @section Value: #' For `get`, `create` and `import`, an object of class `stored_key`, representing the key itself. This has methods for carrying out the operations given by the `key_ops` argument. #' #' For `list`, a vector of key names. #' #' For `backup`, a string representing the backup blob for a key. If the key has multiple versions, the blob will contain all versions. #' #' @seealso #' [key], [vault_object_attrs] #' #' [Azure Key Vault documentation](https://docs.microsoft.com/en-us/azure/key-vault/), #' [Azure Key Vault API reference](https://docs.microsoft.com/en-us/rest/api/keyvault) #' #' @examples #' \dontrun{ #' #' vault <- key_vault("mykeyvault") #' #' vault$keys$create("mynewkey") #' vault$keys$create("myRSAkey", type="RSA", rsa_key_size=4096) #' vault$keys$create("myECkey", type="EC", ec_curve="P-384") #' #' vault$keys$list() #' vault$keys$get("mynewkey") #' #' # specifying an expiry date #' today <- Sys.date() #' vault$keys$create("mynewkey", attributes=vault_object_attrs(expiry_date=today+365)) #' #' # setting management tags #' vault$keys$create("mynewkey", tag1="a value", othertag="another value") #' #' # importing a key from a PEM file #' vault$keys$import("importedkey1", "myprivatekey.pem") #' #' # importing a key generated by OpenSSL #' vault$keys$import("importedkey2", openssl::rsa_keygen()) #' #' # importing a JWK (which is a JSON string) #' key <- openssl::read_key("myprivatekey.pem") #' jwk <- jose::write_jwk(key) #' vault$keys$import("importedkey3", jwk) #' #' # backup and restore a key #' bak <- vault$keys$backup("mynewkey") #' vault$keys$delete("mynewkey", confirm=FALSE) #' vault$keys$restore(bak) #' #' } #' @name keys #' @rdname keys NULL vault_keys <- R6::R6Class("vault_keys", public=list( token=NULL, url=NULL, initialize=function(token, url) { self$token <- token self$url <- url }, create=function(name, type=c("RSA", "EC"), hardware=FALSE, ec_curve=NULL, rsa_key_size=NULL, key_ops=NULL, attributes=vault_object_attrs(), ...) { type <- match.arg(type) key <- switch(type, "RSA"=list(kty=type, key_size=rsa_key_size), "EC"=list(kty=type, crv=ec_curve)) if(hardware) key$kty <- paste0(key$kty, "-HSM") body <- c(key, list(attributes=attributes, key_ops=key_ops, tags=list(...))) op <- construct_path(name, "create") self$do_operation(op, body=body, encode="json", http_verb="POST") self$get(name) }, get=function(name) { stored_key$new(self$token, self$url, name, NULL, self$do_operation(name)) }, delete=function(name, confirm=TRUE) { if(delete_confirmed(confirm, name, "key")) invisible(self$do_operation(name, http_verb="DELETE")) }, list=function(include_managed=FALSE) { objs <- get_vault_paged_list(self$do_operation(), self$token) lst <- lapply(objs, function(props) if(!include_managed && isTRUE(props$managed)) NULL else basename(props$kid)) unlist(compact(lst)) }, backup=function(name) { op <- construct_path(name, "backup") self$do_operation(op, http_verb="POST")$value }, restore=function(backup) { stopifnot(is.character(backup)) op <- construct_path(name, "restore") self$do_operation(op, body=list(value=backup), encode="json", http_verb="POST") }, import=function(name, key, hardware=FALSE, attributes=vault_object_attrs(), ...) { # support importing keys from openssl package, or as json text, or as a PEM file if(is.character(key) && file.exists(key)) key <- openssl::read_key(key) if(inherits(key, "key")) key <- jose::write_jwk(key) if(is.character(key) && jsonlite::validate(key)) key <- jsonlite::fromJSON(key) body <- list(key=key, hsm=hardware, attributes=attributes, tags=list(...)) self$do_operation(name, body=body, encode="json", http_verb="PUT") self$get(name) }, do_operation=function(op="", ..., options=list()) { url <- self$url url$path <- construct_path("keys", op) url$query <- options call_vault_url(self$token, url, ...) }, print=function(...) { url <- self$url url$path <- "keys" cat("<key vault endpoint '", httr::build_url(url), "'>\n", sep="") invisible(self) } ))
/scratch/gouwar.j/cran-all/cranData/AzureKeyVault/R/keys.R
#' Helper functions for key vault objects #' #' @param type For `cert_key_properties`, the type of key to create: RSA or elliptic curve (EC). Note that for keys backing a certificate, only RSA is allowed. #' @param hardware For `cert_key_properties`, whether to use a hardware key or software key. The former requires a premium key vault. #' @param ec_curve For an EC key, the type of elliptic curve. #' @param rsa_key_size For an RSA key, the key size, either 2048, 3072 or 4096. #' @param key_exportable For a key used in a certificate, whether it should be exportable. #' @param reuse_key For a key used in a certificate, whether it should be reused when renewing the certificate. #' @param dns_names,emails,upns For `cert_x509_properties`, the possible subject alternative names (SANs) for a certificate. These should be character vectors. #' @param key_usages For `cert_x509_properties`, a character vector of key usages. #' @param enhanced_key_usages For `cert_x509_properties`, a character vector of enhanced key usages (EKUs). #' @param validity_months For `cert_x509_properties`, the number of months the certificate should be valid for. #' @param issuer For `cert_issuer_properties`, the name of the issuer. Defaults to "self" for a self-signed certificate. #' @param cert_type For `cert_issuer_properties`, the type of certificate to issue, eg "OV-SSL", "DV-SSL" or "EV-SSL". #' @param transparent For `cert_issuer_properties`, whether the certificate should be transparent. #' @param remaining For `cert_expiry_action`, The remaining certificate lifetime at which to take action. If this is a number between 0 and 1, it is interpreted as the percentage of life remaining; otherwise, the number of days remaining. To disable expiry actions, set this to NULL. #' @param action For `cert_expiry_action`, what action to take when a certificate is about to expire. Can be either "AutoRenew" or "EmailContacts". Ignored if `remaining == NULL`. #' @param enabled For `vault_object_attrs`, whether this stored object (key, secret, certificate, storage account) is enabled. #' @param expiry_date,activation_date For `vault_object_attrs`, the optional expiry date and activation date of the stored object. Can be any R object that can be coerced to POSIXct format. #' @param recovery_level For `vault_object_attrs`, the recovery level for the stored object. #' #' @details #' These are convenience functions for specifying the properties of objects stored in a key vault. They return lists of fields to pass to the REST API. #' #' @rdname helpers #' @export cert_key_properties <- function(type=c("RSA", "EC"), hardware=FALSE, ec_curve=NULL, rsa_key_size=NULL, key_exportable=TRUE, reuse_key=FALSE) { type <- match.arg(type) key <- switch(type, "RSA"=list(kty=type, key_size=rsa_key_size), "EC"=list(kty=type, crv=ec_curve)) if(hardware) key$kty <- paste0(key$kty, "-HSM") props <- c(compact(key), reuse_key=reuse_key, exportable=key_exportable) compact(props) } #' @rdname helpers #' @export cert_x509_properties <- function(dns_names=character(), emails=character(), upns=character(), key_usages=c("digitalSignature", "keyEncipherment"), enhanced_key_usages=c("1.3.6.1.5.5.7.3.1", "1.3.6.1.5.5.7.3.2"), validity_months=NULL) { sans <- list(dns_names=I(dns_names), emails=I(emails), upns=I(upns)) props <- list(sans=sans, key_usage=I(key_usages), ekus=I(enhanced_key_usages), validity_months=validity_months) compact(props) } #' @rdname helpers #' @export cert_issuer_properties <- function(issuer="self", cert_type=NULL, transparent=NULL) { compact(list(name=issuer, cty=cert_type, cert_transparency=transparent)) } #' @rdname helpers #' @export cert_expiry_action <- function(remaining=0.1, action=c("AutoRenew", "EmailContacts")) { if(is_empty(remaining)) return(list()) remaining <- as.numeric(remaining) trigger <- if(0 < remaining && remaining < 1) { pct <- round((1 - remaining) * 100) list(lifetime_percentage=pct) } else list(days_before_expiry=remaining) action <- list(action_type=match.arg(action)) list(list(trigger=trigger, action=action)) } #' @rdname helpers #' @export vault_object_attrs <- function(enabled=TRUE, expiry_date=NULL, activation_date=NULL, recovery_level=NULL) { attribs <- list( enabled=enabled, nbf=make_vault_date(activation_date), exp=make_vault_date(expiry_date), recoveryLevel=recovery_level ) compact(attribs) } compact <- function(lst) { lst[!sapply(lst, is.null)] } make_vault_date <- function(date) { if(is_empty(date)) NULL else if(inherits(date, "POSIXt")) as.numeric(date) else as.numeric(as.POSIXct(date)) } int_to_date <- function(dte) { if(is_empty(dte)) NA else as.POSIXct(dte, origin="1970-01-01") }
/scratch/gouwar.j/cran-all/cranData/AzureKeyVault/R/object_props.R
#' Stored secrets in Key Vault #' #' This class represents the collection of secrets stored in a vault. It provides methods for managing secrets, including creating, importing and deleting secrets, and doing backups and restores. #' #' @docType class #' #' @section Methods: #' This class provides the following methods: #' ``` #' create(name, value, content_type=NULL, attributes=vault_object_attrs(), ...) #' get(name) #' delete(name, confirm=TRUE) #' list(include_managed=FALSE) #' backup(name) #' restore(backup) #' ``` #' @section Arguments: #' - `name`: The name of the secret. #' - `value`: For `create`, the secret to store. This should be a character string or a raw vector. #' - `content_type`: For `create`, an optional content type of the secret, such as "application/octet-stream". #' - `attributes`: Optional attributes for the secret, such as the expiry date and activation date. A convenient way to provide this is via the [vault_object_attrs] helper function. #' - `...`: For `create`, other named arguments which will be treated as tags. #' - `include_managed`: For `list`, whether to include secrets that were created by Key Vault to support a managed certificate. #' - `backup`: For `restore`, a string representing the backup blob for a secret. #' #' @section Value: #' For `get`, and `create`, an object of class `stored_secret`, representing the secret. The actual value of the secret is in the `value` field. #' #' For `list`, a vector of secret names. #' #' For `backup`, a string representing the backup blob for a secret. If the secret has multiple versions, the blob will contain all versions. #' #' @seealso #' [vault_object_attrs] #' #' [Azure Key Vault documentation](https://docs.microsoft.com/en-us/azure/key-vault/), #' [Azure Key Vault API reference](https://docs.microsoft.com/en-us/rest/api/keyvault) #' #' @examples #' \dontrun{ #' #' vault <- key_vault("mykeyvault") #' #' vault$secrets$create("mysecret", "secret string") #' #' vault$secrets$list() #' #' secret <- vault$secrets$get("mysecret") #' secret$value # 'secret string' #' #' # specifying an expiry date #' today <- Sys.date() #' vault$secrets$create("mysecret", attributes=vault_object_attrs(expiry_date=today+365)) #' #' # setting management tags #' vault$secrets$create("mysecret", tag1="a value", othertag="another value") #' #' } #' @name secrets #' @rdname secrets NULL vault_secrets <- R6::R6Class("vault_secrets", public=list( token=NULL, url=NULL, initialize=function(token, url) { self$token <- token self$url <- url }, create=function(name, value, content_type=NULL, attributes=vault_object_attrs(), ...) { body <- list(value=value, contentType=content_type, attributes=attributes, tags=list(...)) self$do_operation(name, body=body, encode="json", http_verb="PUT") self$get(name) }, get=function(name, version=NULL) { op <- construct_path(name, version) stored_secret$new(self$token, self$url, name, version, self$do_operation(op)) }, delete=function(name, confirm=TRUE) { if(delete_confirmed(confirm, name, "secret")) invisible(self$do_operation(name, http_verb="DELETE")) }, list=function(include_managed=FALSE) { objs <- get_vault_paged_list(self$do_operation(), self$token) lst <- lapply(objs, function(props) if(!include_managed && isTRUE(props$managed)) NULL else basename(props$id)) unlist(compact(lst)) }, backup=function(name) { self$do_operation(construct_path(name, "backup"), http_verb="POST")$value }, restore=function(name, backup) { stopifnot(is.character(backup)) self$do_operation("restore", body=list(value=backup), encode="json", http_verb="POST") }, do_operation=function(op="", ..., options=list()) { url <- self$url url$path <- construct_path("secrets", op) url$query <- options call_vault_url(self$token, url, ...) }, print=function(...) { url <- self$url url$path <- "secrets" cat("<key vault endpoint '", httr::build_url(url), "'>\n", sep="") invisible(self) } ))
/scratch/gouwar.j/cran-all/cranData/AzureKeyVault/R/secrets.R
#' Storage accounts in Key Vault #' #' This class represents the collection of storage accounts managed by a vault. It provides methods for adding and removing accounts, and doing backups and restores. For operations with a specific account, see [storage]. #' #' @docType class #' #' @section Methods: #' This class provides the following methods: #' ``` #' add(name, storage_account, key_name, regen_key=TRUE, regen_period=30, #' attributes=vault_object_attrs(), ...) #' get(name) #' remove(name, confirm=TRUE) #' list() #' backup(name) #' restore(backup) #' ``` #' @section Arguments: #' - `name`: A name by which to refer to the storage account. #' - `storage_account`: The Azure resource ID of the account. This can also be an object of class `az_resource` or `az_storage`, as provided by the AzureRMR or AzureStor packages respectively; in this case, the resource ID is obtained from the object. #' - `key_name`: The name of the storage access key that Key Vault will manage. #' - `regen_key`: Whether to automatically regenerate the access key at periodic intervals. #' - `regen_period`: How often to regenerate the access key. This can be a number, which will be interpreted as days; or as an ISO-8601 string denoting a duration, eg "P30D" (30 days). #' - `attributes`: Optional attributes for the secret. A convenient way to provide this is via the [vault_object_attrs] helper function. #' - `...`: For `create` and `import`, other named arguments which will be treated as tags. #' - `confirm`: For `remove`, whether to ask for confirmation before removing the account. #' - `backup`: For `restore`, a string representing the backup blob for a key. #' - `email`: For `set_contacts`, the email addresses of the contacts. #' #' @section Value: #' For `get` and `add`, an object of class `stored_account`, representing the storage account itself. #' #' For `list`, a vector of account names. #' #' For `backup`, a string representing the backup blob for a storage account. If the account has multiple versions, the blob will contain all versions. #' #' @seealso #' [storage_account], [vault_object_attrs] #' #' [Azure Key Vault documentation](https://docs.microsoft.com/en-us/azure/key-vault/), #' [Azure Key Vault API reference](https://docs.microsoft.com/en-us/rest/api/keyvault) #' #' @examples #' \dontrun{ #' #' vault <- key_vault("mykeyvault") #' #' # get the storage account details #' library(AzureStor) #' stor <- AzureRMR::get_azure_login()$ #' get_subscription("sub_id")$ #' get_resource_group("rgname")$ #' get_storage_account("mystorageacct") #' vault$storage$create("mystor", stor, "key1") #' #' vault$storage$list() #' vault$storage$get("mystor") #' #' # specifying a regeneration period of 6 months #' vault$storage$create("mystor", regen_period="P6M") #' #' # setting management tags #' vault$storage$create("mystor", tag1="a value", othertag="another value") #' #' # backup and restore an account #' bak <- vault$storage$backup("mystor") #' vault$storage$delete("mystor", confirm=FALSE) #' vault$storage$restore(bak) #' #' } #' @name storage_accounts #' @aliases storage_accounts storage #' @rdname storage_accounts NULL vault_storage_accounts <- R6::R6Class("vault_storage_accounts", public=list( token=NULL, url=NULL, initialize=function(token, url) { self$token <- token self$url <- url }, add=function(name, storage_account, key_name, regen_key=TRUE, regen_period=30, attributes=vault_object_attrs(), ...) { if(is_resource(storage_account)) storage_account <- storage_account$id if(is.numeric(regen_period)) regen_period <- sprintf("P%sD", regen_period) # some attributes not used for storage accounts attributes$nbf <- attributes$exp <- NULL body <- list(resourceId=storage_account, activeKeyName=key_name, autoRegenerateKey=regen_key, regenerationPeriod=regen_period, attributes=attributes, tags=list(...)) self$do_operation(name, body=body, encode="json", http_verb="PUT") self$get(name) }, get=function(name, version=NULL) { op <- construct_path(name, version) stored_account$new(self$token, self$url, name, version, self$do_operation(op)) }, remove=function(name, confirm=TRUE) { if(delete_confirmed(confirm, name, "storage account")) invisible(self$do_operation(name, http_verb="DELETE")) }, list=function() { sapply(get_vault_paged_list(self$do_operation(), self$token), function(props) basename(props$id)) }, backup=function(name) { self$do_operation(construct_path(name, "backup"), http_verb="POST")$value }, restore=function(name, backup) { stopifnot(is.character(backup)) self$do_operation("restore", body=list(value=backup), encode="json", http_verb="POST") }, do_operation=function(op="", ..., options=list(), api_version=getOption("azure_keyvault_api_version")) { url <- self$url url$path <- construct_path("storage", op) url$query <- utils::modifyList(list(`api-version`=api_version), options) call_vault_url(self$token, url, ...) }, print=function(...) { url <- self$url url$path <- "storage" cat("<key vault endpoint '", httr::build_url(url), "'>\n", sep="") invisible(self) } ))
/scratch/gouwar.j/cran-all/cranData/AzureKeyVault/R/storage_accounts.R
#' Managed storage account #' #' This class represents a storage account that Key Vault will manage access to. It provides methods for regenerating keys, and managing shared access signatures (SAS). #' #' @docType class #' #' @section Fields: #' This class provides the following fields: #' - `id`: The internal vault ID of the storage account. #' - `resourceId`: The Azure resource ID of the storage account. #' - `activeKeyName`: The current active storage account key. #' - `autoRegenerateKey`: Whether Key Vault will manage the storage account's key. #' - `regenerationPeriod`: How often the account key is regenerated, in ISO 8601 format. #' #' @section Methods: #' This class provides the following methods: #' ``` #' regenerate_key(key_name) #' create_sas_definition(sas_name, sas_template, validity_period, sas_type="account", #' enabled=TRUE, recovery_level=NULL, ...) #' delete_sas_definition(sas_name, confirm=TRUE) #' get_sas_definition(sas_name) #' list_sas_definitions() #' show_sas(sas_name) #' #' update_attributes(attributes=vault_object_attrs(), ...) #' remove(confirm=TRUE) #' ``` #' @section Arguments: #' - `key_name`: For `regenerate_key`, the name of the access key to regenerate. #' - `sas_name`: The name of a SAS definition. #' - `sas_template`: A string giving the details of the SAS to create. See 'Details' below. #' - `validity_period`: How long the SAS should be valid for. #' - `sas_type`: The type of SAS to generate, either "account" or "service". #' - `enabled`: Whether the SAS definition. is enabled. #' - `recovery_level`: The recovery level of the SAS definition. #' - `...`: For `create_sas_definition`, other named arguments to use as tags for a SAS definition. For `update_attributes`, additional account-specific properties to update. See [storage_accounts]. #' - `attributes`: For `update_attributes`, the new attributes for the object, such as the expiry date and activation date. A convenient way to provide this is via the [vault_object_attrs] helper function. #' - `confirm`: For `delete` and `delete_sas_definition`, whether to ask for confirmation before deleting. #' #' @section Details: #' `create_sas_definition` creates a new SAS definition from a template. This can be created from the Azure Portal, via the Azure CLI, or in R via the AzureStor package (see examples). `get_sas_definition` returns a list representing the template definition; `show_sas` returns the actual SAS. #' #' `regenerate_key` manually regenerates an access key. Note that if the vault is setup to regenerate keys automatically, you won't usually have to use this method. #' #' Unlike the other objects stored in a key vault, storage accounts are not versioned. #' #' @section Value: #' For `create_sas_definition` and `get_sas_definition`, a list representing the SAS definition. For `list_sas_definitions`, a list of such lists. #' #' For `show_sas`, a string containing the SAS. #' #' @seealso #' [storage_accounts] #' #' [Azure Key Vault documentation](https://docs.microsoft.com/en-us/azure/key-vault/), #' [Azure Key Vault API reference](https://docs.microsoft.com/en-us/rest/api/keyvault) #' #' @examples #' \dontrun{ #' #' vault <- key_vault("mykeyvault") #' #' # get the storage account details #' library(AzureStor) #' res <- AzureRMR::get_azure_login()$ #' get_subscription("sub_id")$ #' get_resource_group("rgname")$ #' get_storage_account("mystorageacct") #' #' stor <- vault$storage$create("mystor", res, "key1") #' #' # Creating a new SAS definition #' today <- Sys.time() #' sasdef <- res$get_account_sas(expiry=today + 7*24*60*60, services="b", permissions="rw") #' stor$create_sas_definition("newsas", sasdef, validity_period="P15D") #' #' stor$show_sas("newsas") #' #' } #' @name storage_account #' @rdname storage_account NULL stored_account <- R6::R6Class("stored_account", inherit=stored_object, public=list( type="storage", id=NULL, resourceId=NULL, activeKeyName=NULL, autoRegenerateKey=NULL, regenerationPeriod=NULL, # change delete -> remove for storage accts delete=NULL, remove=function(confirm=TRUE) { if(delete_confirmed(confirm, self$name, "storage")) invisible(self$do_operation(version=NULL, http_verb="DELETE")) }, regenerate_key=function(key_name) { self$do_operation("regeneratekey", body=list(keyName=key_name), http_verb="POST") }, create_sas_definition=function(sas_name, sas_template, validity_period, sas_type="account", enabled=TRUE, recovery_level=NULL, ...) { attribs <- list( enabled=enabled, recoveryLevel=recovery_level ) attribs <- attribs[!sapply(attribs, is_empty)] body <- list( sasType=sas_type, templateUri=sas_template, validityPeriod=validity_period, attributes=attribs, tags=list(...) ) op <- construct_path("sas", sas_name) self$do_operation(op, body=body, encode="json", http_verb="PUT") }, delete_sas_definition=function(sas_name, confirm=TRUE) { if(delete_confirmed(confirm, sas_name, "SAS definition")) { op <- construct_path("sas", sas_name) invisible(self$do_operation(op, http_verb="DELETE")) } }, get_sas_definition=function(sas_name) { op <- construct_path("sas", sas_name) self$do_operation(op) }, list_sas_definitions=function() { get_vault_paged_list(self$do_operation("sas"), self$token) }, show_sas=function(sas_name) { secret_url <- self$get_sas_definition(sas_name)$sid call_vault_url(self$token, secret_url)$value }, print=function(...) { cat("Key Vault managed storage account '", self$name, "'\n", sep="") cat(" Account:", basename(self$resourceId), "\n") invisible(self) } ))
/scratch/gouwar.j/cran-all/cranData/AzureKeyVault/R/stored_acct.R
#' Certificate object #' #' This class represents a certificate stored in a vault. It provides methods for carrying out operations, including encryption and decryption, signing and verification, and wrapping and unwrapping. #' #' @docType class #' #' @section Fields: #' This class provides the following fields: #' - `cer`: The contents of the certificate, in CER format. #' - `id`: The ID of the certificate. #' - `kid`: The ID of the key backing the certificate. #' - `sid`: The ID of the secret backing the certificate. #' - `contentType`: The content type of the secret backing the certificate. #' - `policy`: The certificate management policy, containing the authentication details. #' - `x5t`: The thumbprint of the certificate. #' #' @section Methods: #' This class provides the following methods: #' ``` #' export(file) #' export_cer(file) #' sign(digest, ...) #' verify(signature, digest, ...) #' set_policy(subject=NULL, x509=NULL, issuer=NULL, #' key=NULL, secret_type=NULL, actions=NULL, #' attributes=NULL, wait=TRUE) #' get_policy() #' sync() #' #' update_attributes(attributes=vault_object_attrs(), ...) #' list_versions() #' set_version(version=NULL) #' delete(confirm=TRUE) #' ``` #' @section Arguments: #' - `file`: For `export` and `export_cer`, a connection object or a character string naming a file to export to. #' - `digest`: For `sign`, a hash digest string to sign. For `verify`, a digest to compare to a signature. #' - `signature`: For `verify`, a signature string. #' - `subject,x509,issuer,key,secret_type,actions,wait`: These are the same arguments as used when creating a new certificate. See [certificates] for more information. #' - `attributes`: For `update_attributes`, the new attributes for the object, such as the expiry date and activation date. A convenient way to provide this is via the [vault_object_attrs] helper function. #' - `...`: For `update_attributes`, additional key-specific properties to update. For `sign` and `verify`, additional arguments for the corresponding key object methods. See [keys] and [key]. #' - `version`: For `set_version`, the version ID or NULL for the current version. #' - `confirm`: For `delete`, whether to ask for confirmation before deleting the key. #' #' @section Details: #' `export` exports the full certificate to a file. The format wll be either PEM or PFX (aka PKCS#12), as set by the `format` argument when the certificate was created. `export_cer` exports the public key component, aka the CER file. Note that the public key can also be found in the `cer` field of the object. #' #' `sign` uses the key associated with the a certificate to sign a digest, and `verify` checks a signature against a digest for authenticity. See below for an example of using `sign` to do OAuth authentication with certificate credentials. #' #' `set_policy` updates the authentication details of a certificate: its issuer, identity, key type, renewal actions, and so on. `get_policy` returns the current policy of a certificate. #' #' A certificate can have multiple _versions_, which are automatically generated when a cert is created with the same name as an existing cert. By default, this object contains the information for the most recent (current) version; use `list_versions` and `set_version` to change the version. #' #' @section Value: #' For `get_policy`, a list of certificate policy details. #' #' For `list_versions`, a data frame containing details of each version. #' #' For `set_version`, the key object with the updated version. #' #' @seealso #' [certificates] #' #' [Azure Key Vault documentation](https://docs.microsoft.com/en-us/azure/key-vault/), #' [Azure Key Vault API reference](https://docs.microsoft.com/en-us/rest/api/keyvault) #' #' @examples #' \dontrun{ #' #' vault <- key_vault("mykeyvault") #' #' cert <- vault$certificates$create("mynewcert") #' cert$cer #' cert$export("mynewcert.pem") #' #' # new version of an existing certificate #' vault$certificates$create("mynewcert", x509=cert_x509_properties(validity_months=24)) #' #' cert <- vault$certificates$get("mynewcert") #' vers <- cert$list_versions() #' cert$set_version(vers[2]) #' #' # updating an existing cert version #' cert$set_policy(x509=cert_x509_properties(validity_months=12)) #' #' #' ## signing a JSON web token (JWT) for authenticating with Azure Active Directory #' app <- "app_id" #' tenant <- "tenant_id" #' claim <- jose::jwt_claim( #' iss=app, #' sub=app, #' aud="https://login.microsoftonline.com/tenant_id/oauth2/token", #' exp=as.numeric(Sys.time() + 60*60), #' nbf=as.numeric(Sys.time()) #' ) #' # header includes cert thumbprint #' header <- list(alg="RS256", typ="JWT", x5t=cert$x5t) #' #' token_encode <- function(x) #' { #' jose::base64url_encode(jsonlite::toJSON(x, auto_unbox=TRUE)) #' } #' token_contents <- paste(token_encode(header), token_encode(claim), sep=".") #' #' # get the signature and concatenate it with header and claim to form JWT #' sig <- cert$sign(openssl::sha256(charToRaw(token_contents))) #' cert_creds <- paste(token_contents, sig, sep=".") #' #' AzureAuth::get_azure_token("resource_url", tenant, app, certificate=cert_creds) #' #' } #' @name certificate #' @aliases certificate cert #' @rdname certificate NULL stored_cert <- R6::R6Class("stored_cert", inherit=stored_object, public=list( type="certificates", id=NULL, sid=NULL, kid=NULL, cer=NULL, x5t=NULL, contentType=NULL, pending=NULL, policy=NULL, export=function(file) { if(is.character(file)) { file <- file(file, "wb") on.exit(close(file)) } secret <- call_vault_url(self$token, self$sid) value <- if(secret$contentType == "application/x-pkcs12") openssl::base64_decode(secret$value) else charToRaw(secret$value) writeBin(value, file) }, export_cer=function(file) { if(is.character(file)) { file <- file(file, "wb") on.exit(close(file)) } writeLines(self$cer, file) }, sync=function() { pending <- call_vault_url(self$token, self$pending$id) if(pending$status == "completed" && !is_empty(pending$target)) { props <- call_vault_url(self$token, pending$target) self$initialize(self$token, self$url, self$name, NULL, props) } self }, list_versions=function() { lst <- lapply(get_vault_paged_list(self$do_operation("versions", version=NULL), self$token), function(props) { attr <- props$attributes data.frame( version=basename(props$id), thumbprint=props$x5t, created=int_to_date(attr$created), updated=int_to_date(attr$updated), expiry=int_to_date(attr$exp), not_before=int_to_date(attr$nbf), stringsAsFactors=FALSE ) }) do.call(rbind, lst) }, get_policy=function() { structure(self$do_operation("policy", version=NULL), class="cert_policy") }, set_policy=function(subject=NULL, x509=NULL, issuer=NULL, key=NULL, secret_type=NULL, actions=NULL, attributes=NULL, wait=TRUE) { if(!is.null(secret_type)) { secret_type <- if(secret_type == "pem") "application/x-pem-file" else "application/x-pkcs12" } policy <- list( issuer=issuer, key_props=key, secret_props=list(contentType=secret_type), x509_props=c(subject=subject, x509), lifetime_actions=actions ) body <- list(policy=compact(policy), attributes=attributes) pol <- self$do_operation("policy", body=body, encode="json", version=NULL, http_verb="PATCH") self$policy <- pol structure(pol, class="cert_policy") }, sign=function(digest, ...) { key <- stored_key$new(self$token, self$url, self$name, NULL, call_vault_url(self$token, self$kid)) key$sign(digest, ...) }, verify=function(signature, digest, ...) { key <- stored_key$new(self$token, self$url, self$name, NULL, call_vault_url(self$token, self$kid)) key$verify(signature, digest, ...) }, print=function(...) { cat("Key Vault stored certificate '", self$name, "'\n", sep="") cat(" Version:", if(is.null(self$version)) "<default>" else self$version, "\n") cat(" Subject:", self$policy$x509_props$subject, "\n") cat(" Issuer:", self$policy$issuer$name, "\n") cat(" Valid for:", self$policy$x509_props$validity_months, "months\n") invisible(self) } )) #' @export print.cert_policy <- function(x, ...) { certname <- basename(dirname(x$id)) cat("Policy for Key Vault stored certificate '", certname, "'\n\n", sep="") out <- lapply(x[-1], function(xx) { unl <- unlist(xx) if(!is.null(unl)) { df <- data.frame(matrix(unl, nrow=1)) names(df) <- names(unl) df } else xx }) mapply(function(name, value) { cat(name, ":\n", sep="") print(value, row.names=FALSE) cat("\n") }, names(out), out) invisible(x) }
/scratch/gouwar.j/cran-all/cranData/AzureKeyVault/R/stored_cert.R
#' Encryption key object #' #' This class represents an encryption key stored in a vault. It provides methods for carrying out operations, including encryption and decryption, signing and verification, and wrapping and unwrapping. #' #' @docType class #' #' @section Fields: #' This class provides the following fields: #' - `key`: The key details as a parsed JSON web key (JWK). #' - `managed`: Whether this key's lifetime is managed by Key Vault. TRUE if the key backs a certificate. #' #' @section Methods: #' This class provides the following methods: #' ``` #' encrypt(plaintext, algorithm=c("RSA-OAEP", "RSA-OAEP-256", "RSA1_5")) #' decrypt(ciphertext, algorithm=c("RSA-OAEP", "RSA-OAEP-256", "RSA1_5"), as_raw=TRUE) #' sign(digest, #' algorithm=c("RS256", "RS384", "RS512", "PS256", "PS384", "PS512", #' "ES256", "ES256K", "ES384", "ES512")) #' verify(signature, digest, #' algorithm=c("RS256", "RS384", "RS512", "PS256", "PS384", "PS512", #' "ES256", "ES256K", "ES384", "ES512")) #' wrap(value, algorithm=c("RSA-OAEP", "RSA-OAEP-256", "RSA1_5")) #' unwrap(value, algorithm=c("RSA-OAEP", "RSA-OAEP-256", "RSA1_5"), as_raw=TRUE) #' #' update_attributes(attributes=vault_object_attrs(), ...) #' list_versions() #' set_version(version=NULL) #' delete(confirm=TRUE) #' ``` #' @section Arguments: #' - `plaintext`: For `encrypt`, the plaintext to encrypt. #' - `ciphertext`: For `decrypt`, the ciphertext to decrypt. #' - `digest`: For `sign`, a generated hash to sign. For `verify`, the digest to verify for authenticity. #' - `signature`: For `verify`, a signature to verify for authenticity. #' - `value`: For `wrap`, a symmetric key to be wrapped; for `unwrap`, the value to be unwrapped to obtain the symmetric key. #' - `as_raw`: For `decrypt` and `unwrap`, whether to return a character vector or a raw vector (the default). #' - `algorithm`: The algorithm to use for each operation. Note that the algorithm must be compatible with the key type, eg RSA keys cannot use ECDSA for signing or verifying. #' - `attributes`: For `update_attributes`, the new attributes for the object, such as the expiry date and activation date. A convenient way to provide this is via the [vault_object_attrs] helper function. #' - `...`: For `update_attributes`, additional key-specific properties to update. See [keys]. #' - `version`: For `set_version`, the version ID or NULL for the current version. #' - `confirm`: For `delete`, whether to ask for confirmation before deleting the key. #' #' @section Details: #' The operations supported by a key will be those given by the `key_ops` argument when the key was created. By default, a newly created RSA key supports all the operations listed above: encrypt/decrypt, sign/verify, and wrap/unwrap. An EC key only supports the sign and verify operations. #' #' A key can have multiple _versions_, which are automatically generated when a key is created with the same name as an existing key. By default, the most recent (current) version is used for key operations; use `list_versions` and `set_version` to change the version. #' #' @section Value: #' For the key operations, a raw vector (for `decrypt` and `unwrap`, if `as_raw=TRUE`) or character vector. #' #' For `list_versions`, a data frame containing details of each version. #' #' For `set_version`, the key object with the updated version. #' #' @seealso #' [keys] #' #' [Azure Key Vault documentation](https://docs.microsoft.com/en-us/azure/key-vault/), #' [Azure Key Vault API reference](https://docs.microsoft.com/en-us/rest/api/keyvault) #' #' @examples #' \dontrun{ #' #' vault <- key_vault("mykeyvault") #' #' vault$keys$create("mynewkey") #' # new version of an existing key #' vault$keys$create("mynewkey", type="RSA", rsa_key_size=4096) #' #' key <- vault$keys$get("mynewkey") #' vers <- key$list_versions() #' key$set_version(vers[2]) #' #' plaintext <- "some secret text" #' #' ciphertext <- key$encrypt(plaintext) #' decrypted <- key$decrypt(ciphertext, as_raw=FALSE) #' decrypted == plaintext # TRUE #' #' dig <- openssl::sha2(charToRaw(plaintext)) #' sig <- key$sign(dig) #' key$verify(sig, dig) # TRUE #' #' wraptext <- key$wrap(plaintext) #' unwrap_text <- key$unwrap(wraptext, as_raw=FALSE) #' plaintext == unwrap_text # TRUE #' #' } #' @name key #' @rdname key NULL stored_key <- R6::R6Class("stored_key", inherit=stored_object, public=list( type="keys", key=NULL, list_versions=function() { lst <- lapply(get_vault_paged_list(self$do_operation("versions", version=NULL), self$token), function(props) { attr <- props$attributes data.frame( version=basename(props$kid), created=int_to_date(attr$created), updated=int_to_date(attr$updated), expiry=int_to_date(attr$exp), not_before=int_to_date(attr$nbf), stringsAsFactors=FALSE ) }) do.call(rbind, lst) }, encrypt=function(plaintext, algorithm=c("RSA-OAEP", "RSA-OAEP-256", "RSA1_5")) { if(!is.raw(plaintext) && !is.character(plaintext)) stop("Can only encrypt raw or character plaintext") body <- list( alg=match.arg(algorithm), value=jose::base64url_encode(plaintext) ) self$do_operation("encrypt", body=body, encode="json", http_verb="POST")$value }, decrypt=function(ciphertext, algorithm=c("RSA-OAEP", "RSA-OAEP-256", "RSA1_5"), as_raw=TRUE) { if(!is.raw(ciphertext) && !is.character(ciphertext)) stop("Can only decrypt raw or character ciphertext") body <- list( alg=match.arg(algorithm), value=ciphertext ) out <- jose::base64url_decode( self$do_operation("decrypt", body=body, encode="json", http_verb="POST")$value) if(as_raw) out else rawToChar(out) }, sign=function(digest, algorithm=c("RS256", "RS384", "RS512", "PS256", "PS384", "PS512", "ES256", "ES256K", "ES384", "ES512")) { if(!is.raw(digest) && !is.character(digest)) stop("Can only sign raw or character digest") body <- list( alg=match.arg(algorithm), value=jose::base64url_encode(digest) ) self$do_operation("sign", body=body, encode="json", http_verb="POST")$value }, verify=function(signature, digest, algorithm=c("RS256", "RS384", "RS512", "PS256", "PS384", "PS512", "ES256", "ES256K", "ES384", "ES512")) { if(!is.raw(signature) && !is.character(signature)) stop("Can only verify raw or character signature") if(!is.raw(digest) && !is.character(digest)) stop("Can only verify raw or character digest") body <- list( alg=match.arg(algorithm), digest=jose::base64url_encode(digest), value=signature ) self$do_operation("verify", body=body, encode="json", http_verb="POST")$value }, wrap=function(value, algorithm=c("RSA-OAEP", "RSA-OAEP-256", "RSA1_5")) { if(!is.raw(value) && !is.character(value)) stop("Can only wrap raw or character input") body <- list( alg=match.arg(algorithm), value=jose::base64url_encode(value) ) self$do_operation("wrapkey", body=body, encode="json", http_verb="POST")$value }, unwrap=function(value, algorithm=c("RSA-OAEP", "RSA-OAEP-256", "RSA1_5"), as_raw=TRUE) { if(!is.raw(value) && !is.character(value)) stop("Can only wrap raw or character input") body <- list( alg=match.arg(algorithm), value=value ) out <- jose::base64url_decode( self$do_operation("unwrapkey", body=body, encode="json", http_verb="POST")$value) if(as_raw) out else rawToChar(out) }, print=function(...) { cat("Key Vault stored key '", self$name, "'\n", sep="") cat(" Version:", if(is.null(self$version)) "<default>" else self$version, "\n") key_props <- if(self$key$kty %in% c("RSA", "RSA-HSM")) paste0(length(jose::base64url_decode(self$key$n)) * 8, "-bit") else self$key$crv type <- paste(self$key$kty, key_props, sep="/") cat(" Type:", type, "\n") cat(" Allowed operations:", unlist(self$key$key_ops), "\n") invisible(self) } ))
/scratch/gouwar.j/cran-all/cranData/AzureKeyVault/R/stored_key.R
stored_object <- R6::R6Class("stored_object", public=list( token=NULL, url=NULL, name=NULL, version=NULL, attributes=NULL, managed=NULL, tags=NULL, initialize=function(token, url, name, version, properties) { self$token <- token self$url <- url self$name <- name self$version <- version lapply(names(properties), function(n) { if(exists(n, self)) self[[n]] <- properties[[n]] else warning("Unexpected property: ", n) }) }, delete=function(confirm=TRUE) { type <- if(self$type == "storage") "storage account" else sub("s$", "", self$type) if(delete_confirmed(confirm, self$name, type)) invisible(self$do_operation(version=NULL, http_verb="DELETE")) }, update_attributes=function(attributes=vault_object_attrs(), ...) { body <- list(attributes=attributes, ...) props <- self$do_operation(body=body, encode="json", http_verb="PATCH") self$initialize(self$token, self$url, self$name, self$version, props) self }, set_version=function(version=NULL) { props <- self$do_operation(version=version) self$initialize(self$token, self$url, self$name, version, props) self }, do_operation=function(op="", ..., version=self$version, options=list()) { url <- self$url url$path <- construct_path(self$type, self$name, version, op) url$query <- options call_vault_url(self$token, url, ...) }, print=function(...) { cat("<vault stored object '", self$name, "'>\n") invisible(self) } ))
/scratch/gouwar.j/cran-all/cranData/AzureKeyVault/R/stored_object.R
#' Stored secret object #' #' This class represents a secret stored in a vault. #' #' @docType class #' #' @section Fields: #' This class provides the following fields: #' - `value`: The value of the secret. #' - `id`: The ID of the secret. #' - `kid`: If this secret backs a certificate, the ID of the corresponding key. #' - `managed`: Whether this secret's lifetime is managed by Key Vault. TRUE if the secret backs a certificate. #' - `contentType`: The content type of the secret. #' #' @section Methods: #' This class provides the following methods: #' ``` #' update_attributes(attributes=vault_object_attrs(), ...) #' list_versions() #' set_version(version=NULL) #' delete(confirm=TRUE) #' ``` #' @section Arguments: #' - `attributes`: For `update_attributes`, the new attributes for the object, such as the expiry date and activation date. A convenient way to provide this is via the [vault_object_attrs] helper function. #' - `...`: For `update_attributes`, additional secret-specific properties to update. See [secrets]. #' - `version`: For `set_version`, the version ID or NULL for the current version. #' - `confirm`: For `delete`, whether to ask for confirmation before deleting the secret. #' #' @section Details: #' A secret can have multiple _versions_, which are automatically generated when a secret is created with the same name as an existing secret. By default, the most recent (current) version is used for secret operations; use `list_versions` and `set_version` to change the version. #' #' The value is stored as an object of S3 class "secret_value", which has a print method that hides the value to guard against shoulder-surfing. Note that this will not stop a determined attacker; as a general rule, you should minimise assigning secrets or passing them around your R environment. If you want the raw string value itself, eg when passing it to `jsonlite::toJSON` or other functions which do not accept arbitrary object classes as inputs, use `unclass` to strip the class attribute first. #' #' @section Value: #' For `list_versions`, a data frame containing details of each version. #' #' For `set_version`, the secret object with the updated version. #' #' @seealso #' [secrets] #' #' [Azure Key Vault documentation](https://docs.microsoft.com/en-us/azure/key-vault/), #' [Azure Key Vault API reference](https://docs.microsoft.com/en-us/rest/api/keyvault) #' #' @examples #' \dontrun{ #' #' vault <- key_vault("mykeyvault") #' #' vault$secrets$create("mynewsecret", "secret text") #' # new version of an existing secret #' vault$secrets$create("mynewsecret", "extra secret text")) #' #' secret <- vault$secrets$get("mynewsecret") #' vers <- secret$list_versions() #' secret$set_version(vers[2]) #' #' # printing the value will not show the secret #' secret$value # "<hidden>" #' #' } #' @name storage_account #' @rdname storage_account NULL stored_secret <- R6::R6Class("stored_secret", inherit=stored_object, public=list( type="secrets", id=NULL, kid=NULL, value=NULL, contentType=NULL, initialize=function(...) { super$initialize(...) # basic obfuscation of value to help mitigate shoulder-surfing class(self$value) <- "secret_value" }, list_versions=function() { lst <- lapply(get_vault_paged_list(self$do_operation("versions", version=NULL), self$token), function(props) { content_type <- if(!is_empty(props$contentType)) props$contentType else NA attr <- props$attributes data.frame( version=basename(props$id), content_type=content_type, created=int_to_date(attr$created), updated=int_to_date(attr$updated), expiry=int_to_date(attr$exp), not_before=int_to_date(attr$nbf), stringsAsFactors=FALSE ) }) do.call(rbind, lst) }, print=function(...) { cat("Key Vault stored secret '", self$name, "'\n", sep="") cat(" Version:", if(is.null(self$version)) "<default>" else self$version, "\n") invisible(self) } )) #' @export print.secret_value <- function(x, ...) { cat("<hidden>\n") invisible(x) }
/scratch/gouwar.j/cran-all/cranData/AzureKeyVault/R/stored_secret.R
call_vault_url <- function(token, url, ..., body=NULL, encode="json", api_version=getOption("azure_keyvault_api_version"), http_verb=c("GET", "DELETE", "PUT", "POST", "HEAD", "PATCH"), http_status_handler=c("stop", "warn", "message", "pass")) { if(!inherits(url, "url")) url <- httr::parse_url(url) if(is.null(url$query)) url$query <- list() url$query <- utils::modifyList(url$query, list(`api-version`=api_version)) headers <- process_headers(token, url) # if content-type is json, serialize it manually to ensure proper handling of nulls if(encode == "json") { empty <- vapply(body, is_empty, logical(1)) body <- jsonlite::toJSON(body[!empty], auto_unbox=TRUE, digits=22, null="null") encode <- "raw" } res <- httr::VERB(match.arg(http_verb), url, headers, body=body, encode=encode, ...) process_response(res, match.arg(http_status_handler)) } process_headers <- function(token, url) { headers <- c( Host=url$hostname, Authorization=paste("Bearer", validate_token(token)), `Content-type`="application/json" ) httr::add_headers(.headers=headers) } validate_token <- function(token) { # token can be a string or an object of class AzureToken if(AzureRMR::is_azure_token(token)) { if(!token$validate()) # refresh if needed { message("Access token has expired or is no longer valid; refreshing") token$refresh() } token <- token$credentials$access_token } else if(!is.character(token)) stop("Invalid authentication token", call.=FALSE) token } process_response <- function(response, handler) { if(handler != "pass") { cont <- httr::content(response) handler <- get(paste0(handler, "_for_status"), getNamespace("httr")) handler(response, paste0("complete operation. Message:\n", sub("\\.$", "", error_message(cont)))) if(is.null(cont)) cont <- list() attr(cont, "status") <- httr::status_code(response) cont } else response } error_message <- function(cont) { # kiboze through possible message locations msg <- if(is.character(cont)) cont else if(is.list(cont)) { if(is.character(cont$message)) cont$message else if(is.list(cont$error) && is.character(cont$error$message)) cont$error$message else if(is.list(cont$odata.error)) cont$odata.error$message$value } else "" gsub("\r", "", paste0(strwrap(msg), collapse="\n")) } construct_path <- function(...) { args <- list(...) args <- args[!sapply(args, is.null)] sub("//", "/", do.call(file.path, args)) } get_vault_paged_list <- function(lst, token, next_link_name="nextLink", value_name="value") { res <- lst[[value_name]] while(!is_empty(lst[[next_link_name]])) { lst <- call_vault_url(token, lst[[next_link_name]]) res <- c(res, lst[[value_name]]) } res } # TRUE if delete confirmed, FALSE otherwise delete_confirmed <- function(confirm, name, type) { if(!interactive() || !confirm) return(TRUE) msg <- sprintf("Do you really want to delete the %s '%s'?", type, name) ok <- if(getRversion() < numeric_version("3.5.0")) { msg <- paste(msg, "(yes/No/cancel) ") yn <- readline(msg) if(nchar(yn) == 0) FALSE else tolower(substr(yn, 1, 1)) == "y" } else utils::askYesNo(msg, FALSE) isTRUE(ok) }
/scratch/gouwar.j/cran-all/cranData/AzureKeyVault/R/utils.R
#' Azure Key Vault endpoint class #' #' Class representing the client endpoint for a key vault, exposing methods for working with it. Use the `[key_vault]` function to instantiate new objects of this class. #' #' @docType class #' @section Fields: #' - `keys`: A sub-object for working with encryption keys stored in the vault. See [keys]. #' - `secrets`: A sub-object for working with secrets stored in the vault. See [secrets]. #' - `certificates`: A sub-object for working with certificates stored in the vault. See [certificates]. #' - `storage`: A sub-object for working with storage accounts managed by the vault. See [storage]. #' #' @seealso #' [key_vault], [keys], [secrets], [certificates], [storage] #' #' [Azure Key Vault documentation](https://docs.microsoft.com/en-us/azure/key-vault/), #' [Azure Key Vault API reference](https://docs.microsoft.com/en-us/rest/api/keyvault) #' #' @examples #' \dontrun{ #' #' key_vault("mykeyvault") #' key_vault("https://mykeyvault.vault.azure.net") #' #' # authenticating as a service principal #' key_vault("mykeyvault", tenant="myaadtenant", app="app_id", password="password") #' #' # authenticating with an existing token #' token <- AzureAuth::get_azure_token("https://vault.azure.net", "myaadtenant", #' app="app_id", password="password") #' key_vault("mykeyvault", token=token) #' #' } #' @export AzureKeyVault <- R6::R6Class("AzureKeyVault", public=list( token=NULL, url=NULL, keys=NULL, secrets=NULL, certificates=NULL, storage=NULL, initialize=function(token, url) { self$token <- token self$url <- url self$keys <- vault_keys$new(self$token, self$url) self$secrets <- vault_secrets$new(self$token, self$url) self$certificates <- vault_certificates$new(self$token, self$url) self$storage <- vault_storage_accounts$new(self$token, self$url) }, call_endpoint=function(op="", ..., options=list()) { url <- self$url url$path <- op url$query <- options call_vault_url(self$token, url, ...) }, print=function(...) { cat("Azure Key Vault '", httr::build_url(self$url), "'\n", sep="") cat("<Authentication>\n") if(is_azure_token(self$token)) { fmt_token <- gsub("\n ", "\n ", AzureAuth::format_auth_header(self$token)) cat(" ", fmt_token) } else cat(" <string>\n") invisible(self) } )) #' Azure Key Vault client #' #' @param url The location of the vault. This can be a full URL, or the vault name alone; in the latter case, the `domain` argument is appended to obtain the URL. #' @param tenant,app, Authentication arguments that will be passed to [`AzureAuth::get_azure_token`]. The default is to authenticate interactively. #' @param domain The domain of the vault; for the public Azure cloud, this is `vault.azure.net`. Also the resource for OAuth authentication. #' @param as_managed_identity Whether to authenticate as a managed identity. Use this if your R session is taking place inside an Azure VM or container that has a system- or user-assigned managed identity assigned to it. #' @param ... Further arguments that will be passed to either `get_azure_token` or [`AzureAuth::get_managed_token`], depending on whether `as_managed_identity` is TRUE. #' @param token An OAuth token obtained via `get_azure_token` or `get_managed_token`. If provided, this overrides the other authentication arguments. #' #' @details #' This function creates a new Key Vault client object. It includes the following component objects for working with data in the vault: #' #' - `keys`: A sub-object for working with encryption keys stored in the vault. See [keys]. #' - `secrets`: A sub-object for working with secrets stored in the vault. See [secrets]. #' - `certificates`: A sub-object for working with certificates stored in the vault. See [certificates]. #' - `storage`: A sub-object for working with storage accounts managed by the vault. See [storage]. #' #' @seealso #' [`keys`], [`secrets`], [`certificates`], [`storage`] #' #' [Azure Key Vault documentation](https://docs.microsoft.com/en-us/azure/key-vault/), #' [Azure Key Vault API reference](https://docs.microsoft.com/en-us/rest/api/keyvault) #' #' @examples #' \dontrun{ #' #' key_vault("mykeyvault") #' key_vault("https://mykeyvault.vault.azure.net") #' #' # authenticating as a service principal #' key_vault("mykeyvault", tenant="myaadtenant", app="app_id", password="password") #' #' # authenticating with an existing token #' token <- AzureAuth::get_azure_token("https://vault.azure.net", "myaadtenant", #' app="app_id", password="password") #' key_vault("mykeyvault", token=token) #' #' # authenticating with a system-assigned managed identity #' key_vault("mykeyvault", as_managed_identity=TRUE) #' #' # authenticating with a user-assigned managed identity: #' # - supply one of the identity's object ID, client ID or resource ID #' key_vault("mykeyvault", as_managed_identity=TRUE, #' token_args=list(mi_res_id="/subscriptions/xxxx/resourceGroups/resgrpname/...")) #' #' } #' @export key_vault <- function(url, tenant="common", app=.az_cli_app_id, ..., domain="vault.azure.net", as_managed_identity=FALSE, token=NULL) { if(!is_url(url)) url <- sprintf("https://%s.%s", url, domain) # "https://vault.azure.net/" (with trailing slash) will fail if(is.null(token)) { token <- if(as_managed_identity) AzureAuth::get_managed_token(sprintf("https://%s", domain), ...) else AzureAuth::get_azure_token(sprintf("https://%s", domain), tenant=tenant, app=app, ...) } AzureKeyVault$new(token, httr::parse_url(url)) }
/scratch/gouwar.j/cran-all/cranData/AzureKeyVault/R/vault_endpoint.R
--- title: "Introduction to AzureKeyVault" author: Hong Ooi output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Introduction to AzureKeyVault} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{utf8} --- [Azure Key Vault](https://azure.microsoft.com/services/key-vault/) enables Microsoft Azure applications and users to store and use several types of secret/key data: - Cryptographic keys: Supports multiple key types and algorithms, and enables the use of Hardware Security Modules (HSM) for high value keys. - Secrets: Provides secure storage of secrets, such as passwords and database connection strings. - Certificates: Supports certificates, which are built on top of keys and secrets and add an automated renewal feature. - Azure Storage: Can manage keys of an Azure Storage account for you. Internally, Key Vault can list (sync) keys with an Azure Storage Account, and regenerate (rotate) the keys periodically. AzureKeyVault is an R package for working with the Key Vault service. It provides both a client interface, to access the contents of the vault, and a Resource Manager interface for administering the Key Vault itself. ## Resource Manager interface AzureKeyVault extends the [AzureRMR](https://github.com/Azure/AzureRMR) package to handle key vaults. In addition to creating and deleting vaults, it provides methods to manage access policies for user and service principals. ```r # create a key vault rg <- AzureRMR::get_azure_login()$ get_subscription("sub_id")$ get_resource_group("rgname") kv <- rg$create_key_vault("mykeyvault") # list current principals (by default includes logged-in user) kv$list_principals() # get details for a service principal svc <- AzureGraph::get_graph_login()$ get_service_principal("app_id") # give the service principal read-only access to vault keys and secrets kv$add_principal(svc, key_permissions=c("get", "list", "backup"), secret_permissions=c("get", "list", "backup"), certificate_permissions=NULL, storage_permissions=NULL) ``` ## Client interface The client interface is R6-based. To instantiate a new client object, call the `key_vault` function. This object includes sub-objects for interacting with keys, secrets, certificates and managed storage accounts. ```r vault <- key_vault("https://mykeyvault.vault.azure.net") # can also be done from the ARM resource object vault <- kv$get_endpoint() ``` ### Keys Key Vault supports RSA and elliptic curve (ECDSA) asymmetric encryption keys. The `keys` component of the client object provides methods for managing keys: - `create`: Create a new key, or a new version of an existing key. - `import`: Import a key from a PEM file. - `get`: Retrieve an existing key. - `list`: List all keys in the vault. - `delete`: Delete a key. - `backup`: Return a base64-encoded blob representing the key. - `restore`: Use a blob obtained by the `backup` method to restore a key. - `do_operation`: Carry out arbitrary REST operations on keys. Used by the above methods. In turn, an individual key is represented by an object of class `stored_key`. This has the following methods: - `list_versions`: List the available versions for this key. - `set_version`: Set the version of the key to use. The default is to use the most recently created version. - `encrypt`: Encrypt a character string or raw vector, producing a base64-encoded ciphertext string. - `decrypt`: Decrypt a ciphertext string, producing either a character string or raw vector. The inverse operation of `encrypt`. - `sign`: Sign a hashed digest. - `verify`: Verify the signature of a hash. The inverse operation of `sign`. - `wrap`: Wrap a symmetric key. This is technically the same as encrypting it, but is provided as a distinct operation to allow more granular management of permissions. - `unwrap`: Unwrap a wrapped key. The inverse operation of `wrap`. The key object contains the public key component in the `key` field, as a parsed JSON web key. Note that Azure Key Vault does not provide access to the _private_ key component. ```r # create a new RSA key with 4096-bit key size vault$keys$create("newkey", type="RSA", rsa_key_size=4096) key <- vault$keys$get("newkey") # encrypting and decrypting plaintext <- "super secret" ciphertext <- key$encrypt(plaintext) decrypted_text <- key$decrypt(ciphertext, as_raw=FALSE) plaintext == decrypted_text #> [1] TRUE # signing and verifying dig <- openssl::sha256(charToRaw(plaintext)) sig <- key$sign(dig) key$verify(sig, dig) #> [1] TRUE # exporting the public key component, using the jose and openssl packages pubkey <- key$key openssl::write_pem(jose::read_jwk(pubkey), "pubkey.pem") # importing a key generated by openssl sslkey <- openssl::rsa_keygen() vault$keys$import("sslkey", sslkey) # importing a key from a file openssl::write_pem(sslkey, "sslkey.pem") vault$keys$import("sslkeyfromfile", "sslkey.pem") ``` ### Secrets Key Vault allows you to store confidential information such as passwords, database connection strings, tokens, API keys, and so on. The `secrets` component of the client object provides methods for managing generic secrets: - `create`: Create a new secret, or a new version of an existing secret. - `get`: Retrieve an existing secret. - `list`: List all secrets in the vault. - `delete`: Delete a secret. - `backup`: Return a base64-encoded blob representing the secret. - `restore`: Use a blob obtained by the `backup` method to restore a secret. - `do_operation`: Carry out arbitrary REST operations on secrets. Used by the above methods. An individual secret is represented by an object of class `stored_secret`. Unlike a key, a secret is essentially just data, so the object does not provide any operations. It has the following methods for managing secret versions: - `list_versions`: List the available versions for this secret. - `set_version`: Set the version of the secret to use. The default is to use the most recently created version. The secret itself is in the `value` field of the object, of class `secret_value`. This class has a `print` method that hides the value, to help guard against shoulder-surfing. Note that this will not stop a determined attacker; as a general rule, you should minimise assigning secrets or passing them around your R environment. If you want the raw string value itself, eg when passing it to `jsonlite::toJSON` or other functions which do not accept arbitrary object classes as inputs, use `unclass` to strip the class attribute first. ```r # create a new secret vault$secrets$create("newsecret", "hidden text") secret <- vault$secrets$get("newsecret") secret$value #> <hidden> ``` ### Certificates The `certificates` component provides methods for working with SSL/TLS authentication certificates: - `create`: Create a new certificate, or a new version of an existing certificate. The default is to create a self-signed certificate. - `import`: Import a certificate from a PFX file. - `get`: Retrieve an existing certificate. - `list`: List all certificates in the vault. - `delete`: Delete a certificate. - `backup`: Return a base64-encoded blob representing the certificate. - `restore`: Use a blob obtained by the `backup` method to restore a certificate. - `set_contacts`: Set the email address(es) to contact when a certificate is due for renewal. - `get_contacts`: Get the email address(es) of the contacts. - `add_issuer`: Adds the details for an issuer (certificate authority). - `get_issuer`: Retrieve the details for an issuer. - `remove_issuer`: Removes the details for an issuer. - `list_issuers`: Lists the issuers available to this vault. - `do_operation`: Carry out arbitrary REST operations on certificates. Used by the above methods. An individual certificate is represented by an object of class `stored_certificate`. This has the following methods: - `list_versions`: List the available versions for this certificate. - `set_version`: Set the version of the certificate to use. The default is to use the most recently created version. - `export`: Export the certificate as either a PEM or PFX file (the format is fixed at certificate creation). - `export_cer`: Export the certificate public key as a CER file. - `sign`: Sign a hashed digest. - `verify`: Verify a signature against a digest. - `set_policy`: Sets the policy for a certificate, ie the authentication details. - `get_policy`: Retrieve the policy for a certificate. ```r # create a new self-signed certificate (will also create an associated key and secret) cert <- vault$certificates$create("newcert", subject="CN=example.com", x509=cert_x509_properties(dns_names="example.com")) # import a certificate from a PFX file vault$certificates$import("importedcert", "mycert.pfx") # export the certificate as a PEM file cert$export("newcert.pem") # to export as a PFX file, set the 'format' argument at cert creation newcert2 <- vault$certificates$create("newcert2", subject="CN=example.com", format="pfx") newcert2$export("newcert2.pfx") ``` Note that exporting a certificate to a file should not be done unless absolutely necessary, as the point of using Key Vault is to avoid having to save sensitive data on a local machine. The AzureAuth package is able to make use of certificates stored in Key Vault to authenticate with Azure Active Directory. Here is some example code to do so. The app (client) in question needs to be setup with the certificate public key; we create the app via the AzureGraph package and pass it the key. ```r ## create a registered app in Azure Active Directory with cert credentials gr <- AzureGraph::get_graph_login() certapp <- gr$create_app("certapp", password=FALSE, certificate=cert$cer) # authenticate using data in Key Vault AzureAuth::get_azure_token("resource_url", "mytenant", certapp$properties$appId, certificate=cert) ``` ### Storage accounts Key Vault can be configured to manage access to an [Azure Storage Account](https://azure.microsoft.com/services/storage/), by automatically regenerating access keys and saving commonly-used access patterns as shared access signature (SAS) templates. The `storage` component of the client object provides methods for working with managed accounts: - `add`: Add a new storage account. - `get`: Retrieve an existing account. - `list`: List all storage accounts in the vault. - `remove`: Stop managing a storage account. - `backup`: Return a base64-encoded blob representing the storage account. - `restore`: Use a blob obtained by the `backup` method to restore an account. - `do_operation`: Carry out arbitrary REST operations on accounts. Used by the above methods. An individual certificate is represented by an object of class `stored_account`, which has the following methods. Note that unlike the other types of objects, storage accounts are not versioned. - `regenerate_key`: Manually regenerate an access key. - `create_sas_definition`: Create a SAS definition, from which an actual SAS can be obtained. - `get_sas_definition`: Retrieve an existing SAS definition. - `delete_sas_definition`: Delete a SAS definition. - `list_sas_definitions`: List existing SAS definitions. - `show_sas`: Get a SAS from a definition. ```r # get the storage account details library(AzureStor) res <- AzureRMR::get_azure_login()$ get_subscription("sub_id")$ get_resource_group("rgname")$ get_storage_account("mystorageacct") # add a managed storage account stor <- vault$storage$add("mystorage", res, "key1") # Creating a new SAS definition today <- Sys.time() sasdef <- res$get_account_sas(expiry=today + 7*24*60*60, services="b", permissions="rw") stor$create_sas_definition("newsas", sasdef, validity_period="P15D") stor$show_sas("newsas") ``` ## See also For more information, see the official [Key Vault documentation](https://docs.microsoft.com/en-au/azure/key-vault/).
/scratch/gouwar.j/cran-all/cranData/AzureKeyVault/inst/doc/intro.Rmd
--- title: "Introduction to AzureKeyVault" author: Hong Ooi output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Introduction to AzureKeyVault} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{utf8} --- [Azure Key Vault](https://azure.microsoft.com/services/key-vault/) enables Microsoft Azure applications and users to store and use several types of secret/key data: - Cryptographic keys: Supports multiple key types and algorithms, and enables the use of Hardware Security Modules (HSM) for high value keys. - Secrets: Provides secure storage of secrets, such as passwords and database connection strings. - Certificates: Supports certificates, which are built on top of keys and secrets and add an automated renewal feature. - Azure Storage: Can manage keys of an Azure Storage account for you. Internally, Key Vault can list (sync) keys with an Azure Storage Account, and regenerate (rotate) the keys periodically. AzureKeyVault is an R package for working with the Key Vault service. It provides both a client interface, to access the contents of the vault, and a Resource Manager interface for administering the Key Vault itself. ## Resource Manager interface AzureKeyVault extends the [AzureRMR](https://github.com/Azure/AzureRMR) package to handle key vaults. In addition to creating and deleting vaults, it provides methods to manage access policies for user and service principals. ```r # create a key vault rg <- AzureRMR::get_azure_login()$ get_subscription("sub_id")$ get_resource_group("rgname") kv <- rg$create_key_vault("mykeyvault") # list current principals (by default includes logged-in user) kv$list_principals() # get details for a service principal svc <- AzureGraph::get_graph_login()$ get_service_principal("app_id") # give the service principal read-only access to vault keys and secrets kv$add_principal(svc, key_permissions=c("get", "list", "backup"), secret_permissions=c("get", "list", "backup"), certificate_permissions=NULL, storage_permissions=NULL) ``` ## Client interface The client interface is R6-based. To instantiate a new client object, call the `key_vault` function. This object includes sub-objects for interacting with keys, secrets, certificates and managed storage accounts. ```r vault <- key_vault("https://mykeyvault.vault.azure.net") # can also be done from the ARM resource object vault <- kv$get_endpoint() ``` ### Keys Key Vault supports RSA and elliptic curve (ECDSA) asymmetric encryption keys. The `keys` component of the client object provides methods for managing keys: - `create`: Create a new key, or a new version of an existing key. - `import`: Import a key from a PEM file. - `get`: Retrieve an existing key. - `list`: List all keys in the vault. - `delete`: Delete a key. - `backup`: Return a base64-encoded blob representing the key. - `restore`: Use a blob obtained by the `backup` method to restore a key. - `do_operation`: Carry out arbitrary REST operations on keys. Used by the above methods. In turn, an individual key is represented by an object of class `stored_key`. This has the following methods: - `list_versions`: List the available versions for this key. - `set_version`: Set the version of the key to use. The default is to use the most recently created version. - `encrypt`: Encrypt a character string or raw vector, producing a base64-encoded ciphertext string. - `decrypt`: Decrypt a ciphertext string, producing either a character string or raw vector. The inverse operation of `encrypt`. - `sign`: Sign a hashed digest. - `verify`: Verify the signature of a hash. The inverse operation of `sign`. - `wrap`: Wrap a symmetric key. This is technically the same as encrypting it, but is provided as a distinct operation to allow more granular management of permissions. - `unwrap`: Unwrap a wrapped key. The inverse operation of `wrap`. The key object contains the public key component in the `key` field, as a parsed JSON web key. Note that Azure Key Vault does not provide access to the _private_ key component. ```r # create a new RSA key with 4096-bit key size vault$keys$create("newkey", type="RSA", rsa_key_size=4096) key <- vault$keys$get("newkey") # encrypting and decrypting plaintext <- "super secret" ciphertext <- key$encrypt(plaintext) decrypted_text <- key$decrypt(ciphertext, as_raw=FALSE) plaintext == decrypted_text #> [1] TRUE # signing and verifying dig <- openssl::sha256(charToRaw(plaintext)) sig <- key$sign(dig) key$verify(sig, dig) #> [1] TRUE # exporting the public key component, using the jose and openssl packages pubkey <- key$key openssl::write_pem(jose::read_jwk(pubkey), "pubkey.pem") # importing a key generated by openssl sslkey <- openssl::rsa_keygen() vault$keys$import("sslkey", sslkey) # importing a key from a file openssl::write_pem(sslkey, "sslkey.pem") vault$keys$import("sslkeyfromfile", "sslkey.pem") ``` ### Secrets Key Vault allows you to store confidential information such as passwords, database connection strings, tokens, API keys, and so on. The `secrets` component of the client object provides methods for managing generic secrets: - `create`: Create a new secret, or a new version of an existing secret. - `get`: Retrieve an existing secret. - `list`: List all secrets in the vault. - `delete`: Delete a secret. - `backup`: Return a base64-encoded blob representing the secret. - `restore`: Use a blob obtained by the `backup` method to restore a secret. - `do_operation`: Carry out arbitrary REST operations on secrets. Used by the above methods. An individual secret is represented by an object of class `stored_secret`. Unlike a key, a secret is essentially just data, so the object does not provide any operations. It has the following methods for managing secret versions: - `list_versions`: List the available versions for this secret. - `set_version`: Set the version of the secret to use. The default is to use the most recently created version. The secret itself is in the `value` field of the object, of class `secret_value`. This class has a `print` method that hides the value, to help guard against shoulder-surfing. Note that this will not stop a determined attacker; as a general rule, you should minimise assigning secrets or passing them around your R environment. If you want the raw string value itself, eg when passing it to `jsonlite::toJSON` or other functions which do not accept arbitrary object classes as inputs, use `unclass` to strip the class attribute first. ```r # create a new secret vault$secrets$create("newsecret", "hidden text") secret <- vault$secrets$get("newsecret") secret$value #> <hidden> ``` ### Certificates The `certificates` component provides methods for working with SSL/TLS authentication certificates: - `create`: Create a new certificate, or a new version of an existing certificate. The default is to create a self-signed certificate. - `import`: Import a certificate from a PFX file. - `get`: Retrieve an existing certificate. - `list`: List all certificates in the vault. - `delete`: Delete a certificate. - `backup`: Return a base64-encoded blob representing the certificate. - `restore`: Use a blob obtained by the `backup` method to restore a certificate. - `set_contacts`: Set the email address(es) to contact when a certificate is due for renewal. - `get_contacts`: Get the email address(es) of the contacts. - `add_issuer`: Adds the details for an issuer (certificate authority). - `get_issuer`: Retrieve the details for an issuer. - `remove_issuer`: Removes the details for an issuer. - `list_issuers`: Lists the issuers available to this vault. - `do_operation`: Carry out arbitrary REST operations on certificates. Used by the above methods. An individual certificate is represented by an object of class `stored_certificate`. This has the following methods: - `list_versions`: List the available versions for this certificate. - `set_version`: Set the version of the certificate to use. The default is to use the most recently created version. - `export`: Export the certificate as either a PEM or PFX file (the format is fixed at certificate creation). - `export_cer`: Export the certificate public key as a CER file. - `sign`: Sign a hashed digest. - `verify`: Verify a signature against a digest. - `set_policy`: Sets the policy for a certificate, ie the authentication details. - `get_policy`: Retrieve the policy for a certificate. ```r # create a new self-signed certificate (will also create an associated key and secret) cert <- vault$certificates$create("newcert", subject="CN=example.com", x509=cert_x509_properties(dns_names="example.com")) # import a certificate from a PFX file vault$certificates$import("importedcert", "mycert.pfx") # export the certificate as a PEM file cert$export("newcert.pem") # to export as a PFX file, set the 'format' argument at cert creation newcert2 <- vault$certificates$create("newcert2", subject="CN=example.com", format="pfx") newcert2$export("newcert2.pfx") ``` Note that exporting a certificate to a file should not be done unless absolutely necessary, as the point of using Key Vault is to avoid having to save sensitive data on a local machine. The AzureAuth package is able to make use of certificates stored in Key Vault to authenticate with Azure Active Directory. Here is some example code to do so. The app (client) in question needs to be setup with the certificate public key; we create the app via the AzureGraph package and pass it the key. ```r ## create a registered app in Azure Active Directory with cert credentials gr <- AzureGraph::get_graph_login() certapp <- gr$create_app("certapp", password=FALSE, certificate=cert$cer) # authenticate using data in Key Vault AzureAuth::get_azure_token("resource_url", "mytenant", certapp$properties$appId, certificate=cert) ``` ### Storage accounts Key Vault can be configured to manage access to an [Azure Storage Account](https://azure.microsoft.com/services/storage/), by automatically regenerating access keys and saving commonly-used access patterns as shared access signature (SAS) templates. The `storage` component of the client object provides methods for working with managed accounts: - `add`: Add a new storage account. - `get`: Retrieve an existing account. - `list`: List all storage accounts in the vault. - `remove`: Stop managing a storage account. - `backup`: Return a base64-encoded blob representing the storage account. - `restore`: Use a blob obtained by the `backup` method to restore an account. - `do_operation`: Carry out arbitrary REST operations on accounts. Used by the above methods. An individual certificate is represented by an object of class `stored_account`, which has the following methods. Note that unlike the other types of objects, storage accounts are not versioned. - `regenerate_key`: Manually regenerate an access key. - `create_sas_definition`: Create a SAS definition, from which an actual SAS can be obtained. - `get_sas_definition`: Retrieve an existing SAS definition. - `delete_sas_definition`: Delete a SAS definition. - `list_sas_definitions`: List existing SAS definitions. - `show_sas`: Get a SAS from a definition. ```r # get the storage account details library(AzureStor) res <- AzureRMR::get_azure_login()$ get_subscription("sub_id")$ get_resource_group("rgname")$ get_storage_account("mystorageacct") # add a managed storage account stor <- vault$storage$add("mystorage", res, "key1") # Creating a new SAS definition today <- Sys.time() sasdef <- res$get_account_sas(expiry=today + 7*24*60*60, services="b", permissions="rw") stor$create_sas_definition("newsas", sasdef, validity_period="P15D") stor$show_sas("newsas") ``` ## See also For more information, see the official [Key Vault documentation](https://docs.microsoft.com/en-au/azure/key-vault/).
/scratch/gouwar.j/cran-all/cranData/AzureKeyVault/vignettes/intro.Rmd
#' @importFrom utils head #' @import rlang #' @import dplyr #' @importFrom tidyr nest unnest #' @import DBI #' @import methods NULL utils::globalVariables(c("self", "asc", "con", "make_list")) .onLoad <- function(libname, pkgname) { add_methods() invisible(NULL) }
/scratch/gouwar.j/cran-all/cranData/AzureKusto/R/AzureKusto.R
# documentation is separate from implementation because roxygen still doesn't know how to handle R6 #' Create Kusto/Azure Data Explorer cluster #' #' Method for the [AzureRMR::az_resource_group] class. #' #' @rdname create_kusto_cluster #' @name create_kusto_cluster #' @aliases create_kusto_cluster create_azure_data_explorer #' @section Usage: #' ``` #' create_kusto_cluster(name, location, #' node_size="D14_v2", ...) #' ``` #' @section Arguments: #' - `name`: The name of the cluster. #' - `location`: The location/region in which to create the account. Defaults to the resource group location. #' - `node_size`: The capacity of the nodes in each of the cluster. Defaults to "D14_v2", which should be available in all regions. The availability of other sizes depends on the region the cluster is created in. #' - ... Other named arguments to pass to the [az_kusto] initialization function. #' #' @section Details: #' This method deploys a new Kusto cluster resource, with parameters given by the arguments. #' #' @section Value: #' An object of class `az_kusto` representing the created cluster. #' #' @seealso #' [get_kusto_cluster], [delete_kusto_cluster], [az_kusto] #' #' [Kusto/Azure Data Explorer documentation](https://learn.microsoft.com/en-us/azure/data-explorer/) #' #' @examples #' \dontrun{ #' #' rg <- AzureRMR::get_azure_login("myaadtenant")$ #' get_subscription("subscription_id")$ #' get_resource_group("rgname") #' #' # create a new Kusto cluster #' rg$create_kusto_cluster("mykusto", node_size="L16") #' #' } NULL #' Get existing Kusto/Azure Data Explorer cluster #' #' Method for the [AzureRMR::az_resource_group] class. #' #' @rdname get_kusto_cluster #' @name get_kusto_cluster #' @aliases get_kusto_cluster get_azure_data_explorer #' @section Usage: #' ``` #' get_kusto_cluster(name, location, #' node_size="D14_v2") #' ``` #' @section Arguments: #' - `name`: The name of the cluster. #' #' @section Details: #' This method retrieves an existing Kusto cluster resource. #' #' @section Value: #' An object of class `az_kusto` representing the created cluster. #' #' @seealso #' [create_kusto_cluster], [delete_kusto_cluster], [az_kusto] #' #' [Kusto/Azure Data Explorer documentation](https://learn.microsoft.com/en-us/azure/data-explorer/) #' #' @examples #' \dontrun{ #' #' rg <- AzureRMR::get_azure_login("myaadtenant")$ #' get_subscription("subscription_id")$ #' get_resource_group("rgname") #' #' # get a Kusto cluster #' rg$get_kusto_cluster("mykusto") #' #' } NULL #' Delete Kusto/Azure Data Explorer cluster #' #' Method for the [AzureRMR::az_resource_group] class. #' #' @rdname delete_kusto_cluster #' @name delete_kusto_cluster #' @aliases delete_kusto_cluster, delete_azure_data_explorer #' #' @section Usage: #' ``` #' delete_kusto_cluster(name, confirm=TRUE, wait=FALSE) #' ``` #' @section Arguments: #' - `name`: The name of the cluster. #' - `confirm`: Whether to ask for confirmation before deleting. #' - `wait`: Whether to wait until the deletion is complete. #' #' @section Value: #' NULL on successful deletion. #' #' @seealso #' [create_kusto_cluster], [get_kusto_cluster], [az_kusto] #' #' [Kusto/Azure Data Explorer documentation](https://learn.microsoft.com/en-us/azure/data-explorer/) #' #' @examples #' \dontrun{ #' #' rg <- AzureRMR::az_rm$ #' new(tenant="myaadtenant.onmicrosoft.com", app="app_id", password="password")$ #' get_subscription("subscription_id")$ #' get_resource_group("rgname") #' #' # delete a Kusto cluster #' rg$delete_kusto_cluster("mycluster") #' #' } NULL add_methods <- function() { ## extending AzureRMR classes AzureRMR::az_resource_group$set("public", "create_kusto_cluster", overwrite=TRUE, function(name, location=self$location, node_size="D14_v2", ..., wait=TRUE) { AzureKusto::az_kusto$new(self$token, self$subscription, self$name, type="Microsoft.Kusto/clusters", name=name, location=location, sku=list(name=node_size, tier="Standard"), ..., wait=wait) }) AzureRMR::az_resource_group$set("public", "get_kusto_cluster", overwrite=TRUE, function(name) { AzureKusto::az_kusto$new(self$token, self$subscription, self$name, type="Microsoft.Kusto/clusters", name=name) }) AzureRMR::az_resource_group$set("public", "delete_kusto_cluster", overwrite=TRUE, function(name, confirm=TRUE, wait=FALSE) { self$get_kusto_cluster(name)$delete(confirm=confirm, wait=wait) }) }
/scratch/gouwar.j/cran-all/cranData/AzureKusto/R/add_methods.R
#' Kusto/Azure Data Explorer database resource class #' #' Class representing a Kusto database, exposing methods for working with it. #' #' @docType class #' @section Methods: #' The following methods are available, in addition to those provided by the [AzureRMR::az_resource] class: #' - `new(...)`: Initialize a new storage object. See 'Initialization'. #' - `add_principals(...)`: Add new database principals. See `Principals` below. #' - `remove_principals(...)`: Remove database principals. #' - `list_principals()`: Retrieve all database principals, as a data frame. #' - `get_query_endpoint()`: Get a query endpoint object for interacting with the database. #' - `get_ingestion_endpoint()`: Get an ingestion endpoint object for interacting with the database. #' #' @section Initialization: #' Initializing a new object of this class can either retrieve an existing Kusto database, or create a new database on the server. Generally, the best way to initialize an object is via the `get_database`, `list_databases()` and `create_database` methods of the [az_kusto] class, which handle the details automatically. #' #' @section Principals: #' This class provides methods for managing the principals of a database. #' #' `add_principal` takes the following arguments. It returns a data frame with one row per principal, containing the details for each principal. #' - `name`: The name of the principal to create. #' - `role`: The role of the principal, for example "Admin" or "User". #' - `type`: The type of principal, either "User" or "App". #' - `fqn`: The fully qualified name of the principal, for example "aaduser=username@mydomain" for an Azure Active Directory account. If supplied, the other details will be obtained from this. #' - `email`: For a user principal, the email address. #' - `app_id`: For an application principal, the ID. #' #' `remove_principal` removes a principal. It takes the same arguments as `add_principal`; if the supplied details do not match the actual details for the principal, it is not removed. #' #' @seealso #' [az_kusto], [kusto_database_endpoint], #' [create_database], [get_database], [delete_database] #' #' [Kusto/Azure Data Explorer documentation](https://learn.microsoft.com/en-us/azure/data-explorer/), #' #' @examples #' \dontrun{ #' #' # recommended way of retrieving a resource: via a resource group object #' db <- resgroup$ #' get_kusto_cluster("mykusto")$ #' get_database("mydatabase") #' #' # list principals #' db$list_principals() #' #' # add a new principal #' db$add_principal("New User", role="User", fqn="aaduser=username@mydomain") #' #' # get the endpoint #' db$get_database_endpoint(use_integer64=FALSE) #' #' } #' @export az_kusto_database <- R6::R6Class("az_kusto_database", inherit=AzureRMR::az_resource, public=list( cluster=NULL, initialize=function(..., kusto_cluster=self$cluster) { super$initialize(...) self$cluster <- kusto_cluster }, delete=function(..., confirm=TRUE) { if(confirm && interactive()) { yn <- readline(paste0("Do you really want to delete the Kusto database '", basename(self$name), "'? (y/N) ")) if(tolower(substr(yn, 1, 1)) != "y") return(invisible(NULL)) } super$delete(..., confirm=FALSE) }, add_principals=function(name, role="User", type="User", fqn="", email="", app_id="") { principals <- data.frame( name=name, role=role, type=type, fqn=fqn, email=email, appId=app_id, stringsAsFactors=FALSE ) val <- self$ do_operation("addPrincipals", body=list(value=principals), encode="json", http_verb="POST")$ value do.call(rbind, lapply(val, as.data.frame, stringsAsFactors=FALSE)) }, remove_principals=function(name, role="User", type="User", fqn="", email="", app_id="") { principals <- data.frame( name=name, role=role, type=type, fqn=fqn, email=email, appId=app_id, stringsAsFactors=FALSE ) val <- self$ do_operation("removePrincipals", body=list(value=principals), encode="json", http_verb="POST")$ value do.call(rbind, lapply(val, as.data.frame, stringsAsFactors=FALSE)) }, list_principals=function() { val <- self$do_operation("listPrincipals", http_verb="POST")$value do.call(rbind, lapply(val, as.data.frame, stringsAsFactors=FALSE)) }, get_database_endpoint=function(tenant=NULL, user=NULL, pwd=NULL, ...) { if(is.null(tenant)) tenant <- self$cluster$get_default_tenant() token <- self$cluster$get_query_token(tenant) server <- self$cluster$properties$uri database <- basename(self$name) kusto_database_endpoint(server=server, database=database, tenantid=tenant, .query_token=token, ...) } )) #' @rdname is #' @export is_kusto_database <- function(x) { R6::is.R6(x) && inherits(x, "az_kusto_database") }
/scratch/gouwar.j/cran-all/cranData/AzureKusto/R/az_database.R
#' Kusto/Azure Data Explorer cluster resource class #' #' Class representing a Kusto cluster, exposing methods for working with it. #' #' @docType class #' @section Methods: #' The following methods are available, in addition to those provided by the [AzureRMR::az_resource] class: #' - `new(...)`: Initialize a new storage object. See 'Initialization'. #' - `start()`: Start the cluster. #' - `stop()`: Stop the cluster. #' - `create_database(...)`: Create a new Kusto database. See `Databases` below. #' - `get_database(database))`: Get an existing database. #' - `delete_database(database, confirm=TRUE)`: Delete a database, by default asking for confirmation first. #' - `list_databases()`: List all databases in this cluster. #' - `get_default_tenant()`: Retrieve the default tenant to authenticate with this cluster. #' - `get_query_token(tenant, ...)`: Obtain an authentication token from Azure Active Directory for this cluster's query endpoint. Accepts further arguments that will be passed to [get_kusto_token]. #' - `get_ingestion_token(tenant, ...)`: Obtain an authentication token for this cluster's ingestion endpoint. Accepts further arguments that will be passed to [get_kusto_token]. #' #' @section Initialization: #' Initializing a new object of this class can either retrieve an existing Kusto cluster, or create a new cluster on the host. Generally, the best way to initialize an object is via the `get_kusto_cluster` and `create_kusto_cluster` methods of the [az_resource_group] class, which handle the details automatically. #' #' @section Databases: #' A Kusto cluster can have several databases, which are represented in AzureKusto via [az_kusto_database] R6 objects. The `az_kusto` class provides the `create_database`, `get_database`, `delete_database` and `list_databases` methods for creating, deleting and retrieving databases. It's recommended to use these methods rather than calling `az_kusto_database$new()` directly. #' #' `create_database` takes the following arguments. It returns an object of class [az_kusto_database] #' - `database`: The name of the database to create. #' - `retention_period`: The retention period of the database, after which data will be soft-deleted. #' - `cache_period`: The cache period of the database, the length of time for which queries will be cached. #' #' `get_database` takes a single argument `database`, the name of the database to retrieve, and returns an object of class `az_kusto_database`. `delete_database` takes the name of the database to delete and returns NULL on a successful deletion. `list_databases` takes no arguments and returns a list of `az_kusto_database` objects, one for each database in the cluster. #' #' @seealso #' [az_kusto_database], [kusto_database_endpoint], #' [create_kusto_cluster], [get_kusto_cluster], [delete_kusto_cluster], #' [get_kusto_token] #' #' [Kusto/Azure Data Explorer documentation](https://learn.microsoft.com/en-us/azure/data-explorer/), #' #' @examples #' \dontrun{ #' #' # recommended way of retrieving a resource: via a resource group object #' kus <- resgroup$get_kusto_cluster("mykusto") #' #' # list databases #' kust$list_databases() #' #' # create a new database with a retention period of 6 months #' kust$create_database("newdb", retention_period=180) #' #' # get the default authentication tenant #' kus$get_default_tenant() #' #' # generate an authentication token #' kust$get_aad_token() #' #' } #' @aliases create_database get_database delete_database list_databases #' @export az_kusto <- R6::R6Class("az_kusto", inherit=AzureRMR::az_resource, public=list( start=function() { self$do_operation("start", http_verb="POST") }, stop=function() { self$do_operation("stop", http_verb="POST") }, create_database=function(database, retention_period=3650, cache_period=31) { properties <- list( softDeletePeriodInDays=retention_period, hotCachePeriodInDays=cache_period ) az_kusto_database$new(self$token, self$subscription, self$resource_group, type="Microsoft.Kusto/clusters", name=file.path(self$name, "databases", database), location=self$location, properties=properties, wait=TRUE, kusto_cluster=self) }, get_database=function(database) { name <- file.path(self$name, "databases", database) az_kusto_database$new(self$token, self$subscription, self$resource_group, type="Microsoft.Kusto/clusters", name=file.path(self$name, "databases", database), kusto_cluster=self) }, delete_database=function(database, confirm=TRUE) { self$get_database(database)$delete(confirm=confirm) }, list_databases=function() { res <- AzureRMR::named_list(self$do_operation("databases")$value) names(res) <- basename(names(res)) lapply(res, function(parms) az_kusto_database$new(self$token, self$subscription, deployed_properties=parms)) }, get_default_tenant=function() { # obtain a default tenant for this cluster: # either from the trusted external tenant property, or if blank, from login token tenant <- NULL if(!is_empty(self$properties$trustedExternalTenants)) tenant <- self$properties$trustedExternalTenants[[1]]$value if(is.null(tenant)) tenant <- self$token$tenant if(is.null(tenant)) stop("Unable to find default tenant", call.=FALSE) tenant }, get_query_token=function(tenant=self$get_default_tenant(), ...) { get_kusto_token(server=self$properties$uri, tenant=tenant, ...) }, get_ingestion_token=function(tenant=self$get_default_tenant(), ...) { get_kusto_token(server=self$properties$dataIngestionUri, tenant=tenant, ...) } )) #' Information functions #' #' These functions test whether an object is of the given class. #' #' @param x An R object. #' #' @rdname is #' @export is_kusto_cluster <- function(x) { R6::is.R6(x) && inherits(x, "az_kusto") }
/scratch/gouwar.j/cran-all/cranData/AzureKusto/R/az_kusto.R
#' DBI interface to Kusto #' #' AzureKusto implements a subset of the DBI specification for interfacing with databases in R. The following methods are supported: #' - Connections: [dbConnect], [dbDisconnect], [dbCanConnect] #' - Table management: [dbExistsTable], [dbCreateTable], [dbRemoveTable], [dbReadTable], [dbWriteTable] #' - Querying: [dbGetQuery], [dbSendQuery], [dbFetch], [dbSendStatement], [dbExecute], [dbListFields], [dbColumnInfo] #' #' Kusto is quite different to the SQL databases that DBI targets, which affects the behaviour of certain DBI methods and renders other moot. #' #' - Kusto is connectionless. `dbConnect` simply wraps a database endpoint object, created with [kusto_database_endpoint]. Similarly, `dbDisconnect` always returns TRUE. `dbCanConnect` attempts to check if querying the database will succeed, but this may not be accurate. #' #' - Temporary tables are not a Kusto concept, so `dbCreateTable(*, temporary=TRUE)` will throw an error. #' #' - It only supports synchronous queries, with a default timeout of 4 minutes. `dbSendQuery` and `dbSendStatement` will wait for the query to execute, rather than returning immediately. The object returned contains the full result of the query, which `dbFetch` extracts. #' #' - The Kusto Query Language (KQL) is not SQL, and so higher-level SQL methods are not implemented. #' #' @name kusto-DBI #' @aliases kusto-DBI kusto_dbi AzureKusto_dbi #' @rdname kusto-DBI NULL ## subclasses setOldClass("kusto_database_endpoint") #' Kusto DBI driver class #' #' @keywords internal #' @export setClass("AzureKustoDriver", contains="DBIDriver") #' Kusto DBI connection class #' #' @keywords internal #' @export setClass("AzureKustoConnection", contains="DBIConnection", slots=list( endpoint="kusto_database_endpoint" )) #' Kusto DBI result class #' #' @keywords internal #' @export setClass("AzureKustoResult", contains="DBIResult", slots=list( data="data.frame" )) ## connection/server methods setMethod("show", "AzureKustoConnection", function(object){ cat("<AzureKustoConnection>\n") cat("Endpoint:\n") print(object@endpoint) invisible(object) }) #' @rdname AzureKusto #' @export AzureKusto <- function() { new("AzureKustoDriver") } #' DBI interface: connect to a Kusto cluster #' #' Functions to connect to a Kusto cluster. #' #' @param drv An AzureKusto DBI driver object, instantiated with `AzureKusto()`. #' @param ... Authentication arguments supplied to `kusto_database_endpoint`. #' @param bigint How to treat Kusto long integer columns. By default, they will be converted to R numeric variables. If this is "integer64", they will be converted to `integer64` variables using the bit64 package. #' @param conn For `dbDisconnect`, an AzureKustoConnection object obtained with `dbConnect`. #' #' @details #' Kusto is connectionless, so `dbConnect` simply wraps a database endpoint object, generated with `kusto_database_endpoint(...)`. The endpoint itself can be accessed via the `@endpoint` slot. Similarly, `dbDisconnect` always returns TRUE. #' #' `dbCanConnect` attempts to detect whether querying the database with the given information and credentials will be successful. The result may not be accurate; essentially all it does is check that its arguments are valid Kusto properties. Ultimately the best way to tell if querying will work is to try it. #' #' @return #' For `dbConnect`, an object of class AzureKustoConnection. #' #' For `dbCanConnect`, TRUE if authenticating with the Kusto server succeeded with the given arguments, and FALSE otherwise. #' #' For `dbDisconnect`, always TRUE, invisibly. #' #' @seealso #' [kusto-DBI], [dbReadTable], [dbWriteTable], [dbGetQuery], [dbSendStatement], [kusto_database_endpoint] #' #' @examples #' \dontrun{ #' db <- DBI::dbConnect(AzureKusto(), #' server="https://mycluster.westus.kusto.windows.net", database="database", tenantid="contoso") #' #' DBI::dbDisconnect(db) #' #' # no authentication credentials: returns FALSE #' DBI::dbCanConnect(AzureKusto(), #' server="https://mycluster.westus.kusto.windows.net") #' #' } #' @aliases AzureKusto-connection #' @rdname AzureKusto #' @export setMethod("dbConnect", "AzureKustoDriver", function(drv, ..., bigint=c("numeric", "integer64")) { bigint <- match.arg(bigint) endpoint <- kusto_database_endpoint(..., .use_integer64=(bigint == "integer64")) new("AzureKustoConnection", endpoint=endpoint) }) #' @rdname AzureKusto #' @export setMethod("dbCanConnect", "AzureKustoDriver", function(drv, ...) { res <- try(dbConnect(drv, ...), silent=TRUE) !inherits(res, "try-error") }) #' @rdname AzureKusto #' @export setMethod("dbDisconnect", "AzureKustoDriver", function(conn, ...) { invisible(TRUE) }) ## table methods #' DBI methods for Kusto table management #' #' @param conn An AzureKustoConnection object. #' @param name A string containing a table name. #' @param value For `dbWriteTable`, a data frame to be written to a Kusto table. #' @param fields For `dbCreateTable`, the table specification: either a named character vector, or a data frame of sample values. #' @param method For `dbWriteTable`, the ingestion method to use to write the table. See [ingest_local]. #' @param row.names For `dbCreateTable`, the row names. Not used. #' @param temporary For `dbCreateTable`, whether to create a temporary table. Must be `FALSE` for Kusto. #' @param ... Further arguments passed to `run_query`. #' #' @details #' These functions read, write, create and delete a table, list the tables in a Kusto database, and check for table existence. With the exception of `dbWriteTable`, they ultimately call `run_query` which does the actual work of communicating with the Kusto server. `dbWriteTable` calls `ingest_local` to write the data to the server; note that it only supports ingesting a local data frame, as per the DBI spec. #' #' Kusto does not have the concept of temporary tables, so calling `dbCreateTable` with `temporary` set to anything other than `FALSE` will generate an error. #' #' `dbReadTable` and `dbWriteTable` are likely to be of limited use in practical scenarios, since Kusto tables tend to be much larger than available memory. #' #' @return #' For `dbReadTable`, an in-memory data frame containing the table. #' #' @seealso #' [AzureKusto-connection], [dbConnect], [run_query], [ingest_local] #' #' @examples #' \dontrun{ #' db <- DBI::dbConnect(AzureKusto(), #' server="https://mycluster.location.kusto.windows.net", database="database"...) #' #' DBI::dbListTables(db) #' #' if(!DBI::dbExistsTable(db, "mtcars")) #' DBI::dbCreateTable(db, "mtcars") #' #' DBI::dbWriteTable(db, "mtcars", mtcars, method="inline") #' #' DBI::dbReadTable(db, "mtcars") #' #' DBI::dbRemoveTable(db, "mtcars") #' #' } #' @rdname DBI_table #' @export setMethod("dbReadTable", c("AzureKustoConnection", "character"), function(conn, name, ...) { run_query(conn@endpoint, escape(ident(name))) }) #' @rdname DBI_table #' @export setMethod("dbWriteTable", "AzureKustoConnection", function(conn, name, value, method, ...) { if(!dbExistsTable(conn, name)) dbCreateTable(conn, name, value) ingest_local(conn@endpoint, value, name, method, ...) invisible(TRUE) }) #' @rdname DBI_table #' @export setMethod("dbCreateTable", "AzureKustoConnection", function(conn, name, fields, ..., row.names=NULL, temporary=FALSE) { build_fields <- function() { if(is.character(fields) && !is.null(names(fields)) && !any(is.na(names(fields)))) { # build a dummy list of values # converting string "x" -> object of class x effectively guards against injection fields <- sapply(fields, function(value) { switch(tolower(value), bool=logical(0), int=integer(0), date=, datetime=structure(numeric(0), class=c("POSIXct", "POSIXt")), real=numeric(0), long=structure(numeric(0), class="integer64"), character(0)) }) } else if(!is.list(fields)) stop("Bad fields specification", call.=FALSE) build_param_list(fields) } stopifnot(is.null(row.names)) if(temporary) stop("Kusto does not have temporary tables") cmd <- paste(".create table", escape(ident(name)), build_fields()) run_query(conn@endpoint, cmd) }) #' @rdname DBI_table #' @export setMethod("dbRemoveTable", "AzureKustoConnection", function(conn, name, ...) { cmd <- paste(".drop table", escape(ident(name))) run_query(conn@endpoint, cmd) }) #' @rdname DBI_table #' @export setMethod("dbListTables", "AzureKustoConnection", function(conn, ...) { res <- run_query(conn@endpoint, ".show tables") res$TableName }) #' @rdname DBI_table #' @export setMethod("dbExistsTable", "AzureKustoConnection", function(conn, name, ...) { name %in% dbListTables(conn) }) ## query methods #' DBI methods for Kusto queries and commands #' #' @param conn An AzureKustoConnection object. #' @param statement A string containing a Kusto query or control command. #' @param res An AzureKustoResult resultset object #' @param name For `dbListFields`, a table name. #' @param n The number of rows to return. Not used. #' @param ... Further arguments passed to `run_query`. #' #' @details #' These are the basic DBI functions to query the database. Note that Kusto only supports synchronous queries and commands; in particular, `dbSendQuery` and `dbSendStatement` will wait for the query or statement to complete, rather than returning immediately. #' #' `dbSendStatement` and `dbExecute` are meant for running Kusto control commands, and will throw an error if passed a regular query. `dbExecute` also returns the entire result of running the command, rather than simply a row count. #' #' @seealso #' [dbConnect], [dbReadTable], [dbWriteTable], [run_query] #' @examples #' \dontrun{ #' #' db <- DBI::dbConnect(AzureKusto(), #' server="https://mycluster.location.kusto.windows.net", database="database"...) #' #' DBI::dbGetQuery(db, "iris | count") #' DBI::dbListFields(db, "iris") #' #' # does the same thing as dbGetQuery, but returns an AzureKustoResult object #' res <- DBI::dbSendQuery(db, "iris | count") #' DBI::dbFetch(res) #' DBI::dbColumnInfo(res) #' #' DBI::dbExecute(db, ".show tables") #' #' # does the same thing as dbExecute, but returns an AzureKustoResult object #' res <- DBI::dbSendStatement(db, ".show tables") #' DBI::dbFetch(res) #' #' } #' @rdname DBI_query #' @export setMethod("dbGetQuery", c("AzureKustoConnection", "character"), function(conn, statement, ...) { run_query(conn@endpoint, statement, ...) }) #' @rdname DBI_query #' @export setMethod("dbSendQuery", "AzureKustoConnection", function(conn, statement, ...) { res <- run_query(conn@endpoint, statement, ...) new("AzureKustoResult", data=res) }) #' @rdname DBI_query #' @export setMethod("dbFetch", "AzureKustoResult", function(res, ...) { res@data }) #' @rdname DBI_query #' @export setMethod("dbSendStatement", c("AzureKustoConnection", "character"), function(conn, statement, ...) { if(substr(statement, 1, 1) != ".") stop("dbSendStatement is for control commands only", call.=FALSE) res <- run_query(conn@endpoint, statement, ...) new("AzureKustoResult", data=res) }) #' @rdname DBI_query #' @export setMethod("dbExecute", c("AzureKustoConnection", "character"), function(conn, statement, ...) { if(substr(statement, 1, 1) != ".") stop("dbExecute is for control commands only", call.=FALSE) run_query(conn@endpoint, statement, ...) }) #' @rdname DBI_query #' @export setMethod("dbListFields", c("AzureKustoConnection", "character"), function(conn, name, ...) { cmd <- paste(".show table", escape(ident(name))) res <- run_query(conn@endpoint, cmd) res[[1]] }) #' @rdname DBI_query #' @export setMethod("dbColumnInfo", "AzureKustoResult", function(res, ...) { types <- sapply(res@data, function(x) class(x)[1]) data.frame(names=names(types), types=types, stringsAsFactors=FALSE, row.names=NULL) })
/scratch/gouwar.j/cran-all/cranData/AzureKusto/R/dbi.R
#' Endpoints for communicating with a Kusto database #' #' @param ... Named arguments which are the properties for the endpoint object. See 'Details' below for the properties that AzureKusto recognises. #' @param .connection_string An alternative way of specifying the properties, as a database connection string. Properties supplied here override those in `...` if they overlap. #' @param .query_token Optionally, an Azure Active Directory (AAD) token to authenticate with. If this is supplied, it overrides other tokens specified in `...` or in the connection string. #' @param .use_integer64 For `kusto_database_endpoint`, whether to convert columns with Kusto `long` datatype into 64-bit integers in R, using the bit64 package. If FALSE, represent them as numeric instead. #' #' @details #' This is a list of properties recognised by `kusto_database_endpoint`, and their alternate names. Property names not in this list will generate an error. Note that not all properties that are recognised are currently supported by AzureKusto. #' #' General properties: #' - server: The URI of the server, usually of the form 'https://clustername.location.kusto.windows.net'. #' * addr, address, network address, datasource, host #' - database: The database. #' * initialcatalog, dbname #' - tenantid: The AAD tenant name or ID to authenticate with. #' * authority #' - appclientid: The AAD app/service principal ID #' * applicationclientid #' - traceclientversion: The client version for tracing. #' - queryconsistency: The level of query consistency. Defaults to "weakconsistency". #' - response_dynamic_serialization: How to serialize dynamic responses. #' - response_dynamic_serialization_2: How to serialize dynamic responses. #' #' User authentication properties: # - pwd: The user password. #' * password #' - user: The user name. #' * uid, userid #' - traceusername: The user name for tracing. #' - usertoken: The AAD token for user authentication. #' - * usertoken, usrtoken #' - fed: Logical, whether federated authentication is enabled. Currently unsupported; if this is TRUE, `kusto_database_endpoint` will print a warning and ignore it. #' * federated security, federated, aadfed, aadfederatedsecurity #' #' App authentication properties: #' - appkey: The secret key for the app. #' * applicationkey #' - traceappname: The AAD app for tracing. #' - apptoken: The AAD token for app authentication. #' * apptoken, applicationtoken #' #' Currently, AzureKusto only supports authentication via Azure Active Directory. Authenticating with DSTS is planned for the future. #' #' The way `kusto_database_endpoint` obtains an AAD token is as follows. #' 1. If the `.query_token` argument is supplied, use it. #' 2. Otherwise, if the `usertoken` property is supplied, use it. #' 3. Otherwise, if the `apptoken` property is supplied, use it. #' 4. Otherwise, if the `appclientid` property is supplied, use it to obtain a token: #' - With the `user` and `pwd` properties if available #' - Or with the `appkey` property if available #' - Otherwise do an interactive authentication and ask for the user credentials #' 5. Otherwise, if no `appclientid` property is supplied, authenticate with the KustoClient app: #' - With the `user` and `pwd` properties if available #' - Otherwise do an interactive authentication and ask for the user credentials using a device code #' #' @return #' An object of class `kusto_database_endpoint`. #' #' @examples #' \dontrun{ #' #' kusto_database_endpoint(server="myclust.australiaeast.kusto.windows.net", database="db1") #' #' # supplying a token obtained previously #' token <- get_kusto_token("myclust.australiaeast.kusto.windows.net") #' kusto_database_endpoint(server="myclust.australiaeast.kusto.windows.net", database="db1", #' .query_token=token) #' #' } #' @seealso #' [run_query], [az_kusto_database] #' @rdname database_endpoint #' @export kusto_database_endpoint <- function(..., .connection_string=NULL, .query_token=NULL, .use_integer64=FALSE) { props <- list(...) names(props) <- tolower(names(props)) if(!is.null(.connection_string)) { # simplified connection string handling: ignores quoting issues conn_props <- strsplit(.connection_string, ";")[[1]] names(conn_props) <- tolower(sapply(conn_props, function(x) sub("[ ]*=.+$", "", x))) conn_props <- lapply(conn_props, function(x) { x <- sub("^[^=]+=[ ]*", "", x) find_type_from_connstring(x) }) props <- utils::modifyList(props, conn_props) } # fix all property names to a given (sub)set, remove quotes from quoted values props <- normalize_connstring_properties(props) # Make bare cluster name into FQDN for server if it's not already if (!startsWith(props$server, "https://")) { props$server <- paste0("https://", props$server) if (!endsWith(props$server, ".kusto.windows.net")) props$server <- paste0(props$server, ".kusto.windows.net") } props$token <- find_endpoint_token(props, .query_token) props$use_integer64 <- .use_integer64 props <- check_endpoint_properties(props) class(props) <- "kusto_database_endpoint" props } normalize_connstring_properties <- function(properties) { # valid property names for a Kusto connection string property_list <- list( # general properties traceclientversion="traceclientversion", server=c("server", "addr", "address", "network address", "datasource", "host", "cluster"), database=c("database", "initialcatalog", "dbname"), tenantid=c("tenantid", "authority"), queryconsistency="queryconsistency", response_dynamic_serialization="response_dynamic_serialization", response_dynamic_serialization_2="response_dynamic_serialization_2", # userauth properties -- DSTS not yet supported fed=c("fed", "federated security", "federated", "aadfed", "aadfederatedsecurity"), pwd=c("pwd", "password"), user=c("user", "uid", "userid"), traceusername="traceusername", usertoken=c("usertoken", "usrtoken"), # appauth properties -- cert, DSTS not yet supported appclientid=c("appclientid", "applicationclientid"), appkey=c("appkey", "applicationkey"), traceappname="traceappname", apptoken=c("apptoken", "applicationtoken") ) normalize_name <- function(x) { for(i in seq_along(property_list)) { if(x %in% property_list[[i]]) return(names(property_list)[i]) } stop("Invalid/unsupported property name: ", x, call.=FALSE) } strip_quotes <- function(x) { if(is.character(x)) sub("^['\"](.+)['\"]$", "\\1", x) else x } names(properties) <- sapply(names(properties), normalize_name) lapply(properties, strip_quotes) } # for a property obtained from a connection string, convert to a type other than char if possible find_type_from_connstring <- function(string) { if(identical(string, "NA")) return(NA) if(!is.na(x <- suppressWarnings(as.numeric(string)))) # assign inside comparison! return(x) if(!is.na(l <- as.logical(string))) return(l) string } find_endpoint_token <- function(properties, .query_token) { if(!is.null(.query_token)) return(.query_token) # properties to check for token: usertoken, apptoken, appclientid, appkey if(!is_empty(properties$usertoken)) return(properties$usertoken) if(!is_empty(properties$apptoken)) return(properties$apptoken) # if no app ID supplied, insert Kusto app ID if(is_empty(properties$appclientid)) { message("No app ID supplied; using KustoClient app") properties$appclientid <- .kusto_app_id auth_type <- "authorization_code" } else auth_type <- NULL # KustoClient needs devicecode, otherwise let get_azure_token choose # possibilities for authenticating with AAD: # - appid + username + userpwd # - appid + appkey # - appid only (auth_code/device_code flow) token_pwd <- token_user <- NULL if(!is_empty(properties$user) && !is_empty(properties$pwd)) { token_pwd <- properties$pwd token_user <- properties$user auth_type <- "resource_owner" } else if(!is_empty(properties$appkey) && properties$appclientid != .kusto_app_id) { token_pwd <- properties$appkey auth_type <- "client_credentials" } return(get_kusto_token(properties$server, tenant=properties$tenantid, app=properties$appclientid, password=token_pwd, username=token_user, auth_type=auth_type)) } # internal checks on various properties check_endpoint_properties <- function(props) { if(isTRUE(props$use_integer64) && !requireNamespace("bit64", quietly=TRUE)) { warning("bit64 package not installed, cannot use 64-bit integers") props$use_integer64 <- FALSE } if(!is_empty(props[["response_dynamic_serialization"]]) && tolower(props[["response_dynamic_serialization"]]) != "string") { warning("Serialization of dynamic response to JSON is not yet supported") props[["response_dynamic_serialization"]] <- NULL } props } #' @export print.kusto_database_endpoint <- function(x, ...) { url <- httr::parse_url(x$server) url$path <- x$database cat("<Kusto database endpoint '", httr::build_url(url), "'>\n", sep="") invisible(x) } #' This function uploads a local data frame into a remote data source, creating the table definition as needed. #' If the table exists, it will append the data to the existing table. If not, it will create a new table. #' @export #' @param dest remote data source #' @param df local data frame #' @param name Name for new remote table #' @param overwrite If `TRUE`, will overwrite an existing table with #' name `name`. If `FALSE`, will throw an error if `name` already #' exists. #' @param method For local ingestion, the method to use. "inline", "streaming", or "indirect". #' @param ... other parameters passed to the query #' @seealso [collect()] for the opposite action; downloading remote data into a local tbl. copy_to.kusto_database_endpoint <- function(dest, df, name=deparse(substitute(df)), overwrite = FALSE, method = "inline", ...) { if (!is.data.frame(df) && !inherits(df, "tbl_kusto")) stop("`df` must be a local dataframe or a remote tbl_kusto", call. = FALSE) if (inherits(df, "tbl_kusto") && dest$server == df$src$server) out <- compute(df, name = name, ...) else { df <- collect(df) class(df) <- "data.frame" # avoid S4 dispatch problem in dbSendPreparedQuery #initialize DBI connection cnxn <- new("AzureKustoConnection", endpoint=dest) tableExists <- DBI::dbExistsTable(cnxn, name) if (tableExists) { if(overwrite) DBI::dbRemoveTable(cnxn, name) else stop(paste0("table ", name, " already exists. If you wish to overwrite it, specify overwrite=TRUE")) } dbWriteTable(cnxn, name, df, method=method) out <- tbl_kusto(dest, name) } invisible(out) }
/scratch/gouwar.j/cran-all/cranData/AzureKusto/R/endpoint.R
c_character <- function(...) { x <- c(...) if (is_empty(x)) return(character()) if (!is.character(x)) stop("Character input expected", call. = FALSE) x } #' Flag a character string as a Kusto identifier #' @param ... character strings to flag as Kusto identifiers ident <- function(...) { x <- c_character(...) structure(x, class = c("ident", "character")) } setOldClass(c("ident", "character"), ident()) #' Pass an already-escaped string to Kusto #' @param ... character strings to treat as already-escaped identifiers ident_q <- function(...) { x <- c_character(...) structure(x, class=c("ident_q", "ident", "character")) }
/scratch/gouwar.j/cran-all/cranData/AzureKusto/R/ident.R
#' Ingestion functions for Kusto #' #' @param database A Kusto database endpoint object, created with [kusto_database_endpoint]. #' @param src The source data. This can be either a data frame, local filename, or URL. #' @param dest_table The name of the destination table. #' @param method For local ingestion, the method to use. See 'Details' below. #' @param staging_container For local ingestion, an Azure storage container to use for staging the dataset. This can be an object of class either [AzureStor::blob_container] or [AzureStor::adls_filesystem]. Only used if `method="indirect"`. #' @param ingestion_token For local ingestion, an Azure Active Directory authentication token for the cluster ingestion endpoint. Only used if `method="streaming"`. #' @param http_status_handler For local ingestion, how to handle HTTP conditions >= 300. Defaults to "stop"; alternatives are "warn", "message" and "pass". The last option will pass through the raw response object from the server unchanged, regardless of the status code. This is mostly useful for debugging purposes, or if you want to see what the Kusto REST API does. Only used if `method="streaming"`. #' @param key,token,sas Authentication arguments for the Azure storage ingestion methods. If multiple arguments are supplied, a key takes priority over a token, which takes priority over a SAS. Note that these arguments are for authenticating with the Azure _storage account_, as opposed to Kusto itself. #' @param async For the URL ingestion functions, whether to do the ingestion asychronously. If TRUE, the function will return immediately while the server handles the operation in the background. #' @param ... Named arguments to be treated as ingestion parameters. #' #' @details #' There are up to 3 possible ways to ingest a local dataset, specified by the `method` argument. #' - `method="indirect"`: The data is uploaded to blob storage, and then ingested from there. This is the default if the AzureStor package is present. #' - `method="streaming"`: The data is uploaded to the cluster ingestion endpoint. This is the default if the AzureStor package is not present, however be aware that currently (as of February 2019) streaming ingestion is in beta and has to be enabled for a cluster by filing a support ticket. #' - `method="inline"`: The data is embedded into the command text itself. This is only recommended for testing purposes, or small datasets. #' #' Note that the destination table must be created ahead of time for the ingestion to proceed. #' #' @examples #' \dontrun{ #' #' # ingesting from local: #' #' # ingest via Azure storage #' cont <- AzureStor::storage_container("https://mystorage.blob.core.windows.net/container", #' sas="mysas") #' ingest_local(db, "file.csv", "table", #' method="indirect", storage_container=cont) #' # # ingest by streaming #' ingest_local(db, "file.csv", "table", method="streaming") #' #' # ingest by inlining data into query #' ingest_inline(db, "file.csv", "table", method="inline") #' #' # ingesting online data: #' #' # a public dataset: Microsoft web data from UCI machine learning repository #' ingest_url(db, #' "https://archive.ics.uci.edu/ml/machine-learning-databases/anonymous/anonymous-msweb.data", #' "table") #' #' # from blob storage: #' ingest_blob(db, #' "https://mystorage.blob.core.windows.net/container/myblob", #' "table", #' sas="mysas") #' #' # from ADLSGen2: #' token <- AzureRMR::get_azure_token("https://storage.azure.com", "mytenant", "myapp", "password") #' ingest_blob(db, #' "abfss://[email protected]/data/myfile", #' "table", #' token=token) #' #' } #' @rdname ingest #' @export ingest_local <- function(database, src, dest_table, method=NULL, staging_container=NULL, ingestion_token=database$token, http_status_handler="stop", ...) { AzureStor <- requireNamespace("AzureStor", quietly=TRUE) if(is.null(method)) method <- if(AzureStor) "indirect" else "streaming" switch(as.character(method), indirect= ingest_indirect(database, src, dest_table, staging_container, ...), streaming= ingest_streaming(database, src, dest_table, ingestion_token, http_status_handler, ...), inline= ingest_inline(database, src, dest_table, ...), stop("Bad ingestion method argument", call.=FALSE) ) } #' @rdname ingest #' @export ingest_url <- function(database, src, dest_table, async=FALSE, ...) { prop_list <- get_ingestion_properties(...) cmd <- paste(".ingest", if(async) "async" else NULL, "into table", escape(ident(dest_table)), "(", obfuscate_string(src), ")", prop_list) run_query(database, cmd) } #' @rdname ingest #' @export ingest_blob <- function(database, src, dest_table, async=FALSE, key=NULL, token=NULL, sas=NULL, ...) { if(!is.null(key)) src <- paste0(src, ";", key) else if(!is.null(token)) stop("Kusto does not support authenticating to blob storage with a token", call.=FALSE) else if(!is.null(sas)) src <- paste0(src, "?", sas) ingest_url(database, src, dest_table, async, ...) } #' @rdname ingest #' @export ingest_adls2 <- function(database, src, dest_table, async=FALSE, key=NULL, token=NULL, sas=NULL, ...) { # convert https URI into abfss for Kusto src_uri <- httr::parse_url(src) if(grepl("^http", src_uri$scheme)) { message("ADLSgen2 URIs should be specified as 'abfss://filesystem@host/path/file'") src_uri$scheme <- "abfss" src_uri$username <- sub("/.+$", "", src_uri$path) src_uri$path <- sub("^[^/]+/", "", src_uri$path) src <- httr::build_url(src_uri) } else if(src_uri$scheme == "adl") stop("ADLSgen2 URIs do not use the adl: scheme; did you mean to call ingest_adls1()?", call.=FALSE) if(!is.null(key)) src <- paste0(src, ";", key) else if(!is.null(token)) src <- paste0(src, ";token=", validate_token(token)) else if(!is.null(sas)) stop("ADLSgen2 does not support use of shared access signatures", call.=FALSE) else src <- paste0(src, ";impersonate") ingest_url(database, src, dest_table, async, ...) } #' @rdname ingest #' @export ingest_adls1 <- function(database, src, dest_table, async=FALSE, key=NULL, token=NULL, sas=NULL, ...) { # convert https URI into adl for Kusto src_uri <- httr::parse_url(src) if(grepl("^http", src_uri$scheme)) { warning("ADLSgen1 URIs should use the adl: scheme; did you mean to call ingest_adls2()?") src_uri$scheme <- "adl" src <- httr::build_url(src_uri) } else if(src_uri$scheme == "abfss") stop("ADLSgen1 URIs do not use the abfss: scheme; did you mean to call ingest_adls2()?", call.=FALSE) if(!is.null(key)) stop("ADLSgen1 does not use shared keys; did you mean to call ingest_adls2()?", call.=FALSE) else if(!is.null(token)) src <- paste0(src, ";token=", validate_token(token)) else if(!is.null(sas)) stop("ADLSgen1 does not support use of shared access signatures", call.=FALSE) ingest_url(database, src, dest_table, async, ...) } ingest_streaming <- function(database, src, dest_table, ingestion_token=database$token, http_status_handler=c("stop", "warn", "message", "pass"), ...) { opts <- list(...) if(is.data.frame(src)) { con <- textConnection(NULL, "w") on.exit(close(con)) utils::write.table(src, con, row.names=FALSE, col.names=FALSE, sep=",") body <- textConnectionValue(con) opts <- utils::modifyList(opts, list(streamFormat="Csv")) } else body <- readLines(src) ingest_uri <- httr::parse_url(database$server) ingest_uri$path <- file.path("v1/rest/ingest", database$database, dest_table) ingest_uri$query <- opts headers <- httr::add_headers(Authorization=paste("Bearer", validate_token(ingestion_token))) res <- httr::POST(ingest_uri, headers, body=body, encode="raw") http_status_handler <- match.arg(http_status_handler) if(http_status_handler == "pass") return(res) cont <- httr::content(res, simplifyVector=TRUE) handler <- get(paste0(http_status_handler, "_for_status"), getNamespace("httr")) handler(res, make_error_message(cont)) cont } ingest_indirect <- function(database, src, dest_table, staging_container=NULL, ...) { if(!requireNamespace("AzureStor", quietly=TRUE)) stop("AzureStor package must be installed to do indirect ingestion", call.=FALSE) if(is.null(staging_container)) stop("Must provide an Azure storage container object for staging", call.=FALSE) opts <- utils::modifyList(list(...), list( key=staging_container$endpoint$key, token=staging_container$endpoint$token, sas=staging_container$endpoint$sas)) if(is.data.frame(src)) { utils::write.table(src, textConnection("con", "w"), row.names=FALSE, col.names=FALSE, sep=",") src <- textConnection(con, "r") opts <- utils::modifyList(opts, list(streamFormat="Csv")) } if(inherits(staging_container, "blob_container")) { uploadfunc <- get("upload_blob", getNamespace("AzureStor")) uploadfunc(staging_container, src, dest_table) url <- httr::parse_url(staging_container$endpoint$url) url$path <- file.path(staging_container$name, dest_table) do.call(ingest_blob, c(list(database, httr::build_url(url), dest_table), opts)) } else if(inherits(staging_container, "adls_filesystem")) { uploadfunc <- get("upload_adls_file", getNamespace("AzureStor")) uploadfunc(staging_container, src, dest_table) url <- httr::parse_url(staging_container$endpoint$url) url$scheme <- "abfss" url$username <- staging_container$name url$path <- dest_table do.call(ingest_adls2, c(list(database, httr::build_url(url), dest_table), opts)) } else stop("Unsupported staging container type", call.=FALSE) } ingest_inline <- function(database, src, dest_table, ...) { prop_list <- get_ingestion_properties(...) if(is.data.frame(src)) { con <- textConnection(NULL, "w") on.exit(close(con)) utils::write.table(src, con, row.names=FALSE, col.names=FALSE, sep=",") records <- textConnectionValue(con) } else records <- readLines(src) cmd <- paste0(".ingest inline into table ", escape(ident(dest_table)), " ", prop_list, "<|\n", paste0(records, collapse="\n")) run_query(database, cmd) } obfuscate_string <- function(string) { paste0("h", escape(string)) } get_ingestion_properties <- function(...) { props <- list(...) if(is_empty(props)) return(NULL) prop_list <- mapply(function(name, value) { paste(name, escape(value), sep="=") }, names(props), props) paste("with (", paste(prop_list, collapse=", "), ")") }
/scratch/gouwar.j/cran-all/cranData/AzureKusto/R/ingest.R
#' Build the tbl object into a data structure representing a Kusto query #' @param op A nested sequence of query operations, i.e. tbl_kusto$ops #' @export kql_build <- function(op) { UseMethod("kql_build") } #' @export kql_build.tbl_kusto_abstract <- function(op) { q <- flatten_query(op$ops) built_q <- lapply(q, kql_build) kql_query(built_q, src=op$src) } #' @export kql_build.op_base_local <- function(op, ...) { ident("df") } #' @export kql_build.op_base_remote <- function(op, ...) { ident(op$src$x) } #' @export kql_build.op_select <- function(op, ...) { kql_clause_select(translate_kql(!!! op$dots)) } #' @export kql_build.op_filter <- function(op, ...) { dots <- mapply(get_expr, op$dots) dot_names <- mapply(all_names, dots) # throw an exception if any filter expression references # a var that isn't a column in the table tidyselect::vars_select(op$vars, !!! dot_names) translated_dots <- lapply(dots, translate_kql) built_dots <- lapply(translated_dots, build_kql) clauses <- lapply(built_dots, kql_clause_filter) clauses } #' @export kql_build.op_distinct <- function(op, ...) { if (is_empty(op$dots)) cols <- op$vars else cols <- tidyselect::vars_select(op$vars, !!! op$dots) kql_clause_distinct(ident(cols)) } #' @export kql_build.op_rename <- function(op, ...) { assigned_exprs <- mapply(get_expr, op$dots) stmts <- lapply(assigned_exprs, translate_kql) pieces <- lapply(seq_along(assigned_exprs), function(i) sprintf("%s = %s", escape(ident(names(assigned_exprs)[i])), stmts[i])) kql(paste0("project-rename ", paste0(pieces, collapse=", "))) } #' dplyr's mutate verb can include aggregations, but Kusto's extend verb cannot. #' If the mutate contains no aggregations, then it can emit an extend clause. #' If the mutate contains an aggregation and the tbl is ungrouped, #' then it must emit a summarize clause grouped by all variables. #' If the mutate contains an aggregation and the tbl is grouped, #' then it must join to a subquery containing the summarize clause. #' @param op A nested sequence of query operations, i.e. tbl_kusto$ops #' @param ... Needed for agreement with generic. Not otherwise used. #' @export kql_build.op_mutate <- function(op, ...) { assigned_exprs <- mapply(get_expr, op$dots) calls <- unlist(mapply(all_calls, assigned_exprs)) calls_agg <- mapply(is_agg, calls) groups <- build_kql(escape(ident(op$groups), collapse = ", ")) all_vars <- build_kql(escape(ident(op$vars), collapse = ", ")) existing_vars <- build_kql(escape(ident(setdiff(op$vars, names(assigned_exprs))), collapse = ", ")) if (any(calls_agg)) { has_agg <- TRUE if (nchar(groups) == 0) { has_grouping <- FALSE verb <- "summarize " by <- build_kql(" by ", existing_vars) } else { has_grouping <- TRUE verb <- "as tmp | join kind=leftouter (tmp | summarize " by <- build_kql(" by ", groups) on <- build_kql(") on ", groups) project <- build_kql("\n| project ", all_vars) by <- paste0(by, on, project) } } else { has_agg <- FALSE verb <- "extend " by <- "" } stmts <- mapply(translate_kql, assigned_exprs) pieces <- lapply(seq_along(assigned_exprs), function(i) sprintf("%s = %s", escape(ident(names(assigned_exprs)[i])), stmts[i])) kql(paste0(verb, pieces, by)) } #' @export kql_build.op_arrange <- function(op, ...) { dots <- mapply(append_asc, op$dots) order_vars <- translate_kql(!!! dots) build_kql("order by ", build_kql(escape(order_vars, collapse = ", "))) } #' @export kql_build.op_summarise <- function(op, ...) { assigned_exprs <- mapply(get_expr, op$dots) stmts <- mapply(translate_kql, assigned_exprs) pieces <- lapply(seq_along(assigned_exprs), function(i) sprintf("%s = %s", escape(ident(names(assigned_exprs)[i])), stmts[i])) groups <- build_kql(escape(ident(op_grps(op)), collapse = ", ")) by <- ifelse(nchar(groups) > 0, paste0(" by ", groups), "") .strategy <- if(!is.null(op$args$.strategy)) paste0(" hint.strategy = ", op$args$.strategy) else NULL .shufflekeys <- if(!is.null(op$args$.shufflekeys)) { vars <- sapply(op$args$.shufflekeys, function(x) escape(ident(x))) paste0(" hint.shufflekey = ", vars, collapse="") } else NULL .num_partitions <- if(is.numeric(op$args$.num_partitions)) paste0(" hint.num_partitions = ", op$args$.num_partitions) else if(!is.null(op$args$.num_partitions)) stop(".num_partitions must be a number", .call=FALSE) else NULL # paste(c(*), collapse="") will not insert extra spaces when NULLs present smry_str <- paste(c("summarize", .strategy, .shufflekeys, .num_partitions, " "), collapse="") smry_clauses <- paste(pieces, collapse=", ") kql(ident_q(paste0(smry_str, smry_clauses, by))) } #' @export kql_build.op_group_by <- function(op, ...) { NULL } #' @export kql_build.op_ungroup <- function(op, ...) { NULL } #' @export kql_build.op_unnest <- function(op, ...) { if (!is.null(op$args$.id)) { with_itemindex <- build_kql("with_itemindex=", escape(ident(op$args$.id)), " ") } else { with_itemindex <- kql("") } cols_to_unnest <- unname(tidyselect::vars_select(op_vars(op), !!! op$dots)) if (is_empty(cols_to_unnest)) cols_to_unnest <- setdiff(op_vars(op), op_grps(op)) build_kql("mv-expand ", with_itemindex, build_kql(escape(ident(cols_to_unnest), collapse = ", "))) } #' @export kql_build.op_head <- function(op, ...) { n <- lapply(op$args$n, translate_kql) build_kql("take ", kql(escape(n, parens = FALSE))) } #' @export kql_build.op_slice_sample <- function(op, ...) { n <- lapply(op$args$n, translate_kql) build_kql("sample ", kql(escape(n, parens = FALSE))) } #' @export kql_build.op_join <- function(op, ...) { join_type <- op$args$type by <- op$args$by by_x <- escape(ident(by$x)) if (identical(by$x, by$y)) by_clause <- by_x else { by_y <- escape(ident(by$y)) by_clause <- kql(ident(paste0(mapply(build_by_clause, by$x, by$y), collapse = ", "))) } y_render <- kql(kql_render(kql_build(op$y))) .strategy <- if(!is.null(op$args$.strategy)) paste0(" hint.strategy = ", op$args$.strategy) else NULL .shufflekeys <- if(!is.null(op$args$.shufflekeys)) { vars <- sapply(op$args$.shufflekeys, function(x) escape(ident(x))) paste0(" hint.shufflekey = ", vars, collapse="") } else NULL .num_partitions <- if(is.numeric(op$args$.num_partitions)) paste0(" hint.num_partitions = ", op$args$.num_partitions) else if(!is.null(op$args$.num_partitions)) stop(".num_partitions must be a number", .call=FALSE) else NULL .remote <- if(!is.null(op$args$.remote)) paste0(" hint.remote = ", op$args$.remote, collapse="") else NULL kind <- switch(join_type, inner_join="inner", left_join="leftouter", right_join="rightouter", full_join="fullouter", semi_join="leftsemi", anti_join="leftanti", stop("unknown join type") ) # paste(c(*), collapse="") will not insert extra spaces when NULLs present join_str <- ident_q(paste(c("join kind = ", kind, .strategy, .shufflekeys, .num_partitions, .remote, " "), collapse="")) build_kql(join_str, "(", y_render, ") on ", by_clause) } #' @export kql_build.op_set_op <- function(op, ...) { op_type <- op$args$type y_render <- kql(kql_render(kql_build(op$y))) switch(op_type, union_all= build_kql("union kind = outer (", y_render, ")"), build_kql("union kind = inner (", y_render, ")") ) } append_asc <- function(dot) { if (inherits(quo_get_expr(dot), "name")) quo_set_expr(dot, call2(expr(asc), quo_get_expr(dot))) else if (inherits(quo_get_expr(dot), "call")) if (quo_get_expr(dot)[[1]] != expr("desc")) quo_set_expr(dot, call2(expr(asc), quo_get_expr(dot))) else dot else dot } #' Walks the tree of ops and builds a stack. #' @param op the current operation #' @param ops the stack of operations to append to, recursively #' @export flatten_query <- function(op, ops=list()) { if (inherits(op, "tbl_df") || inherits(op, "character")) return(ops) if (inherits(op, "tbl_kusto_abstract")) flat_op <- op$ops else flat_op <- op flat_op$vars <- op_vars(flat_op) flat_op$groups <- op_grps(flat_op) if (is_empty(ops)) new_ops <- list(flat_op) else new_ops <- c(list(flat_op), ops) if (inherits(op, "op_base")) return(new_ops) else flatten_query(flat_op$x, new_ops) } kql_clause_select <- function(select) { stopifnot(is.character(select)) if (is_empty(select)) abort("Query contains no columns") build_kql( "project ", escape(select, collapse = ", ") ) } kql_clause_distinct <- function(distinct) { stopifnot(is.character(distinct)) build_kql( "distinct ", escape(distinct, collapse = ", ") ) } kql_clause_filter <- function(where) { if (!is_empty(where)) { where_paren <- escape(where, parens = FALSE) build_kql("where ", kql_vector(where_paren, collapse = " and ")) } } kql_query <- function(ops, src) { structure( list( ops = ops, src = src ), class = "kql_query" ) } build_by_clause <- function(x, y) { sprintf("$left.%s == $right.%s", escape(ident(x)), escape(ident(y))) }
/scratch/gouwar.j/cran-all/cranData/AzureKusto/R/kql-build.R
#' Escape/quote a string. #' #' @param x An object to escape. Existing kql vectors will be left as is, #' character vectors are escaped with single quotes, numeric vectors have #' trailing `.0` added if they're whole numbers, identifiers are #' escaped with double quotes. #' @param parens,collapse Controls behaviour when multiple values are supplied. #' `parens` should be a logical flag, or if `NA`, will wrap in #' parens if length > 1. #' #' Default behaviour: lists are always wrapped in parens and separated by #' commas, identifiers are separated by commas and never wrapped, #' atomic vectors are separated by spaces and wrapped in parens if needed. #' @export escape <- function(x, parens = NA, collapse = " ") { UseMethod("escape") } #' @export escape.ident <- function(x, parens = FALSE, collapse = ", ") { y <- kql_escape_ident(x) kql_vector(y, parens, collapse) } #' @export escape.ident_q <- function(x, parens = FALSE, collapse = ", ") { y <- kql_escape_ident_q(x) kql_vector(y, parens, collapse) } #' @export escape.logical <- function(x, parens = NA, collapse = ", ") { kql_vector(kql_escape_logical(x), parens, collapse) } #' @export escape.factor <- function(x, parens = NA, collapse = ", ") { escape(as.character(x), parens = parens, collapse = collapse) } #' @export escape.Date <- function(x, parens = NA, collapse = ", ") { escape(as.character(x), parens = parens, collapse = collapse) } #' @export escape.POSIXt <- function(x, parens = NA, collapse = ", ") { x <- strftime(x, "%Y-%m-%dT%H:%M:%OSZ", tz = "UTC") escape.character(x, parens = parens, collapse = collapse) } #' @export escape.character <- function(x, parens = NA, collapse = ", ") { # Kusto doesn't support null strings, instead use empty string out <- x out[is.na(x)] <- "" out[is.null(x)] <- "" kql_vector(kql_escape_string(out), parens, collapse) } #' @export escape.double <- function(x, parens = NA, collapse = ", ") { out <- as.character(x) out[is.na(x)] <- "real(null)" inf <- is.infinite(x) out[inf & x > 0] <- "'real(+inf)'" out[inf & x < 0] <- "'real(-inf)'" kql_vector(out, parens, collapse) } #' @export escape.integer <- function(x, parens = NA, collapse = ", ") { x[is.na(x)] <- "int(null)" kql_vector(x, parens, collapse) } #' @export escape.integer64 <- function(x, parens = NA, collapse = ", ") { x <- as.character(x) x[is.na(x)] <- "long(null)" kql_vector(x, parens, collapse) } #' @export escape.NULL <- function(x, parens = NA, collapse = " ") { kql("null") } #' @export escape.kql <- function(x, parens = NULL, collapse = NULL) { kql_vector(x, isTRUE(parens), collapse) } #' @export escape.list <- function(x, parens = TRUE, collapse = ", ") { pieces <- vapply(x, escape, character(1)) kql_vector(pieces, parens, collapse) } #' @export #' @rdname escape kql_vector <- function(x, parens = NA, collapse = " ") { if (is_empty(x)) { if (!is.null(collapse)) return(if (isTRUE(parens)) kql("()") else kql("")) else return(kql()) } if (is.na(parens)) parens <- length(x) > 1L x <- paste(x, collapse = collapse) if (parens) x <- paste0("(", x, ")") kql(x) } #' Build a KQL string. #' @param ... input to convert to KQL. Use [kql()] to preserve #' user input as is (dangerous), and [ident()] to label user #' input as kql identifiers (safe) #' @param .env the environment in which to evaluate the arguments. Should not #' be needed in typical use. #' @export build_kql <- function(..., .env = parent.frame()) { escape_expr <- function(x) { # If it's a string, leave it as is if (is.character(x)) return(x) val <- eval_bare(x, .env) # Skip nulls, so you can use if statements like in paste if (is.null(val)) return("") escape(val) } pieces <- vapply(dots(...), escape_expr, character(1)) kql(paste0(pieces, collapse = "")) } #' Helper function for quoting kql elements. #' #' If the quote character is present in the string, it will be doubled. #' `NA`s will be replaced with NULL. #' #' @export #' @param x Character vector to escape. #' @param quote Single quoting character. #' @export #' @keywords internal #' @examples #' kql_quote("abc", "'") #' kql_quote("I've had a good day", "'") #' kql_quote(c("abc", NA), "'") kql_quote <- function(x, quote) { if (is_empty(x)) return(x) y <- gsub(quote, paste0(quote, quote), x, fixed = TRUE) y <- paste0(quote, y, quote) y[is.na(x)] <- "NULL" names(y) <- names(x) y } #' Escape a Kusto string by single-quoting #' @param x A string to escape #' @export kql_escape_string <- function(x) { kql_quote(x, "'") } #' Escape a Kusto identifier with \[' '\] #' @param x An identifier to escape #' @export kql_escape_ident <- function(x) { if(!is_empty(x)) paste0("[", kql_escape_string(x), "]") else x } #' Escape a Kusto logical value. #' Converts TRUE/FALSE to true / false #' @param x A logical value to escape #' @export kql_escape_logical <- function(x) { y <- tolower(as.character(x)) y[is.na(x)] <- "null" y } #' Pass through an already-escaped Kusto identifier #' @param x An identifier to pass through #' @export kql_escape_ident_q <- function(x) { x }
/scratch/gouwar.j/cran-all/cranData/AzureKusto/R/kql-escape.R
#' Render a set of operations on a tbl_kusto_abstract to a Kusto query #' @param query The tbl_kusto instance with a sequence of operations in $ops #' @param ... needed for agreement with generic. Not otherwise used. #' @export kql_render <- function(query, ...) { UseMethod("kql_render") } #' @export kql_render.kql_query <- function(query, ...) { tblname <- sprintf("cluster('%s').database('%s').%s", query$src$server, query$src$database, kql(query$src$table)) q_str <- paste(unlist(query$ops[-1]), collapse = "\n| ") if (nchar(q_str) > 0) q_str <- kql(paste(tblname, q_str, sep="\n| ")) else q_str <- tblname q_str } #' @export kql_render.tbl_kusto_abstract <- function(query, ...) { qry <- kql_build(query$ops, ...) kql_render(qry, ...) } #' @export kql_render.op <- function(query, ...) { kql_render(kql_build(query, ...), ...) } #' @export kql_render.ident <- function(query, ..., root = TRUE) { query } #' @export kql_render.kql <- function(query, ...) { query }
/scratch/gouwar.j/cran-all/cranData/AzureKusto/R/kql-render.R
# Azure Active Directory app used to talk to Kusto .kusto_app_id <- 'db662dc1-0cfe-4e1c-a843-19a68e65be58' #' Manage AAD authentication tokens for Kusto clusters #' #' @param server The URI of your Kusto cluster. If not supplied, it is obtained from the `clustername` and `location` arguments. #' @param clustername The cluster name. #' @param location The cluster location. Leave this blank for a Microsoft-internal Kusto cluster like "help". #' @param tenant Your Azure Active Directory (AAD) tenant. Can be a GUID, a name ("myaadtenant") or a fully qualified domain name ("myaadtenant.com"). #' @param app The ID of the Azure Active Directory app/service principal to authenticate with. Defaults to the ID of the KustoClient app. #' @param auth_type The authentication method to use. Can be one of "authorization_code", "device_code", "client_credentials" or "resource_owner". The default is to pick one based on the other arguments. #' @param version The AAD version to use. There should be no reason to change this from the default value of 2. #' @param hash For `delete_kusto_token`, the MD5 hash of the token. This is used to identify the token if provided. #' @param confirm For `delete_kusto_token`, whether to ask for confirmation before deleting the token. #' @param ... Other arguments to pass to [AzureAuth::get_azure_token]. #' #' @details #' `get_kusto_token` returns an authentication token for the given cluster, caching its value on disk. `delete_kusto_token` deletes a cached token, and `list_kusto_tokens` lists all cached tokens. #' #' By default, authentication tokens will be obtained using the main KustoClient Active Directory app. This app can be used to authenticate with any Kusto cluster (assuming, of course, you have the proper credentials). #' #' @return #' `get_kusto_token` returns an object of class AzureAuth::AzureToken representing the authentication token, while `list_kusto_tokens` returns a list of such objects. `delete_azure_token` returns NULL on a successful delete. #' #' @seealso #' [kusto_database_endpoint], [AzureAuth::get_azure_token] #' #' @examples #' \dontrun{ #' #' get_kusto_token("https://myclust.australiaeast.kusto.windows.net") #' get_kusto_token(clustername="myclust", location="australiaeast") #' #' # authenticate using client_credentials method: see ?AzureAuth::get_azure_token #' get_kusto_token("https://myclust.australiaeast.kusto.windows.net", #' tenant="mytenant", app="myapp", password="password") #' #' } #' @export get_kusto_token <- function(server=NULL, clustername, location=NULL, tenant=NULL, app=.kusto_app_id, auth_type=NULL, version=2, ...) { tenant <- if(is.null(tenant)) "common" else AzureAuth::normalize_tenant(tenant) if(is.null(server)) { location <- normalize_location(location) cluster <- normalize_cluster(clustername, location) server <- paste0("https://", cluster, ".kusto.windows.net") } if(version == 2 && httr::parse_url(server)$path == "") server <- c(paste0(sub("/$", "", server), "/.default"), "offline_access", "openid") # Used to default to "device_code" but "authorization_code" has better ease of use # and also works with .kusto_app_id without supplying a username. if(is.null(auth_type) && app == .kusto_app_id && (!"username" %in% names(list(...)))) auth_type <- "authorization_code" AzureAuth::get_azure_token(server, tenant, app, auth_type=auth_type, version=version, ...) } #' @rdname get_kusto_token #' @export delete_kusto_token <- function(server=NULL, clustername, location=NULL, tenant=NULL, app=.kusto_app_id, auth_type=NULL, version=2, ..., hash=NULL, confirm=TRUE) { # use hash if provided if(!is.null(hash)) return(AzureAuth::delete_azure_token(hash=hash, confirm=confirm)) tenant <- if(is.null(tenant)) "common" else AzureAuth::normalize_tenant(tenant) if(is.null(server)) { location <- normalize_location(location) cluster <- normalize_cluster(clustername, location) server <- paste0("https://", cluster, ".kusto.windows.net") } if(version == 2 && httr::parse_url(server)$path == "") server <- c(paste0(sub("/$", "", server), "/.default"), "offline_access", "openid") # KustoClient requires devicecode auth if username not supplied if(is.null(auth_type) && app == .kusto_app_id && (!"username" %in% names(list(...)))) auth_type <- "device_code" AzureAuth::delete_azure_token(server, tenant, app, auth_type=auth_type, version=version, confirm=confirm, ...) } #' @rdname get_kusto_token #' @export list_kusto_tokens <- function() { lst <- AzureAuth::list_azure_tokens() is_kusto <- function(x) { !is.null(x) && grepl("kusto.windows.net", x, fixed=TRUE) } lst[sapply(lst, function(tok) { is_kusto(tok$resource) || is_kusto(tok$scope) || is_kusto(tok$credentials$resource) })] } # Kusto prettifies location eg "West US" instead of "westus", unprettify it for URL fiddling purposes normalize_location <- function(location) { if(is.null(location)) NULL else tolower(gsub(" ", "", location)) } normalize_cluster <- function(clustername, location=NULL) { if(is.null(location)) clustername else paste(clustername, location, sep=".") }
/scratch/gouwar.j/cran-all/cranData/AzureKusto/R/kusto_token.R
#' The "base case" operation representing the tbl itself and its column variables #' @export #' @param x A tbl object #' @param vars A vector of column variables in the tbl #' @param class The class that op_base should inherit from, default is character() op_base <- function(x, vars, class = character()) { stopifnot(is.character(vars)) structure( list( x = x, vars = vars ), class = c(paste0("op_base_", class), "op_base", "op") ) } op_base_local <- function(df) { op_base(df, names(df), class = "local") } op_base_remote <- function(x, vars) { op_base(x, vars, class = "remote") } #' A class representing a single-table verb #' @export #' @param name the name of the operation verb, e.g. "select", "filter" #' @param x the tbl object #' @param dots expressions passed to the operation verb function #' @param args other arguments passed to the operation verb function op_single <- function(name, x, dots = list(), args = list()) { structure( list( name = name, x = x, dots = dots, args = args ), class = c(paste0("op_", name), "op_single", "op") ) } #' Append an operation representing a single-table verb to the tbl_kusto object's ops list #' @export #' @param name The name of the operation, e.g. 'select', 'filter' #' @param .data The tbl_kusto object to append the operation to #' @param dots The expressions passed as arguments to the operation verb #' @param args Other non-expression arguments passed to the operation verb add_op_single <- function(name, .data, dots = list(), args = list()) { .data$ops <- op_single(name, x = .data$ops, dots = dots, args = args) .data } #' A double-table verb, e.g. joins, setops #' @export #' @param name The name of the operation, e.g. 'left_join', 'union_all' #' @param x The "left" tbl #' @param y The "right" tbl #' @param args Other arguments passed to the operation verb op_double <- function(name, x, y, args = list()) { structure( list( name = name, x = x, y = y, args = args ), class = c(paste0("op_", name), "op_double", "op") ) } #' Append a join operation to the tbl_kusto object's ops list #' @export #' @param type The name of the join type, #' one of: inner_join, left_join, right_join, full_join, semi_join, anti_join #' @param x The "left" tbl #' @param y The "right" tbl #' @param by A vector of column names; keys by which tbl x and tbl y will be joined #' @param suffix A vector of strings that will be appended to the names of non-join key columns that exist in both tbl x and tbl y to distinguish them by source tbl. #' @param .strategy A strategy hint to provide to Kusto. #' @param .shufflekeys A character vector of column names to shuffle on, if `.strategy = "shuffle"`. #' @param .remote A strategy hint to provide to Kusto for cross-cluster joins. #' @param .num_partitions The number of partitions for a shuffle query. add_op_join <- function(type, x, y, by = NULL, suffix = NULL, .strategy = NULL, .shufflekeys = NULL, .num_partitions = NULL, .remote = NULL) { by <- common_by(by, x, y) vars <- join_vars(op_vars(x), op_vars(y), type = type, by = by, suffix = suffix) x$ops <- op_double("join", x, y, args = list( vars = vars, type = type, by = by, suffix = suffix, .strategy = .strategy, .shufflekeys = .shufflekeys, .num_partitions = .num_partitions, .remote = .remote )) x } #' Append a set operation to the tbl_kusto object's ops list #' @export #' @param x The "left" tbl #' @param y The "right" tbl #' @param type The type of set operation to perform, currently only supports union_all add_op_set_op <- function(x, y, type) { x$ops <- op_double("set_op", x, y, args = list(type = type)) x } join_vars <- function(x_names, y_names, type, by, suffix = c(".x", ".y")) { # Remove join keys from y's names y_names <- setdiff(y_names, by$y) if(!is.character(suffix) || length(suffix) != 2) stop("`suffix` must be a character vector of length 2.", call. = FALSE) suffix <- list(x = suffix[1], y = suffix[2]) x_new <- add_suffixes(x_names, y_names, suffix$x) y_new <- add_suffixes(y_names, x_names, suffix$y) # In left and inner joins, return key values only from x # In right joins, return key values only from y # In full joins, return key values by coalescing values from x and y x_x <- x_names x_y <- by$y[match(x_names, by$x)] x_y[type == "left_join" | type == "inner_join"] <- NA x_x[type == "right_join" & !is.na(x_y)] <- NA y_x <- rep_len(NA, length(y_names)) y_y <- y_names # Return a list with 3 parallel vectors # At each position, values in the 3 vectors represent # alias - name of column in join result # x - name of column from left table or NA if only from right table # y - name of column from right table or NA if only from left table list(alias = c(x_new, y_new), x = c(x_x, y_x), y = c(x_y, y_y)) } add_suffixes <- function(x, y, suffix) { if (identical(suffix, "")) return(x) out <- rep_len(na_chr, length(x)) for (i in seq_along(x)) { nm <- x[[i]] while (nm %in% y || nm %in% out) nm <- paste0(nm, suffix) out[[i]] <- nm } out } #' Look up the applicable grouping variables for an operation #' based on the data source and preceding sequence of operations #' @param op An operation instance #' @export op_grps <- function(op) UseMethod("op_grps") #' @export op_grps.op_base <- function(op) character() #' @export op_grps.op_group_by <- function(op) { if (isTRUE(op$args$add)) union(op_grps(op$x), names(op$dots)) else names(op$dots) } #' @export op_grps.op_ungroup <- function(op) { character() } #' @export op_grps.op_summarise <- function(op) { grps <- op_grps(op$x) } #' @export op_grps.op_rename <- function(op) { names(tidyselect::vars_rename(op_grps(op$x), !!! op$dots, .strict = FALSE)) } #' @export op_grps.op_single <- function(op) { op_grps(op$x) } #' @export op_grps.op_double <- function(op) { op_grps(op$x) } #' @export op_grps.tbl_kusto_abstract <- function(op) { op_grps(op$ops) } #' @export op_grps.tbl_df <- function(op) { character() } #' Look up the applicable variables in scope for a given operation #' based on the data source and preceding sequence of operations #' @param op An operation instance #' @export op_vars <- function(op) UseMethod("op_vars") #' @export op_vars.op_base <- function(op) { op$vars } #' @export op_vars.op_select <- function(op) { names(tidyselect::vars_select(op_vars(op$x), !!! op$dots, .include = op_grps(op$x))) } #' @export op_vars.op_rename <- function(op) { names(tidyselect::vars_rename(op_vars(op$x), !!! op$dots)) } #' @export op_vars.op_summarise <- function(op) { c(op_grps(op$x), names(op$dots)) } #' @export op_vars.op_distinct <- function(op) { if (is_empty(op$dots)) op_vars(op$x) else unique(c(op_vars(op$x), names(op$dots))) } #' @export op_vars.op_mutate <- function(op) { unique(c(op_vars(op$x), names(op$dots))) } #' @export op_vars.op_single <- function(op) { op_vars(op$x) } #' @export op_vars.op_join <- function(op) { op$args$vars$alias } #' @export op_vars.op_join <- function(op) { op$args$vars$alias } #' @export op_vars.op_semi_join <- function(op) { op_vars(op$x) } #' @export op_vars.op_set_op <- function(op) { union(op_vars(op$x), op_vars(op$y)) } #' @export op_vars.tbl_kusto_abstract <- function(op) { op_vars(op$ops) } #' @export op_vars.tbl_df <- function(op) { names(op) }
/scratch/gouwar.j/cran-all/cranData/AzureKusto/R/ops.R
#' Partially evaluate an expression. #' #' This function partially evaluates an expression, using information from #' the tbl to determine whether names refer to local expressions #' or remote variables. This simplifies translation because expressions #' don't need to carry around their environment - all relevant information #' is incorporated into the expression. #' #' @section Symbol substitution: #' #' `partial_eval()` needs to guess if you're referring to a variable on the #' server (remote), or in the current environment (local). #' #' You can override the guesses using `local()` and `remote()` to force #' computation, or by using the `.data` and `.env` pronouns of tidy evaluation. #' #' @param call an unevaluated expression, as produced by [quote()] #' @param vars character vector of variable names. #' @param env environment in which to search for local values #' @export #' @keywords internal #' @examples #' vars <- c("year", "id") #' partial_eval(quote(year > 1980), vars = vars) #' #' ids <- c("ansonca01", "forceda01", "mathebo01") #' partial_eval(quote(id %in% ids), vars = vars) #' #' # cf. #' partial_eval(quote(id == .data$ids), vars = vars) #' #' # You can use local() or .env to disambiguate between local and remote #' # variables: otherwise remote is always preferred #' year <- 1980 #' partial_eval(quote(year > year), vars = vars) #' partial_eval(quote(year > local(year)), vars = vars) #' partial_eval(quote(year > .env$year), vars = vars) #' #' # Functions are always assumed to be remote. Use local to force evaluation #' # in R. #' f <- function(x) x + 1 #' partial_eval(quote(year > f(1980)), vars = vars) #' partial_eval(quote(year > local(f(1980))), vars = vars) partial_eval <- function(call, vars = character(), env = caller_env()) { switch_type(call, "NULL" = NULL, symbol = sym_partial_eval(call, vars, env), language = lang_partial_eval(call, vars, env), logical =, integer =, double =, complex =, string =, character = call, formula = { f_rhs(call) <- partial_eval(f_rhs(call), vars, f_env(call) %||% env) if (length(call) == 3) { f_lhs(call) <- partial_eval(f_lhs(call), vars, f_env(call) %||% env) } call }, list = lapply(call, partial_eval, vars = vars, env = env), abort(paste("Unknown input type: ", class(call))) ) } sym_partial_eval <- function(sym, vars, env) { name <- as_string(sym) if (name %in% vars) { sym } else if (env_has(env, name, inherit = TRUE)) { eval_bare(sym, env) } else { sym } } is_namespaced_dplyr_call <- function(call) { is_symbol(call[[1]], "::") && is_symbol(call[[2]], "dplyr") } is_tidy_pronoun <- function(call) { is_symbol(call[[1]], c("$", "[[")) && is_symbol(call[[2]], c(".data", ".env")) } lang_partial_eval <- function(call, vars, env) { fun <- call[[1]] # Try to find the name of inlined functions if (is.function(fun)) { fun_name <- find_fun(fun) if (is.null(fun_name)) { return(eval_bare(call, env)) } call[[1]] <- fun <- sym(fun_name) } # Qualified calls, EXCEPT dplyr::foo() if (is.call(fun)) { if (is_namespaced_dplyr_call(fun)) { call[[1]] <- fun[[3]] } else if (is_tidy_pronoun(fun)) { stop("Use local() or remote() to force evaluation of functions", call. = FALSE) } else { return(eval_bare(call, env)) } } # .data$, .data[[]], .env$, .env[[]] need special handling if (is_tidy_pronoun(call)) { if (is_symbol(call[[1]], "$")) { idx <- call[[3]] } else { idx <- as.name(eval_bare(call[[3]], env)) } if (is_symbol(call[[2]], ".data")) { idx } else { eval_bare(idx, env) } } else { # Process call arguments recursively, unless user has manually called # remote/local name <- as_string(call[[1]]) if (name == "local") { eval_bare(call[[2]], env) } else if (name == "remote") { call[[2]] } else { call[-1] <- lapply(call[-1], partial_eval, vars = vars, env = env) call } } } find_fun <- function(fun) { if (is_lambda(fun)) { body <- body(fun) if (!is_call(body)) { return(NULL) } fun_name <- body[[1]] if (!is_symbol(fun_name)) { return(NULL) } as.character(fun_name) } else if (is.function(fun)) { fun_name(fun) } } fun_name <- function(fun) { pkg_env <- env_parent(global_env()) known <- c(ls(base_agg), ls(base_scalar)) for (x in known) { if (!env_has(pkg_env, x, inherit = TRUE)) next fun_x <- env_get(pkg_env, x, inherit = TRUE) if (identical(fun, fun_x)) return(x) } NULL }
/scratch/gouwar.j/cran-all/cranData/AzureKusto/R/partial_eval.R
.qry_opt_names <- c( "queryconsistency", "response_dynamic_serialization", "response_dynamic_serialization_2" ) #' Run a query or command against a Kusto database #' #' @param database A Kusto database endpoint object, as returned by `kusto_database_endpoint`. #' @param qry_cmd A string containing the query or command. In KQL, a database management command is a statement that starts with a "." #' @param ... Named arguments to be used as parameters for a parameterized query. These are ignored for database management commands. #' @param .http_status_handler The function to use to handle HTTP status codes. The default "stop" will throw an R error via `httr::stop_for_status` if the status code is not less than 300; other possibilities are "warn", "message" and "pass". The last option will pass through the raw response object from the server unchanged, regardless of the status code. This is mostly useful for debugging purposes, or if you want to see what the Kusto REST API does. #' #' @details #' This function is the workhorse of the AzureKusto package. It communicates with the Kusto server and returns the query or command results, as data frames. #' #' @seealso #' [kusto_database_endpoint], [ingest_local], [ingest_url], [ingest_blob], [ingest_adls2] #' #' @examples #' \dontrun{ #' #' endp <- kusto_database_endpoint(server="myclust.australiaeast.kusto.windows.net", database="db1") #' #' # a command #' run_query(endp, ".show table iris") #' #' # a query #' run_query(endp, "iris | count") #' #' } #' @export run_query <- function(database, qry_cmd, ..., .http_status_handler="stop") { server <- database$server db <- database$database token <- database$token user <- database$user password <- database$pwd qry_opts <- database[names(database) %in% .qry_opt_names] is_cmd <- substr(qry_cmd, 1, 1) == "." uri <- paste0(server, if(is_cmd) "/v1/rest/mgmt" else "/v1/rest/query") query_params <- if(is_cmd) list() else list(...) body <- build_request_body(db, qry_cmd, query_options=qry_opts, query_parameters=query_params) auth_str <- build_auth_str(token, user, password) result <- call_kusto(uri, body, auth_str, http_status_handler=.http_status_handler) if(is_cmd) parse_command_result(result, database$use_integer64) else parse_query_result(result, database$use_integer64) } build_param_list <- function(query_params) { ps <- mapply(function(name, value) { type <- switch(class(value)[1], "logical"="bool", "numeric"="real", "integer64"="long", "integer"="int", "Date"="datetime", "POSIXct"="datetime", "string" ) paste(name, type, sep=":") }, names(query_params), query_params) paste0("(", paste(ps, collapse=", "), ")") } build_request_body <- function(db, qry_cmd, query_options=list(), query_parameters=list()) { default_query_options <- list( queryconsistency="strongconsistency", response_dynamic_serialization="string", response_dynamic_serialization_2="legacy") query_options <- utils::modifyList(default_query_options, query_options) body <- list( properties=list(Options=query_options), csl=qry_cmd ) if(!is.null(db)) body <- c(body, db=db) if(!is_empty(query_parameters)) { body$csl <- paste( "declare query_parameters", build_param_list(query_parameters), ";", body$csl) body$properties$Parameters <- query_parameters } body } build_auth_str <- function(token=NULL, user=NULL, password=NULL) { auth_str <- if(!is.null(token)) paste("Bearer", validate_token(token)) else if(!is.null(user) && !is.null(password)) paste("Basic", openssl::base64_encode(paste(user, password, sep=":"))) else stop("Must provide authentication details") auth_str } call_kusto <- function(uri, body, auth_str, http_status_handler=c("stop", "warn", "message", "pass")) { res <- httr::POST(uri, httr::add_headers(Authorization=auth_str), body=body, encode="json") http_status_handler <- match.arg(http_status_handler) if(http_status_handler == "pass") return(res) cont <- httr::content(res, simplifyVector=TRUE) handler <- get(paste0(http_status_handler, "_for_status"), getNamespace("httr")) handler(res, make_error_message(cont)) cont$Tables } make_error_message <- function(content) { msg <- if(!is.null(content$Message)) content$Message else if(!is.null(content$error)) { err <- content$error sprintf("%s\n%s", err$message, err$`@message`) } else "" paste0("complete Kusto operation. Message:\n", sub("\\.$", "", msg)) } parse_query_result <- function(tables, .use_integer64) { # if raw http response, pass through unchanged if(inherits(tables, "response")) return(tables) # load TOC table n <- nrow(tables) toc <- convert_result_types(tables$Rows[[n]], tables$Columns[[n]], .use_integer64) result_tables <- which(toc$Name == "PrimaryResult") res <- Map(convert_result_types, tables$Rows[result_tables], tables$Columns[result_tables], MoreArgs=list(.use_integer64=.use_integer64)) if(length(res) == 1) res[[1]] else res } parse_command_result <- function(tables, .use_integer64) { # if raw http response, pass through unchanged if(inherits(tables, "response")) return(tables) ## Command response only has DataType attribute, no ColumnType, so copy DataType into ColumnType. if(!("ColumnType" %in% tables$Columns[[1]])) tables$Columns[[1]]$ColumnType <- tables$Columns[[1]]$DataType res <- Map(convert_result_types, tables$Rows, coltypes_df=tables$Columns, MoreArgs=list(.use_integer64=.use_integer64)) if(length(res) == 1) res[[1]] else res } convert_result_types <- function(df, coltypes_df, .use_integer64) { if(is_empty(df)) return(list()) convert_kusto_datatype <- function(column, kusto_type, .use_integer64) { switch(kusto_type, long=, Int64= if(.use_integer64) bit64::as.integer64(column) else as.numeric(column), int=, integer=, Int32= as.integer(column), datetime=, DateTime= as.POSIXct(strptime(column, format='%Y-%m-%dT%H:%M:%OSZ', tz='UTC')), real=, double=, float=, decimal=, Decimal=, SqlDecimal=, Double=, Float= as.numeric(column), bool=, Boolean= as.logical(column), dynamic= lapply(column, function(x) if (!is.na(x)) tryCatch(jsonlite::fromJSON(x), error=function(e) return(x))), as.character(column) ) } df <- as.data.frame(df, stringsAsFactors=FALSE) names(df) <- coltypes_df$ColumnName df[] <- Map(convert_kusto_datatype, df, coltypes_df$ColumnType, MoreArgs=list(.use_integer64=.use_integer64)) df } validate_token <- function(token) { # token can be a string or an object of class AzureRMR::AzureToken if(AzureRMR::is_azure_token(token)) { if(!token$validate()) # refresh if needed { message("Access token has expired or is no longer valid; refreshing") token$refresh() } token <- token$credentials$access_token } else if(!is.character(token)) stop("Invalid authentication token", call.=FALSE) token }
/scratch/gouwar.j/cran-all/cranData/AzureKusto/R/query.R
# reexport functions from dplyr to satisfy R CMD check #' @export dplyr::filter #' @export dplyr::intersect #' @export dplyr::setdiff #' @export dplyr::setequal #' @export dplyr::union
/scratch/gouwar.j/cran-all/cranData/AzureKusto/R/reexport-dplyr.R
#' Create a local lazy tbl #' #' Useful for testing KQL generation without a remote connection. #' #' @keywords internal #' @export #' @examples #' library(dplyr) #' df <- data.frame(x = 1, y = 2) #' #' df <- tbl_kusto_abstract(df, "table1") #' df %>% #' summarise(x = sd(x)) %>% #' show_query() tbl_kusto_abstract <- function(df, table_name, ...) { params <- list(...) src <- structure( list( database = "local_df", server = "local_df", table = escape(ident(table_name)) ), class = "kusto_database_endpoint" ) make_tbl("kusto_abstract", ops = op_base_local(df), src = src, params = params) } setOldClass(c("tbl_kusto_abstract", "tbl")) #' @export select.tbl_kusto_abstract <- function(.data, ...) { dots <- quos(...) add_op_single("select", .data, dots = dots) } #' @export distinct.tbl_kusto_abstract <- function(.data, ...) { dots <- quos(...) dots <- partial_eval(dots, vars = op_vars(.data)) add_op_single("distinct", .data, dots = dots) } #' @export rename.tbl_kusto_abstract <- function(.data, ...) { dots <- quos(...) add_op_single("rename", .data, dots = dots) } #' @export filter.tbl_kusto_abstract <- function(.data, ...) { dots <- quos(...) # add the tbl params into the environment of the expression's quosure dots <- lapply(dots, add_params_to_quosure, params = .data$params) dots <- partial_eval(dots, vars = op_vars(.data)) add_op_single("filter", .data, dots = dots) } #' @export mutate.tbl_kusto_abstract <- function(.data, ...) { dots <- quos(..., .named = TRUE) dots <- lapply(dots, add_params_to_quosure, params = .data$params) dots <- partial_eval(dots, vars = op_vars(.data)) add_op_single("mutate", .data, dots = dots) } #' @export arrange.tbl_kusto_abstract <- function(.data, ...) { dots <- quos(...) dots <- partial_eval(dots, vars = op_vars(.data)) names(dots) <- NULL add_op_single("arrange", .data, dots = dots) } #' @export group_by.tbl_kusto_abstract <- function(.data, ..., add = FALSE) { dots <- quos(...) dots <- partial_eval(dots, vars = op_vars(.data)) if (is_empty(dots)) { return(.data) } # Updated for dplyr deprecation of .dots and add params groups <- group_by_prepare(.data, !!!dots, .add = add) names <- vapply(groups$groups, as_string, character(1)) add_op_single("group_by", groups$data, dots = set_names(groups$groups, names), args = list(add = FALSE) ) } #' @export ungroup.tbl_kusto_abstract <- function(x, ...) { add_op_single("ungroup", x) } #' Summarise method for Kusto tables #' #' This method is the same as other summarise methods, with the exception of the `.strategy`, `.shufflekeys` and `.num_partitions` optional arguments. They provide hints to the Kusto engine on how to execute the summarisation, and can sometimes be useful to speed up a query. See the Kusto documentation for more details. #' #' @param .data A Kusto tbl. #' @param ... Summarise expressions. #' @param .strategy A summarise strategy to pass to Kusto. Currently the only value supported is "shuffle". #' @param .shufflekeys A character vector of column names to use as shuffle keys. #' @param .num_partitions The number of partitions for a shuffle query. #' @seealso #' [dplyr::summarise] #' #' @examples #' \dontrun{ #' #' tbl1 <- tbl_kusto(db, "table1") #' #' ## standard dplyr syntax: #' summarise(tbl1, mx = mean(x)) #' #' ## Kusto extensions: #' summarise(tbl1, mx = mean(x), .strategy = "broadcast") # a broadcast summarise #' #' summarise(tbl1, mx = mean(x), .shufflekeys = c("var1", "var2")) # a shuffle summarise with keys #' #' summarise(tbl1, mx = mean(x), .num_partitions = 5) # no. of partitions for a shuffle summarise #' } #' #' @rdname summarise #' @export summarise.tbl_kusto_abstract <- function(.data, ..., .strategy = NULL, .shufflekeys = NULL, .num_partitions = NULL) { dots <- quos(..., .named = TRUE) dots <- partial_eval(dots, vars = op_vars(.data)) add_op_single("summarise", .data, dots = dots, args = list(.strategy = .strategy, .shufflekeys = .shufflekeys, .num_partitions = .num_partitions) ) } #' Unnest method for Kusto tables #' #' This method takes a list column and expands it so that each element of the list gets its own row. #' unnest() translates to Kusto's mv-expand operator. #' #' @param data A Kusto tbl. #' @param cols Specification of columns to unnest. #' @param ... `r lifecycle::badge("deprecated")`: #' previously you could write `df %>% unnest(x, y, z)`. #' Convert to `df %>% unnest(c(x, y, z))`. If you previously created a new #' variable in `unnest()` you'll now need to do it explicitly with `mutate()`. #' Convert `df %>% unnest(y = fun(x, y, z))` #' to `df %>% mutate(y = fun(x, y, z)) %>% unnest(y)`. #' @param keep_empty Needed for agreement with generic. Not otherwise used. Kusto does not keep empty rows. #' @param ptype Needed for agreement with generic. Not otherwise used. #' @param names_sep Needed for agreement with generic. Not otherwise used. #' @param names_repair Needed for agreement with generic. Not otherwise used. #' @param .drop Needed for agreement with generic. Not otherwise used. #' @param .id Data frame identifier - if supplied, will create a new column with name .id, giving a unique identifier. This is most useful if the list column is named. #' @param .sep Needed for agreement with generic. Not otherwise used. #' @param .preserve Needed for agreement with generic. Not otherwise used. #' @export unnest.tbl_kusto_abstract <- function(data, cols, ..., keep_empty = FALSE, ptype = NULL, names_sep = NULL, names_repair = NULL, .drop = NULL, .id = NULL, .sep = NULL, .preserve = NULL) { # dots <- quos(...) dots <- enquo(cols) add_op_single("unnest", data, dots = dots, args = list(.id = .id)) } #' Nest method for Kusto tables #' #' This method collapses a column into a list #' #' @param .data A kusto tbl. #' @param ... Specification of columns to nest. Translates to summarize make_list() in Kusto. #' @export nest.tbl_kusto_abstract <- function(.data, ...) { nest_vars <- unname(tidyselect::vars_select(op_vars(.data), ...)) if (is_empty(nest_vars)) { nest_vars <- op_vars(.data) } group_vars <- union(op_grps(.data), setdiff(op_vars(.data), nest_vars)) nest_vars <- setdiff(nest_vars, group_vars) dot_calls <- mapply(function(x) expr(make_list(!!as.name(x))), nest_vars) if (is_empty(group_vars)) { summarise(.data, !!!dot_calls) } else { summarise(group_by(.data, !!as.name(group_vars)), !!!dot_calls) } } #' @export head.tbl_kusto_abstract <- function(x, n = 6L, ...) { add_op_single("head", x, args = list(n = n)) } #' @export slice_sample.tbl_kusto_abstract <- function(.data, ..., n = 6L, prop, by, weight_by, replace) { add_op_single("slice_sample", .data, args = list(n = n)) } #' Join methods for Kusto tables #' #' These methods are the same as other joining methods, with the exception of the `.strategy`, `.shufflekeys` and `.num_partitions` optional arguments. They provide hints to the Kusto engine on how to execute the join, and can sometimes be useful to speed up a query. See the Kusto documentation for more details. #' #' @param x,y Kusto tbls. #' @param by The columns to join on. #' @param copy Needed for agreement with generic. Not otherwise used. #' @param suffix The suffixes to use for deduplicating column names. #' @param ... Other arguments passed to lower-level functions. #' @param keep Needed for agreement with generic. Not otherwise used. Kusto retains keys from both sides of joins. #' @param .strategy A join strategy hint to pass to Kusto. Currently the values supported are "shuffle" and "broadcast". #' @param .shufflekeys A character vector of column names to use as shuffle keys. #' @param .num_partitions The number of partitions for a shuffle query. #' @param .remote A join strategy hint to use for cross-cluster joins. Can be "left", "right", "local" or "auto" (the default). #' @seealso #' [dplyr::join] #' #' @examples #' \dontrun{ #' #' tbl1 <- tbl_kusto(db, "table1") #' tbl2 <- tbl_kusto(db, "table2") #' #' # standard dplyr syntax: #' left_join(tbl1, tbl2) #' #' # Kusto extensions: #' left_join(tbl1, tbl2, .strategy = "broadcast") # a broadcast join #' #' left_join(tbl1, tbl2, .shufflekeys = c("var1", "var2")) # shuffle join with shuffle keys #' #' left_join(tbl1, tbl2, .num_partitions = 5) # no. of partitions for a shuffle join #' } #' #' @aliases inner_join left_join right_join full_join semi_join anti_join #' #' @rdname join #' @export inner_join.tbl_kusto_abstract <- function(x, y, by = NULL, copy = NULL, suffix = c(".x", ".y"), ..., keep = NULL, .strategy = NULL, .shufflekeys = NULL, .num_partitions = NULL, .remote = NULL) { add_op_join("inner_join", x, y, by = by, suffix = suffix, .strategy = .strategy, .shufflekeys = .shufflekeys, .num_partitions = .num_partitions, .remote = .remote, ... ) } #' @rdname join #' @export left_join.tbl_kusto_abstract <- function(x, y, by = NULL, copy = NULL, suffix = c(".x", ".y"), ..., keep = NULL, .strategy = NULL, .shufflekeys = NULL, .num_partitions = NULL, .remote = NULL) { add_op_join("left_join", x, y, by = by, suffix = suffix, .strategy = .strategy, .shufflekeys = .shufflekeys, .num_partitions = .num_partitions, .remote = .remote, ... ) } #' @rdname join #' @export right_join.tbl_kusto_abstract <- function(x, y, by = NULL, copy = NULL, suffix = c(".x", ".y"), ..., keep = NULL, .strategy = NULL, .shufflekeys = NULL, .num_partitions = NULL, .remote = NULL) { add_op_join("right_join", x, y, by = by, suffix = suffix, .strategy = .strategy, .shufflekeys = .shufflekeys, .num_partitions = .num_partitions, .remote = .remote, ... ) } #' @rdname join #' @export full_join.tbl_kusto_abstract <- function(x, y, by = NULL, copy = NULL, suffix = c(".x", ".y"), ..., keep = NULL, .strategy = NULL, .shufflekeys = NULL, .num_partitions = NULL, .remote = NULL) { add_op_join("full_join", x, y, by = by, suffix = suffix, .strategy = .strategy, .shufflekeys = .shufflekeys, .num_partitions = .num_partitions, .remote = .remote, ... ) } #' @rdname join #' @export semi_join.tbl_kusto_abstract <- function(x, y, by = NULL, copy = NULL, ..., suffix = c(".x", ".y"), .strategy = NULL, .shufflekeys = NULL, .num_partitions = NULL, .remote = NULL) { add_op_join("semi_join", x, y, by = by, suffix = suffix, .strategy = .strategy, .shufflekeys = .shufflekeys, .num_partitions = .num_partitions, .remote = .remote, ... ) } #' @rdname join #' @export anti_join.tbl_kusto_abstract <- function(x, y, by = NULL, copy = NULL, suffix = c(".x", ".y"), .strategy = NULL, .shufflekeys = NULL, .num_partitions = NULL, .remote = NULL, ...) { add_op_join("anti_join", x, y, by = by, suffix = suffix, .strategy = .strategy, .shufflekeys = .shufflekeys, .num_partitions = .num_partitions, .remote = .remote, ... ) } #' @export union_all.tbl_kusto_abstract <- function(x, y, ...) { add_op_set_op(x, y, "union_all") } #' @export union.tbl_kusto_abstract <- function(x, y, ...) { stop("Kusto does not support union(). Please use union_all() instead.") } #' @export setdiff.tbl_kusto_abstract <- function(x, y, ...) { stop("Kusto does not support setdiff() at this time.") } #' @export setequal.tbl_kusto_abstract <- function(x, y, ...) { stop("Kusto does not support setequal() at this time.") } #' @export intersect.tbl_kusto_abstract <- function(x, y, ...) { stop("Kusto does not support intersect() at this time.") } #' @export tbl_vars.tbl_kusto_abstract <- function(x) { op_vars(x$ops) } #' @export group_vars.tbl_kusto_abstract <- function(x) { op_grps(x$ops) } #' Translate a sequence of dplyr operations on a tbl into a Kusto query string. #' @export #' @param x A tbl_kusto or tbl_kusto_abstract instance #' @param ... needed for agreement with generic. Not otherwise used. show_query.tbl_kusto_abstract <- function(x, ...) { qry <- kql_build(x) kql_render(qry) } #' A tbl object representing a table in a Kusto database. #' @export #' @param kusto_database An instance of kusto_database_endpoint that this table should be queried from #' @param table_name The name of the table in the Kusto database #' @param ... parameters to pass in case the Kusto source table is a parameterized function. tbl_kusto <- function(kusto_database, table_name, ...) { stopifnot(inherits(kusto_database, "kusto_database_endpoint")) params <- list(...) # in case the table name is a function like MyFunction(arg1, arg2) we need to split it table_ident <- strsplit(table_name, split = "\\(")[[1]] table_ident[1] <- escape(ident(table_ident[1])) escaped_table_name <- paste(table_ident, collapse = "(") kusto_database$table <- escaped_table_name query_str <- sprintf("%s | take 1", escaped_table_name) vars <- names(run_query(kusto_database, query_str, ...)) ops <- op_base_remote(table_name, vars) make_tbl(c("kusto", "kusto_abstract"), src = kusto_database, ops = ops, params = params) } #' Compile the preceding dplyr operations into a kusto query, execute it on the remote server, #' and return the result as a tibble. #' @export #' @param x An instance of class tbl_kusto representing a Kusto table #' @param ... needed for agreement with generic. Not otherwise used. collect.tbl_kusto <- function(x, ...) { q <- kql_build(x) q_str <- kql_render(q) params <- c(x$params, list(...)) params$database <- x$src params$qry_cmd <- q_str res <- do.call(run_query, params) tibble::as_tibble(res) } generate_table_name <- function() { paste0("Rtbl_", paste0(sample(letters, 8), collapse = "")) } #' Execute the query, store the results in a table, and return a reference to the new table #' @export #' @param x An instance of class tbl_kusto representing a Kusto table #' @param ... other parameters passed to the query #' @param name The name for the Kusto table to be created. #' If name is omitted, the table will be named Rtbl_ + 8 random lowercase letters compute.tbl_kusto <- function(x, ..., name = generate_table_name()) { q <- kql_build(x) q_str <- kql_render(q) new_tbl_name <- kql_escape_ident(name) set_cmd <- kql(paste0(".set ", new_tbl_name, " <|\n")) q_str <- kql(paste0(set_cmd, q_str)) params <- c(x$params, list(...)) params$database <- x$src params$qry_cmd <- q_str res <- do.call(run_query, params) invisible(tbl_kusto(x$src, name)) } #' Execute the query, store the results in a table, and return a reference to the new table #' Run a Kusto query and export results to Azure Storage in Parquet or CSV #' format. #' #' @param query The text of the Kusto query to run #' @param storage_uri The URI of the blob storage container to export to #' @param name_prefix The filename prefix for each exported file #' @param key The account key for the storage container. #' uses the identity that is signed into Kusto to authenticate to Azure Storage. #' @param format Options are "parquet", "csv", "tsv", "json" #' @param distributed logical, indicates whether Kusto should distributed the #' export job to multiple nodes, in which case multiple files will be written #' to storage concurrently. kusto_export_cmd <- function( query, storage_uri, name_prefix, key, format, distributed) { # Make sure the storage uri ends with a slash if (!(format %in% c("parquet", "csv", "tsv", "json"))) { stop("Format must be one of parquet, csv, tsv, or json.") } if (!endsWith(storage_uri, "/")) { storage_uri <- paste0(storage_uri, "/") } distr <- ifelse(distributed, "true", "false") compr <- ifelse(format == "parquet", "snappy", "gzip") sprintf(".export compressed to %s (h@'%s%s;%s') with ( sizeLimit=1073741824, namePrefix='%s', fileExtension='%s', compressionType='%s', includeHeaders='firstFile', encoding='UTF8NoBOM', distributed=%s ) <| %s ", format, storage_uri, name_prefix, key, name_prefix, format, compr, distr, query) } #' Execute the Kusto query and export the result to Azure Storage. #' @param tbl An object representing a table or database. #' @param storage_uri The Azure Storage URI to export files to. #' @param query A Kusto query string #' @param name_prefix The filename prefix to use for exported files. #' @param key default "impersonate" which uses the account signed into Kusto to #' authenticate to Azure Storage. An Azure Storage account key. #' @param format Options are "parquet", "csv", "tsv", "json" #' @param distributed logical, indicates whether Kusto should distributed the #' export job to multiple nodes, in which case multiple files will be written #' to storage concurrently. #' @param ... needed for agreement with generic. Not otherwise used. #' @rdname export #' @export export <- function( tbl, storage_uri, query = NULL, name_prefix = "export", key = "impersonate", format = "parquet", distributed = FALSE, ...) { UseMethod("export") } #' Execute the Kusto query and export the result to Azure Storage. #' @param tbl A Kusto database endpoint object, as returned by `kusto_database_endpoint`. #' @param query A Kusto query string #' @param storage_uri The Azure Storage URI to export files to. #' @param name_prefix The filename prefix to use for exported files. #' @param key default "impersonate" which uses the account signed into Kusto to #' authenticate to Azure Storage. An Azure Storage account key. #' @param format Options are "parquet", "csv", "tsv", "json" #' @param distributed logical, indicates whether Kusto should distributed the #' export job to multiple nodes, in which case multiple files will be written #' to storage concurrently. #' @param ... needed for agreement with generic. Not otherwise used. #' @rdname export #' @export export.kusto_database_endpoint <- function( tbl, storage_uri, query = NULL, name_prefix = "export", key = "impersonate", format = "parquet", distributed = FALSE, ...) { if (missing(query)) stop("query parameter is required.") is_cmd <- substr(query, 1, 1) == "." if (is_cmd) stop("Management commands cannot be used with export()") q_str <- kusto_export_cmd( query = query, storage_uri = storage_uri, name_prefix = name_prefix, key = key, format = format, distributed = distributed ) run_query(tbl, q_str, ...) } #' @rdname export #' @export export.tbl_kusto <- function( tbl, storage_uri, query = NULL, name_prefix = "export", key = "impersonate", format = "parquet", distributed = FALSE, ...) { database <- tbl$src q <- kql_render(kql_build(tbl)) q_str <- kusto_export_cmd( query = q, storage_uri = storage_uri, name_prefix = name_prefix, key = key, format = format, distributed = distributed ) res <- run_query(database, q_str, ...) tibble::as_tibble(res) } #' @keywords internal #' @export print.tbl_kusto_abstract <- function(x, ...) { # different paths if this is a query, simulated table, or real table if (!inherits(x$ops, "op_base")) { cat("<Kusto query>\n") print(show_query(x)) } else if (!inherits(x, "tbl_kusto")) { cat("<Simulated Kusto table '") name <- paste0("local_df/", x$src$table) cat(name, "'>\n", sep = "") } else { cat("<Kusto table '") url <- httr::parse_url(x$src$server) url$path <- file.path(x$src$database, x$src$table) cat(httr::build_url(url), "'>\n", sep = "") } invisible(x) } add_params_to_quosure <- function(quosure, params) { new_env <- list2env(params, envir = get_env(quosure)) quo_set_env(quosure, new_env) }
/scratch/gouwar.j/cran-all/cranData/AzureKusto/R/tbl.R
#' Translate R expressions into Kusto Query Language equivalents. #' @param ... Expressions to translate. #' @export translate_kql <- function(...) { dots <- quos(...) if (is_empty(dots)) return(kql()) stopifnot(is.list(dots)) if (!any(have_name(dots))) names(dots) <- NULL variant <- kql_translate_env() pieces <- lapply(dots, function(x) { if (is_atomic(get_expr(x))) escape(get_expr(x)) else { mask <- kql_mask(x, variant) escape(eval_tidy(x, mask)) } }) kql(unlist(pieces)) } kql_mask <- function(expr, variant) { # Default for unknown functions unknown <- setdiff(all_calls(expr), names(variant)) top_env <- ceply(unknown, default_op, parent = empty_env()) # Known R -> KQL functions special_calls <- copy_env(variant$scalar, parent = top_env) special_calls2 <- copy_env(variant$aggregate, parent = special_calls) # Existing symbols in expression names <- all_names(expr) idents <- lapply(names, ident) name_env <- ceply(idents, escape, parent = special_calls2) # Known kql expressions symbol_env <- env_clone(base_symbols, parent = name_env) new_data_mask(symbol_env, top_env) } # character vector -> environment ceply <- function(x, f, ..., parent = parent.frame()) { if (is_empty(x)) return(new.env(parent = parent)) l <- lapply(x, f, ...) names(l) <- x list2env(l, parent = parent) } #' Build a kql_variant class out of the environments holding scalar and aggregation #' function definitions #' @export kql_translate_env <- function() { kql_variant( base_scalar, base_agg ) } kql_variant <- function(scalar = kql_translator(), aggregate = kql_translator()) { stopifnot(is.environment(scalar)) stopifnot(is.environment(aggregate)) structure( list(scalar = scalar, aggregate = aggregate), class = "kql_variant" ) } #' Builds an environment from a list of R -> Kusto query language translation pairs. #' @param ... Pairs of R call = Kusto call translations as individual arguments #' @param .funs Parse of R call = Kusto call translations in list format #' @param .parent A parent environment to attach this env onto #' @export kql_translator <- function(..., .funs = list(), .parent = new.env(parent = emptyenv())) { funs <- c(list(...), .funs) if (is_empty(funs)) return(.parent) list2env(funs, copy_env(.parent)) } copy_env <- function(from, to = NULL, parent = parent.env(from)) { list2env(as.list(from), envir = to, parent = parent) } #' Return a function representing a scalar KQL infix operator #' @param f Name of a Kusto infix operator / function #' @export kql_infix <- function(f) { stopifnot(is.character(f)) function(x, y) { # If y is a table/query we need to render and inline it if (inherits(y, "tbl_kusto_abstract")) { # KQL requires double parens around queries as RHS of in operator build_kql(x, " ", kql(f), " ((", kql(kql_render(kql_build(y))), "))") } else { build_kql(x, " ", kql(f), " ", y) } } } #' Return a function representing a scalar KQL prefix function #' @param f Name of a Kusto infix function #' @param n Number of arguments accepted by the Kusto prefix function #' @export kql_prefix <- function(f, n = NULL) { stopifnot(is.character(f)) function(...) { args <- list(...) if (!is.null(n) && length(args) != n) { stop( "Invalid number of args to ", f, ". Expecting ", n, call. = FALSE ) } if (any(names2(args) != "")) warning("Named arguments ignored for ", f, call. = FALSE) build_kql(kql(f), args) } } #' Return a function representing a KQL aggregation function #' @param f Name of the Kusto aggregation function #' @export kql_aggregate <- function(f) { stopifnot(is.character(f)) function(x, na.rm = FALSE) { check_na_rm(f, na.rm) build_kql(kql(f), list(x)) } } #' Return a function representing a KQL window function #' @param f Name of the Kusto aggregation function #' @export kql_window <- function(f) { stopifnot(is.character(f)) function(x, na.rm = FALSE) { check_na_rm(f, na.rm) build_kql(kql(f), list(x)) } } check_na_rm <- function(f, na.rm) { if (identical(na.rm, TRUE)) return() warning( "Missing values are always removed in KQL.\n", "Use `", f, "(x, na.rm = TRUE)` to silence this warning", call. = FALSE ) } all_names <- function(x) { if (is.name(x)) return(as.character(x)) if (!is.call(x)) return(NULL) unique(unlist(lapply(x[-1], all_names), use.names = FALSE)) } all_calls <- function(x) { if (!is.call(x)) return(NULL) fname <- as.character(x[[1]]) unique(c(fname, unlist(lapply(x[-1], all_calls), use.names = FALSE))) } is_infix_base <- function(x) { x %in% c("::", "$", "@", "^", "*", "/", "+", "-", ">", ">=", "<", "<=", "==", "!=", "!", "&", "&&", "|", "||", "~", "<-", "<<-") } is_infix_user <- function(x) { grepl("^%.*%$", x) } default_op <- function(x) { stopifnot(is.character(x)) if (is_infix_base(x)) { kql_infix(x) } else if (is_infix_user(x)) { x <- substr(x, 2, nchar(x) - 1) kql_infix(x) } else { kql_prefix(x) } } #' Scalar operator translations (infix and prefix) #' @export base_scalar <- kql_translator( `+` = kql_infix("+"), `*` = kql_infix("*"), `/` = kql_infix("/"), `%%` = kql_infix("%"), `^` = kql_prefix("power", 2), `-` = function(x, y = NULL) { if (is.null(y)) if (is.numeric(x)) -x else build_kql(kql("-"), x) else build_kql(x, kql(" - "), y) }, `!=` = kql_infix("!="), `==` = kql_infix("=="), `<` = kql_infix("<"), `<=` = kql_infix("<="), `>` = kql_infix(">"), `>=` = kql_infix(">="), `%in%` = kql_infix("in"), `%in~%` = kql_infix("in~"), `%!in%` = kql_infix("!in"), `%!in~%` = kql_infix("!in~"), `!` = kql_prefix("not"), `&` = kql_infix("and"), `&&` = kql_infix("and"), `|` = kql_infix("or"), `||` = kql_infix("or"), xor = function(x, y) { kql(sprintf("(%1$s or %2$s) and not (%1$s and %2$s)", escape(x), escape(y))) }, abs = kql_prefix("abs", 1), acos = kql_prefix("acos", 1), asin = kql_prefix("asin", 1), atan = kql_prefix("atan", 1), atan2 = kql_prefix("atan2", 2), ceil = kql_prefix("ceiling", 1), ceiling = kql_prefix("ceiling", 1), cos = kql_prefix("cos", 1), cot = kql_prefix("cot", 1), exp = kql_prefix("exp", 1), floor = kql_prefix("floor", 1), log = function(x, base = exp(1)) { if (isTRUE(all.equal(base, exp(1)))) { prefix("log") } else if (is.TRUE(all.equal(base, 2))) { prefix("log2") } else if (is.TRUE(all.equal(base, 10))) { prefix("log10") } else { stop("KQL only supports logarithms with base e, 2, or 10.") } }, log10 = kql_prefix("log10", 1), round = kql_prefix("round", 2), sign = kql_prefix("sign", 1), sin = kql_prefix("sin", 1), sinh = kql_prefix("sinh", 1), sqrt = kql_prefix("sqrt", 1), tan = kql_prefix("tan", 1), tanh = kql_prefix("tanh", 1), tolower = kql_prefix("tolower", 1), toupper = kql_prefix("toupper", 1), #trimws = kql_prefix("trim", 1), nchar = kql_prefix("strlen", 1), substr = function(x, start, stop) { start <- as.integer(start) length <- pmax(as.integer(stop) - start + 1L, 0L) build_kql(kql("substring"), list(x, start, length)) }, `if` = kql_prefix("iif", 3), if_else = kql_prefix("iif", 3), ifelse = kql_prefix("iif", 3), case_when = kql_prefix("case"), kql = function(...) kql(...), `(` = function(x) { build_kql("(", x, ")") }, `{` = function(x) { build_kql("(", x, ")") }, `$` = kql_infix("."), asc = function(x) { build_kql(x, kql(" asc")) }, desc = function(x) { build_kql(x, kql(" desc")) }, is.null = kql_prefix("isnull"), is.na = kql_prefix("isnull"), coalesce = kql_prefix("coalesce"), as.numeric = kql_prefix("todouble", 1), as.double = kql_prefix("todouble", 1), as.integer = kql_prefix("toint", 1), as.character = kql_prefix("tostring", 1), as.Date = kql_prefix("todatetime", 1), as.POSIXct = kql_prefix("todatetime", 1), as.POSIXlt = kql_prefix("todatetime", 1), strptime = function(dt_str, format_str, tz="UTC") { if(tz != "UTC") { warning("Kusto only supports datetimes in UTC timezone. Non-UTC datetimes will be cast as UTC.") } kql_prefix("todatetime", 1)(dt_str) }, c = function(...) c(...), `:` = function(from, to) from:to, between = function(x, left, right) { build_kql(x, " between (", left, " .. ", right, ")") }, pmin = kql_prefix("min"), pmax = kql_prefix("max"), `%>%` = `%>%`, str_length = kql_prefix("strlen"), str_to_upper = kql_prefix("toupper"), str_to_lower = kql_prefix("tolower"), str_replace_all = function(string, pattern, replacement){ build_kql( "replace(", pattern, ", ", replacement, ", ", string, ")" )}, str_detect = function(string, pattern){ build_kql( string, " matches regex ", pattern )}, str_trim = function(string, side = "both"){ build_kql( kql(ifelse(side == "both" | side == "left", "trim_start(' '", "(")), kql(ifelse(side == "both" | side == "right", "trim_end(' '", "(")), string, "))" )} ) #' Tag character strings as Kusto Query Language. Assumes the string is valid and properly escaped. #' @param ... character strings to tag as KQL #' @export kql <- function(...) { x <- c_character(...) structure(x, class = c("kql", "character")) } #' @export print.kql <- function(x, ...) { cat("<KQL> ", x, "\n", sep = "") } base_symbols <- kql_translator( pi = kql("pi()"), `NULL` = kql("nupll") ) #' Aggregation function translations #' @export base_agg <- kql_translator( n = function() kql("count()"), mean = kql_aggregate("avg"), var = kql_aggregate("variance"), sum = kql_aggregate("sum"), min = kql_aggregate("min"), max = kql_aggregate("max"), n_distinct = kql_aggregate("dcount") ) #' Window function translations #' @export base_window <- kql_translator( row_number = kql_window("row_number") ) dots <- function(...) { eval_bare(substitute(alist(...))) } is_agg <- function(f) { ef <- enexpr(f) if (is.symbol(ef)) sf <- as_string(ef) else if (typeof(ef) == "character") sf <- ef else return(FALSE) sf %in% ls(base_agg) }
/scratch/gouwar.j/cran-all/cranData/AzureKusto/R/translate-kql.R
## ---- include = FALSE--------------------------------------------------------- knitr::opts_chunk$set( collapse = TRUE, comment = "##" ) ## ----setup, eval = FALSE------------------------------------------------------ # library(AzureKusto) # ## The first time you import AzureKusto, you'll be asked if you'd like to create a directory to cache OAuth2 tokens. # # ## Connect to an AzureKusto database with (default) device code authentication: # Samples <- kusto_database_endpoint(server = "https://help.kusto.windows.net", database = "Samples") # # (New in 1.1.0) Some other ways to call this that also work: # # Samples <- kusto_database_endpoint(server="help", database="Samples") # # Samples <- kusto_database_endpoint(cluster="help", database="Samples") # # # No app ID supplied; using KustoClient app # # Waiting for authentication in browser... # # Press Esc/Ctrl + C to abort # # VSCode WebView only supports showing local http content. # # Opening in external browser... # # Browsing https://login.microsoftonline.com/common/oauth2/v2.0/authorize... # # Authentication complete. ## ----run_query, eval = FALSE-------------------------------------------------- # res <- run_query(Samples, "StormEvents | summarize EventCount = count() by State | order by State asc") # head(res) # # ## State EventCount # ## 1 ALABAMA 1315 # ## 2 ALASKA 257 # ## 3 AMERICAN SAMOA 16 # ## 4 ARIZONA 340 # ## 5 ARKANSAS 1028 # ## 6 ATLANTIC NORTH 188 ## ----run_query_params, eval = FALSE------------------------------------------- # res <- run_query(Samples, "MyFunction(lim)", lim = 10L) # head(res) # # ## StartTime EndTime EpisodeId EventId State # ## 1 2007-09-29 08:11:00 2007-09-29 08:11:00 11091 61032 ATLANTIC SOUTH # ## 2 2007-09-18 20:00:00 2007-09-19 18:00:00 11074 60904 FLORIDA # ## 3 2007-09-20 21:57:00 2007-09-20 22:05:00 11078 60913 FLORIDA # ## 4 2007-12-30 16:00:00 2007-12-30 16:05:00 11749 64588 GEORGIA # ## 5 2007-12-20 07:50:00 2007-12-20 07:53:00 12554 68796 MISSISSIPPI # ## 6 2007-12-20 10:32:00 2007-12-20 10:36:00 12554 68814 MISSISSIPPI ## ----run_query_commands, eval = FALSE----------------------------------------- # res <- run_query(Samples, ".show tables | count") # res[[1]] # # ## Count # ## 1 5 ## ----dplyr, eval = FALSE------------------------------------------------------ # library(dplyr) # # StormEvents <- tbl_kusto(Samples, "StormEvents") # # q <- StormEvents %>% # group_by(State) %>% # summarize(EventCount = n()) %>% # arrange(State) # # show_query(q) # # ## <KQL> database('Samples').['StormEvents'] # ## | summarize ['EventCount'] = count() by ['State'] # ## | order by ['State'] asc # # collect(q) # # ## # A tibble: 67 x 2 # ## State EventCount # ## <chr> <dbl> # ## 1 ALABAMA 1315 # ## 2 ALASKA 257 # ## 3 AMERICAN SAMOA 16 # ## 4 ARIZONA 340 # ## 5 ARKANSAS 1028 # ## 6 ATLANTIC NORTH 188 # ## 7 ATLANTIC SOUTH 193 # ## 8 CALIFORNIA 898 # ## 9 COLORADO 1654 # ## 10 CONNECTICUT 148 # ## # ... with 57 more rows ## ----dollar, eval = FALSE----------------------------------------------------- # q <- StormEvents %>% # slice_sample(10) %>% # mutate(Description = as.character(StormSummary$Details$Description)) %>% # select(EventId, Description) # # show_query(q) # # # <KQL> cluster('https://help.kusto.windows.net').database('Samples').['StormEvents'] # # | sample 10 # # | extend ['Description'] = tostring(['StormSummary'] . ['Details'] . ['Description']) # # | project ['EventId'], ['Description'] # # # # A tibble: 10 × 2 # # EventId Description # # <int> <chr> # # 1 61032 A waterspout formed in the Atlantic southeast of Melbourne Beach and briefly moved toward shore. # # 2 60904 As much as 9 inches of rain fell in a 24-hour period across parts of coastal Volusia County. # # 3 60913 A tornado touched down in the Town of Eustis at the northern end of West Crooked Lake. The tornado quickly intensified to EF1 strength as it moved north northwest through Eustis. The track was just under two miles long… # # 4 64588 The county dispatch reported several trees were blown down along Quincey Batten Loop near State Road 206. The cost of tree removal was estimated. # # 5 68796 Numerous large trees were blown down with some down on power lines. Damage occurred in eastern Adams county. # # 6 68814 This tornado began as a small, narrow path of minor damage, including a porch being blown off a house. It reached its maximum intensity as it crossed highway 29. Here, a brick home had all of its roof structure blown o… # # 7 68834 Several trees and power lines were blown down along Zetus Road in the Zetus Community. A few of those trees were down on a mobile home which caused significant damage. # # 8 68846 A swath of penny to quarter sized hail fell from just east of French Camp to about 6 miles north of Weir. # # 9 73241 The heavy rain from an active monsoonal trough that had been nearly stationary just to the south of the islands caused widespread flooding across Tutuila. Flash Flooding was reported from the Malaeimi Valley to the Ba… # # 10 64725 State Route 8 and Rock Run Road were flooded and impassable ## ----tbl_kusto_params, eval = FALSE------------------------------------------- # MyFunctionDate <- tbl_kusto(Samples, "MyFunctionDate(dt)", dt = as.Date("2019-01-01")) # # MyFunctionDate %>% # select(StartTime, EndTime, EpisodeId, EventId, State) %>% # head() %>% # collect() # # ## # A tibble: 6 x 5 # ## StartTime EndTime EpisodeId EventId State # ## <dttm> <dttm> <int> <int> <chr> # ## 1 2007-09-29 08:11:00 2007-09-29 08:11:00 11091 61032 ATLANTIC SOUTH # ## 2 2007-09-18 20:00:00 2007-09-19 18:00:00 11074 60904 FLORIDA # ## 3 2007-09-20 21:57:00 2007-09-20 22:05:00 11078 60913 FLORIDA # ## 4 2007-12-30 16:00:00 2007-12-30 16:05:00 11749 64588 GEORGIA # ## 5 2007-12-20 07:50:00 2007-12-20 07:53:00 12554 68796 MISSISSIPPI # ## 6 2007-12-20 10:32:00 2007-12-20 10:36:00 12554 68814 MISSISSIPPI ## ----exporting, eval = FALSE-------------------------------------------------- # export( # database = Samples, # storage_uri = "https://mystorage.blob.core.windows.net/StormEvents", # query = "StormEvents | summarize EventCount = count() by State | order by State", # name_prefix = "events", # format = "parquet" # ) # # # Path NumRecords SizeInBytes # # 1 https://mystorage.blob.core.windows.net/StormEvents/events/events_1.snappy.parquet 67 1511 # # library(dplyr) # StormEvents <- tbl_kusto(Samples, "StormEvents") # q <- StormEvents %>% # group_by(State) %>% # summarize(EventCount = n()) %>% # arrange(State) %>% # export("https://mystorage.blob.core.windows.net/StormEvents") # # # # A tibble: 1 × 3 # # Path NumRecords SizeInBytes # # <chr> <dbl> <dbl> # # 1 https://mystorage.blob.core.windows.net/StormEvents/export/export_1.snappy.parquet 50 59284 ## ----dbi, eval = FALSE-------------------------------------------------------- # library(DBI) # # Samples <- dbConnect(AzureKusto(), # server = "https://help.kusto.windows.net", # database = "Samples" # ) # # dbListTables(Samples) # # ## [1] "StormEvents" "demo_make_series1" "demo_series2" # ## [4] "demo_series3" "demo_many_series1" # # dbExistsTable(Samples, "StormEvents") # # ## [1] TRUE # # dbGetQuery(Samples, "StormEvents | summarize ct = count()") # # ## ct # ## 1 59066
/scratch/gouwar.j/cran-all/cranData/AzureKusto/inst/doc/AzureKusto.R
--- title: "AzureKusto" date: "2022-12-20" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{AzureKusto} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r, include = FALSE} knitr::opts_chunk$set( collapse = TRUE, comment = "##" ) ``` AzureKusto is the R interface to [Azure Data Explorer](https://azure.microsoft.com/en-us/products/data-explorer/) (internally codenamed "Kusto"), a fast, fully managed data analytics service from Microsoft. AzureKusto provides an interface (including [DBI](https://dbi.r-dbi.org/) compliant methods) for connecting to Kusto clusters and submitting [Kusto Query Language (KQL)](https://learn.microsoft.com/en-us/azure/data-explorer/kusto/query/) statements, as well as a [dbplyr](https://dbplyr.tidyverse.org/) style backend that translates [dplyr](https://dplyr.tidyverse.org/) queries into KQL statements. ```{r setup, eval = FALSE} library(AzureKusto) ## The first time you import AzureKusto, you'll be asked if you'd like to create a directory to cache OAuth2 tokens. ## Connect to an AzureKusto database with (default) device code authentication: Samples <- kusto_database_endpoint(server = "https://help.kusto.windows.net", database = "Samples") # (New in 1.1.0) Some other ways to call this that also work: # Samples <- kusto_database_endpoint(server="help", database="Samples") # Samples <- kusto_database_endpoint(cluster="help", database="Samples") # No app ID supplied; using KustoClient app # Waiting for authentication in browser... # Press Esc/Ctrl + C to abort # VSCode WebView only supports showing local http content. # Opening in external browser... # Browsing https://login.microsoftonline.com/common/oauth2/v2.0/authorize... # Authentication complete. ``` Now you can issue KQL queries to the Kusto database with `run_query()` and get the results back as a data.frame object. ```{r run_query, eval = FALSE} res <- run_query(Samples, "StormEvents | summarize EventCount = count() by State | order by State asc") head(res) ## State EventCount ## 1 ALABAMA 1315 ## 2 ALASKA 257 ## 3 AMERICAN SAMOA 16 ## 4 ARIZONA 340 ## 5 ARKANSAS 1028 ## 6 ATLANTIC NORTH 188 ``` `run_query()` also supports query parameters, to allow you to call parameterized Kusto functions. Simply pass your parameters as additional keyword arguments and they will be escaped and interpolated into the query string. ```{r run_query_params, eval = FALSE} res <- run_query(Samples, "MyFunction(lim)", lim = 10L) head(res) ## StartTime EndTime EpisodeId EventId State ## 1 2007-09-29 08:11:00 2007-09-29 08:11:00 11091 61032 ATLANTIC SOUTH ## 2 2007-09-18 20:00:00 2007-09-19 18:00:00 11074 60904 FLORIDA ## 3 2007-09-20 21:57:00 2007-09-20 22:05:00 11078 60913 FLORIDA ## 4 2007-12-30 16:00:00 2007-12-30 16:05:00 11749 64588 GEORGIA ## 5 2007-12-20 07:50:00 2007-12-20 07:53:00 12554 68796 MISSISSIPPI ## 6 2007-12-20 10:32:00 2007-12-20 10:36:00 12554 68814 MISSISSIPPI ``` `run_query()` can also handle command statements, which begin with a '.' character. Command statements do not accept parameters and cannot be combined together with query statements in the same request. Command statements return a list where the first element is the table returned by the command (if any) and the other elements contain command metadata. ```{r run_query_commands, eval = FALSE} res <- run_query(Samples, ".show tables | count") res[[1]] ## Count ## 1 5 ``` ### dplyr Interface The package also implements a [dplyr](https://github.com/tidyverse/dplyr)-style interface for building a query upon a `tbl_kusto` object and then running it on the remote Kusto database and returning the result as a regular tibble object with `collect()`. ```{r dplyr, eval = FALSE} library(dplyr) StormEvents <- tbl_kusto(Samples, "StormEvents") q <- StormEvents %>% group_by(State) %>% summarize(EventCount = n()) %>% arrange(State) show_query(q) ## <KQL> database('Samples').['StormEvents'] ## | summarize ['EventCount'] = count() by ['State'] ## | order by ['State'] asc collect(q) ## # A tibble: 67 x 2 ## State EventCount ## <chr> <dbl> ## 1 ALABAMA 1315 ## 2 ALASKA 257 ## 3 AMERICAN SAMOA 16 ## 4 ARIZONA 340 ## 5 ARKANSAS 1028 ## 6 ATLANTIC NORTH 188 ## 7 ATLANTIC SOUTH 193 ## 8 CALIFORNIA 898 ## 9 COLORADO 1654 ## 10 CONNECTICUT 148 ## # ... with 57 more rows ``` (New in 1.1.0) The `$` operator can be used to access fields in dynamic columns: ```{r dollar, eval = FALSE} q <- StormEvents %>% slice_sample(10) %>% mutate(Description = as.character(StormSummary$Details$Description)) %>% select(EventId, Description) show_query(q) # <KQL> cluster('https://help.kusto.windows.net').database('Samples').['StormEvents'] # | sample 10 # | extend ['Description'] = tostring(['StormSummary'] . ['Details'] . ['Description']) # | project ['EventId'], ['Description'] # # A tibble: 10 × 2 # EventId Description # <int> <chr> # 1 61032 A waterspout formed in the Atlantic southeast of Melbourne Beach and briefly moved toward shore. # 2 60904 As much as 9 inches of rain fell in a 24-hour period across parts of coastal Volusia County. # 3 60913 A tornado touched down in the Town of Eustis at the northern end of West Crooked Lake. The tornado quickly intensified to EF1 strength as it moved north northwest through Eustis. The track was just under two miles long… # 4 64588 The county dispatch reported several trees were blown down along Quincey Batten Loop near State Road 206. The cost of tree removal was estimated. # 5 68796 Numerous large trees were blown down with some down on power lines. Damage occurred in eastern Adams county. # 6 68814 This tornado began as a small, narrow path of minor damage, including a porch being blown off a house. It reached its maximum intensity as it crossed highway 29. Here, a brick home had all of its roof structure blown o… # 7 68834 Several trees and power lines were blown down along Zetus Road in the Zetus Community. A few of those trees were down on a mobile home which caused significant damage. # 8 68846 A swath of penny to quarter sized hail fell from just east of French Camp to about 6 miles north of Weir. # 9 73241 The heavy rain from an active monsoonal trough that had been nearly stationary just to the south of the islands caused widespread flooding across Tutuila. Flash Flooding was reported from the Malaeimi Valley to the Ba… # 10 64725 State Route 8 and Rock Run Road were flooded and impassable ``` `tbl_kusto` also accepts query parameters, in case the Kusto source table is a parameterized function: ```{r tbl_kusto_params, eval = FALSE} MyFunctionDate <- tbl_kusto(Samples, "MyFunctionDate(dt)", dt = as.Date("2019-01-01")) MyFunctionDate %>% select(StartTime, EndTime, EpisodeId, EventId, State) %>% head() %>% collect() ## # A tibble: 6 x 5 ## StartTime EndTime EpisodeId EventId State ## <dttm> <dttm> <int> <int> <chr> ## 1 2007-09-29 08:11:00 2007-09-29 08:11:00 11091 61032 ATLANTIC SOUTH ## 2 2007-09-18 20:00:00 2007-09-19 18:00:00 11074 60904 FLORIDA ## 3 2007-09-20 21:57:00 2007-09-20 22:05:00 11078 60913 FLORIDA ## 4 2007-12-30 16:00:00 2007-12-30 16:05:00 11749 64588 GEORGIA ## 5 2007-12-20 07:50:00 2007-12-20 07:53:00 12554 68796 MISSISSIPPI ## 6 2007-12-20 10:32:00 2007-12-20 10:36:00 12554 68814 MISSISSIPPI ``` ### Exporting to storage (New in 1.1.0) The function `export()` enables you to export a query result to Azure Storage in one step. ```{r exporting, eval = FALSE} export( database = Samples, storage_uri = "https://mystorage.blob.core.windows.net/StormEvents", query = "StormEvents | summarize EventCount = count() by State | order by State", name_prefix = "events", format = "parquet" ) # Path NumRecords SizeInBytes # 1 https://mystorage.blob.core.windows.net/StormEvents/events/events_1.snappy.parquet 67 1511 library(dplyr) StormEvents <- tbl_kusto(Samples, "StormEvents") q <- StormEvents %>% group_by(State) %>% summarize(EventCount = n()) %>% arrange(State) %>% export("https://mystorage.blob.core.windows.net/StormEvents") # # A tibble: 1 × 3 # Path NumRecords SizeInBytes # <chr> <dbl> <dbl> # 1 https://mystorage.blob.core.windows.net/StormEvents/export/export_1.snappy.parquet 50 59284 ``` ### DBI interface AzureKusto implements a subset of the DBI specification for interfacing with databases in R. The following methods are supported: - Connections: `dbConnect`, `dbDisconnect`, `dbCanConnect` - Table management: `dbExistsTable`, `dbCreateTable`, `dbRemoveTable`, `dbReadTable`, `dbWriteTable` - Querying: `dbGetQuery`, `dbSendQuery`, `dbFetch`, `dbSendStatement`, `dbExecute`, `dbListFields`, `dbColumnInfo` Azure Data Explorer is quite different to the SQL databases that DBI targets, which affects the behaviour of certain DBI methods and renders other moot. - Communication goes through the REST API rather than a socket connection. Therefore, `dbConnect` simply wraps a database endpoint object, created with [kusto_database_endpoint]. Similarly, `dbDisconnect` always returns TRUE. `dbCanConnect` attempts to check if querying the database will succeed, but this may not be accurate. - Temporary tables are not supported, so `dbCreateTable(*, temporary=TRUE)` will throw an error. - It only supports synchronous queries, with a default timeout of 4 minutes. `dbSendQuery` and `dbSendStatement` will wait for the query to execute, rather than returning immediately. The object returned contains the full result of the query, which `dbFetch` extracts. - The Kusto Query Language (KQL) is not SQL, and so higher-level SQL methods are not implemented. ```{r dbi, eval = FALSE} library(DBI) Samples <- dbConnect(AzureKusto(), server = "https://help.kusto.windows.net", database = "Samples" ) dbListTables(Samples) ## [1] "StormEvents" "demo_make_series1" "demo_series2" ## [4] "demo_series3" "demo_many_series1" dbExistsTable(Samples, "StormEvents") ## [1] TRUE dbGetQuery(Samples, "StormEvents | summarize ct = count()") ## ct ## 1 59066 ```
/scratch/gouwar.j/cran-all/cranData/AzureKusto/inst/doc/AzureKusto.Rmd
--- title: "AzureKusto" date: "2022-12-20" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{AzureKusto} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r, include = FALSE} knitr::opts_chunk$set( collapse = TRUE, comment = "##" ) ``` AzureKusto is the R interface to [Azure Data Explorer](https://azure.microsoft.com/en-us/products/data-explorer/) (internally codenamed "Kusto"), a fast, fully managed data analytics service from Microsoft. AzureKusto provides an interface (including [DBI](https://dbi.r-dbi.org/) compliant methods) for connecting to Kusto clusters and submitting [Kusto Query Language (KQL)](https://learn.microsoft.com/en-us/azure/data-explorer/kusto/query/) statements, as well as a [dbplyr](https://dbplyr.tidyverse.org/) style backend that translates [dplyr](https://dplyr.tidyverse.org/) queries into KQL statements. ```{r setup, eval = FALSE} library(AzureKusto) ## The first time you import AzureKusto, you'll be asked if you'd like to create a directory to cache OAuth2 tokens. ## Connect to an AzureKusto database with (default) device code authentication: Samples <- kusto_database_endpoint(server = "https://help.kusto.windows.net", database = "Samples") # (New in 1.1.0) Some other ways to call this that also work: # Samples <- kusto_database_endpoint(server="help", database="Samples") # Samples <- kusto_database_endpoint(cluster="help", database="Samples") # No app ID supplied; using KustoClient app # Waiting for authentication in browser... # Press Esc/Ctrl + C to abort # VSCode WebView only supports showing local http content. # Opening in external browser... # Browsing https://login.microsoftonline.com/common/oauth2/v2.0/authorize... # Authentication complete. ``` Now you can issue KQL queries to the Kusto database with `run_query()` and get the results back as a data.frame object. ```{r run_query, eval = FALSE} res <- run_query(Samples, "StormEvents | summarize EventCount = count() by State | order by State asc") head(res) ## State EventCount ## 1 ALABAMA 1315 ## 2 ALASKA 257 ## 3 AMERICAN SAMOA 16 ## 4 ARIZONA 340 ## 5 ARKANSAS 1028 ## 6 ATLANTIC NORTH 188 ``` `run_query()` also supports query parameters, to allow you to call parameterized Kusto functions. Simply pass your parameters as additional keyword arguments and they will be escaped and interpolated into the query string. ```{r run_query_params, eval = FALSE} res <- run_query(Samples, "MyFunction(lim)", lim = 10L) head(res) ## StartTime EndTime EpisodeId EventId State ## 1 2007-09-29 08:11:00 2007-09-29 08:11:00 11091 61032 ATLANTIC SOUTH ## 2 2007-09-18 20:00:00 2007-09-19 18:00:00 11074 60904 FLORIDA ## 3 2007-09-20 21:57:00 2007-09-20 22:05:00 11078 60913 FLORIDA ## 4 2007-12-30 16:00:00 2007-12-30 16:05:00 11749 64588 GEORGIA ## 5 2007-12-20 07:50:00 2007-12-20 07:53:00 12554 68796 MISSISSIPPI ## 6 2007-12-20 10:32:00 2007-12-20 10:36:00 12554 68814 MISSISSIPPI ``` `run_query()` can also handle command statements, which begin with a '.' character. Command statements do not accept parameters and cannot be combined together with query statements in the same request. Command statements return a list where the first element is the table returned by the command (if any) and the other elements contain command metadata. ```{r run_query_commands, eval = FALSE} res <- run_query(Samples, ".show tables | count") res[[1]] ## Count ## 1 5 ``` ### dplyr Interface The package also implements a [dplyr](https://github.com/tidyverse/dplyr)-style interface for building a query upon a `tbl_kusto` object and then running it on the remote Kusto database and returning the result as a regular tibble object with `collect()`. ```{r dplyr, eval = FALSE} library(dplyr) StormEvents <- tbl_kusto(Samples, "StormEvents") q <- StormEvents %>% group_by(State) %>% summarize(EventCount = n()) %>% arrange(State) show_query(q) ## <KQL> database('Samples').['StormEvents'] ## | summarize ['EventCount'] = count() by ['State'] ## | order by ['State'] asc collect(q) ## # A tibble: 67 x 2 ## State EventCount ## <chr> <dbl> ## 1 ALABAMA 1315 ## 2 ALASKA 257 ## 3 AMERICAN SAMOA 16 ## 4 ARIZONA 340 ## 5 ARKANSAS 1028 ## 6 ATLANTIC NORTH 188 ## 7 ATLANTIC SOUTH 193 ## 8 CALIFORNIA 898 ## 9 COLORADO 1654 ## 10 CONNECTICUT 148 ## # ... with 57 more rows ``` (New in 1.1.0) The `$` operator can be used to access fields in dynamic columns: ```{r dollar, eval = FALSE} q <- StormEvents %>% slice_sample(10) %>% mutate(Description = as.character(StormSummary$Details$Description)) %>% select(EventId, Description) show_query(q) # <KQL> cluster('https://help.kusto.windows.net').database('Samples').['StormEvents'] # | sample 10 # | extend ['Description'] = tostring(['StormSummary'] . ['Details'] . ['Description']) # | project ['EventId'], ['Description'] # # A tibble: 10 × 2 # EventId Description # <int> <chr> # 1 61032 A waterspout formed in the Atlantic southeast of Melbourne Beach and briefly moved toward shore. # 2 60904 As much as 9 inches of rain fell in a 24-hour period across parts of coastal Volusia County. # 3 60913 A tornado touched down in the Town of Eustis at the northern end of West Crooked Lake. The tornado quickly intensified to EF1 strength as it moved north northwest through Eustis. The track was just under two miles long… # 4 64588 The county dispatch reported several trees were blown down along Quincey Batten Loop near State Road 206. The cost of tree removal was estimated. # 5 68796 Numerous large trees were blown down with some down on power lines. Damage occurred in eastern Adams county. # 6 68814 This tornado began as a small, narrow path of minor damage, including a porch being blown off a house. It reached its maximum intensity as it crossed highway 29. Here, a brick home had all of its roof structure blown o… # 7 68834 Several trees and power lines were blown down along Zetus Road in the Zetus Community. A few of those trees were down on a mobile home which caused significant damage. # 8 68846 A swath of penny to quarter sized hail fell from just east of French Camp to about 6 miles north of Weir. # 9 73241 The heavy rain from an active monsoonal trough that had been nearly stationary just to the south of the islands caused widespread flooding across Tutuila. Flash Flooding was reported from the Malaeimi Valley to the Ba… # 10 64725 State Route 8 and Rock Run Road were flooded and impassable ``` `tbl_kusto` also accepts query parameters, in case the Kusto source table is a parameterized function: ```{r tbl_kusto_params, eval = FALSE} MyFunctionDate <- tbl_kusto(Samples, "MyFunctionDate(dt)", dt = as.Date("2019-01-01")) MyFunctionDate %>% select(StartTime, EndTime, EpisodeId, EventId, State) %>% head() %>% collect() ## # A tibble: 6 x 5 ## StartTime EndTime EpisodeId EventId State ## <dttm> <dttm> <int> <int> <chr> ## 1 2007-09-29 08:11:00 2007-09-29 08:11:00 11091 61032 ATLANTIC SOUTH ## 2 2007-09-18 20:00:00 2007-09-19 18:00:00 11074 60904 FLORIDA ## 3 2007-09-20 21:57:00 2007-09-20 22:05:00 11078 60913 FLORIDA ## 4 2007-12-30 16:00:00 2007-12-30 16:05:00 11749 64588 GEORGIA ## 5 2007-12-20 07:50:00 2007-12-20 07:53:00 12554 68796 MISSISSIPPI ## 6 2007-12-20 10:32:00 2007-12-20 10:36:00 12554 68814 MISSISSIPPI ``` ### Exporting to storage (New in 1.1.0) The function `export()` enables you to export a query result to Azure Storage in one step. ```{r exporting, eval = FALSE} export( database = Samples, storage_uri = "https://mystorage.blob.core.windows.net/StormEvents", query = "StormEvents | summarize EventCount = count() by State | order by State", name_prefix = "events", format = "parquet" ) # Path NumRecords SizeInBytes # 1 https://mystorage.blob.core.windows.net/StormEvents/events/events_1.snappy.parquet 67 1511 library(dplyr) StormEvents <- tbl_kusto(Samples, "StormEvents") q <- StormEvents %>% group_by(State) %>% summarize(EventCount = n()) %>% arrange(State) %>% export("https://mystorage.blob.core.windows.net/StormEvents") # # A tibble: 1 × 3 # Path NumRecords SizeInBytes # <chr> <dbl> <dbl> # 1 https://mystorage.blob.core.windows.net/StormEvents/export/export_1.snappy.parquet 50 59284 ``` ### DBI interface AzureKusto implements a subset of the DBI specification for interfacing with databases in R. The following methods are supported: - Connections: `dbConnect`, `dbDisconnect`, `dbCanConnect` - Table management: `dbExistsTable`, `dbCreateTable`, `dbRemoveTable`, `dbReadTable`, `dbWriteTable` - Querying: `dbGetQuery`, `dbSendQuery`, `dbFetch`, `dbSendStatement`, `dbExecute`, `dbListFields`, `dbColumnInfo` Azure Data Explorer is quite different to the SQL databases that DBI targets, which affects the behaviour of certain DBI methods and renders other moot. - Communication goes through the REST API rather than a socket connection. Therefore, `dbConnect` simply wraps a database endpoint object, created with [kusto_database_endpoint]. Similarly, `dbDisconnect` always returns TRUE. `dbCanConnect` attempts to check if querying the database will succeed, but this may not be accurate. - Temporary tables are not supported, so `dbCreateTable(*, temporary=TRUE)` will throw an error. - It only supports synchronous queries, with a default timeout of 4 minutes. `dbSendQuery` and `dbSendStatement` will wait for the query to execute, rather than returning immediately. The object returned contains the full result of the query, which `dbFetch` extracts. - The Kusto Query Language (KQL) is not SQL, and so higher-level SQL methods are not implemented. ```{r dbi, eval = FALSE} library(DBI) Samples <- dbConnect(AzureKusto(), server = "https://help.kusto.windows.net", database = "Samples" ) dbListTables(Samples) ## [1] "StormEvents" "demo_make_series1" "demo_series2" ## [4] "demo_series3" "demo_many_series1" dbExistsTable(Samples, "StormEvents") ## [1] TRUE dbGetQuery(Samples, "StormEvents | summarize ct = count()") ## ct ## 1 59066 ```
/scratch/gouwar.j/cran-all/cranData/AzureKusto/vignettes/AzureKusto.Rmd
#' @import AzureStor #' @import AzureRMR NULL utils::globalVariables(c("self", "private")) .onLoad <- function(libname, pkgname) { AzureStor::az_storage$set("public", "get_queue_endpoint", overwrite=TRUE, function(key=self$list_keys()[1], sas=NULL, token=NULL) { queue_endpoint(self$properties$primaryEndpoints$queue, key=key, sas=sas, token=token) }) } # assorted imports of friend functions delete_confirmed <- getNamespace("AzureStor")$delete_confirmed is_endpoint_url <- getNamespace("AzureStor")$is_endpoint_url generate_endpoint_container <- getNamespace("AzureStor")$generate_endpoint_container get_classic_metadata_headers <- getNamespace("AzureStor")$get_classic_metadata_headers set_classic_metadata_headers <- getNamespace("AzureStor")$set_classic_metadata_headers
/scratch/gouwar.j/cran-all/cranData/AzureQstor/R/AzureQstor.R
new_message <- function(message, queue) { message <- unlist(message, recursive=FALSE) QueueMessage$new(message, queue) } #' R6 class representing a message from an Azure storage queue #' @description #' This class stores the data, metadata and behaviour associated with a message. #' #' To generate a message object, call one of the methods exposed by the [`StorageQueue`] class. #' @examples #' \dontrun{ #' #' endp <- storage_endpoint("https://mystorage.queue.core.windows.net", key="key") #' queue <- storage_queue(endp, "queue1") #' #' msg <- queue$get_message() #' msg$update(visibility_timeout=60, text="updated message") #' msg$delete() #' #' } #' @aliases message #' @export QueueMessage <- R6::R6Class("QueueMessage", public=list( #' @field queue The queue this message is from, an object of class [`StorageQueue`] #' @field id The message ID. #' @field insertion_time The message insertion (creation) time. #' @field expiry_time The message expiration time. #' @field text The message text. #' @field receipt A pop receipt. This is present if the message was obtained by means other than [peeking][StorageQueue], and is required for updating or deleting the message. #' @field next_visible_time The time when this message will be next visible. #' @field dequeue_count The number of times this message has been read. queue=NULL, id=NULL, insertion_time=NULL, expiry_time=NULL, text=NULL, receipt=NULL, next_visible_time=NULL, dequeue_count=NULL, #' @description #' Creates a new message object. Rather than calling the `new` method manually, objects of this class should be created via the methods exposed by the [`StorageQueue`] object. #' @param message Details about the message. #' @param queue Object of class `StorageQueue`. initialize=function(message, queue) { self$queue <- queue self$id <- message$MessageId self$insertion_time <- message$InsertionTime self$expiry_time <- message$ExpirationTime self$text <- message$MessageText self$receipt <- message$PopReceipt self$next_visible_time <- message$TimeNextVisible self$dequeue_count <- message$DequeueCount }, #' @description #' Deletes this message from the queue. #' @return #' NULL, invisibly. delete=function() { private$check_receipt() opts <- list(popreceipt=self$receipt) do_container_op(self$queue, file.path("messages", self$id), options=opts, http_verb="DELETE") invisible(NULL) }, #' @description #' Updates this message in the queue. #' #' This operation can be used to continually extend the invisibility of a queue message. This functionality can be useful if you want a worker role to "lease" a message. For example, if a worker role calls [`get_messages`][StorageQueue] and recognizes that it needs more time to process a message, it can continually extend the message's invisibility until it is processed. If the worker role were to fail during processing, eventually the message would become visible again and another worker role could process it. #' @param visibility_timeout The new visibility timeout (time to when the message will again be visible). #' @param text Optionally, new message text, either a raw or character vector. If a raw vector, it is base64-encoded, and if a character vector, it is collapsed into a single string before being sent to the queue. #' @return #' The message object, invisibly. update=function(visibility_timeout, text=self$text) { private$check_receipt() text <- if(is.raw(text)) openssl::base64_encode(text) else if(is.character(text)) paste0(text, collapse="\n") else stop("Message text must be raw or character", call.=FALSE) opts <- list(popreceipt=self$receipt, visibilitytimeout=visibility_timeout) body <- paste0("<QueueMessage><MessageText>", text, "</MessageText></QueueMessage>") hdrs <- list(`content-length`=sprintf("%.0f", nchar(body))) res <- do_container_op(self$queue, file.path("messages", self$id), options=opts, headers=hdrs, body=body, http_verb="PUT", return_headers=TRUE) self$receipt <- res$`x-ms-popreceipt` self$next_visible_time <- res$`x-ms-next-visible-time` self$text <- text invisible(self) }, #' @description #' Print method for this class. #' @param ... Not currently used. #' @return #' The message object, invisibly. print=function(...) { cat("<queue message ", self$id, ">\n", sep="") cat(" insertion time: ", self$insertion_time, "\n") cat(" expiration time:", self$expiry_time, "\n") cat("---\n") cat(self$text, "\n", sep="") invisible(self) } ), private=list( check_receipt=function() { if(is_empty(self$receipt)) stop("Must have a pop receipt to perform this operation", call.=FALSE) } ))
/scratch/gouwar.j/cran-all/cranData/AzureQstor/R/QueueMessage.R
#' R6 class representing an Azure storage queue #' @description #' A storage queue holds messages. A queue can contain an unlimited number of messages, each of which can be up to 64KB in size. Messages are generally added to the end of the queue and retrieved from the front of the queue, although first in, first out (FIFO) behavior is not guaranteed. #' #' To generate a queue object, use one of the [`storage_queue`], [`list_storage_queues`] or [`create_storage_queue`] functions rather than calling the `new()` method directly. #' #' @seealso #' [`QueueMessage`] #' #' @examples #' \dontrun{ #' #' endp <- storage_endpoint("https://mystorage.queue.core.windows.net", key="key") #' #' # to talk to an existing queue #' queue <- storage_queue(endp, "queue1") #' #' # to create a new queue #' queue2 <- create_storage_queue(endp, "queue2") #' #' # various ways to delete a queue (will ask for confirmation first) #' queue2$delete() #' delete_storage_queue(queue2) #' delete_storage_queue(endp, "queue2") #' #' # to get all queues in this storage account #' queue_lst <- list_storage_queues(endp) #' #' # working with a queue: put, get, update and delete messages #' queue$put_message("new message") #' msg <- queue$get_message() #' msg$update(visibility_timeout=60, text="updated message") #' queue$delete_message(msg) #' #' # delete_message simply calls the message's delete() method, so this is equivalent #' msg$delete() #' #' # retrieving multiple messages at a time (up to 32) #' msgs <- queue$get_messages(30) #' #' # deleting is still per-message #' lapply(msgs, function(m) m$delete()) #' #' # you can use the process pool from AzureRMR to do this in parallel #' AzureRMR::init_pool() #' AzureRMR::pool_lapply(msgs, function(m) m$delete()) #' AzureRMR::delete_pool() #' #' } #' @aliases queue #' @export StorageQueue <- R6::R6Class("StorageQueue", public=list( #' @field endpoint A queue endpoint object. This contains the account and authentication information for the queue. #' @field name The name of the queue. endpoint=NULL, name=NULL, #' @description #' Initialize the queue object. Rather than calling this directly, you should use one of the [`storage_queue`], [`list_storage_queues`] or [`create_storage_queue`] functions. #' #' Note that initializing this object is a local operation only. If a queue of the given name does not already exist in the storage account, it has to be created remotely by calling the `create` method. #' #' @param endpoint An endpoint object. #' @param name The name of the queue. initialize=function(endpoint, name) { self$endpoint <- endpoint self$name <- name }, #' @description #' Creates a storage queue in Azure, using the storage endpoint and name from this R6 object. #' @return #' The queue object, invisibly. create=function() { do_container_op(self, http_verb="PUT") invisible(self) }, #' @description #' Deletes this storage queue in Azure. #' @param confirm Whether to ask for confirmation before deleting. #' @return #' The queue object, invisibly. delete=function(confirm=TRUE) { if(!delete_confirmed(confirm, paste0(self$endpoint$url, name), "queue")) return(invisible(NULL)) do_container_op(self, http_verb="DELETE") invisible(self) }, #' @description #' Clears (deletes) all messages in this storage queue. #' @return #' The queue object, invisibly. clear=function() { do_container_op(self, "messages", http_verb="DELETE") invisible(self) }, #' @description #' Retrieves user-defined metadata for the queue. #' @return #' A named list of metadata properties. get_metadata=function() { res <- do_container_op(self, "", options=list(comp="metadata"), http_verb="HEAD") get_classic_metadata_headers(res) }, #' @description #' Sets user-defined metadata for the queue. #' @param ... Name-value pairs to set as metadata. #' @param keep_existing Whether to retain existing metadata information. #' @return #' A named list of metadata properties, invisibly. set_metadata=function(..., keep_existing=TRUE) { meta <- if(keep_existing) utils::modifyList(self$get_metadata(), list(...)) else list(...) do_container_op(self, options=list(comp="metadata"), headers=set_classic_metadata_headers(meta), http_verb="PUT") invisible(meta) }, #' @description #' Reads a message from the front of the storage queue. #' #' When a message is read, the consumer is expected to process the message and then delete it. After the message is read, it is made invisible to other consumers for a specified interval. If the message has not yet been deleted at the time the interval expires, its visibility is restored, so that another consumer may process it. #' @return #' A new object of class [`QueueMessage`]. get_message=function() { new_message(do_container_op(self, "messages")$QueueMessage, self) }, #' @description #' Reads several messages at once from the front of the storage queue. #' #' When a message is read, the consumer is expected to process the message and then delete it. After the message is read, it is made invisible to other consumers for a specified interval. If the message has not yet been deleted at the time the interval expires, its visibility is restored, so that another consumer may process it. #' @param n How many messages to read. The maximum is 32. #' @return #' A list of objects of class [`QueueMessage`]. get_messages=function(n=1) { opts <- list(numofmessages=n) lapply(do_container_op(self, "messages", options=opts), new_message, queue=self) }, #' @description #' Reads a message from the storage queue, but does not alter its visibility. #' #' Note that a message obtained via the `peek_message` or `peek_messages` method will not include a pop receipt, which is required to delete or update it. #' @return #' A new object of class [`QueueMessage`]. peek_message=function() { opts <- list(peekonly=TRUE) new_message(do_container_op(self, "messages", options=opts)$QueueMessage, self) }, #' @description #' Reads several messages at once from the storage queue, without altering their visibility. #' #' Note that a message obtained via the `peek_message` or `peek_messages` method will not include a pop receipt, which is required to delete or update it. #' @param n How many messages to read. The maximum is 32. #' @return #' A list of objects of class [`QueueMessage`]. peek_messages=function(n=1) { opts <- list(peekonly=TRUE, numofmessages=n) lapply(do_container_op(self, "messages", options=opts), new_message, queue=self) }, #' @description #' Reads a message from the storage queue, removing it at the same time. This is equivalent to calling [`get_message`](#method-get_message) and [`delete_message`](#method-delete_message) successively. #' @return #' A new object of class [`QueueMessage`]. pop_message=function() { msg <- self$get_message() msg$delete() msg }, #' @description #' Reads several messages at once from the storage queue, and then removes them. #' @param n How many messages to read. The maximum is 32. #' @return #' A list of objects of class [`QueueMessage`]. pop_messages=function(n=1) { msgs <- self$get_messages(n) lapply(msgs, function(msg) msg$delete()) msgs }, #' @description #' Writes a message to the back of the message queue. #' @param text The message text, either a raw or character vector. If a raw vector, it is base64-encoded, and if a character vector, it is collapsed into a single string before being sent to the queue. #' @param visibility_timeout Optional visibility timeout after being read, in seconds. The default is 30 seconds. #' @param time_to_live Optional message time-to-live, in seconds. The default is 7 days. #' @return #' The message text, invisibly. put_message=function(text, visibility_timeout=NULL, time_to_live=NULL) { text <- if(is.raw(text)) openssl::base64_encode(text) else if(is.character(text)) paste0(text, collapse="\n") else stop("Message text must be raw or character", call.=FALSE) opts <- list() if(!is.null(visibility_timeout)) opts <- c(opts, visibilitytimeout=visibility_timeout) if(!is.null(time_to_live)) opts <- c(opts, messagettl=time_to_live) body <- paste0("<QueueMessage><MessageText>", text, "</MessageText></QueueMessage>") hdrs <- list(`content-length`=sprintf("%.0f", nchar(body))) res <- do_container_op(self, "messages", options=opts, headers=hdrs, body=body, http_verb="POST") invisible(res$QueueMessage) }, #' @description #' Updates a message in the queue. This requires that the message object must include a pop receipt, which is present if it was obtained by means other than [peeking](#method-peek_message). #' #' This operation can be used to continually extend the invisibility of a queue message. This functionality can be useful if you want a worker role to "lease" a message. For example, if a worker role calls [`get_messages`](#method-get_messages) and recognizes that it needs more time to process a message, it can continually extend the message's invisibility until it is processed. If the worker role were to fail during processing, eventually the message would become visible again and another worker role could process it. #' @param msg A message object, of class [`QueueMessage`]. #' @param visibility_timeout The new visibility timeout (time to when the message will again be visible). #' @param text Optionally, new message text, either a raw or character vector. If a raw vector, it is base64-encoded, and if a character vector, it is collapsed into a single string before being sent to the queue. #' @return #' The message object, invisibly. update_message=function(msg, visibility_timeout, text=msg$text) { stopifnot(inherits(msg, "QueueMessage")) msg$update(visibility_timeout, text) }, #' @description #' Deletes a message from the queue. This requires that the message object must include a pop receipt, which is present if it was obtained by means other than [peeking](#method-peek_message). #' @param msg A message object, of class [`QueueMessage`]. delete_message=function(msg) { stopifnot(inherits(msg, "QueueMessage")) msg$delete() }, #' @description #' Print method for this class. #' @param ... Not currently used. print=function(...) { url <- httr::parse_url(self$endpoint$url) url$path <- self$name cat("<Azure storage queue '", self$name, "'>\n", sep="") cat("url: ", httr::build_url(url), "\n", sep="") invisible(self) } ))
/scratch/gouwar.j/cran-all/cranData/AzureQstor/R/StorageQueue.R
#' Message queues #' #' Get, list, create, or delete queues. #' #' @param endpoint Either a queue endpoint object as created by [storage_endpoint], or a character string giving the URL of the endpoint. #' @param key,token,sas If an endpoint object is not supplied, authentication credentials: either an access key, an Azure Active Directory (AAD) token, or a SAS, in that order of priority. #' @param api_version If an endpoint object is not supplied, the storage API version to use when interacting with the host. Currently defaults to `"2019-07-07"`. #' @param name The name of the queue to get, create, or delete. #' @param confirm For deleting a queue, whether to ask for confirmation. #' @param ... Further arguments passed to lower-level functions. #' #' @details #' You can call these functions in a couple of ways: by passing the full URL of the storage queue, or by passing the endpoint object and the name of the share as a string. #' #' @return #' For `storage_queue` and `create_storage_queue`, an object of class [`StorageQueue`]. For `list_storage_queues`, a list of such objects. #' #' @seealso #' [`StorageQueue`], [`queue_endpoint`] #' @examples #' \dontrun{ #' #' endp <- storage_endpoint("https://mystorage.queue.core.windows.net", key="key") #' #' # to talk to an existing queue #' queue <- storage_queue(endp, "queue1") #' #' # to create a new queue #' queue2 <- create_storage_queue(endp, "queue2") #' #' # various ways to delete a queue (will ask for confirmation first) #' queue2$delete() #' delete_storage_queue(queue2) #' delete_storage_queue(endp, "queue2") #' } #' @rdname queue #' @export storage_queue <- function(endpoint, ...) { UseMethod("storage_queue") } #' @rdname queue #' @export storage_queue.character <- function(endpoint, key=NULL, token=NULL, sas=NULL, api_version=getOption("azure_storage_api_version"), ...) { do.call(storage_queue, generate_endpoint_container(endpoint, key, token, sas, api_version)) } #' @rdname queue #' @export storage_queue.queue_endpoint <- function(endpoint, name, ...) { StorageQueue$new(endpoint, name) } #' @rdname queue #' @export list_storage_queues <- function(endpoint, ...) { UseMethod("list_storage_queues") } #' @rdname queue #' @export list_storage_queues.character <- function(endpoint, key=NULL, token=NULL, sas=NULL, api_version=getOption("azure_storage_api_version"), ...) { do.call(list_storage_queues, generate_endpoint_container(endpoint, key, token, sas, api_version)) } #' @rdname queue #' @export list_storage_queues.queue_endpoint <- function(endpoint, ...) { res <- call_storage_endpoint(endpoint, "/", options=list(comp="list")) lst <- lapply(res$Queue, function(cont) storage_queue(endpoint, cont$Name[[1]])) while(length(res$NextMarker) > 0) { res <- call_storage_endpoint(endpoint, "/", options=list(comp="list", marker=res$NextMarker[[1]])) lst <- c(lst, lapply(res$Queue, function(cont) storage_queue(endpoint, cont$Name[[1]]))) } named_list(lst) } #' @rdname queue #' @export list_storage_containers.queue_endpoint <- function(endpoint, ...) list_storage_queues(endpoint, ...) #' @rdname queue #' @export create_storage_queue <- function(endpoint, ...) { UseMethod("create_storage_queue") } #' @rdname queue #' @export create_storage_queue.character <- function(endpoint, key=NULL, token=NULL, sas=NULL, api_version=getOption("azure_storage_api_version"), ...) { endp <- generate_endpoint_container(endpoint, key, token, sas, api_version) create_storage_queue(endp$endpoint, endp$name, ...) } #' @rdname queue #' @export create_storage_queue.queue_endpoint <- function(endpoint, name, ...) { obj <- storage_queue(endpoint, name) create_storage_queue(obj) } #' @rdname queue #' @export create_storage_queue.StorageQueue <- function(endpoint, ...) { endpoint$create() } #' @rdname queue #' @export delete_storage_queue <- function(endpoint, ...) { UseMethod("delete_storage_queue") } #' @rdname queue #' @export delete_storage_queue.character <- function(endpoint, key=NULL, token=NULL, sas=NULL, api_version=getOption("azure_storage_api_version"), ...) { endp <- generate_endpoint_container(endpoint, key, token, sas, api_version) delete_storage_queue(endp$endpoint, endp$name, ...) } #' @rdname queue #' @export delete_storage_queue.queue_endpoint <- function(endpoint, name, ...) { obj <- storage_queue(endpoint, name) delete_storage_queue(obj, ...) } #' @rdname queue #' @export delete_storage_queue.StorageQueue <- function(endpoint, confirm=TRUE, ...) { endpoint$delete(confirm=confirm) }
/scratch/gouwar.j/cran-all/cranData/AzureQstor/R/container.R
#' Create a queue endpoint object #' #' @param endpoint The URL (hostname) for the endpoint, of the form `http[s]://{account-name}.queue.{core-host-name}`. On the public Azure cloud, endpoints will be of the form `https://{account-name}.queue.core.windows.net`. #' @param key The access key for the storage account. #' @param token An Azure Active Directory (AAD) authentication token. This can be either a string, or an object of class AzureToken created by [AzureRMR::get_azure_token]. The latter is the recommended way of doing it, as it allows for automatic refreshing of expired tokens. #' @param sas A shared access signature (SAS) for the account. #' @param api_version The storage API version to use when interacting with the host. Defaults to `"2019-07-07"`. #' #' @details #' This is the queue storage counterpart to the endpoint functions defined in the AzureStor package. #' @return #' An object of class `queue_endpoint`, inheriting from `storage_endpoint`. #' @seealso #' [`AzureStor::storage_endpoint`], [`AzureStor::blob_endpoint`], [`storage_queue`] #' @examples #' \dontrun{ #' #' # obtaining an endpoint from the storage account resource object #' AzureRMR::get_azure_login()$ #' get_subscription("sub_id")$ #' get_resource_group("rgname")$ #' get_storage_account("mystorage")$ #' get_queue_endpoint() #' #' # creating an endpoint standalone #' queue_endpoint("https://mystorage.queue.core.windows.net/", key="access_key") #' #' } #' @export queue_endpoint <- function(endpoint, key=NULL, token=NULL, sas=NULL, api_version=getOption("azure_storage_api_version")) { if(!is_endpoint_url(endpoint, "queue")) warning("Not a recognised queue endpoint", call.=FALSE) obj <- list(url=endpoint, key=key, token=token, sas=sas, api_version=api_version) class(obj) <- c("queue_endpoint", "storage_endpoint") obj }
/scratch/gouwar.j/cran-all/cranData/AzureQstor/R/endpoint.R
#' @export get_storage_metadata.StorageQueue <- function(object, ...) { object$get_metadata() } #' @export set_storage_metadata.StorageQueue <- function(object, ..., keep_existing=TRUE) { object$set_metadata(..., keep_existing=keep_existing) }
/scratch/gouwar.j/cran-all/cranData/AzureQstor/R/metadata.R
--- title: "Introduction to AzureQstor" author: Hong Ooi output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Introduction to AzureQstor} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{utf8} --- ## Azure queue storage [Azure queue storage](https://azure.microsoft.com/en-us/services/storage/queues/) is a service for storing large numbers of messages that can be accessed from anywhere in the world via authenticated calls using HTTP or HTTPS. A single queue message can be up to 64 KB in size, and a queue can contain millions of messages, up to the total capacity limit of a storage account. Queue storage is often used to create a backlog of work to process asynchronously. AzureQstor is an R interface to queue storage, building on the functionality provided by the [AzureStor](https://github.com/Azure/AzureStor) package. You can easily create and delete queues, and read and write messages to queues. ## Queue endpoint AzureQstor uses a combination of S3 and R6 classes. The queue endpoint is an S3 object for compatibility with AzureStor. It has methods for creating, retrieving and deleting queues that mirror those in AzureStor for ADLS2, blob and file storage. ```r library(AzureQstor) endp <- storage_endpoint("https://mystorage.queue.core.windows.net", key="access_key") # creating, retrieving and deleting queues qu <- create_storage_queue(endp, "myqueue") qu2 <- storage_queue(endp, "myotherqueue") delete_storage_queue(qu2, confirm=FALSE) # list all storage queues in this account list_storage_queues(endp) ``` ## Queues and messages Queues and messages are represented using R6 classes. The `list_storage_queues`, `storage_queue` and `create_storage_queue` calls above return objects of class `StorageQueue`, which has methods for reading, writing, updating and deleting messages. ```r qu <- storage_queue(endp, "myqueue") # write a message to the back of the queue qu$put("New message") # read a message from the front of the queue msg <- qu$get_message() ``` Once we have read a message, we have a time window (by default 30 seconds) in which to process it. During this window, the message still exists in the queue, but is invisible: further requests for messages will skip over it. If we need more time to process a message, we can update it on the queue to extend the invisibility window. ```r qu$update_message(msg, visibility_timeout=60) ``` Once we are done with the message, we delete it from the queue: ```r qu$delete_message(msg) ``` To retrieve a message from a queue without affecting its visibility, we can use the `peek_message` method. This can be useful if we only want to examine a message's contents without any further processing. ```r msg <- qu$peek_message() ``` The `StorageQueue` class also provides methods to retrieve multiple messages at once, to a maximum of 32. ```r # read a batch of 30 messages; returns a list of message objects qu$read_messages(n=30) # peek at the next 30 messages qu$peek_messages(n=30) ``` Messages themselves are objects of class `QueueMessage`, which has methods for updates and deletes. In fact, the above `delete_message` and `update_message` queue methods simply call the corresponding method in the message object. ```r msg <- qu$get_message() msg$update(visibility_timeout=60) msg$delete() ``` The content of a message is in its `text` field, which will (usually) be a text string. ```r msg$text ## [1] "New message" ``` ## Metadata You can get and set metadata for a queue object with the `get/set_metadata` R6 methods. If you prefer S3, you can also use the AzureStor `get/set_storage_metadata` S3 generics, which have methods for queue objects. ```r set_storage_metadata(qu, name1="value1", name2="value2") get_storage_metadata(qu) ## $name1 ## [1] "value1" ## ## $name2 ## [1] "value2" # same as above qu$set_metadata(name1="value1", name2="value2") qu$get_metadata() ```
/scratch/gouwar.j/cran-all/cranData/AzureQstor/inst/doc/intro.Rmd
--- title: "Introduction to AzureQstor" author: Hong Ooi output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Introduction to AzureQstor} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{utf8} --- ## Azure queue storage [Azure queue storage](https://azure.microsoft.com/en-us/services/storage/queues/) is a service for storing large numbers of messages that can be accessed from anywhere in the world via authenticated calls using HTTP or HTTPS. A single queue message can be up to 64 KB in size, and a queue can contain millions of messages, up to the total capacity limit of a storage account. Queue storage is often used to create a backlog of work to process asynchronously. AzureQstor is an R interface to queue storage, building on the functionality provided by the [AzureStor](https://github.com/Azure/AzureStor) package. You can easily create and delete queues, and read and write messages to queues. ## Queue endpoint AzureQstor uses a combination of S3 and R6 classes. The queue endpoint is an S3 object for compatibility with AzureStor. It has methods for creating, retrieving and deleting queues that mirror those in AzureStor for ADLS2, blob and file storage. ```r library(AzureQstor) endp <- storage_endpoint("https://mystorage.queue.core.windows.net", key="access_key") # creating, retrieving and deleting queues qu <- create_storage_queue(endp, "myqueue") qu2 <- storage_queue(endp, "myotherqueue") delete_storage_queue(qu2, confirm=FALSE) # list all storage queues in this account list_storage_queues(endp) ``` ## Queues and messages Queues and messages are represented using R6 classes. The `list_storage_queues`, `storage_queue` and `create_storage_queue` calls above return objects of class `StorageQueue`, which has methods for reading, writing, updating and deleting messages. ```r qu <- storage_queue(endp, "myqueue") # write a message to the back of the queue qu$put("New message") # read a message from the front of the queue msg <- qu$get_message() ``` Once we have read a message, we have a time window (by default 30 seconds) in which to process it. During this window, the message still exists in the queue, but is invisible: further requests for messages will skip over it. If we need more time to process a message, we can update it on the queue to extend the invisibility window. ```r qu$update_message(msg, visibility_timeout=60) ``` Once we are done with the message, we delete it from the queue: ```r qu$delete_message(msg) ``` To retrieve a message from a queue without affecting its visibility, we can use the `peek_message` method. This can be useful if we only want to examine a message's contents without any further processing. ```r msg <- qu$peek_message() ``` The `StorageQueue` class also provides methods to retrieve multiple messages at once, to a maximum of 32. ```r # read a batch of 30 messages; returns a list of message objects qu$read_messages(n=30) # peek at the next 30 messages qu$peek_messages(n=30) ``` Messages themselves are objects of class `QueueMessage`, which has methods for updates and deletes. In fact, the above `delete_message` and `update_message` queue methods simply call the corresponding method in the message object. ```r msg <- qu$get_message() msg$update(visibility_timeout=60) msg$delete() ``` The content of a message is in its `text` field, which will (usually) be a text string. ```r msg$text ## [1] "New message" ``` ## Metadata You can get and set metadata for a queue object with the `get/set_metadata` R6 methods. If you prefer S3, you can also use the AzureStor `get/set_storage_metadata` S3 generics, which have methods for queue objects. ```r set_storage_metadata(qu, name1="value1", name2="value2") get_storage_metadata(qu) ## $name1 ## [1] "value1" ## ## $name2 ## [1] "value2" # same as above qu$set_metadata(name1="value1", name2="value2") qu$get_metadata() ```
/scratch/gouwar.j/cran-all/cranData/AzureQstor/vignettes/intro.Rmd
#' @import AzureAuth #' @import AzureGraph #' @importFrom utils modifyList NULL #' @export AzureGraph::named_list #' @export AzureGraph::is_empty #' @export AzureGraph::format_public_fields #' @export AzureGraph::format_public_methods utils::globalVariables(c("self", "private", "pool")) .onLoad <- function(libname, pkgname) { options(azure_api_version="2021-04-01") options(azure_api_mgmt_version="2016-09-01") options(azure_roledef_api_version="2018-01-01-preview") options(azure_roleasn_api_version="2018-12-01-preview") invisible(NULL) } .onUnLoad <- function(libname, pkgname) { if(exists("pool", envir=.AzureR, inherits=FALSE)) try(parallel::stopCluster(.AzureR$pool), silent=TRUE) } # default authentication app ID: leverage the az CLI .az_cli_app_id <- "04b07795-8ddb-461a-bbee-02f9e1bf7b46"
/scratch/gouwar.j/cran-all/cranData/AzureRMR/R/AzureRMR.R
#' Login to Azure Resource Manager #' #' @param tenant The Azure Active Directory tenant for which to obtain a login client. Can be a name ("myaadtenant"), a fully qualified domain name ("myaadtenant.onmicrosoft.com" or "mycompanyname.com"), or a GUID. The default is to login via the "common" tenant, which will infer your actual tenant from your credentials. #' @param app The client/app ID to use to authenticate with Azure Active Directory. The default is to login interactively using the Azure CLI cross-platform app, but you can supply your own app credentials as well. #' @param password If `auth_type == "client_credentials"`, the app secret; if `auth_type == "resource_owner"`, your account password. #' @param username If `auth_type == "resource_owner"`, your username. #' @param certificate If `auth_type == "client_credentials", a certificate to authenticate with. This is a more secure alternative to using an app secret. #' @param auth_type The OAuth authentication method to use, one of "client_credentials", "authorization_code", "device_code" or "resource_owner". If `NULL`, this is chosen based on the presence of the `username` and `password` arguments. #' @param host Your ARM host. Defaults to `https://management.azure.com/`. Change this if you are using a government or private cloud. #' @param aad_host Azure Active Directory host for authentication. Defaults to `https://login.microsoftonline.com/`. Change this if you are using a government or private cloud. #' @param version The Azure Active Directory version to use for authenticating. #' @param scopes The Azure Service Management scopes (permissions) to obtain for this login. Only for `version=2`. #' @param config_file Optionally, a JSON file containing any of the arguments listed above. Arguments supplied in this file take priority over those supplied on the command line. You can also use the output from the Azure CLI `az ad sp create-for-rbac` command. #' @param token Optionally, an OAuth 2.0 token, of class [AzureToken]. This allows you to reuse the authentication details for an existing session. If supplied, the other arguments above to `create_azure_login` will be ignored. #' @param graph_host The Microsoft Graph endpoint. See 'Microsoft Graph integration' below. #' @param refresh For `get_azure_login`, whether to refresh the authentication token on loading the client. #' @param selection For `get_azure_login`, if you have multiple logins for a given tenant, which one to use. This can be a number, or the input MD5 hash of the token used for the login. If not supplied, `get_azure_login` will print a menu and ask you to choose a login. #' @param confirm For `delete_azure_login`, whether to ask for confirmation before deleting. #' @param ... For `create_azure_login`, other arguments passed to `get_azure_token`. #' #' @details #' `create_azure_login` creates a login client to authenticate with Azure Resource Manager (ARM), using the supplied arguments. The Azure Active Directory (AAD) authentication token is obtained using [get_azure_token], which automatically caches and reuses tokens for subsequent sessions. Note that credentials are only cached if you allowed AzureRMR to create a data directory at package startup. #' #' `create_azure_login()` without any arguments is roughly equivalent to the Azure CLI command `az login`. #' #' `get_azure_login` returns a login client by retrieving previously saved credentials. It searches for saved credentials according to the supplied tenant; if multiple logins are found, it will prompt for you to choose one. #' #' One difference between `create_azure_login` and `get_azure_login` is the former will delete any previously saved credentials that match the arguments it was given. You can use this to force AzureRMR to remove obsolete tokens that may be lying around. #' #' @section Microsoft Graph integration: #' If the AzureGraph package is installed and the `graph_host` argument is not `NULL`, `create_azure_login` will also create a login client for Microsoft Graph with the same credentials. This is to facilitate working with registered apps and service principals, eg when managing roles and permissions. Some Azure services also require creating service principals as part of creating a resource (eg Azure Kubernetes Service), and keeping the Graph credentials consistent with ARM helps ensure nothing breaks. #' #' @section Linux DSVM note: #' If you are using a Linux [Data Science Virtual Machine](https://azure.microsoft.com/en-us/products/virtual-machines/data-science-virtual-machines/) in Azure, you may have problems running `create_azure_login()` (ie, without any arguments). In this case, try `create_azure_login(auth_type="device_code")`. #' #' @return #' For `get_azure_login` and `create_azure_login`, an object of class `az_rm`, representing the ARM login client. For `list_azure_logins`, a (possibly nested) list of such objects. #' #' If the AzureRMR data directory for saving credentials does not exist, `get_azure_login` will throw an error. #' #' @seealso #' [az_rm], [AzureAuth::get_azure_token] for more details on authentication methods, [AzureGraph::create_graph_login] for the corresponding function to create a Microsoft Graph login client #' #' [Azure Resource Manager overview](https://learn.microsoft.com/en-us/azure/azure-resource-manager/resource-group-overview), #' [REST API reference](https://learn.microsoft.com/en-us/rest/api/resources/) #' #' [Authentication in Azure Active Directory](https://learn.microsoft.com/en-us/azure/active-directory/develop/authentication-scenarios) #' #' [Azure CLI documentation](https://learn.microsoft.com/en-us/cli/azure/?view=azure-cli-latest) #' #' @examples #' \dontrun{ #' #' # without any arguments, this will create a client using your AAD credentials #' az <- create_azure_login() #' #' # retrieve the login in subsequent sessions #' az <- get_azure_login() #' #' # this will create a Resource Manager client for the AAD tenant 'myaadtenant.onmicrosoft.com', #' # using the client_credentials method #' az <- create_azure_login("myaadtenant", app="app_id", password="password") #' #' # you can also login using credentials in a json file #' az <- create_azure_login(config_file="~/creds.json") #' #' } #' @rdname azure_login #' @export create_azure_login <- function(tenant="common", app=.az_cli_app_id, password=NULL, username=NULL, certificate=NULL, auth_type=NULL, version=2, host="https://management.azure.com/", aad_host="https://login.microsoftonline.com/", scopes=".default", config_file=NULL, token=NULL, graph_host="https://graph.microsoft.com/", ...) { if(!is_azure_token(token)) { if(!is.null(config_file)) { conf <- jsonlite::fromJSON(config_file) call <- as.list(match.call())[-1] call$config_file <- NULL call <- lapply(modifyList(call, conf), function(x) eval.parent(x)) return(do.call(create_azure_login, call)) } tenant <- normalize_tenant(tenant) app <- normalize_guid(app) newhost <- if(version == 2) c(paste0(host, scopes), "openid", "offline_access") else host token_args <- list(resource=newhost, tenant=tenant, app=app, password=password, username=username, certificate=certificate, auth_type=auth_type, aad_host=aad_host, version=version, ...) hash <- do.call(token_hash, token_args) tokenfile <- file.path(AzureR_dir(), hash) if(file.exists(tokenfile)) { message("Deleting existing Azure Active Directory token for this set of credentials") file.remove(tokenfile) } message("Creating Azure Resource Manager login for ", format_tenant(tenant)) token <- do.call(get_azure_token, token_args) } else tenant <- token$tenant client <- az_rm$new(token=token) # save login info for future sessions arm_logins <- load_arm_logins() arm_logins[[tenant]] <- sort(unique(c(arm_logins[[tenant]], client$token$hash()))) save_arm_logins(arm_logins) make_graph_login_from_token(token, host, graph_host) client } #' @rdname azure_login #' @export get_azure_login <- function(tenant="common", selection=NULL, app=NULL, scopes=NULL, auth_type=NULL, refresh=TRUE) { if(!dir.exists(AzureR_dir())) stop("AzureR data directory does not exist; cannot load saved logins") tenant <- normalize_tenant(tenant) arm_logins <- load_arm_logins() this_login <- arm_logins[[tenant]] if(is_empty(this_login)) { msg <- paste0("No Azure Resource Manager logins found for ", format_tenant(tenant), ";\nuse create_azure_login() to create one") stop(msg, call.=FALSE) } message("Loading Azure Resource Manager login for ", format_tenant(tenant)) # do we need to choose which login client to use? have_selection <- !is.null(selection) have_auth_spec <- any(!is.null(app), !is.null(scopes), !is.null(auth_type)) token <- if(length(this_login) > 1 || have_selection || have_auth_spec) choose_token(this_login, selection, app, scopes, auth_type) else load_azure_token(this_login) if(is.null(token)) return(NULL) client <- az_rm$new(token=token) if(refresh) client$token$refresh() client } #' @rdname azure_login #' @export delete_azure_login <- function(tenant="common", confirm=TRUE) { if(!dir.exists(AzureR_dir())) { warning("AzureR data directory does not exist; no logins to delete") return(invisible(NULL)) } tenant <- normalize_tenant(tenant) if(!delete_confirmed(confirm, format_tenant(tenant), "Azure Resource Manager login(s) for", FALSE)) return(invisible(NULL)) arm_logins <- load_arm_logins() arm_logins[[tenant]] <- NULL save_arm_logins(arm_logins) invisible(NULL) } #' @rdname azure_login #' @export list_azure_logins <- function() { arm_logins <- load_arm_logins() logins <- sapply(arm_logins, function(tenant) { sapply(tenant, function(hash) az_rm$new(token=load_azure_token(hash)), simplify=FALSE) }, simplify=FALSE) logins } load_arm_logins <- function() { file <- file.path(AzureR_dir(), "arm_logins.json") if(!file.exists(file)) return(named_list()) jsonlite::fromJSON(file) } save_arm_logins <- function(logins) { if(!dir.exists(AzureR_dir())) { message("AzureR data directory does not exist; login credentials not saved") return(invisible(NULL)) } if(is_empty(logins)) names(logins) <- character(0) file <- file.path(AzureR_dir(), "arm_logins.json") writeLines(jsonlite::toJSON(logins, auto_unbox=TRUE, pretty=TRUE), file) invisible(NULL) } format_tenant <- function(tenant) { if(tenant == "common") "default tenant" else paste0("tenant '", tenant, "'") } # algorithm for choosing a token: # if given a hash, choose it (error if no match) # otherwise if given a number, use it (error if out of bounds) # otherwise if given any of app|scopes|auth_type, use those (error if no match, ask if multiple matches) # otherwise ask choose_token <- function(hashes, selection, app, scopes, auth_type) { if(is.character(selection)) { if(!(selection %in% hashes)) stop("Token with selected hash not found", call.=FALSE) return(load_azure_token(selection)) } if(is.numeric(selection)) { if(selection <= 0 || selection > length(hashes)) stop("Invalid numeric selection", call.=FALSE) return(load_azure_token(hashes[selection])) } tokens <- lapply(hashes, load_azure_token) ok <- rep(TRUE, length(tokens)) # filter down list of tokens based on auth criteria if(!is.null(app) || !is.null(scopes) || !is.null(auth_type)) { if(!is.null(scopes)) scopes <- tolower(scopes) # look for matching token for(i in seq_along(hashes)) { app_match <- scope_match <- auth_match <- TRUE if(!is.null(app) && tokens[[i]]$client$client_id != app) app_match <- FALSE if(!is.null(scopes)) { # AAD v1.0 tokens do not have scopes if(is.null(tokens[[i]]$scope)) scope_match <- is.na(scopes) else { tok_scopes <- tolower(basename(grep("^.+://", tokens[[i]]$scope, value=TRUE))) if(!setequal(scopes, tok_scopes)) scope_match <- FALSE } } if(!is.null(auth_type) && tokens[[i]]$auth_type != auth_type) auth_match <- FALSE if(!app_match || !scope_match || !auth_match) ok[i] <- FALSE } } tokens <- tokens[ok] if(length(tokens) == 0) stop("No tokens found with selected authentication parameters", call.=FALSE) else if(length(tokens) == 1) return(tokens[[1]]) # bring up a menu tenant <- tokens[[1]]$tenant choices <- sapply(tokens, function(token) { app <- token$client$client_id scopes <- if(!is.null(token$scope)) paste(tolower(basename(grep("^.+://", token$scope, value=TRUE))), collapse=" ") else "<NA>" paste0("App ID: ", app, "\n Scopes: ", scopes, "\n Authentication method: ", token$auth_type, "\n MD5 Hash: ", token$hash()) }) msg <- paste0("Choose a Microsoft Graph login for ", format_tenant(tenant)) selection <- utils::menu(choices, title=msg) if(selection == 0) invisible(NULL) else tokens[[selection]] }
/scratch/gouwar.j/cran-all/cranData/AzureRMR/R/az_login.R
#' Azure resource group class #' #' Class representing an Azure resource group. #' #' @docType class #' @section Methods: #' - `new(token, subscription, id, ...)`: Initialize a resource group object. See 'Initialization' for more details. #' - `delete(confirm=TRUE)`: Delete this resource group, after a confirmation check. This is asynchronous: while the method returns immediately, the delete operation continues on the host in the background. For resource groups containing a large number of deployed resources, this may take some time to complete. #' - `sync_fields()`: Synchronise the R object with the resource group it represents in Azure. #' - `list_templates(filter, top)`: List deployed templates in this resource group. `filter` and `top` are optional arguments to filter the results; see the [Azure documentation](https://learn.microsoft.com/en-us/rest/api/resources/deployments/listbyresourcegroup) for more details. If `top` is specified, the returned list will have a maximum of this many items. #' - `get_template(name)`: Return an object representing an existing template. #' - `deploy_template(...)`: Deploy a new template. See 'Templates' for more details. By default, AzureRMR will set the `createdBy` tag on a newly-deployed template to the value `AzureR/AzureRMR`. #' - `delete_template(name, confirm=TRUE, free_resources=FALSE)`: Delete a deployed template, and optionally free any resources that were created. #' - `get_resource(...)`: Return an object representing an existing resource. See 'Resources' for more details. #' - `create_resource(...)`: Create a new resource. By default, AzureRMR will set the `createdBy` tag on a newly-created resource to the value `AzureR/AzureRMR`. #' - `delete_resource(..., confirm=TRUE, wait=FALSE)`: Delete an existing resource. Optionally wait for the delete to finish. #' - `resource_exists(...)`: Check if a resource exists. #' - `list_resources(filter, expand, top)`: Return a list of resource group objects for this subscription. `filter`, `expand` and `top` are optional arguments to filter the results; see the [Azure documentation](https://learn.microsoft.com/en-us/rest/api/resources/resources/list) for more details. If `top` is specified, the returned list will have a maximum of this many items. #' - `do_operation(...)`: Carry out an operation. See 'Operations' for more details. #' - `set_tags(..., keep_existing=TRUE)`: Set the tags on this resource group. The tags can be either names or name-value pairs. To delete a tag, set it to `NULL`. #' - `get_tags()`: Get the tags on this resource group. #' - `create_lock(name, level)`: Create a management lock on this resource group (which will propagate to all resources within it). #' - `get_lock(name)`: Returns a management lock object. #' - `delete_lock(name)`: Deletes a management lock object. #' - `list_locks()`: List all locks that apply to this resource group. Note this includes locks created at the subscription level, and for any resources within the resource group. #' - `add_role_assignment(name, ...)`: Adds a new role assignment. See 'Role-based access control' below. #' - `get_role_assignment(id)`: Retrieves an existing role assignment. #' - `remove_role_assignment(id)`: Removes an existing role assignment. #' - `list_role_assignments()`: Lists role assignments. #' - `get_role_definition(id)`: Retrieves an existing role definition. #' - `list_role_definitions()` Lists role definitions. #' #' @section Initialization: #' Initializing a new object of this class can either retrieve an existing resource group, or create a new resource group on the host. Generally, the easiest way to create a resource group object is via the `get_resource_group`, `create_resource_group` or `list_resource_groups` methods of the [az_subscription] class, which handle this automatically. #' #' To create a resource group object in isolation, supply (at least) an Oauth 2.0 token of class [AzureToken], the subscription ID, and the resource group name. If this object refers to a _new_ resource group, supply the location as well (use the `list_locations` method of the `az_subscription class` for possible locations). You can also pass any optional parameters for the resource group as named arguments to `new()`. #' #' @section Templates: #' To deploy a new template, pass the following arguments to `deploy_template()`: #' - `name`: The name of the deployment. #' - `template`: The template to deploy. This can be provided in a number of ways: #' 1. A nested list of name-value pairs representing the parsed JSON #' 2. The name of a template file #' 3. A vector of strings containing unparsed JSON #' 4. A URL from which the template can be downloaded #' - `parameters`: The parameters for the template. This can be provided using any of the same methods as the `template` argument. #' - `wait`: Optionally, whether or not to wait until the deployment is complete before returning. Defaults to `FALSE`. #' #' Retrieving or deleting a deployed template requires only the name of the deployment. #' #' @section Resources: #' There are a number of arguments to `get_resource()`, `create_resource()` and `delete_resource()` that serve to identify the specific resource in question: #' - `id`: The full ID of the resource, including subscription ID and resource group. #' - `provider`: The provider of the resource, eg `Microsoft.Compute`. #' - `path`: The full path to the resource, eg `virtualMachines`. #' - `type`: The combination of provider and path, eg `Microsoft.Compute/virtualMachines`. #' - `name`: The name of the resource instance, eg `myWindowsVM`. #' #' Providing the `id` argument will fill in the values for all the other arguments. Similarly, providing the `type` argument will fill in the values for `provider` and `path`. Unless you provide `id`, you must also provide `name`. #' #' To create/deploy a new resource, specify any extra parameters that the provider needs as named arguments to `create_resource()`. Like `deploy_template()`, `create_resource()` also takes an optional `wait` argument that specifies whether to wait until resource creation is complete before returning. #' #' @section Operations: #' The `do_operation()` method allows you to carry out arbitrary operations on the resource group. It takes the following arguments: #' - `op`: The operation in question, which will be appended to the URL path of the request. #' - `options`: A named list giving the URL query parameters. #' - `...`: Other named arguments passed to [call_azure_rm], and then to the appropriate call in httr. In particular, use `body` to supply the body of a PUT, POST or PATCH request, and `api_version` to set the API version. #' - `http_verb`: The HTTP verb as a string, one of `GET`, `PUT`, `POST`, `DELETE`, `HEAD` or `PATCH`. #' #' Consult the Azure documentation for what operations are supported. #' #' @section Role-based access control: #' AzureRMR implements a subset of the full RBAC functionality within Azure Active Directory. You can retrieve role definitions and add and remove role assignments, at the subscription, resource group and resource levels. See [rbac] for more information. #' #' @seealso #' [az_subscription], [az_template], [az_resource], #' [Azure resource group overview](https://learn.microsoft.com/en-us/azure/azure-resource-manager/resource-group-overview#resource-groups), #' [Resources API reference](https://learn.microsoft.com/en-us/rest/api/resources/resources), #' [Template API reference](https://learn.microsoft.com/en-us/rest/api/resources/deployments) #' #' For role-based access control methods, see [rbac] #' #' For management locks, see [lock] #' #' @examples #' \dontrun{ #' #' # recommended way to retrieve a resource group object #' rg <- get_azure_login("myaadtenant")$ #' get_subscription("subscription_id")$ #' get_resource_group("rgname") #' #' # list resources & templates in this resource group #' rg$list_resources() #' rg$list_templates() #' #' # get a resource (virtual machine) #' rg$get_resource(type="Microsoft.Compute/virtualMachines", name="myvm") #' #' # create a resource (storage account) #' rg$create_resource(type="Microsoft.Storage/storageAccounts", name="mystorage", #' kind="StorageV2", #' sku=list(name="Standard_LRS")) #' #' # delete a resource #' rg$delete_resource(type="Microsoft.Storage/storageAccounts", name="mystorage") #' #' # deploy a template #' rg$deploy_template("tplname", #' template="template.json", #' parameters="parameters.json") #' #' # deploy a template with parameters inline #' rg$deploy_template("mydeployment", #' template="template.json", #' parameters=list(parm1="foo", parm2="bar")) #' #' # delete a template and free resources #' rg$delete_template("tplname", free_resources=TRUE) #' #' # delete the resource group itself #' rg$delete() #' #' } #' @format An R6 object of class `az_resource_group`. #' @export az_resource_group <- R6::R6Class("az_resource_group", public=list( subscription=NULL, id=NULL, name=NULL, type=NULL, location=NULL, managed_by=NULL, properties=NULL, tags=NULL, token=NULL, # constructor: can refer to an existing RG, or create a new RG initialize=function(token, subscription, name=NULL, ..., parms=list()) { if(is_empty(name) && is_empty(parms)) stop("Must supply either resource group name, or parameter list") self$token <- token self$subscription <- subscription parms <- if(!is_empty(list(...))) private$init_and_create(name, ...) else private$init(name, parms) self$id <- parms$id self$type <- parms$type self$location <- parms$location self$managed_by <- parms$managedBy self$properties <- parms$properties self$tags <- parms$tags NULL }, delete=function(confirm=TRUE) { if(!delete_confirmed(confirm, self$name, "resource group")) return(invisible(NULL)) private$rg_op(http_verb="DELETE") message("Deleting resource group '", self$name, "'. This operation may take some time to complete.") invisible(NULL) }, list_templates=function(filter=NULL, top=NULL) { opts <- list(`$filter`=filter, `$top`=top) cont <- private$rg_op("providers/Microsoft.Resources/deployments", options=opts) lst <- lapply( if(is.null(top)) get_paged_list(cont, self$token) else cont$value, function(parms) az_template$new(self$token, self$subscription, self$name, deployed_properties=parms) ) named_list(lst) }, deploy_template=function(name, template, parameters, ...) { az_template$new(self$token, self$subscription, self$name, name, template, parameters, ...) }, get_template=function(name) { az_template$new(self$token, self$subscription, self$name, name) }, delete_template=function(name, confirm=TRUE, free_resources=FALSE) { self$get_template(name)$delete(confirm=confirm, free_resources=free_resources) }, list_resources=function(filter=NULL, expand=NULL, top=NULL) { opts <- list(`$filter`=filter, `$expand`=expand, `$top`=top) cont <- private$rg_op("resources", options=opts) lst <- lapply( if(is.null(top)) get_paged_list(cont, self$token) else cont$value, function(parms) az_resource$new(self$token, self$subscription, deployed_properties=parms) ) names(lst) <- sapply(lst, function(x) sub("^.+providers/(.+$)", "\\1", x$id)) lst }, get_resource=function(provider, path, type, name, id, api_version=NULL) { az_resource$new(self$token, self$subscription, resource_group=self$name, provider=provider, path=path, type=type, name=name, id=id, api_version=api_version) }, resource_exists=function(provider, path, type, name, id) { # HEAD seems to be broken; use GET and check if it succeeds res <- try(self$get_resource(provider, path, type, name, id), silent=TRUE) !inherits(res, "try-error") }, delete_resource=function(provider, path, type, name, id, api_version=NULL, confirm=TRUE, wait=FALSE) { # supply deployed_properties arg to prevent querying host for resource info az_resource$ new(self$token, self$subscription, self$name, provider=provider, path=path, type=type, name=name, id=id, deployed_properties=list(NULL), api_version=api_version)$ delete(confirm=confirm, wait=wait) }, create_resource=function(provider, path, type, name, id, location=self$location, ...) { az_resource$new(self$token, self$subscription, resource_group=self$name, provider=provider, path=path, type=type, name=name, id=id, location=location, ...) }, sync_fields=function() { self$initialize(self$token, self$subscription, name=self$name) invisible(NULL) }, set_tags=function(..., keep_existing=TRUE) { # if tags is uninitialized (NULL), set it to named list if(is.null(self$tags)) self$tags <- named_list() tags <- match.call(expand.dots=FALSE)$... unvalued <- if(is.null(names(tags))) rep(TRUE, length(tags)) else names(tags) == "" values <- lapply(seq_along(unvalued), function(i) { if(unvalued[i]) "" else as.character(eval(tags[[i]], parent.frame(3))) }) names(values) <- ifelse(unvalued, as.character(tags), names(tags)) if(keep_existing) values <- modifyList(self$tags, values) # delete tags specified to be null values <- values[!sapply(values, is_empty)] private$rg_op(body=jsonlite::toJSON(list(tags=values), auto_unbox=TRUE, digits=22), encode="raw", http_verb="PATCH") self$sync_fields() }, get_tags=function() { if(is.null(self$tags)) named_list() else self$tags }, do_operation=function(..., options=list(), http_verb="GET") { private$rg_op(..., options=options, http_verb=http_verb) }, print=function(...) { cat("<Azure resource group ", self$name, ">\n", sep="") cat(format_public_fields(self, exclude=c("subscription", "name"))) cat(format_public_methods(self)) invisible(self) } ), private=list( init=function(name, parms) { if(is_empty(parms)) { self$name <- name parms <- private$rg_op() } else { # private$validate_parms(parms) self$name <- parms$name } parms }, init_and_create=function(name, ...) { parms <- modifyList(list(...), list(name=name)) parms$tags <- add_creator_tag(parms$tags) # private$validate_parms(parms) self$name <- name private$rg_op(body=parms, encode="json", http_verb="PUT") }, # validate_parms=function(parms) # { # required_names <- c("location", "name") # optional_names <- c("id", "managedBy", "tags", "properties", "type") # validate_object_names(names(parms), required_names, optional_names) # }, rg_op=function(op="", ...) { op <- construct_path("resourcegroups", self$name, op) call_azure_rm(self$token, self$subscription, op, ...) } ))
/scratch/gouwar.j/cran-all/cranData/AzureRMR/R/az_resgroup.R
#' Azure resource class #' #' Class representing a generic Azure resource. #' #' @docType class #' @section Methods: #' - `new(...)`: Initialize a new resource object. See 'Initialization' for more details. #' - `delete(confirm=TRUE, wait=FALSE)`: Delete this resource, after a confirmation check. Optionally wait for the delete to finish. #' - `update(...)`: Update this resource on the host. #' - `sync_fields()`: Synchronise the R object with the resource it represents in Azure. Returns the `properties$provisioningState` field, so you can query this programmatically to check if a resource has finished provisioning. Not all resource types require explicit provisioning, in which case this method will return NULL. #' - `set_api_version(api_version, stable_only=TRUE)`: Set the API version to use when interacting with the host. If `api_version` is not supplied, use the latest version available, either the latest stable version (if `stable_only=TRUE`) or the latest preview version (if `stable_only=FALSE`). #' - `get_api_version()`: Get the current API version. #' - `get_subresource(type, name)`: Get a sub-resource of this resource. See 'Sub-resources' below. #' - `create_subresource(type, name, ...)`: Create a sub-resource of this resource. #' - `delete_subresource(type, name, confirm=TRUE)`: Delete a sub-resource of this resource. #' - `do_operation(...)`: Carry out an operation. See 'Operations' for more details. #' - `set_tags(..., keep_existing=TRUE)`: Set the tags on this resource. The tags can be either names or name-value pairs. To delete a tag, set it to `NULL`. #' - `get_tags()`: Get the tags on this resource. #' - `create_lock(name, level)`: Create a management lock on this resource. #' - `get_lock(name)`: Returns a management lock object. #' - `delete_lock(name)`: Deletes a management lock object. #' - `list_locks()`: List all locks that apply to this resource. Note this includes locks created at the subscription or resource group level. #' - `add_role_assignment(name, ...)`: Adds a new role assignment. See 'Role-based access control' below. #' - `get_role_assignment(id)`: Retrieves an existing role assignment. #' - `remove_role_assignment(id)`: Removes an existing role assignment. #' - `list_role_assignments()`: Lists role assignments. #' - `get_role_definition(id)`: Retrieves an existing role definition. #' - `list_role_definitions()` Lists role definitions. #' #' @section Initialization: #' There are multiple ways to initialize a new resource object. The `new()` method can retrieve an existing resource, deploy/create a new resource, or create an empty/null object (without communicating with the host), based on the arguments you supply. #' #' All of these initialization options have the following arguments in common. #' 1. `token`: An OAuth 2.0 token, as generated by [get_azure_token]. #' 2. `subscription`: The subscription ID. #' 3. `api_version`: Optionally, the API version to use when interacting with the host. By default, this is NULL in which case the latest API version will be used. #' 4. A set of _identifying arguments_: #' - `resource_group`: The resource group containing the resource. #' - `id`: The full ID of the resource. This is a string of the form `/subscriptions/{uuid}/resourceGroups/{resource-group-name}/provider/{resource-provider-name}/{resource-path}/{resource-name}`. #' - `provider`: The provider of the resource, eg `Microsoft.Compute`. #' - `path`: The path to the resource, eg `virtualMachines`. #' - `type`: The combination of provider and path, eg `Microsoft.Compute/virtualMachines`. #' - `name`: The name of the resource instance, eg `myWindowsVM`. #' #' Providing `id` will fill in the values for all the other identifying arguments. Similarly, providing `type` will fill in the values for `provider` and `path`. Unless you provide `id`, you must also provide `name`. #' #' The default behaviour for `new()` is to retrieve an existing resource, which occurs if you supply only the arguments listed above. If you also supply an argument `deployed_properties=NULL`, this will create a null object. If you supply any other (named) arguments, `new()` will create a new object on the host, with the supplied arguments as parameters. #' #' Generally, the easiest way to initialize an object is via the `get_resource`, `create_resource` or `list_resources` methods of the [az_resource_group] class, which will handle all the gory details automatically. #' #' @section Operations: #' The `do_operation()` method allows you to carry out arbitrary operations on the resource. It takes the following arguments: #' - `op`: The operation in question, which will be appended to the URL path of the request. #' - `options`: A named list giving the URL query parameters. #' - `...`: Other named arguments passed to [call_azure_rm], and then to the appropriate call in httr. In particular, use `body` to supply the body of a PUT, POST or PATCH request. #' - `http_verb`: The HTTP verb as a string, one of `GET`, `PUT`, `POST`, `DELETE`, `HEAD` or `PATCH`. #' #' Consult the Azure documentation for your resource to find out what operations are supported. #' #' @section Sub-resources: #' Some resource types can have sub-resources: objects exposed by Resource Manager that make up a part of their parent's functionality. For example, a storage account (type `Microsoft.Storage/storageAccounts`) provides the blob storage service, which can be accessed via Resource Manager as a sub-resource of type `Microsoft.Storage/storageAccounts/blobServices/default`. #' #' To retrieve an existing sub-resource, use the `get_subresource()` method. You do not need to include the parent resource's type and name. For example, if `res` is a resource for a storage account, and you want to retrieve the sub-resource for the blob container "myblobs", call #' #' ``` #' res$get_subresource(type="blobServices/default/containers", name="myblobs") #' ``` #' #' Notice that the storage account's resource type and name are omitted from the `get_subresource` arguments. Similarly, to create a new subresource, call the `create_subresource()` method with the same naming convention, passing any required fields as named arguments; and to delete it, call `delete_subresource()`. #' #' @section Role-based access control: #' AzureRMR implements a subset of the full RBAC functionality within Azure Active Directory. You can retrieve role definitions and add and remove role assignments, at the subscription, resource group and resource levels. See [rbac] for more information. #' #' @seealso #' [az_resource_group], [call_azure_rm], [call_azure_url], #' [Resources API reference](https://learn.microsoft.com/en-us/rest/api/resources/resources) #' #' For role-based access control methods, see [rbac] #' #' For management locks, see [lock] #' #' @examples #' \dontrun{ #' #' # recommended way to retrieve a resource: via a resource group object #' # storage account: #' stor <- resgroup$get_resource(type="Microsoft.Storage/storageAccounts", name="mystorage") #' # virtual machine: #' vm <- resgroup$get_resource(type="Microsoft.Compute/virtualMachines", name="myvm") #' #' ## carry out operations on a resource #' #' # storage account: get access keys #' stor$do_operation("listKeys", http_verb="POST") #' #' # virtual machine: run a script #' vm$do_operation("runCommand", #' body=list( #' commandId="RunShellScript", # RunPowerShellScript for Windows #' script=as.list("ifconfig > /tmp/ifconfig.out") #' ), #' encode="json", #' http_verb="POST") #' #' ## retrieve properties #' #' # storage account: endpoint URIs #' stor$properties$primaryEndpoints$file #' stor$properties$primaryEndpoints$blob #' #' # virtual machine: hardware profile #' vm$properties$hardwareProfile #' #' ## update a resource: resizing a VM #' properties <- list(hardwareProfile=list(vmSize="Standard_DS3_v2")) #' vm$do_operation(http_verb="PATCH", #' body=list(properties=properties), #' encode="json") #' #' # sync with Azure: useful to track resource creation/update status #' vm$sync_fields() #' #' ## subresource: create a public blob container #' stor$create_subresource(type="blobservices/default/containers", name="mycontainer", #' properties=list(publicAccess="container")) #' #' ## delete a subresource and resource #' stor$delete_subresource(type="blobservices/default/containers", name="mycontainer") #' stor$delete() #' #' } #' @format An R6 object of class `az_resource`. #' @export az_resource <- R6::R6Class("az_resource", public=list( subscription=NULL, resource_group=NULL, type=NULL, name=NULL, id=NULL, identity=NULL, kind=NULL, location=NULL, managed_by=NULL, plan=NULL, properties=NULL, sku=NULL, tags=NULL, token=NULL, etag=NULL, ext=list(), # constructor overloads: # 1. deploy resource: resgroup, {provider, path}|type, name, ... # 2. deploy resource by id: id, ... # 3. get from passed-in data: deployed_properties # 4. get from host: resgroup, {provider, path}|type, name # 5. get from host by id: id initialize=function(token, subscription, resource_group, provider, path, type, name, id, ..., deployed_properties=list(), api_version=NULL, wait=FALSE) { self$token <- token self$subscription <- subscription private$init_id_fields(resource_group, provider, path, type, name, id, deployed_properties) # by default this is unset at initialisation, for efficiency private$api_version <- api_version parms <- if(!is_empty(list(...))) private$init_and_deploy(..., wait=wait) else if(!is_empty(deployed_properties)) private$init_from_parms(deployed_properties) else private$init_from_host() self$identity <- parms$identity self$kind <- parms$kind self$location <- parms$location self$managed_by <- parms$managedBy self$plan <- parms$plan self$properties <- parms$properties self$sku <- parms$sku self$tags <- parms$tags self$etag <- parms$etag self$ext <- get_extended_resource_fields(parms) NULL }, get_api_version=function() { private$api_version }, set_api_version=function(api_version=NULL, stable_only=TRUE) { if(!is_empty(api_version)) { private$api_version <- api_version return(invisible(api_version)) } # API versions vary across different providers; find the latest for this resource slash <- regexpr("/", self$type) provider <- substr(self$type, 1, slash - 1) path <- substr(self$type, slash + 1, nchar(self$type)) temp_sub <- az_subscription$new(self$token, self$subscription, list(NULL)) ver <- temp_sub$get_provider_api_version(provider, path, stable_only=stable_only) if(ver == "") stop("No API versions found (try setting stable_only=FALSE") private$api_version <- ver invisible(private$api_version) }, sync_fields=function() { self$initialize(self$token, self$subscription, id=self$id, api_version=private$api_version) self$properties$provisioningState }, delete=function(confirm=TRUE, wait=FALSE) { if(!delete_confirmed(confirm, file.path(self$type, self$name), "resource")) return(invisible(NULL)) message("Deleting resource '", construct_path(self$type, self$name), "'") private$res_op(http_verb="DELETE") if(wait) { for(i in 1:1000) { status <- httr::status_code(private$res_op(http_status_handler="pass")) if(status >= 300) break Sys.sleep(5) } if(status < 300) warning("Attempt to delete resource did not succeed", call.=FALSE) } invisible(NULL) }, get_subresource=function(type, name, id, api_version=NULL) { name <- file.path(self$name, type, name) az_resource$new(self$token, self$subscription, resource_group=self$resource_group, type=self$type, name=name, id=id, api_version=api_version) }, create_subresource=function(type, name, id, location=self$location, ...) { name <- file.path(self$name, type, name) az_resource$new(self$token, self$subscription, resource_group=self$resource_group, type=self$type, name=name, id=id, location=location, ...) }, delete_subresource=function(type, name, id, api_version=NULL, confirm=TRUE, wait=FALSE) { name <- file.path(self$name, type, name) # supply deployed_properties arg to prevent querying host for resource info az_resource$ new(self$token, self$subscription, self$resource_group, type=self$type, name=name, id=id, deployed_properties=list(NULL), api_version=api_version)$ delete(confirm=confirm, wait=wait) }, do_operation=function(..., options=list(), http_verb="GET") { private$res_op(..., options=options, http_verb=http_verb) }, update=function(..., options=list()) { parms <- list(...) # private$validate_update_parms(names(parms)) private$res_op( body=jsonlite::toJSON(parms, auto_unbox=TRUE, digits=22, null="null"), options=options, encode="raw", http_verb="PATCH" ) self$sync_fields() }, set_tags=function(..., keep_existing=TRUE) { tags <- match.call(expand.dots=FALSE)$... unvalued <- if(is.null(names(tags))) rep(TRUE, length(tags)) else names(tags) == "" values <- lapply(seq_along(unvalued), function(i) { if(unvalued[i]) "" else as.character(eval(tags[[i]], parent.frame(3))) }) names(values) <- ifelse(unvalued, as.character(tags), names(tags)) if(keep_existing && !is_empty(self$tags)) values <- modifyList(self$tags, values) # delete tags specified to be null values <- values[!sapply(values, is_empty)] self$update(tags=values) invisible(NULL) }, get_tags=function() { self$tags }, print=function(...) { # generate label from id, since type and name are not guaranteed to be fixed for sub-resources cat("<Azure resource ", sub("^.+providers/(.+$)", "\\1", self$id), ">\n", sep="") cat(format_public_fields(self, exclude=c("subscription", "resource_group", "type", "name"))) cat(format_public_methods(self)) invisible(self) } ), private=list( api_version=NULL, # initialise identifier fields from multiple ways of constructing object init_id_fields=function(resource_group, provider, path, type, name, id, parms=list()) { # if these are supplied, use to fill in everything else if(!is_empty(parms$id) && !is_empty(parms$type) && !is_empty(parms$name)) { resource_group <- sub("^.+resourceGroups/([^/]+)/.*$", "\\1", parms$id, ignore.case=TRUE) type <- parms$type name <- parms$name id <- parms$id } else if(!missing(id)) { resource_group <- sub("^.+resourceGroups/([^/]+)/.*$", "\\1", id, ignore.case=TRUE) id2 <- sub("^.+providers/", "", id) type_delim <- attr(regexpr("^[^/]+/[^/]+/", id2), "match.length") type <- substr(id2, 1, type_delim - 1) name <- substr(id2, type_delim + 1, nchar(id2)) } else { if(missing(type)) type <- construct_path(provider, path) id <- construct_path("/subscriptions", self$subscription, "resourceGroups", resource_group, "providers", type, name) } self$resource_group <- resource_group self$type <- type self$name <- name self$id <- id }, init_from_parms=function(parms) { # allow list(NULL) as special case for creating an empty object # if(!identical(parms, list(NULL))) # private$validate_response_parms(parms) parms }, init_from_host=function() { private$res_op() }, init_and_deploy=function(..., wait) { properties <- list(...) # check if we were passed a json object if(length(properties) == 1 && is.character(properties[[1]]) && jsonlite::validate(properties[[1]])) properties <- jsonlite::fromJSON(properties[[1]], simplifyVector=FALSE) # private$validate_deploy_parms(properties) properties$tags <- add_creator_tag(properties$tags) private$res_op(body=properties, encode="json", http_verb="PUT") # do we wait until resource has finished provisioning? if(wait) { message("Waiting for provisioning to complete") for(i in 1:1000) # some resources can take a long time to provision (AKS, Kusto) { message(".", appendLF=FALSE) # some resources return from creation before they can be retrieved, let http 404's through res <- private$res_op(http_status_handler="pass") http_stat <- httr::status_code(res) state <- httr::content(res)$properties$provisioningState # some resources don't have provisioning state (eg Microsoft.Compute/sshPublicKey) if(is.null(state)) state <- "Succeeded" success <- http_stat < 300 && state == "Succeeded" failure <- http_stat >= 300 || state %in% c("Error", "Failed") if(success || failure) break Sys.sleep(5) } if(success) message("\nDeployment successful") else stop("\nUnable to create resource", call.=FALSE) httr::content(res) } else { # allow time for provisioning setup, then get properties Sys.sleep(2) private$res_op() } }, # validate_deploy_parms=function(parms) # { # required_names <- character(0) # optional_names <- # c("identity", "kind", "location", "managedBy", "plan", "properties", "sku", "tags", "etag") # validate_object_names(names(parms), required_names, optional_names) # }, # validate_response_parms=function(parms) # { # required_names <- c("id", "name", "type") # optional_names <- # c("identity", "kind", "location", "managedBy", "plan", "properties", "sku", "tags", "etag") # validate_object_names(names(parms), required_names, optional_names) # }, # validate_update_parms=function(parms) # { # required_names <- character(0) # optional_names <- # c("identity", "kind", "location", "managedBy", "plan", "properties", "sku", "tags", "etag") # validate_object_names(names(parms), required_names, optional_names) # }, res_op=function(op="", ..., api_version=private$api_version) { # make sure we have an API to call if(is.null(private$api_version)) { res <- try(self$set_api_version(), silent=TRUE) if(inherits(res, "try-error")) { warning("No stable API versions found, falling back to the latest preview version", call.=FALSE) res <- try(self$set_api_version(stable_only=FALSE), silent=TRUE) } if(inherits(res, "try-error")) stop("No API versions found", call.=FALSE) } op <- construct_path("resourcegroups", self$resource_group, "providers", self$type, self$name, op) call_azure_rm(self$token, self$subscription, op, ..., api_version=api_version) } )) get_extended_resource_fields <- function(res_fields) { known_fields <- c("id", "name", "type", "identity", "kind", "location", "managedBy", "plan", "properties", "sku", "tags", "etag") nms <- names(res_fields) res_fields[!(nms %in% known_fields)] }
/scratch/gouwar.j/cran-all/cranData/AzureRMR/R/az_resource.R
### base Resource Manager class #' Azure Resource Manager #' #' Base class for interacting with Azure Resource Manager. #' #' @docType class #' @section Methods: #' - `new(tenant, app, ...)`: Initialize a new ARM connection with the given credentials. See 'Authentication` for more details. #' - `list_subscriptions()`: Returns a list of objects, one for each subscription associated with this app ID. #' - `get_subscription(id)`: Returns an object representing a subscription. #' - `get_subscription_by_name(name)`: Returns the subscription with the given name (as opposed to a GUID). #' - `do_operation(...)`: Carry out an operation. See 'Operations' for more details. #' #' @section Authentication: #' The recommended way to authenticate with ARM is via the [get_azure_login] function, which creates a new instance of this class. #' #' To authenticate with the `az_rm` class directly, provide the following arguments to the `new` method: #' - `tenant`: Your tenant ID. This can be a name ("myaadtenant"), a fully qualified domain name ("myaadtenant.onmicrosoft.com" or "mycompanyname.com"), or a GUID. #' - `app`: The client/app ID to use to authenticate with Azure Active Directory. The default is to login interactively using the Azure CLI cross-platform app, but it's recommended to supply your own app credentials if possible. #' - `password`: if `auth_type == "client_credentials"`, the app secret; if `auth_type == "resource_owner"`, your account password. #' - `username`: if `auth_type == "resource_owner"`, your username. #' - `certificate`: If `auth_type == "client_credentials", a certificate to authenticate with. This is a more secure alternative to using an app secret. #' - `auth_type`: The OAuth authentication method to use, one of "client_credentials", "authorization_code", "device_code" or "resource_owner". See [get_azure_token] for how the default method is chosen, along with some caveats. #' - `version`: The Azure Active Directory version to use for authenticating. #' - `host`: your ARM host. Defaults to `https://management.azure.com/`. Change this if you are using a government or private cloud. #' - `aad_host`: Azure Active Directory host for authentication. Defaults to `https://login.microsoftonline.com/`. Change this if you are using a government or private cloud. #' - `...`: Further arguments to pass to `get_azure_token`. #' - `scopes`: The Azure Service Management scopes (permissions) to obtain for this login. Only for `version=2`. #' - `token`: Optionally, an OAuth 2.0 token, of class [AzureToken]. This allows you to reuse the authentication details for an existing session. If supplied, all other arguments will be ignored. #' #' @section Operations: #' The `do_operation()` method allows you to carry out arbitrary operations on the Resource Manager endpoint. It takes the following arguments: #' - `op`: The operation in question, which will be appended to the URL path of the request. #' - `options`: A named list giving the URL query parameters. #' - `...`: Other named arguments passed to [call_azure_rm], and then to the appropriate call in httr. In particular, use `body` to supply the body of a PUT, POST or PATCH request, and `api_version` to set the API version. #' - `http_verb`: The HTTP verb as a string, one of `GET`, `PUT`, `POST`, `DELETE`, `HEAD` or `PATCH`. #' #' Consult the Azure documentation for what operations are supported. #' #' @seealso #' [create_azure_login], [get_azure_login] #' #' [Azure Resource Manager overview](https://learn.microsoft.com/en-us/azure/azure-resource-manager/resource-group-overview), #' [REST API reference](https://learn.microsoft.com/en-us/rest/api/resources/) #' #' @examples #' \dontrun{ #' #' # start a new Resource Manager session #' az <- az_rm$new(tenant="myaadtenant.onmicrosoft.com", app="app_id", password="password") #' #' # authenticate with credentials in a file #' az <- az_rm$new(config_file="creds.json") #' #' # authenticate with device code #' az <- az_rm$new(tenant="myaadtenant.onmicrosoft.com", app="app_id", auth_type="device_code") #' #' # retrieve a list of subscription objects #' az$list_subscriptions() #' #' # a specific subscription #' az$get_subscription("subscription_id") #' #' } #' @format An R6 object of class `az_rm`. #' @export az_rm <- R6::R6Class("az_rm", public=list( host=NULL, tenant=NULL, token=NULL, # authenticate and get subscriptions initialize=function(tenant="common", app=.az_cli_app_id, password=NULL, username=NULL, certificate=NULL, auth_type=NULL, version=2, host="https://management.azure.com/", aad_host="https://login.microsoftonline.com/", scopes=".default", token=NULL, ...) { if(is_azure_token(token)) { self$host <- httr::build_url(find_resource_host(token)) self$tenant <- token$tenant self$token <- token return(NULL) } self$host <- host self$tenant <- normalize_tenant(tenant) app <- normalize_guid(app) if(version == 2) host <- c(paste0(host, scopes), "openid", "offline_access") token_args <- list(resource=host, tenant=self$tenant, app=app, password=password, username=username, certificate=certificate, auth_type=auth_type, aad_host=aad_host, version=version, ...) self$token <- do.call(get_azure_token, token_args) NULL }, # return a subscription object get_subscription=function(id) { az_subscription$new(self$token, id) }, # return a subscription object given its name get_subscription_by_name=function(name) { subs <- self$list_subscriptions() found <- which(sapply(subs, function(x) x$name) == name) if(is_empty(found)) stop("Subscription '", name, "' not found", call.=FALSE) if(length(found) > 1) stop("More than 1 subscription with the name '", name, "'", call.=FALSE) # sanity check subs[[found]] }, # return all subscriptions for this app list_subscriptions=function() { cont <- call_azure_rm(self$token, subscription="", operation="") lst <- lapply(get_paged_list(cont, self$token), function(parms) az_subscription$new(self$token, parms=parms)) named_list(lst, "id") }, do_operation=function(..., options=list(), http_verb="GET") { private$rm_op(..., options=options, http_verb=http_verb) }, print=function(...) { cat("<Azure Resource Manager client>\n") cat("<Authentication>\n") fmt_token <- gsub("\n ", "\n ", format_auth_header(self$token)) cat(" ", fmt_token) cat("---\n") cat(format_public_methods(self)) invisible(self) } ), private=list( rm_op=function(op="", options=list(), ...) { call_azure_rm(self$token, subscription=NULL, op, ...) } ))
/scratch/gouwar.j/cran-all/cranData/AzureRMR/R/az_rm.R
#' Azure role definition class #' #' @docType class #' @section Fields: #' - `id`: The full resource ID for this role definition. #' - `type`: The resource type for a role definition. Always `Microsoft.Authorization/roleDefinitions`. #' - `name`: A GUID that identifies this role definition. #' - `properties`: Properties for the role definition. #' #' @section Methods: #' This class has no methods. #' #' @section Initialization: #' The recommended way to create new instances of this class is via the [get_role_definition] method for subscription, resource group and resource objects. #' #' Technically role assignments and role definitions are Azure _resources_, and could be implemented as subclasses of `az_resource`. AzureRMR treats them as distinct, due to limited RBAC functionality currently supported. In particular, role definitions are read-only: you can retrieve a definition, but not modify it, nor create new definitions. #' #' @seealso #' [get_role_definition], [get_role_assignment], [az_role_assignment] #' #' [Overview of role-based access control](https://learn.microsoft.com/en-us/azure/role-based-access-control/overview) #' #' @format An R6 object of class `az_role_definition`. #' @export az_role_definition <- R6::R6Class("az_role_definition", public=list( id=NULL, name=NULL, type=NULL, properties=NULL, initialize=function(parameters) { self$id <- parameters$id self$name <- parameters$name self$type <- parameters$type self$properties <- parameters$properties }, print=function(...) { cat("<Azure role definition>\n") cat(" role:", self$properties$roleName, "\n") cat(" description:", self$properties$description, "\n") cat(" role definition ID:", self$name, "\n") invisible(self) } )) #' Azure role assignment class #' #' @docType class #' @section Fields: #' - `id`: The full resource ID for this role assignment. #' - `type`: The resource type for a role assignment. Always `Microsoft.Authorization/roleAssignments`. #' - `name`: A GUID that identifies this role assignment. #' - `role_name`: The role definition name (in text), eg "Contributor". #' - `properties`: Properties for the role definition. #' - `token`: An OAuth token, obtained via [get_azure_token]. #' #' @section Methods: #' - `remove(confirm=TRUE)`: Removes this role assignment. #' #' @section Initialization: #' The recommended way to create new instances of this class is via the [add_role_assignment] and [get_role_assignment] methods for subscription, resource group and resource objects. #' #' Technically role assignments and role definitions are Azure _resources_, and could be implemented as subclasses of `az_resource`. AzureRMR treats them as distinct, due to limited RBAC functionality currently supported. #' #' @seealso #' [add_role_assignment], [get_role_assignment], [get_role_definition], [az_role_definition] #' #' [Overview of role-based access control](https://learn.microsoft.com/en-us/azure/role-based-access-control/overview) #' #' @format An R6 object of class `az_role_assignment`. #' @export az_role_assignment <- R6::R6Class("az_role_assignment", public=list( # text name of role definition role_name=NULL, id=NULL, name=NULL, type=NULL, properties=NULL, token=NULL, initialize=function(token, parameters, role_name=NULL, api_func=NULL) { self$token <- token self$id <- parameters$id self$name <- parameters$name self$type <- parameters$type self$properties <- parameters$properties self$role_name <- role_name private$api_func <- api_func }, remove=function(confirm=TRUE) { if(!delete_confirmed(confirm, self$name, "role assignment")) return(invisible(NULL)) op <- file.path("providers/Microsoft.Authorization/roleAssignments", self$name) res <- private$api_func(op, api_version=getOption("azure_roleasn_api_version"), http_verb="DELETE") if(attr(res, "status") == 204) warning("Role assignment not found or could not be deleted") invisible(NULL) }, print=function(...) { cat("<Azure role assignment>\n") cat(" principal:", self$properties$principalId, "\n") if(!is_empty(self$role_name)) cat(" role:", self$role_name, "\n") else cat(" role: <unknown>\n") cat(" role definition ID:", basename(self$properties$roleDefinitionId), "\n") cat(" role assignment ID:", self$name, "\n") invisible(self) } ), private=list( api_func=NULL ))
/scratch/gouwar.j/cran-all/cranData/AzureRMR/R/az_role.R
### Azure subscription class: all info about a subscription #' Azure subscription class #' #' Class representing an Azure subscription. #' #' @docType class #' @section Methods: #' - `new(token, id, ...)`: Initialize a subscription object. #' - `list_resource_groups(filter, top)`: Return a list of resource group objects for this subscription. `filter` and `top` are optional arguments to filter the results; see the [Azure documentation](https://learn.microsoft.com/en-us/rest/api/resources/resourcegroups/list) for more details. If `top` is specified, the returned list will have a maximum of this many items. #' - `get_resource_group(name)`: Return an object representing an existing resource group. #' - `create_resource_group(name, location)`: Create a new resource group in the specified region/location, and return an object representing it. By default, AzureRMR will set the `createdBy` tag on a newly-created resource group to the value `AzureR/AzureRMR`. #' - `delete_resource_group(name, confirm=TRUE)`: Delete a resource group, after asking for confirmation. #' - `resource_group_exists(name)`: Check if a resource group exists. #' - `list_resources(filter, expand, top)`: List all resources deployed under this subscription. `filter`, `expand` and `top` are optional arguments to filter the results; see the [Azure documentation](https://learn.microsoft.com/en-us/rest/api/resources/resources/list) for more details. If `top` is specified, the returned list will have a maximum of this many items. #' - `list_locations(info=c("partial", "all"))`: List locations available. The default `info="partial"` returns a subset of the information about each location; set `info="all"` to return everything. #' - `get_provider_api_version(provider, type, which=1, stable_only=TRUE)`: Get the current API version for the given resource provider and type. If no resource type is supplied, returns a vector of API versions, one for each resource type for the given provider. If neither provider nor type is supplied, returns the API versions for all resources and providers. Set `stable_only=FALSE` to allow preview APIs to be returned. Set `which` to a number > 1 to return an API other than the most recent. #' - `do_operation(...)`: Carry out an operation. See 'Operations' for more details. #' - `create_lock(name, level)`: Create a management lock on this subscription (which will propagate to all resources within it). #' - `get_lock(name)`: Returns a management lock object. #' - `delete_lock(name)`: Deletes a management lock object. #' - `list_locks()`: List all locks that exist in this subscription. #' - `add_role_assignment(name, ...)`: Adds a new role assignment. See 'Role-based access control' below. #' - `get_role_assignment(id)`: Retrieves an existing role assignment. #' - `remove_role_assignment(id)`: Removes an existing role assignment. #' - `list_role_assignments()`: Lists role assignments. #' - `get_role_definition(id)`: Retrieves an existing role definition. #' - `list_role_definitions()` Lists role definitions. #' - `get_tags()` Get the tags on this subscription. #' #' @section Details: #' Generally, the easiest way to create a subscription object is via the `get_subscription` or `list_subscriptions` methods of the [az_rm] class. To create a subscription object in isolation, call the `new()` method and supply an Oauth 2.0 token of class [AzureToken], along with the ID of the subscription. #' #' @section Operations: #' The `do_operation()` method allows you to carry out arbitrary operations on the subscription. It takes the following arguments: #' - `op`: The operation in question, which will be appended to the URL path of the request. #' - `options`: A named list giving the URL query parameters. #' - `...`: Other named arguments passed to [call_azure_rm], and then to the appropriate call in httr. In particular, use `body` to supply the body of a PUT, POST or PATCH request, and `api_version` to set the API version. #' - `http_verb`: The HTTP verb as a string, one of `GET`, `PUT`, `POST`, `DELETE`, `HEAD` or `PATCH`. #' #' Consult the Azure documentation for what operations are supported. #' #' @section Role-based access control: #' AzureRMR implements a subset of the full RBAC functionality within Azure Active Directory. You can retrieve role definitions and add and remove role assignments, at the subscription, resource group and resource levels. See [rbac] for more information. #' #' @seealso #' [Azure Resource Manager overview](https://learn.microsoft.com/en-us/azure/azure-resource-manager/resource-group-overview) #' #' For role-based access control methods, see [rbac] #' #' For management locks, see [lock] #' #' @examples #' \dontrun{ #' #' # recommended way to retrieve a subscription object #' sub <- get_azure_login("myaadtenant")$ #' get_subscription("subscription_id") #' #' # retrieve list of resource group objects under this subscription #' sub$list_resource_groups() #' #' # get a resource group #' sub$get_resource_group("rgname") #' #' # check if a resource group exists, and if not, create it #' rg_exists <- sub$resource_group_exists("rgname") #' if(!rg_exists) #' sub$create_resource_group("rgname", location="australiaeast") #' #' # delete a resource group #' sub$delete_resource_group("rgname") #' #' # get provider API versions for some resource types #' sub$get_provider_api_version("Microsoft.Compute", "virtualMachines") #' sub$get_provider_api_version("Microsoft.Storage", "storageAccounts") #' #' } #' @format An R6 object of class `az_subscription`. #' @export az_subscription <- R6::R6Class("az_subscription", public=list( id=NULL, name=NULL, state=NULL, policies=NULL, authorization_source=NULL, tags=NULL, token=NULL, initialize=function(token, id=NULL, parms=list()) { if(is_empty(id) && is_empty(parms)) stop("Must supply either subscription ID, or parameter list") self$token <- token if(is_empty(parms)) parms <- call_azure_rm(self$token, subscription=id, operation="") self$id <- parms$subscriptionId self$name <- parms$displayName self$state <- parms$state self$policies <- parms$subscriptionPolicies self$authorization_source <- parms$authorizationSource self$tags <- parms$tags NULL }, list_locations=function(info=c("partial", "all")) { info <- match.arg(info) res <- self$do_operation("locations", http_status_handler="pass") cont <- httr::content(res, simplifyVector=TRUE) httr::stop_for_status(res, paste0("complete operation. Message:\n", sub("\\.$", "", error_message(cont)))) locs <- cont$value locs$metadata$longitude <- as.numeric(locs$metadata$longitude) locs$metadata$latitude <- as.numeric(locs$metadata$latitude) if(info == "partial") cbind(locs[c("name", "displayName")], locs$metadata[c("longitude", "latitude", "regionType")]) else locs }, # API versions vary across different providers; find the latest get_provider_api_version=function(provider=NULL, type=NULL, which=1, stable_only=TRUE) { select_version <- function(api) { versions <- unlist(api$apiVersions) if(stable_only) versions <- grep("preview", versions, value=TRUE, invert=TRUE) if(length(versions) >= which) versions[which] else "" } if(is_empty(provider)) { apis <- named_list(private$sub_op("providers")$value, "namespace") lapply(apis, function(api) { api <- named_list(api$resourceTypes, "resourceType") sapply(api, select_version) }) } else { op <- construct_path("providers", provider) apis <- named_list(private$sub_op(op)$resourceTypes, "resourceType") if(!is_empty(type)) { # case-insensitive matching names(apis) <- tolower(names(apis)) select_version(apis[[tolower(type)]]) } else sapply(apis, select_version) } }, get_tags=function() { if(is.null(self$tags)) named_list() else self$tags }, get_resource_group=function(name) { az_resource_group$new(self$token, self$id, name) }, list_resource_groups=function(filter=NULL, top=NULL) { opts <- list(`$filter`=filter, `$top`=top) cont <- private$sub_op("resourcegroups", options=opts) lst <- lapply( if(is.null(top)) get_paged_list(cont, self$token) else cont$value, function(parms) az_resource_group$new(self$token, self$id, parms=parms) ) named_list(lst) }, create_resource_group=function(name, location, ...) { az_resource_group$new(self$token, self$id, name, location=location, ...) }, delete_resource_group=function(name, confirm=TRUE) { if(name == "") stop("Must supply a resource group name", call.=FALSE) self$get_resource_group(name)$delete(confirm=confirm) }, resource_group_exists=function(name) { res <- private$sub_op(construct_path("resourceGroups", name), http_verb="HEAD", http_status_handler="pass") httr::status_code(res) < 300 }, list_resources=function(filter=NULL, expand=NULL, top=NULL) { opts <- list(`$filter`=filter, `$expand`=expand, `$top`=top) cont <- private$sub_op("resources", options=opts) lst <- lapply( if(is.null(top)) get_paged_list(cont, self$token) else cont$value, function(parms) az_resource$new(self$token, self$id, deployed_properties=parms) ) names(lst) <- sapply(lst, function(x) sub("^.+providers/(.+$)", "\\1", x$id)) lst }, do_operation=function(..., options=list(), http_verb="GET") { private$sub_op(..., options=options, http_verb=http_verb) }, print=function(...) { cat("<Azure subscription ", self$id, ">\n", sep="") cat(format_public_fields(self, exclude="id")) cat(format_public_methods(self)) invisible(self) } ), private=list( sub_op=function(op="", ...) { call_azure_rm(self$token, self$id, op, ...) } ))
/scratch/gouwar.j/cran-all/cranData/AzureRMR/R/az_subscription.R
#' Azure template class #' #' Class representing an Azure deployment template. #' #' @docType class #' @section Methods: #' - `new(token, subscription, resource_group, name, ...)`: Initialize a new template object. See 'Initialization' for more details. #' - `check()`: Check the deployment status of the template; throw an error if the template has been deleted. #' - `cancel(free_resources=FALSE)`: Cancel an in-progress deployment. Optionally free any resources that have already been created. #' - `delete(confirm=TRUE, free_resources=FALSE)`: Delete a deployed template, after a confirmation check. Optionally free any resources that were created. If the template was deployed in Complete mode (its resource group is exclusive to its use), the latter process will delete the entire resource group. Otherwise resources are deleted in the order given by the template's output resources list; in this case, some may be left behind if the ordering is incompatible with dependencies. #' - `list_resources()`: Returns a list of Azure resource objects that were created by the template. This returns top-level resources only, not those that represent functionality provided by another resource. #' - `get_tags()`: Returns the tags for the deployment template (note: this is not the same as the tags applied to resources that are deployed). #' #' @section Initialization: #' Initializing a new object of this class can either retrieve an existing template, or deploy a new template on the host. Generally, the easiest way to create a template object is via the `get_template`, `deploy_template` or `list_templates` methods of the [az_resource_group] class, which handle the details automatically. #' #' To initialize an object that refers to an existing deployment, supply the following arguments to `new()`: #' - `token`: An OAuth 2.0 token, as generated by [get_azure_token]. #' - `subscription`: The subscription ID. #' - `resource_group`: The resource group. #' - `name`: The deployment name`. #' #' If you also supply the following arguments to `new()`, a new template will be deployed: #' - `template`: The template to deploy. This can be provided in a number of ways: #' 1. A nested list of R objects, which will be converted to JSON via `jsonlite::toJSON` #' 2. A vector of strings containing unparsed JSON #' 3. The name of a template file #' 4. A URL from which the host can download the template #' - `parameters`: The parameters for the template. This can be provided using any of the same methods as the `template` argument. #' - `wait`: Optionally, whether to wait until the deployment is complete. Defaults to FALSE, in which case the method will return immediately. #' #' You can use the `build_template_definition` and `build_template_parameters` helper functions to construct the inputs for deploying a template. These can take as inputs R lists, JSON text strings, or file connections, and can also be extended by other packages. #' #' @seealso #' [az_resource_group], [az_resource], [build_template_definition], [build_template_parameters] #' [Template overview](https://learn.microsoft.com/en-us/azure/templates/), #' [Template API reference](https://learn.microsoft.com/en-us/rest/api/resources/deployments) #' #' @examples #' \dontrun{ #' #' # recommended way to deploy a template: via a resource group object #' #' tpl <- resgroup$deploy_template("mydeployment", #' template="template.json", #' parameters="parameters.json") #' #' # retrieve list of created resource objects #' tpl$list_resources() #' #' # delete template (will not touch resources) #' tpl$delete() #' #' # delete template and free resources #' tpl$delete(free_resources=TRUE) #' #' } #' @format An R6 object of class `az_template`. #' @export az_template <- R6::R6Class("az_template", public=list( subscription=NULL, resource_group=NULL, id=NULL, name=NULL, properties=NULL, tags=NULL, token=NULL, # constructor overloads: 1) get an existing template from host; 2) from passed-in data; 3) deploy new template initialize=function(token, subscription, resource_group, name=NULL, template, parameters, ..., deployed_properties=list(), wait=FALSE) { self$token <- token self$subscription <- subscription self$resource_group <- resource_group parms <- if(!is_empty(name) && !missing(template)) private$init_and_deploy(name, template, parameters, ..., wait=wait) else if(!is_empty(name)) private$init_from_host(name) else if(!is_empty(deployed_properties)) private$init_from_parms(deployed_properties) else stop("Invalid initialization call") self$id <- parms$id self$properties <- parms$properties self$tags <- parms$tags NULL }, cancel=function(free_resources=FALSE) { message("Cancelling deployment of template '", self$name, "'") if(free_resources) { message("Also freeing associated resources:") private$free_resources() } else message("Associated resources will not be freed") private$tpl_op("cancel", http_verb="POST") invisible(NULL) }, delete=function(confirm=TRUE, free_resources=FALSE) { # mode = Complete and free_resources = TRUE: delete entire resource group # mode = Incr and free_resources = TRUE: delete resources individually # mode = Complete and free_resources = FALSE: delete template # mode = Incr and free_resources = FALSE: delete template del <- if(!free_resources) "tpl" else if(self$properties$mode == "Complete") "rg" else "res" type <- if(del %in% c("tpl", "res")) "template" else "resource group" name <- if(del == "tpl") sprintf("'%s'", self$name) else if(del == "rg") sprintf("'%s'", self$resource_group) else sprintf("'%s' and associated resources", self$name) if(!(delete_confirmed(confirm, name, type, FALSE))) return(invisible(NULL)) if(del == "rg") return(az_resource_group$new(self$token, self$subscription, self$resource_group)$delete(confirm=FALSE)) message("Deleting template '", self$name, "'") if(free_resources) { message("Also freeing associated resources:") private$free_resources() } else message("Associated resources will not be freed") private$tpl_op(http_verb="DELETE") invisible(NULL) }, # update state of template: deployment accepted/deployment failed/updating/running check=function() { self$initialize(self$token, self$subscription, self$resource_group, self$name) self$properties$provisioningState }, list_resources=function() { outlst <- lapply(self$properties$outputResources, function(res) { res <- res$id # return only top-level resources; error out if resource has been deleted if(grepl("providers/[^/]+/[^/]+/[^/]+$", res)) az_resource$new(self$token, self$subscription, self$resource_group, id=res) else NULL }) nulls <- sapply(outlst, is.null) named_list(outlst[!nulls], c("type", "name")) }, get_tags=function() { self$tags }, print=function(...) { cat("<Azure template ", self$name, ">\n", sep="") cat(format_public_fields(self, exclude=c("subscription", "resource_group", "name"))) cat(format_public_methods(self)) invisible(self) } ), private=list( init_from_host=function(name) { self$name <- name private$tpl_op() }, init_from_parms=function(parms) { # private$validate_response_parms(parms) self$name <- parms$name parms }, # deployment workhorse function init_and_deploy=function(name, template, parameters, ..., wait=FALSE) { message("Deploying template '", name, "'") default_properties <- list( debugSetting=list(detailLevel="requestContent, responseContent"), mode="Incremental" ) properties <- modifyList(default_properties, list(...)) # private$validate_deploy_parms(properties) # rather than working with R objects, convert to JSON and do text munging # this allows adding template/params that are already JSON text without conversion roundtrip properties <- generate_json(properties) # fold template data into properties properties <- if(is.list(template)) append_json(properties, template=generate_json(template)) else if(is_file_spec(template)) append_json(properties, template=readLines(template)) else if(is_url(template)) append_json(properties, templateLink=generate_json(list(uri=template))) else append_json(properties, template=template) # handle case of missing or empty parameters arg # must be a _named_ list for jsonlite to turn into an object, not an array if(missing(parameters) || is_empty(parameters)) parameters <- named_list() # fold parameter data into properties properties <- if(is_empty(parameters)) append_json(properties, parameters=generate_json(parameters)) else if(is.list(parameters)) append_json(properties, parameters=do.call(build_template_parameters, parameters)) else if(is_file_spec(parameters)) append_json(properties, parameters=readLines(parameters)) else if(is_url(parameters)) append_json(properties, parametersLink=generate_json(list(uri=parameters))) else append_json(properties, parameters=parameters) self$name <- name tags <- jsonlite::toJSON(list(createdBy="AzureR/AzureRMR"), auto_unbox=TRUE) parms <- private$tpl_op( body=jsonlite::prettify(sprintf('{"properties": %s, "tags": %s}', properties, tags)), encode="raw", http_verb="PUT" ) # do we wait until template has finished provisioning? if(wait) { message("Waiting for provisioning to complete") for(i in 1:1000) # some templates can take a long time to provision (HDInsight) { message(".", appendLF=FALSE) parms <- private$tpl_op() status <- parms$properties$provisioningState if(status %in% c("Succeeded", "Error", "Failed")) break Sys.sleep(5) } if(status == "Succeeded") message("\nDeployment successful") else { err_details <- lapply(parms$properties$error$details, `[[`, "message") msg <- if(is.list(err_details) && !is_empty(err_details)) paste0("\nUnable to deploy template. Message(s):\n", do.call(paste, c(err_details, sep="\n"))) else "\nUnable to deploy template" stop(msg, call.=FALSE) } } parms }, # validate_response_parms=function(parms) # { # required_names <- c("name") # optional_names <- c("id", "properties") # validate_object_names(names(parms), required_names, optional_names) # }, # validate_deploy_parms=function(parms) # { # required_names <- c("debugSetting", "mode") # optional_names <- c("onErrorDeployment") # validate_object_names(names(parms), required_names, optional_names) # }, # delete resources that were created (which may not be the same as resources that are required) free_resources=function() { # assumption: outputResources is sorted to allow for dependencies resources <- self$properties$outputResources for(i in seq_along(resources)) { id <- resources[[i]]$id # only attempt to delete top-level resources if(grepl("/providers/[^/]+/[^/]+/[^/]+$", id)) { # supply deployed_properties arg to prevent querying host for resource info try(az_resource $ new(self$token, self$subscription, id=id, deployed_properties=list(NULL)) $ delete(confirm=FALSE, wait=TRUE)) } } }, tpl_op=function(op="", ...) { op <- construct_path("resourcegroups", self$resource_group, "providers/Microsoft.Resources/deployments", self$name, op) call_azure_rm(self$token, self$subscription, op, ...) } ))
/scratch/gouwar.j/cran-all/cranData/AzureRMR/R/az_template.R
#' Build the JSON for a template and its parameters #' #' @param ... For `build_template_parameters`, named arguments giving the values of each template parameter. For `build_template_definition`, further arguments passed to class methods. #' @param parameters For `build_template_definition`, the parameter names and types for the template. See 'Details' below. #' @param variables Internal variables used by the template. #' @param functions User-defined functions used by the template. #' @param resources List of resources that the template should deploy. #' @param outputs The template outputs. #' @param schema,version,api_profile Less commonly used arguments that can be used to customise the template. See the guide to template syntax on Microsoft Docs, linked below. #' #' @details #' `build_template_definition` is used to generate a template from its components. The main arguments are `parameters`, `variables`, `functions`, `resources` and `outputs`. Each of these can be specified in various ways: #' - As character strings containing unparsed JSON text. #' - As an R list of (nested) objects, which will be converted to JSON via `jsonlite::toJSON`. #' - A connection pointing to a JSON file or object. #' - For the `parameters` argument, this can also be a character vector containing the types of each parameter. #' #' `build_template_parameters` is for creating the list of parameters to be passed along with the template. Its arguments should all be named, and contain either the JSON text or an R list giving the parsed JSON. #' #' Both of these are generics and can be extended by other packages to handle specific deployment scenarios, eg virtual machines. #' #' @return #' The JSON text for the template definition and its parameters. #' #' @seealso #' [az_template], [jsonlite::toJSON] #' #' [Guide to template syntax](https://learn.microsoft.com/en-us/azure/azure-resource-manager/templates/template-syntax) #' @examples #' # dummy example #' # note that 'resources' arg should be a _list_ of resources #' build_template_definition(resources=list(list(name="resource here"))) #' #' # specifying parameters as a list #' build_template_definition(parameters=list(par1=list(type="string")), #' resources=list(list(name="resource here"))) #' #' # specifying parameters as a vector #' build_template_definition(parameters=c(par1="string"), #' resources=list(list(name="resource here"))) #' #' # a user-defined function #' build_template_definition( #' parameters=c(name="string"), #' functions=list( #' list( #' namespace="mynamespace", #' members=list( #' prefixedName=list( #' parameters=list( #' list(name="name", type="string") #' ), #' output=list( #' type="string", #' value="[concat('AzureR', parameters('name'))]" #' ) #' ) #' ) #' ) #' ) #' ) #' #' # realistic example: storage account #' build_template_definition( #' parameters=c( #' name="string", #' location="string", #' sku="string" #' ), #' variables=list( #' id="[resourceId('Microsoft.Storage/storageAccounts', parameters('name'))]" #' ), #' resources=list( #' list( #' name="[parameters('name')]", #' location="[parameters('location')]", #' type="Microsoft.Storage/storageAccounts", #' apiVersion="2018-07-01", #' sku=list( #' name="[parameters('sku')]" #' ), #' kind="Storage" #' ) #' ), #' outputs=list( #' storageId="[variables('id')]" #' ) #' ) #' #' # providing JSON text as input #' build_template_definition( #' parameters=c(name="string", location="string", sku="string"), #' resources='[ #' { #' "name": "[parameters(\'name\')]", #' "location": "[parameters(\'location\')]", #' "type": "Microsoft.Storage/storageAccounts", #' "apiVersion": "2018-07-01", #' "sku": { #' "name": "[parameters(\'sku\')]" #' }, #' "kind": "Storage" #' } #' ]' #' ) #' #' # parameter values #' build_template_parameters(name="mystorageacct", location="westus", sku="Standard_LRS") #' #' build_template_parameters( #' param='{ #' "name": "myname", #' "properties": { "prop1": 42, "prop2": "hello" } #' }' #' ) #' #' param_json <- '{ #' "name": "myname", #' "properties": { "prop1": 42, "prop2": "hello" } #' }' #' build_template_parameters(param=textConnection(param_json)) #' #' \dontrun{ #' # reading JSON definitions from files #' build_template_definition( #' parameters=file("parameter_def.json"), #' resources=file("resource_def.json") #' ) #' #' build_template_parameters(name="myres_name", complex_type=file("myres_params.json")) #' } #' #' @rdname build_template #' @aliases build_template #' @export build_template_definition <- function(...) { UseMethod("build_template_definition") } #' @rdname build_template #' @export build_template_definition.default <- function( parameters=named_list(), variables=named_list(), functions=list(), resources=list(), outputs=named_list(), schema="2019-04-01", version="1.0.0.0", api_profile=NULL, ...) { # special treatment for parameters arg: convert 'c(name="type")' to 'list(name=list(type="type"))' if(is.character(parameters)) parameters <- sapply(parameters, function(type) list(type=type), simplify=FALSE) parts <- lapply( list( `$schema`=paste0("https://schema.management.azure.com/schemas/", schema, "/deploymentTemplate.json#"), contentVersion=version, apiProfile=api_profile, parameters=parameters, variables=variables, functions=functions, resources=resources, outputs=outputs, ... ), function(x) { if(inherits(x, "connection")) { on.exit(close(x)) readLines(x) } else generate_json(x) } ) parts <- parts[parts != "null"] # json <- "{}" # for(i in seq_along(parts)) # if(parts[i] != "null") # json <- do.call(append_json, c(json, parts[i])) jsonlite::prettify(do.call(append_json, c(list("{}"), parts))) } #' @rdname build_template #' @export build_template_parameters <- function(...) { UseMethod("build_template_parameters") } #' @rdname build_template #' @export build_template_parameters.default <- function(...) { dots <- list(...) # handle no-parameter case if(is_empty(dots)) return("{}") parms <- lapply(dots, function(value) { # need to duplicate functionality of generate_json, one level down if(inherits(value, "connection")) { on.exit(close(value)) generate_json(list(value=jsonlite::fromJSON(readLines(value), simplifyVector=FALSE))) } else if(is.character(value) && jsonlite::validate(value)) generate_json(list(value=jsonlite::fromJSON(value, simplifyVector=FALSE))) else generate_json(list(value=value)) }) jsonlite::prettify(do.call(append_json, c(list("{}"), parms))) } generate_json <- function(object) { if(is.character(object) && jsonlite::validate(object)) object else jsonlite::toJSON(object, auto_unbox=TRUE, null="null", digits=22) } append_json <- function(props, ...) { lst <- list(...) lst_names <- names(lst) if(is.null(lst_names) || any(lst_names == "")) stop("Deployment properties and parameters must be named", call.=FALSE) for(i in seq_along(lst)) { lst_i <- lst[[i]] if(inherits(lst_i, "connection")) { on.exit(close(lst_i)) lst_i <- readLines(lst_i) } newprop <- sprintf('"%s": %s}', lst_names[i], paste0(lst_i, collapse="\n")) if(!grepl("^\\{[[:space:]]*\\}$", props)) newprop <- paste(",", newprop) props <- sub("\\}$", newprop, props) } props } is_file_spec <- function(x) { inherits(x, "connection") || (is.character(x) && length(x) == 1 && file.exists(x)) }
/scratch/gouwar.j/cran-all/cranData/AzureRMR/R/build_tpl_json.R
#' Call the Azure Resource Manager REST API #' #' @param token An Azure OAuth token, of class [AzureToken]. #' @param subscription For `call_azure_rm`, a subscription ID. #' @param operation The operation to perform, which will form part of the URL path. #' @param options A named list giving the URL query parameters. #' @param api_version The API version to use, which will form part of the URL sent to the host. #' @param url A complete URL to send to the host. #' @param http_verb The HTTP verb as a string, one of `GET`, `PUT`, `POST`, `DELETE`, `HEAD` or `PATCH`. #' @param http_status_handler How to handle in R the HTTP status code of a response. `"stop"`, `"warn"` or `"message"` will call the appropriate handlers in httr, while `"pass"` ignores the status code. #' @param auto_refresh Whether to refresh/renew the OAuth token if it is no longer valid. #' @param body The body of the request, for `PUT`/`POST`/`PATCH`. #' @param encode The encoding (really content-type) for the request body. The default value "json" means to serialize a list body into a JSON object. If you pass an already-serialized JSON object as the body, set `encode` to "raw". #' @param ... Other arguments passed to lower-level code, ultimately to the appropriate functions in httr. #' #' @details #' These functions form the low-level interface between R and Azure. `call_azure_rm` builds a URL from its arguments and passes it to `call_azure_url`. Authentication is handled automatically. #' #' @return #' If `http_status_handler` is one of `"stop"`, `"warn"` or `"message"`, the status code of the response is checked. If an error is not thrown, the parsed content of the response is returned with the status code attached as the "status" attribute. #' #' If `http_status_handler` is `"pass"`, the entire response is returned without modification. #' #' @seealso #' [httr::GET], [httr::PUT], [httr::POST], [httr::DELETE], [httr::stop_for_status], [httr::content] #' @rdname call_azure #' @export call_azure_rm <- function(token, subscription, operation, ..., options=list(), api_version=getOption("azure_api_version")) { url <- find_resource_host(token) url$path <- if(!missing(subscription) && !is.null(subscription)) construct_path("subscriptions", subscription, operation) else operation url$query <- modifyList(list(`api-version`=api_version), options) call_azure_url(token, url, ...) } #' @rdname call_azure #' @export call_azure_url <- function(token, url, ..., body=NULL, encode="json", http_verb=c("GET", "DELETE", "PUT", "POST", "HEAD", "PATCH"), http_status_handler=c("stop", "warn", "message", "pass"), auto_refresh=TRUE) { headers <- process_headers(token, url, auto_refresh) # if content-type is json, serialize it manually to ensure proper handling of nulls if(encode == "json") { null <- vapply(body, is.null, logical(1)) body <- jsonlite::toJSON(body[!null], auto_unbox=TRUE, digits=22, null="null") encode <- "raw" } # do actual API call res <- httr::VERB(match.arg(http_verb), url, headers, body=body, encode=encode, ...) process_response(res, match.arg(http_status_handler)) } process_headers <- function(token, host, auto_refresh) { # if token has expired, renew it if(auto_refresh && !token$validate()) { message("Access token has expired or is no longer valid; refreshing") token$refresh() } access_token <- extract_jwt(token) headers <- c( Host=httr::parse_url(host)$hostname, Authorization=paste("Bearer", access_token), `Content-Type`="application/json" ) httr::add_headers(.headers=headers) } process_response <- function(response, handler) { if(handler != "pass") { cont <- httr::content(response) handler <- get(paste0(handler, "_for_status"), getNamespace("httr")) handler(response, paste0("complete operation. Message:\n", sub("\\.$", "", error_message(cont)))) if(is.null(cont)) cont <- list() attr(cont, "status") <- httr::status_code(response) cont } else response } # provide complete error messages from Resource Manager error_message <- function(cont) { # kiboze through possible message locations msg <- if(is.character(cont)) cont else if(is.list(cont)) as.character(unlist(cont)) else "" paste0(strwrap(msg), collapse="\n") } find_resource_host <- function(token) { if(is_azure_v2_token(token)) { # search the vector of scopes for the actual resource URL url <- list() i <- 1 while(is.null(url$scheme) && i <= length(token$scope)) { url <- httr::parse_url(token$scope[i]) i <- i + 1 } } else url <- httr::parse_url(token$resource) # v1 token is the easy case if(is.null(url$scheme)) stop("Could not find Resource Manager host URL", call.=FALSE) url$path <- NULL url }
/scratch/gouwar.j/cran-all/cranData/AzureRMR/R/call_azure_rm.R
#' Informational functions #' #' These functions return whether the object is of the corresponding AzureRMR class. #' #' @param object An R object. #' #' @return #' A boolean. #' @rdname info #' @export is_azure_login <- function(object) { R6::is.R6(object) && inherits(object, "az_rm") } #' @rdname info #' @export is_subscription <- function(object) { R6::is.R6(object) && inherits(object, "az_subscription") } #' @rdname info #' @export is_resource_group <- function(object) { R6::is.R6(object) && inherits(object, "az_resource_group") } #' @rdname info #' @export is_resource <- function(object) { R6::is.R6(object) && inherits(object, "az_resource") } #' @rdname info #' @export is_template <- function(object) { R6::is.R6(object) && inherits(object, "az_template") } #' @rdname info #' @export is_role_definition <- function(object) { R6::is.R6(object) && inherits(object, "az_role_definition") } #' @rdname info #' @export is_role_assignment <- function(object) { R6::is.R6(object) && inherits(object, "az_role_assignment") }
/scratch/gouwar.j/cran-all/cranData/AzureRMR/R/is.R
#' Management locks #' #' Create, retrieve and delete locks. These are methods for the `az_subscription`, `az_resource_group` and `az_resource` classes. #' #' @section Usage: #' ``` #' create_lock(name, level = c("cannotdelete", "readonly"), notes = "") #' #' get_lock(name) #' #' delete_lock(name) #' #' list_locks() #' ``` #' @section Arguments: #' - `name`: The name of a lock. #' - `level`: The level of protection that the lock provides. #' - `notes`: An optional character string to describe the lock. #' #' @section Details: #' Management locks in Resource Manager can be assigned at the subscription, resource group, or resource level. They serve to protect a resource against unwanted changes. A lock can either protect against deletion (`level="cannotdelete"`) or against modification of any kind (`level="readonly"`). #' #' Locks assigned at parent scopes also apply to lower ones, recursively. The most restrictive lock in the inheritance takes precedence. To modify/delete a resource, any existing locks for its subscription and resource group must also be removed. #' #' Note if you logged in via a custom service principal, it must have "Owner" or "User Access Administrator" access to manage locks. #' #' @section Value: #' The `create_lock` and `get_lock` methods return a lock object, which is itself an Azure resource. The `list_locks` method returns a list of such objects. The `delete_lock` method returns NULL on a successful delete. #' #' The `get_role_definition` method returns an object of class `az_role_definition`. This is a plain-old-data R6 class (no methods), which can be used as input for creating role assignments (see the examples below). #' #' The `list_role_definitions` method returns a list of `az_role_definition` if the `as_data_frame` argument is FALSE. If this is TRUE, it instead returns a data frame containing the most broadly useful fields for each role definition: the definition ID and role name. #' #' @seealso #' [rbac] #' #' [Overview of management locks](https://learn.microsoft.com/en-us/azure/azure-resource-manager/resource-group-lock-resources) #' #' @examples #' \dontrun{ #' #' az <- get_azure_login("myaadtenant") #' sub <- az$get_subscription("subscription_id") #' rg <- sub$get_resource_group("rgname") #' res <- rg$get_resource(type="provider_type", name="resname") #' #' sub$create_lock("lock1", "cannotdelete") #' rg$create_lock("lock2", "cannotdelete") #' #' # error! resource is locked #' res$delete() #' #' # subscription level #' rg$delete_lock("lock2") #' sub$delete_lock("lock1") #' #' # now it works #' res$delete() #' #' } #' @aliases lock create_lock get_lock delete_lock list_locks #' @rdname lock #' @name lock NULL ## subscription methods az_subscription$set("public", "create_lock", overwrite=TRUE, function(name, level=c("cannotdelete", "readonly"), notes="") { create_lock(name, match.arg(level), notes, private$sub_op, self$token, self$id) }) az_subscription$set("public", "get_lock", overwrite=TRUE, function(name) { get_lock(name, private$sub_op, self$token, self$id) }) az_subscription$set("public", "delete_lock", overwrite=TRUE, function(name) { delete_lock(name, private$sub_op) }) az_subscription$set("public", "list_locks", overwrite=TRUE, function() { list_locks(private$sub_op, self$token, self$id) }) ## resource group methods az_resource_group$set("public", "create_lock", overwrite=TRUE, function(name, level=c("cannotdelete", "readonly"), notes="") { create_lock(name, match.arg(level), notes, private$rg_op, self$token, self$subscription) }) az_resource_group$set("public", "get_lock", overwrite=TRUE, function(name) { get_lock(name, private$rg_op, self$token, self$subscription) }) az_resource_group$set("public", "delete_lock", overwrite=TRUE, function(name) { delete_lock(name, private$rg_op) }) az_resource_group$set("public", "list_locks", overwrite=TRUE, function() { list_locks(private$rg_op, self$token, self$subscription) }) ## resource methods az_resource$set("public", "create_lock", overwrite=TRUE, function(name, level=c("cannotdelete", "readonly"), notes="") { create_lock(name, match.arg(level), notes, private$res_op, self$token, self$subscription) }) az_resource$set("public", "get_lock", overwrite=TRUE, function(name) { get_lock(name, private$res_op, self$token, self$subscription) }) az_resource$set("public", "delete_lock", overwrite=TRUE, function(name) { delete_lock(name, private$res_op) }) az_resource$set("public", "list_locks", overwrite=TRUE, function() { list_locks(private$res_op, self$token, self$subscription) }) ## implementations create_lock <- function(name, level, notes, api_func, token, subscription) { api <- getOption("azure_api_mgmt_version") op <- file.path("providers/Microsoft.Authorization/locks", name) body <- list(properties=list(level=level)) if(notes != "") body$notes <- notes res <- api_func(op, body=body, encode="json", http_verb="PUT", api_version=api) az_resource$new(token, subscription, deployed_properties=res, api_version=api) } get_lock <- function(name, api_func, token, subscription) { api <- getOption("azure_api_mgmt_version") op <- file.path("providers/Microsoft.Authorization/locks", name) res <- api_func(op, api_version=api) az_resource$new(token, subscription, deployed_properties=res, api_version=api) } delete_lock <- function(name, api_func) { api <- getOption("azure_api_mgmt_version") op <- file.path("providers/Microsoft.Authorization/locks", name) api_func(op, http_verb="DELETE", api_version=api) invisible(NULL) } list_locks <- function(api_func, token, subscription) { api <- getOption("azure_api_mgmt_version") op <- "providers/Microsoft.Authorization/locks" cont <- api_func(op, api_version=api) lst <- lapply(get_paged_list(cont, token), function(parms) az_resource$new(token, subscription, deployed_properties=parms, api_version=api)) names(lst) <- sapply(lst, function(x) sub("^.+providers/(.+$)", "\\1", x$id)) lst }
/scratch/gouwar.j/cran-all/cranData/AzureRMR/R/locks.R
make_graph_login_from_token <- function(token, azure_host, graph_host) { if(is_empty(graph_host)) return() message("Also creating Microsoft Graph login for ", format_tenant(token$tenant)) newtoken <- token$clone() if(is_azure_v1_token(newtoken)) newtoken$resource <- graph_host else newtoken$scope <- c(paste0(graph_host, ".default"), "openid", "offline_access") newtoken$refresh() res <- try(AzureGraph::create_graph_login(tenant=token$tenant, token=newtoken)) if(inherits(res, "try-error")) warning("Unable to create Microsoft Graph login", call.=FALSE) }
/scratch/gouwar.j/cran-all/cranData/AzureRMR/R/make_graph_login.R
#' Manage parallel Azure connections #' #' @param size For `init_pool`, the number of background R processes to create. Limit this is you are low on memory. #' @param restart For `init_pool`, whether to terminate an already running pool first. #' @param ... Other arguments passed on to functions in the parallel package. See below. #' #' @details #' AzureRMR provides the ability to parallelise communicating with Azure by utilizing a pool of R processes in the background. This often leads to major speedups in scenarios like downloading large numbers of small files, or working with a cluster of virtual machines. This functionality is intended for use by packages that extend AzureRMR (and was originally implemented as part of the AzureStor package), but can also be called directly by the end-user. #' #' A small API consisting of the following functions is currently provided for managing the pool. They pass their arguments down to the corresponding functions in the parallel package. #' - `init_pool` initialises the pool, creating it if necessary. The pool is created by calling `parallel::makeCluster` with the pool size and any additional arguments. If `init_pool` is called and the current pool is smaller than `size`, it is resized. #' - `delete_pool` shuts down the background processes and deletes the pool. #' - `pool_exists` checks for the existence of the pool, returning a TRUE/FALSE value. #' - `pool_size` returns the size of the pool, or zero if the pool does not exist. #' - `pool_export` exports variables to the pool nodes. It calls `parallel::clusterExport` with the given arguments. #' - `pool_lapply`, `pool_sapply` and `pool_map` carry out work on the pool. They call `parallel::parLapply`, `parallel::parSapply` and `parallel::clusterMap` with the given arguments. #' - `pool_call` and `pool_evalq` execute code on the pool nodes. They call `parallel::clusterCall` and `parallel::clusterEvalQ` with the given arguments. #' #' The pool is persistent for the session or until terminated by `delete_pool`. You should initialise the pool by calling `init_pool` before running any code on it. This restores the original state of the pool nodes by removing any objects that may be in memory, and resetting the working directory to the master working directory. #' #' @seealso #' [parallel::makeCluster], [parallel::clusterCall], [parallel::parLapply] #' @examples #' \dontrun{ #' #' init_pool() #' #' pool_size() #' #' x <- 42 #' pool_export("x") #' pool_sapply(1:5, function(i) i + x) #' #' init_pool() #' # error: x no longer exists on nodes #' try(pool_sapply(1:5, function(i) i + x)) #' #' delete_pool() #' #' } #' @rdname pool #' @export init_pool <- function(size=10, restart=FALSE, ...) { if(restart || !pool_exists() || pool_size() < size) { delete_pool() message("Creating background pool") .AzureR$pool <- parallel::makeCluster(size, ...) pool_evalq(loadNamespace("AzureRMR")) } else { # restore original state, set working directory to master working directory pool_call(function(wd) { setwd(wd) rm(list=ls(envir=.GlobalEnv, all.names=TRUE), envir=.GlobalEnv) }, wd=getwd()) } invisible(NULL) } #' @rdname pool #' @export delete_pool <- function() { if(!pool_exists()) return(invisible(NULL)) message("Deleting background pool") parallel::stopCluster(.AzureR$pool) rm(pool, envir=.AzureR) } #' @rdname pool #' @export pool_exists <- function() { exists("pool", envir=.AzureR) && inherits(.AzureR$pool, "cluster") } #' @rdname pool #' @export pool_size <- function() { if(!pool_exists()) return(0) length(.AzureR$pool) } #' @rdname pool #' @export pool_export <- function(...) { pool_check() parallel::clusterExport(cl=.AzureR$pool, ...) } #' @rdname pool #' @export pool_lapply <- function(...) { pool_check() parallel::parLapply(cl=.AzureR$pool, ...) } #' @rdname pool #' @export pool_sapply <- function(...) { pool_check() parallel::parSapply(cl=.AzureR$pool, ...) } #' @rdname pool #' @export pool_map <- function(...) { pool_check() parallel::clusterMap(cl=.AzureR$pool, ...) } #' @rdname pool #' @export pool_call <- function(...) { pool_check() parallel::clusterCall(cl=.AzureR$pool, ...) } #' @rdname pool #' @export pool_evalq <- function(...) { pool_check() parallel::clusterEvalQ(cl=.AzureR$pool, ...) } .AzureR <- new.env() pool_check <- function() { if(!pool_exists()) stop("AzureR pool does not exist; call init_pool() to create it", call.=FALSE) }
/scratch/gouwar.j/cran-all/cranData/AzureRMR/R/pool.R
#' Role-based access control (RBAC) #' #' Basic methods for RBAC: manage role assignments and retrieve role definitions. These are methods for the `az_subscription`, `az_resource_group` and `az_resource` classes. #' #' @section Usage: #' ``` #' add_role_assignment(principal, role, scope = NULL) #' #' get_role_assignment(id) #' #' remove_role_assignment(id, confirm = TRUE) #' #' list_role_assignments(filter = "atScope()", as_data_frame = TRUE) #' #' get_role_definition(id) #' #' list_role_definitions(filter=NULL, as_data_frame = TRUE) #' ``` #' @section Arguments: #' - `principal`: For `add_role_assignment`, the principal for which to assign a role. This can be a GUID, or an object of class `az_user`, `az_app` or `az_storage_principal` (from the AzureGraph package). #' - `role`: For `add_role_assignment`, the role to assign the principal. This can be a GUID, a string giving the role name (eg "Contributor"), or an object of class `[az_role_definition]`. #' - `scope`: For `add_role_assignment`, an optional scope for the assignment. #' - `id`: A role ID. For `get_role_assignment` and `remove_role_assignment`, this is a role assignment GUID. For `get_role_definition`, this can be a role definition GUID or a role name. #' - `confirm`: For `remove_role_assignment`, whether to ask for confirmation before removing the role assignment. #' - `filter`: For `list_role_assignments` and `list_role_definitions`, an optional filter condition to limit the returned roles. #' - `as_data_frame`: For `list_role_assignments` and `list_role_definitions`, whether to return a data frame or a list of objects. See 'Value' below. #' #' @section Details: #' AzureRMR implements a subset of the full RBAC functionality within Azure Active Directory. You can retrieve role definitions and add and remove role assignments, at the subscription, resource group and resource levels. #' #' @section Value: #' The `add_role_assignment` and `get_role_assignment` methods return an object of class `az_role_assignment`. This is a simple R6 class, with one method: `remove` to remove the assignment. #' #' The `list_role_assignments` method returns a list of `az_role_assignment` objects if the `as_data_frame` argument is FALSE. If this is TRUE, it instead returns a data frame containing the most broadly useful fields for each assigned role: the role assignment ID, the principal, and the role name. #' #' The `get_role_definition` method returns an object of class `az_role_definition`. This is a plain-old-data R6 class (no methods), which can be used as input for creating role assignments (see the examples below). #' #' The `list_role_definitions` method returns a list of `az_role_definition` if the `as_data_frame` argument is FALSE. If this is TRUE, it instead returns a data frame containing the most broadly useful fields for each role definition: the definition ID and role name. #' #' @seealso #' [az_rm], [az_role_definition], [az_role_assignment] #' #' [Overview of role-based access control](https://learn.microsoft.com/en-us/azure/role-based-access-control/overview) #' #' @examples #' \dontrun{ #' #' az <- get_azure_login("myaadtenant") #' sub <- az$get_subscription("subscription_id") #' rg <- sub$get_resource_group("rgname") #' res <- rg$get_resource(type="provider_type", name="resname") #' #' sub$list_role_definitions() #' sub$list_role_assignments() #' sub$get_role_definition("Contributor") #' #' # get an app using the AzureGraph package #' app <- get_graph_login("myaadtenant")$get_app("app_id") #' #' # subscription level #' asn1 <- sub$add_role_assignment(app, "Reader") #' #' # resource group level #' asn2 <- rg$add_role_assignment(app, "Contributor") #' #' # resource level #' asn3 <- res$add_role_assignment(app, "Owner") #' #' res$remove_role_assignment(asn3$id) #' rg$remove_role_assignment(asn2$id) #' sub$remove_role_assignment(asn1$id) #' #' } #' #' @aliases rbac add_role_assignment get_role_assignment remove_role_assignment list_role_assignments #' get_role_definition list_role_definitions #' @rdname rbac #' @name rbac NULL ## subscription methods az_subscription$set("public", "add_role_assignment", overwrite=TRUE, function(principal, role, scope=NULL) { if(!is_role_definition(role)) role <- self$get_role_definition(role) add_role_assignment(principal, role, scope, private$sub_op) }) az_subscription$set("public", "get_role_assignment", overwrite=TRUE, function(id) { get_role_assignment(id, self$list_role_definitions(), private$sub_op) }) az_subscription$set("public", "remove_role_assignment", overwrite=TRUE, function(id, confirm=TRUE) { remove_role_assignment(id, confirm, private$sub_op) }) az_subscription$set("public", "list_role_assignments", overwrite=TRUE, function(filter="atScope()", as_data_frame=TRUE) { list_role_assignments(filter, as_data_frame, self$list_role_definitions(), private$sub_op) }) az_subscription$set("public", "get_role_definition", overwrite=TRUE, function(id) { get_role_definition(id, private$sub_op) }) az_subscription$set("public", "list_role_definitions", overwrite=TRUE, function(filter=NULL, as_data_frame=TRUE) { list_role_definitions(filter, as_data_frame, private$sub_op) }) ## resource group methods az_resource_group$set("public", "add_role_assignment", overwrite=TRUE, function(principal, role, scope=NULL) { if(!is_role_definition(role)) role <- self$get_role_definition(role) add_role_assignment(principal, role, scope, private$rg_op) }) az_resource_group$set("public", "get_role_assignment", overwrite=TRUE, function(id) { get_role_assignment(id, self$list_role_definitions(), private$rg_op) }) az_resource_group$set("public", "remove_role_assignment", overwrite=TRUE, function(id, confirm=TRUE) { remove_role_assignment(id, confirm, private$rg_op) }) az_resource_group$set("public", "list_role_assignments", overwrite=TRUE, function(filter="atScope()", as_data_frame=TRUE) { list_role_assignments(filter, as_data_frame, self$list_role_definitions(), private$rg_op) }) az_resource_group$set("public", "get_role_definition", overwrite=TRUE, function(id) { get_role_definition(id, private$rg_op) }) az_resource_group$set("public", "list_role_definitions", overwrite=TRUE, function(filter=NULL, as_data_frame=TRUE) { list_role_definitions(filter, as_data_frame, private$rg_op) }) ## resource methods az_resource$set("public", "add_role_assignment", overwrite=TRUE, function(principal, role, scope=NULL) { if(!is_role_definition(role)) role <- self$get_role_definition(role) add_role_assignment(principal, role, scope, private$res_op) }) az_resource$set("public", "get_role_assignment", overwrite=TRUE, function(id) { get_role_assignment(id, self$list_role_definitions(), private$res_op) }) az_resource$set("public", "remove_role_assignment", overwrite=TRUE, function(id, confirm=TRUE) { remove_role_assignment(id, confirm, private$res_op) }) az_resource$set("public", "list_role_assignments", overwrite=TRUE, function(filter="atScope()", as_data_frame=TRUE) { list_role_assignments(filter, as_data_frame, self$list_role_definitions(), private$res_op) }) az_resource$set("public", "get_role_definition", overwrite=TRUE, function(id) { get_role_definition(id, private$res_op) }) az_resource$set("public", "list_role_definitions", overwrite=TRUE, function(filter=NULL, as_data_frame=TRUE) { list_role_definitions(filter, as_data_frame, private$res_op) }) ## implementations add_role_assignment <- function(principal, role, scope, api_func) { # obtain object ID from a service principal or registered app if(inherits(principal, c("az_service_principal", "az_user"))) principal <- principal$properties$id else if(inherits(principal, "az_app")) principal <- principal$get_service_principal()$properties$id token <- environment(api_func)$self$token op <- file.path("providers/Microsoft.Authorization/roleAssignments", uuid::UUIDgenerate()) body <- list( properties=list( roleDefinitionId=role$id, principalId=principal ) ) if(!is.null(scope)) body$properties$scope <- scope res <- api_func(op, body=body, encode="json", api_version=getOption("azure_roleasn_api_version"), http_verb="PUT") az_role_assignment$new(token, res, role$properties$roleName, api_func) } get_role_assignment <- function(id, defs, api_func) { token <- environment(api_func)$self$token op <- file.path("providers/Microsoft.Authorization/roleAssignments", id) res <- api_func(op, api_version=getOption("azure_roleasn_api_version")) role_name <- defs$name[defs$definition_id == basename(res$properties$roleDefinitionId)] az_role_assignment$new(token, res, role_name, api_func) } remove_role_assignment <- function(id, confirm, api_func) { token <- environment(api_func)$self$token # pass minimal list of parameters to init, rather than making useless API calls res <- list(name=basename(id)) az_role_assignment$new(token, res, api_func=api_func)$remove(confirm=confirm) } list_role_assignments <- function(filter, as_data_frame, defs, api_func) { token <- environment(api_func)$self$token op <- "providers/Microsoft.Authorization/roleAssignments" lst <- api_func(op, options=list(`$filter`=filter), api_version=getOption("azure_roleasn_api_version")) if(as_data_frame) { lst <- lapply(lst$value, function(res) { role_name <- defs$name[defs$definition_id == basename(res$properties$roleDefinitionId)] data.frame(assignment_id=res$name, principal=res$properties$principalId, role=role_name, stringsAsFactors=FALSE) }) do.call(rbind, lst) } else lapply(lst$value, function(res) { role_name <- defs$name[defs$definition_id == basename(res$properties$roleDefinitionId)] az_role_assignment$new(token, res, role_name, api_func) }) } get_role_definition <- function(id, api_func) { # if text rolename supplied, use it to filter the list of roles if(!is_guid(id)) { op <- "providers/Microsoft.Authorization/roleDefinitions" filter <- sprintf("roleName eq '%s'", id) lst <- api_func(op, options=list(`$filter`=filter), api_version=getOption("azure_roledef_api_version")) if(is_empty(lst$value)) stop("Role definition not found", call.=FALSE) return(az_role_definition$new(lst$value[[1]])) } op <- file.path("providers/Microsoft.Authorization/roleDefinitions", id) res <- api_func(op, api_version=getOption("azure_roledef_api_version")) az_role_definition$new(res) } list_role_definitions <- function(filter, as_data_frame, api_func) { op <- "providers/Microsoft.Authorization/roleDefinitions" lst <- api_func(op, options=list(`$filter`=filter), api_version=getOption("azure_roledef_api_version")) if(as_data_frame) { lst <- lapply(lst$value, function(res) data.frame(definition_id=res$name, name=res$properties$roleName, stringsAsFactors=FALSE)) do.call(rbind, lst) } else { lst <- lapply(lst$value, function(res) az_role_definition$new(res)) names(lst) <- sapply(lst, function(res) res$properties$roleName) lst } }
/scratch/gouwar.j/cran-all/cranData/AzureRMR/R/rbac.R
#' @export AzureAuth::clean_token_directory #' @export AzureAuth::delete_azure_token #' @export AzureAuth::get_azure_token #' @export AzureAuth::is_azure_token #' @export AzureAuth::is_azure_v1_token #' @export AzureAuth::is_azure_v1_token #' @export AzureAuth::is_guid #' @export AzureAuth::list_azure_tokens #' @export AzureAuth::AzureR_dir
/scratch/gouwar.j/cran-all/cranData/AzureRMR/R/reexport_AzureAuth.R
#' Miscellaneous utility functions #' #' @param lst A named list of objects. #' @param x For `is_url`, An R object. #' @param https_only For `is_url`, whether to allow only HTTPS URLs. #' @param token For `get_paged_list`, an Azure OAuth token, of class [AzureToken]. #' @param next_link_name,value_name For `get_paged_list`, the names of the next link and value components in the `lst` argument. The default values are correct for Resource Manager. #' #' @details #' `get_paged_list` reconstructs a complete list of objects from a paged response. Many Resource Manager list operations will return _paged_ output, that is, the response contains a subset of all items, along with a URL to query to retrieve the next subset. `get_paged_list` retrieves each subset and returns all items in a single list. #' #' @return #' For `get_paged_list`, a list. #' #' For `is_url`, whether the object appears to be a URL (is character of length 1, and starts with the string `"http"`). Optionally, restricts the check to HTTPS URLs only. #' #' @rdname utils #' @export is_url <- function(x, https_only=FALSE) { pat <- if(https_only) "^https://" else "^https?://" is.character(x) && length(x) == 1 && grepl(pat, x) } # combine several pages of objects into a single list #' @rdname utils #' @export get_paged_list <- function(lst, token, next_link_name="nextLink", value_name="value") { res <- lst[[value_name]] while(!is_empty(lst[[next_link_name]])) { lst <- call_azure_url(token, lst[[next_link_name]]) res <- c(res, lst[[value_name]]) } res } # check that 1) all required names are present; 2) optional names may be present; 3) no other names are present # validate_object_names <- function(x, required, optional=character(0)) # { # valid <- all(required %in% x) && all(x %in% c(required, optional)) # if(!valid) # stop("Invalid object names") # } # handle different behaviour of file_path on Windows/Linux wrt trailing / construct_path <- function(...) { sub("/$", "", file.path(..., fsep="/")) } # TRUE if delete confirmed, FALSE otherwise delete_confirmed <- function(confirm, name, type, quote_name=TRUE) { if(!interactive() || !confirm) return(TRUE) msg <- if(quote_name) sprintf("Do you really want to delete the %s '%s'?", type, name) else sprintf("Do you really want to delete the %s %s?", type, name) ok <- if(getRversion() < numeric_version("3.5.0")) { msg <- paste(msg, "(yes/No/cancel) ") yn <- readline(msg) if(nchar(yn) == 0) FALSE else tolower(substr(yn, 1, 1)) == "y" } else utils::askYesNo(msg, FALSE) isTRUE(ok) } # add a tag on objects created by this package add_creator_tag <- function(tags) { if(!is.list(tags)) tags <- list() utils::modifyList(list(createdBy="AzureR/AzureRMR"), tags) }
/scratch/gouwar.j/cran-all/cranData/AzureRMR/R/utils.R
--- title: "Authentication basics" author: Hong Ooi output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Authentication} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{utf8} --- There are a number of ways to authenticate to the Azure Resource Manager API with AzureRMR. This vignette goes through the most common scenarios. ## Interactive authentication This is the scenario where you're using R interactively, such as in your local desktop or laptop, or in a hosted RStudio Server, Jupyter notebook or ssh session. The first time you authenticate with AzureRMR, you run `create_azure_login()`: ```r # on first use library(AzureRMR) az <- create_azure_login() ``` Notice that you _don't_ enter your username and password. AzureRMR will attempt to detect which authentication flow to use, based on your session details. In most cases, it will bring up the Azure Active Directory (AAD) login page in your browser, which is where you enter your user credentials. This is also known as the "authorization code" flow. There are some complications to be aware of: - If you are running R in a hosted session, trying to start a browser will usually fail. In this case, specify the device code authentication flow, with the `auth_type` argument: ```r az <- create_azure_login(auth_type="device_code") ``` - If you have a personal account that is also a guest in an organisational tenant, you may have to specify your tenant explicitly: ```r az <- create_azure_login(tenant="yourtenant") ``` - By default, AzureRMR identifies itself using the Azure CLI app registration ID. You can also supply your own app ID if you have one, for example if you want to restrict access to a specific subscription or resource group. See "Creating a custom app registration" below for more information. ```r az <- create_azure_login(app="yourappid") ``` All of the above arguments can be combined, eg this will authenticate using the device code flow, with an explicit tenant name, and a custom app ID: ```r az <- create_azure_login(tenant="yourtenant", app="yourappid", auth_type="device_code") ``` If needed, you can also supply other arguments that will be passed to `AzureAuth::get_azure_token()`. Having created the login, in subsequent sessions you run `get_azure_login()`. This will load your previous authentication details, saving you from having to login again. If you specified the tenant in the `create_azure_login()` call, you'll also need to specify it for `get_azure_login()`; the other arguments don't have to be repeated. ```r az <- get_azure_login() # if you specified the tenant in create_azure_login az <- get_azure_login(tenant="yourtenant") ``` ## Non-interactive authentication This is the scenario where you want to use AzureRMR as part of an automated script or unattended session, for example in a deployment pipeline. The appropriate authentication flow in this case is the client credentials flow. For this scenario, you must have a custom app ID and client secret. On the client side, these are supplied in the `app` and `password` arguments. You must also specify your tenant as AAD won't be able to detect it from a user's credentials. ```r az <- create_azure_login(tenant="yourtenant", app="yourccappid", password="client_secret") ``` In the non-interactive scenario, you don't use `get_azure_login()`; instead, you simply call `create_azure_login()` as part of your script. ## Creating a custom app registration This part is meant mostly for Azure tenant administrators, or users who have the appropriate rights to create AAD app registrations. You can create your own app registration to authenticate with, if the default Azure CLI app ID is insufficient. In particular, you'll need a custom app ID if you are using AzureRMR in a non-interactive session. If security is a concern, a custom app ID also lets you restrict the scope of the resources that AzureRMR that manipulate. You can create a new app registration using any of the usual methods. For example to create an app registration in the Azure Portal (`https://portal.azure.com/`), click on "Azure Active Directory" in the menu bar down the left, go to "App registrations" and click on "New registration". Name the app something suitable, eg "AzureRMR custom app". - If you want your users to be able to login with the authorization code flow, you must add a **public client/native redirect URI** of `http://localhost:1410`. This is appropriate if your users will be running R on their local PCs, with an Internet browser available. - If you want your users to be able to login with the device code flow, you must **enable the "Allow public client flows" setting** for your app. In the Portal, you can find this setting in the "Authentication" pane once the app registration is complete. This is appropriate if your users are running R in a remote session. - If the app is meant for non-interactive use, you must give the app a **client secret**, which is much the same as a password (and should similarly be kept secure). In the Portal, you can set this in the "Certificates and Secrets" pane for your app registration. Once the app registration has been created, note the app ID and, if applicable, the client secret. The latter can't be viewed after app creation, so make sure you note its value now. It's also possible to authenticate with a **client certificate (public key)**, but this is more complex and we won't go into it here. For more details, see the [Azure Active Directory documentation](https://learn.microsoft.com/en-au/azure/active-directory/develop/v2-oauth2-client-creds-grant-flow) and the [AzureAuth intro vignette](https://cran.r-project.org/package=AzureAuth/vignettes/token.html). ### Set the app role and scope You'll also need to set the role assignment and scope(s) for your app ID. The former determines the kinds of actions that AzureRMR can take; the latter determines which resources those action can be applied to. The main role assignments are - **Owner**: can manage all aspects of resources, including role assignments - **Contributor**: can modify, create and delete resources, but cannot modify role assignments - **Reader**: can view resources but not make changes It's generally recommended to use the most restrictive role assignment that still lets you carry out your tasks. In the Portal, you can set the role assignment for your app ID by going to a specific subscription/resource group/resource and clicking on "Access Control (IAM)". Role assignments for subscriptions and resource groups will propagate to objects further down in the hierarchy. Any resources that don't have a role for your app will not be accessible.
/scratch/gouwar.j/cran-all/cranData/AzureRMR/inst/doc/auth.Rmd
## ---- eval=FALSE-------------------------------------------------------------- # az_storage <- R6::R6Class("az_storage", inherit=AzureRMR::az_resource, # # public=list( # # list_keys=function() # { # keys <- named_list(private$res_op("listKeys", http_verb="POST")$keys, "keyName") # sapply(keys, `[[`, "value") # }, # # get_blob_endpoint=function(key=self$list_keys()[1], sas=NULL) # { # blob_endpoint(self$properties$primaryEndpoints$blob, key=key, sas=sas) # }, # # get_file_endpoint=function(key=self$list_keys()[1], sas=NULL) # { # file_endpoint(self$properties$primaryEndpoints$file, key=key, sas=sas) # } # )) ## ---- eval=FALSE-------------------------------------------------------------- # az_vm_template <- R6::R6Class("az_vm_template", inherit=AzureRMR::az_template, # # public=list( # disks=NULL, # status=NULL, # ip_address=NULL, # dns_name=NULL, # clust_size=NULL, # # initialize=function(token, subscription, resource_group, name, ...) # { # super$initialize(token, subscription, resource_group, name, ...) # # # fill in fields that don't require querying the host # num_instances <- self$properties$outputs$numInstances # if(is_empty(num_instances)) # { # self$clust_size <- 1 # vmnames <- self$name # } # else # { # self$clust_size <- as.numeric(num_instances$value) # vmnames <- paste0(self$name, seq_len(self$clust_size) - 1) # } # # private$vm <- sapply(vmnames, function(name) # { # az_vm_resource$new(self$token, self$subscription, self$resource_group, # type="Microsoft.Compute/virtualMachines", name=name) # }, simplify=FALSE) # # # get the hostname/IP address for the VM # outputs <- unlist(self$properties$outputResources) # ip_id <- grep("publicIPAddresses/.+$", outputs, ignore.case=TRUE, value=TRUE) # ip <- lapply(ip_id, function(id) # az_resource$new(self$token, self$subscription, id=id)$properties) # # self$ip_address <- sapply(ip, function(x) x$ipAddress) # self$dns_name <- sapply(ip, function(x) x$dnsSettings$fqdn) # # lapply(private$vm, function(obj) obj$sync_vm_status()) # self$disks <- lapply(private$vm, "[[", "disks") # self$status <- lapply(private$vm, "[[", "status") # # NULL # } # # # ... other VM-specific methods ... # ), # # private=list( # # will store a list of VM objects after initialisation # vm=NULL # # # ... other private members ... # ) # )) ## ---- eval=FALSE-------------------------------------------------------------- # res <- az_rm$new("tenant_id", "app_id", "secret") $ # get_subscription("subscription_id") $ # get_resource_group("resgroup") $ # get_my_resource("myresource") ## ---- eval=FALSE-------------------------------------------------------------- # # # all methods adding methods to classes in external package must go in .onLoad # .onLoad <- function(libname, pkgname) # { # AzureRMR::az_resource_group$set("public", "create_storage_account", overwrite=TRUE, # function(name, location, # kind="Storage", # sku=list(name="Standard_LRS", tier="Standard"), # ...) # { # AzureStor::az_storage$new(self$token, self$subscription, self$name, # type="Microsoft.Storage/storageAccounts", name=name, location=location, # kind=kind, sku=sku, ...) # }) # # AzureRMR::az_resource_group$set("public", "get_storage_account", overwrite=TRUE, # function(name) # { # AzureStor::az_storage$new(self$token, self$subscription, self$name, # type="Microsoft.Storage/storageAccounts", name=name) # }) # # AzureRMR::az_resource_group$set("public", "delete_storage_account", overwrite=TRUE, # function(name, confirm=TRUE, wait=FALSE) # { # self$get_storage_account(name)$delete(confirm=confirm, wait=wait) # }) # # # ... other startup code ... # } ## ---- eval=FALSE-------------------------------------------------------------- # .onLoad <- function(libname, pkgname) # { # AzureRMR::az_resource_group$set("public", "create_vm_cluster", overwrite=TRUE, # function(name, location, # os=c("Windows", "Ubuntu"), size="Standard_DS3_v2", # username, passkey, userauth_type=c("password", "key"), # ext_file_uris=NULL, inst_command=NULL, # clust_size, template, parameters, # ..., wait=TRUE) # { # os <- match.arg(os) # userauth_type <- match.arg(userauth_type) # # if(missing(parameters) && (missing(username) || missing(passkey))) # stop("Must supply login username and password/private key", call.=FALSE) # # # find template given input args # if(missing(template)) # template <- get_dsvm_template(os, userauth_type, clust_size, # ext_file_uris, inst_command) # # # convert input args into parameter list for template # if(missing(parameters)) # parameters <- make_dsvm_param_list(name=name, size=size, # username=username, userauth_type=userauth_type, passkey=passkey, # ext_file_uris=ext_file_uris, inst_command=inst_command, # clust_size=clust_size, template=template) # # AzureVM::az_vm_template$new(self$token, self$subscription, self$name, name, # template=template, parameters=parameters, ..., wait=wait) # }) # # # ... other startup code ... # } ## ---- eval=FALSE-------------------------------------------------------------- # #' Get existing Azure resource type 'foo' # #' # #' Methods for the [AzureRMR::az_resource_group] and [AzureRMR::az_subscription] classes. # #' # #' @rdname get_foo # #' @name get_foo # #' @aliases get_foo list_foos # #' # #' @section Usage: # #' ``` # #' get_foo(name) # #' list_foos() # #' ``` # #' @section Arguments: # #' - `name`: For `get_foo()`, the name of the resource. # #' # #' @section Details: # #' The `AzureRMR::az_resource_group` class has both `get_foo()` and `list_foos()` methods, while the `AzureRMR::az_subscription` class only has the latter. # #' # #' @section Value: # #' For `get_foo()`, an object of class `az_foo` representing the foo resource. # #' # #' For `list_foos()`, a list of such objects. # #' # #' @seealso # #' [create_foo], [delete_foo], [az_foo] # NULL ## ---- eval=FALSE-------------------------------------------------------------- # # blob endpoint for a storage account # blob_endpoint <- function(endpoint, key=NULL, sas=NULL, api_version=getOption("azure_storage_api_version")) # { # if(!is_endpoint_url(endpoint, "blob")) # stop("Not a blob endpoint", call.=FALSE) # # obj <- list(url=endpoint, key=key, sas=sas, api_version=api_version) # class(obj) <- c("blob_endpoint", "storage_endpoint") # obj # } # # # # S3 generic and methods to create an object representing a blob container within an endpoint # blob_container <- function(endpoint, ...) # { # UseMethod("blob_container") # } # # blob_container.character <- function(endpoint, key=NULL, sas=NULL, # api_version=getOption("azure_storage_api_version")) # { # do.call(blob_container, generate_endpoint_container(endpoint, key, sas, api_version)) # } # # blob_container.blob_endpoint <- function(endpoint, name) # { # obj <- list(name=name, endpoint=endpoint) # class(obj) <- "blob_container" # obj # } # # # # download a file from a blob container # download_blob <- function(container, src, dest, overwrite=FALSE, lease=NULL) # { # headers <- list() # if(!is.null(lease)) # headers[["x-ms-lease-id"]] <- as.character(lease) # do_container_op(container, src, headers=headers, config=httr::write_disk(dest, overwrite)) # }
/scratch/gouwar.j/cran-all/cranData/AzureRMR/inst/doc/extend.R
--- title: "Extending AzureRMR" Author: Hong Ooi output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Extending AzureRMR} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{utf8} --- AzureRMR provides a generic framework for managing Azure resources. While you can use it as provided to work with any Azure service, you may also want to extend it to provide more features for a particular service. This vignette describes the process of doing so. We'll use examples from some of the other AzureR packages to show how this works. ## Subclass resource/template classes Create subclasses of `az_resource` and/or `az_template` to represent the resources used by this service. For example, the AzureStor package provides a new class, `az_storage`, that inherits from `az_resource`. This class represents a storage accounts and has new methods specific to storage, such as listing access keys, generating a shared access signature (SAS), and creating a client endpoint object. Here is a simplified version of the `az_storage` class. ```{r, eval=FALSE} az_storage <- R6::R6Class("az_storage", inherit=AzureRMR::az_resource, public=list( list_keys=function() { keys <- named_list(private$res_op("listKeys", http_verb="POST")$keys, "keyName") sapply(keys, `[[`, "value") }, get_blob_endpoint=function(key=self$list_keys()[1], sas=NULL) { blob_endpoint(self$properties$primaryEndpoints$blob, key=key, sas=sas) }, get_file_endpoint=function(key=self$list_keys()[1], sas=NULL) { file_endpoint(self$properties$primaryEndpoints$file, key=key, sas=sas) } )) ``` In most cases, you can rely on the default `az_resource$initialize` method to handle object construction. You can override this method if your resource class contains new data fields that have to be initialised. A more complex example of a custom class is the `az_vm_template` class in the AzureVM package. This represents the resources used by a virtual machine, or cluster of virtual machines, in Azure. The initialisation code not only handles the details of deploying or getting the template used to create the VM(s), but also retrieves the individual resource objects themselves. ```{r, eval=FALSE} az_vm_template <- R6::R6Class("az_vm_template", inherit=AzureRMR::az_template, public=list( disks=NULL, status=NULL, ip_address=NULL, dns_name=NULL, clust_size=NULL, initialize=function(token, subscription, resource_group, name, ...) { super$initialize(token, subscription, resource_group, name, ...) # fill in fields that don't require querying the host num_instances <- self$properties$outputs$numInstances if(is_empty(num_instances)) { self$clust_size <- 1 vmnames <- self$name } else { self$clust_size <- as.numeric(num_instances$value) vmnames <- paste0(self$name, seq_len(self$clust_size) - 1) } private$vm <- sapply(vmnames, function(name) { az_vm_resource$new(self$token, self$subscription, self$resource_group, type="Microsoft.Compute/virtualMachines", name=name) }, simplify=FALSE) # get the hostname/IP address for the VM outputs <- unlist(self$properties$outputResources) ip_id <- grep("publicIPAddresses/.+$", outputs, ignore.case=TRUE, value=TRUE) ip <- lapply(ip_id, function(id) az_resource$new(self$token, self$subscription, id=id)$properties) self$ip_address <- sapply(ip, function(x) x$ipAddress) self$dns_name <- sapply(ip, function(x) x$dnsSettings$fqdn) lapply(private$vm, function(obj) obj$sync_vm_status()) self$disks <- lapply(private$vm, "[[", "disks") self$status <- lapply(private$vm, "[[", "status") NULL } # ... other VM-specific methods ... ), private=list( # will store a list of VM objects after initialisation vm=NULL # ... other private members ... ) )) ``` ## Add accessor functions Once you've created your new class(es), you should add accessor functions to `az_resource_group` (and optionally `az_subscription` as well, if your service has subscription-level API calls) to create, get and delete resources. This allows the convenience of _method chaining_: ```{r, eval=FALSE} res <- az_rm$new("tenant_id", "app_id", "secret") $ get_subscription("subscription_id") $ get_resource_group("resgroup") $ get_my_resource("myresource") ``` Note that if you are writing a package that extends AzureRMR, these methods _must_ be defined in the package's `.onLoad` function. This is because the methods must be added at runtime, when the user loads your package, rather than at compile time, when it is built or installed. The `create_storage_account`, `get_storage_account` and `delete_storage_account` methods from the AzureStor package are defined like this. Note that calls to your class methods should include the `pkgname::` qualifier, to ensure they will work even if your package is not attached. ```{r, eval=FALSE} # all methods adding methods to classes in external package must go in .onLoad .onLoad <- function(libname, pkgname) { AzureRMR::az_resource_group$set("public", "create_storage_account", overwrite=TRUE, function(name, location, kind="Storage", sku=list(name="Standard_LRS", tier="Standard"), ...) { AzureStor::az_storage$new(self$token, self$subscription, self$name, type="Microsoft.Storage/storageAccounts", name=name, location=location, kind=kind, sku=sku, ...) }) AzureRMR::az_resource_group$set("public", "get_storage_account", overwrite=TRUE, function(name) { AzureStor::az_storage$new(self$token, self$subscription, self$name, type="Microsoft.Storage/storageAccounts", name=name) }) AzureRMR::az_resource_group$set("public", "delete_storage_account", overwrite=TRUE, function(name, confirm=TRUE, wait=FALSE) { self$get_storage_account(name)$delete(confirm=confirm, wait=wait) }) # ... other startup code ... } ``` The corresponding accessor functions for AzureVM's `az_vm_template` class are more complex, as might be imagined. Here is a fragment of that package's `onLoad` function showing the `az_resource_group$create_vm_cluster` method. ```{r, eval=FALSE} .onLoad <- function(libname, pkgname) { AzureRMR::az_resource_group$set("public", "create_vm_cluster", overwrite=TRUE, function(name, location, os=c("Windows", "Ubuntu"), size="Standard_DS3_v2", username, passkey, userauth_type=c("password", "key"), ext_file_uris=NULL, inst_command=NULL, clust_size, template, parameters, ..., wait=TRUE) { os <- match.arg(os) userauth_type <- match.arg(userauth_type) if(missing(parameters) && (missing(username) || missing(passkey))) stop("Must supply login username and password/private key", call.=FALSE) # find template given input args if(missing(template)) template <- get_dsvm_template(os, userauth_type, clust_size, ext_file_uris, inst_command) # convert input args into parameter list for template if(missing(parameters)) parameters <- make_dsvm_param_list(name=name, size=size, username=username, userauth_type=userauth_type, passkey=passkey, ext_file_uris=ext_file_uris, inst_command=inst_command, clust_size=clust_size, template=template) AzureVM::az_vm_template$new(self$token, self$subscription, self$name, name, template=template, parameters=parameters, ..., wait=wait) }) # ... other startup code ... } ``` ### Adding documentation Documenting methods added to a class in this way can be problematic. R's .Rd help format is designed around traditional functions, and R6 classes and methods are usually not a good fit. The popular Roxygen format also (as of October 2018) doesn't deal very well with R6 classes. The fact that we are adding methods to a class defined in an external package is an additional complication. Here is an example documentation skeleton in Roxygen format, copied from AzureStor. You can add this as a separate block in the source file where you define the accessor method(s). The block uses Markdown formatting, so you will need to have installed roxygen2 version 6.0.1 or later. ```{r, eval=FALSE} #' Get existing Azure resource type 'foo' #' #' Methods for the [AzureRMR::az_resource_group] and [AzureRMR::az_subscription] classes. #' #' @rdname get_foo #' @name get_foo #' @aliases get_foo list_foos #' #' @section Usage: #' ``` #' get_foo(name) #' list_foos() #' ``` #' @section Arguments: #' - `name`: For `get_foo()`, the name of the resource. #' #' @section Details: #' The `AzureRMR::az_resource_group` class has both `get_foo()` and `list_foos()` methods, while the `AzureRMR::az_subscription` class only has the latter. #' #' @section Value: #' For `get_foo()`, an object of class `az_foo` representing the foo resource. #' #' For `list_foos()`, a list of such objects. #' #' @seealso #' [create_foo], [delete_foo], [az_foo] NULL ``` We note the following: - The `@aliases` tag includes all the names that will bring up this page when using the `?` command, _including_ the default name. - Rather than using the standard `@usage`, `@param`, `@details` and `@return` tags, the block uses `@section` to create sections with the appropriate titles (including one named 'Arguments'). - The usage block is explicitly formatted as fixed-width using Markdown backticks. - The arguments are formatted as a (bulleted) list rather than the usual table format for function arguments. These changes are necessary because what we're technically documenting is not a standalone function, but a method inside a class. The `@usage`, `@param` tags et al only apply to functions, and if you use them here, `R CMD check` will generate a warning when it can't find a function with the given name. This can be important if you want to publish your package on CRAN. ## Add client-facing interface The AzureRMR class framework allows you to work with resources at the _Azure_ level, via Azure Resource Manager. If a service exposes a _client_ endpoint that is independent of ARM, you may also want to create a separate R interface for the endpoint. As the client interface is independent of the ARM interface, you have flexibility to tailor its design. For example, rather than using R6, the AzureStor package uses S3 classes to represent storage endpoints and individual containers and shares within an endpoint. It further defines (S3) methods for these classes to perform common operations like listing directories, uploading and downloading files, and so on. This is consistent with most other data access and manipulation packages in R, which usually stick to S3. ```{r, eval=FALSE} # blob endpoint for a storage account blob_endpoint <- function(endpoint, key=NULL, sas=NULL, api_version=getOption("azure_storage_api_version")) { if(!is_endpoint_url(endpoint, "blob")) stop("Not a blob endpoint", call.=FALSE) obj <- list(url=endpoint, key=key, sas=sas, api_version=api_version) class(obj) <- c("blob_endpoint", "storage_endpoint") obj } # S3 generic and methods to create an object representing a blob container within an endpoint blob_container <- function(endpoint, ...) { UseMethod("blob_container") } blob_container.character <- function(endpoint, key=NULL, sas=NULL, api_version=getOption("azure_storage_api_version")) { do.call(blob_container, generate_endpoint_container(endpoint, key, sas, api_version)) } blob_container.blob_endpoint <- function(endpoint, name) { obj <- list(name=name, endpoint=endpoint) class(obj) <- "blob_container" obj } # download a file from a blob container download_blob <- function(container, src, dest, overwrite=FALSE, lease=NULL) { headers <- list() if(!is.null(lease)) headers[["x-ms-lease-id"]] <- as.character(lease) do_container_op(container, src, headers=headers, config=httr::write_disk(dest, overwrite)) } ```
/scratch/gouwar.j/cran-all/cranData/AzureRMR/inst/doc/extend.Rmd
--- title: "Introduction to AzureRMR" author: Hong Ooi output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Introduction to AzureRMR} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{utf8} --- AzureRMR is a package for interacting with Azure Resource Manager: authenticate, list subscriptions, manage resource groups, deploy and delete templates and resources. It calls the Resource Manager [REST API](https://learn.microsoft.com/en-us/rest/api/resources) directly, so you don't need to have PowerShell or Python installed. As a general-purpose interface to Azure Resource Manager (ARM), you can use AzureRMR to work with nearly any Azure object that ARM can handle: subscriptions, resource groups, resources, templates and so on. The things you can do include: - Create a new resource - Carry out arbitrary operations on a resource - Delete a resource - Deploy a template - Delete a template, and, optionally, any resources that it created - Create and delete resource groups (if you gave your service principal subscription-level access) ## Authentication Under the hood, AzureRMR uses a similar authentication process to the [Azure CLI](https://learn.microsoft.com/en-us/cli/azure/?view=azure-cli-latest). The first time you authenticate with a given Azure Active Directory tenant, you call `create_azure_login()`, which will log you into Azure. R will prompt you for permission to create a special data directory in which to save your credentials. Once this information is saved on your machine, it can be retrieved in subsequent R sessions with `get_azure_login()`. Your credentials will be automatically refreshed so you don't have to reauthenticate. Unless you have a good reason otherwise, you should allow this caching directory to be created. Note that many other cloud engineering tools save credentials in this way, including the Azure CLI itself. You can see the location of the caching directory with the function `AzureR_dir()`. ```r library(AzureRMR) #> The AzureR packages can save your authentication credentials in the directory: #> #> C:\Users\hongooi\AppData\Local\AzureR #> #> This saves you having to reauthenticate with Azure in future sessions. Create this directory? (Y/n) y AzureR_dir() #> [1] "C:\\Users\\hongooi\\AppData\\Local\\AzureR" # if this is the first time you're logging in az <- create_azure_login() #> Creating Azure Resource Manager login for default tenant #> Waiting for authentication in browser... #> Press Esc/Ctrl + C to abort #> Authentication complete. # for subsequent sessions az <- get_azure_login() #> Loading Azure Resource Manager login for default tenant # you can also list the tenants that you've previously authenticated with list_azure_logins() ``` See the "Authentication basics" vignette for more details on how to authenticate with AzureRMR. ## Subscriptions and resource groups AzureRMR allows you to work with your subscriptions and resource groups. Note that if you created your service principal via the cloud shell, as described in this vignette, you probably only have access to one subscription. Regardless, you can list all subscriptions that you can work with: ```r # all subscriptions az$list_subscriptions() #> $`5710aa44-281f-49fe-bfa6-69e66bb55b11` #> <Azure subscription 5710aa44-281f-49fe-bfa6-69e66bb55b11> #> authorization_source: RoleBased #> name: Visual Studio Ultimate with MSDN #> policies: list(locationPlacementId, quotaId, spendingLimit) #> state: Enabled #> --- #> Methods: #> create_resource_group, delete_resource_group, get_provider_api_version, get_resource_group, #> list_locations, list_resource_groups, list_resources #> #> $`e26f4a80-370f-4a77-88df-5a8d291cd2f9` #> <Azure subscription e26f4a80-370f-4a77-88df-5a8d291cd2f9> #> authorization_source: RoleBased #> name: ADLTrainingMS #> policies: list(locationPlacementId, quotaId, spendingLimit) #> state: Enabled #> --- #> Methods: #> create_resource_group, delete_resource_group, get_provider_api_version, get_resource_group, #> list_locations, list_resource_groups, list_resources #> #> ... ``` Notice that AzureRMR is based on R6 classes, where methods are part of the object itself (much like objects in C++, C# and Java). Thus `list_subscriptions` is a member of the `az` object, and we call it with `az$list_subscriptions()`. R6 is used because it allows objects to have persistent state; in this case, the objects in R represent corresponding objects in Azure. The `list_subscriptions()` call returns a list of subscription objects. You can retrieve the details for a single subscription with `get_subscription`: ```r # get a subscription (sub1 <- az$get_subscription("5710aa44-281f-49fe-bfa6-69e66bb55b11")) #> <Azure subscription 5710aa44-281f-49fe-bfa6-69e66bb55b11> #> authorization_source: Legacy #> name: Visual Studio Ultimate with MSDN #> policies: list(locationPlacementId, quotaId, spendingLimit) #> state: Enabled #> --- #> Methods: #> create_resource_group, delete_resource_group, get_provider_api_version, get_resource_group, #> list_locations, list_resource_groups, list_resources ``` A subscription object in turn has methods to get, create and delete resource groups (and also list all resource groups): ```r (rg <- sub1$get_resource_group("rdev1")) #> <Azure resource group rdev1> #> id: /subscriptions/5710aa44-281f-49fe-bfa6-69e66bb55b11/resourceGroups/rdev1 #> location: australiaeast #> properties: list(provisioningState) #> --- #> Methods: #> check, create_resource, delete, delete_resource, delete_template, deploy_template, get_resource, #> get_template, list_resources, list_templates # create and delete a resource group test <- sub1$create_resource_group("test_group") test$delete(confirm=FALSE) ``` ## Resources and templates Methods for working with resources and templates are exposed as part of the `az_resource_group` class. You can retrieve an existing resource/template, create a new one, or delete an existing one. Below is a short introduction to resources; for templates, see the "Working with templates" vignette. ```r (stor <- rg$get_resource(type="Microsoft.Storage/storageServices", name="rdevstor1")) #> <Azure resource Microsoft.Storage/storageAccounts/rdevstor1> #> id: /subscriptions/5710aa44-281f-49fe-bfa6-69e66bb55b11/resourceGroups/rdev1/providers/Microsoft.Sto ... #> is_synced: TRUE #> kind: Storage #> location: australiasoutheast #> properties: list(networkAcls, trustedDirectories, supportsHttpsTrafficOnly, encryption, #> provisioningState, creationTime, primaryEndpoints, primaryLocation, statusOfPrimary) #> sku: list(name, tier) #> tags: list() #> --- #> Methods: #> check, delete, do_operation, set_api_version, sync_fields, update ``` One benefit of the syntax that AzureRMR uses is that _method chaining_ works. This is the OOP version of pipelines, which most R users will recognise from the tidyverse. ```r # use method chaining to get a resource without creating a bunch of intermediaries # same result as above stor <- az$ get_subscription("5710aa44-281f-49fe-bfa6-69e66bb55b11")$ get_resource_group("rdev1")$ get_resource(type="Microsoft.Storage/storageServices", name="rdevstor1") ``` Once we have a resource, we can do _things_ with it, via the `do_operation()` method. In this case, we have a storage account. One of the things we can do with a storage account is retrieve its access keys: ```r stor$do_operation("listKeys", http_verb="POST") #> $`keys` #> $`keys`[[1]] #> $`keys`[[1]]$`keyName` #> [1] "key1" #> #> $`keys`[[1]]$value #> [1] "k0gGFi8LirKcDNe73fzwDzhZ2+4oRKzvz+6+Pfn2ZCKO/JLnpyBSpVO7btLxBXQj+j8MZatDTGZ2NXUItye/vA==" #> #> $`keys`[[1]]$permissions #> [1] "FULL" #> ... ``` Here is another example. If we have a virtual machine, we can start it, execute shell commands, and then shut it down again: ```r vm <- rg$get_resource(type="Microsoft.Compute/virtualMachines", name="myVirtualMachine") vm$do_operation("start", http_verb="POST") # may take a while vm$do_operation("runCommand", body=list( commandId="RunShellScript", # RunPowerShellScript for Windows script=as.list("ifconfig > /tmp/ifconfig.out") ), encode="json", http_verb="POST") vm$do_operation("powerOff", http_verb="POST") ``` For the types of operations you can carry out on a resource, consult the [Azure REST API documentation](https://learn.microsoft.com/en-us/rest/api/?view=Azure). You can also interrogate the fields of a resource object; in particular the `properties` field can contain arbitrary information about an Azure resource. For example, a storage account's properties includes the endpoint URIs, and a virtual machine's properties includes its admin login details. ```r # file and blob storage endpoint stor$properties$primaryEndpoints$file stor$properties$primaryEndpoints$blob # OS profile for a VM: includes login details vm$properties$osProfile ``` ## Common methods The following types of functionality apply at multiple levels: resource, resource group and/or subscription. ### Tagging Resources and resource groups can be assigned _tags_. Tags are labels that help admins to organise and categorise Azure resources. To set and unset tags, use the `set_tags` method, and to view them, use `get_tags`. ```r rg$set_tags(comment1="hello world!", created_by="AzureRMR") # a name-only comment rg$set_tags(comment2) # to unset a tag, set it to NULL rg$set_tags(created_by=NULL) # see the tags rg$get_tags() #> $comment1 #> [1] "hello world!" #> #> $comment2 #> [1] "" # specify keep_existing=FALSE to unset all existing tags rg$set_tags(newcomment="my new comment", keep_existing=FALSE) ``` ### Locking As of version 2.0.0, AzureRMR includes the ability to lock and unlock subscriptions, resource groups and resources. The methods involved are: * `create_lock(name, level)`: Create a management lock on this object. The `level` argument can be either "cannotdelete" or "readonly". * `get_lock(name`): Returns a management lock object. * `delete_lock(name)`: Deletes a management lock object. * `list_locks()`: List all locks that apply to this object. Locks applied to a resource group also apply to all its resources, and similarly locks applied to a subscription also apply to all its resource groups (and resources). If you logged in via a custom service principal, it must have "Owner" or "User Access Administrator" access to manage locks. ```r # protect this resource group and its resources against deletion rg$create_lock("mylock", "cannotdelete") rg$list_locks() rg$delete_lock("mylock") ``` ### Role-based access control As of version 2.1.0, AzureRMR includes limited support for [role-based access control](https://learn.microsoft.com/en-us/azure/role-based-access-control/overview) (RBAC). You can read role definitions, and read, add and remove role assignments. This applies to subscription, resource group and resource objects. ```r rg$list_role_definitions() #> definition_id name #> 1 a7b1b19a-0e83-4fe5-935c-faaefbfd18c3 Avere Cluster Create #> 2 e078ab98-ef3a-4c9a-aba7-12f5172b45d0 Avere Cluster Runtime Operator #> 3 21d96096-b162-414a-8302-d8354f9d91b2 Azure Service Deploy Release Management Contributor #> 4 7b266cd7-0bba-4ae2-8423-90ede5e1e898 CAL-Custom-Role #> 5 b91f4c0b-46e3-47bb-a242-eecfe23b3b5b Dsms Role (deprecated) #> ... rg$get_role_definition("Reader") #> <Azure role definition> #> role: Reader #> description: Lets you view everything, but not make any changes. #> role definition ID: acdd72a7-3385-48ef-bd42-f606fba81ae7 # assign Reader role to the principal with the given ID rg$add_role_assignment("041ff2be-4eb0-11e9-8f38-394fbcd0b29d", "Reader") ``` You can assign roles to either a user or a service principal, although note that the ID of a service principal is _not_ the app ID of its corresponding registered app. The AzureGraph package can help you in specifying the principal to which to assign a role. ```r gr <- AzureGraph::get_graph_login() # can get a user by their email address usr <- gr$get_user("[email protected]") # get the service principal for an app by its app ID svc <- gr$get_service_principal(app_id="b9ed4812-4eba-11e9-9a1e-1fda262d9c77") rg$add_role_assignment(usr, "Reader") rg$add_role_assignment(svc, "Contributor") ``` Technically role definitions and assignments are _resources_ and could be manipulated as such, but AzureRMR currently treats them as independent classes. ## Conclusion This has been a quick introduction to the features of AzureRMR. Remember that this package is only meant to be a generic mechanism for working with Resource Manager. You can extend it to provide support for service-specific features; examples of packages that do this include [AzureVM](https://github.com/cloudyr/AzureVM) for [virtual machines](https://azure.microsoft.com/en-us/products/virtual-machines/), and [AzureStor](https://github.com/cloudyr/AzureStor) for [storage accounts](https://azure.microsoft.com/en-us/products/category/storage/). For more information, see the "Extending AzureRMR" vignette.
/scratch/gouwar.j/cran-all/cranData/AzureRMR/inst/doc/intro.Rmd
--- title: "Parallel connections using a background process pool" author: Hong Ooi output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Parallel connections} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{utf8} --- AzureRMR provides the ability to parallelise communicating with Azure by utilising a pool of R processes in the background. This often leads to major speedups in scenarios like downloading large numbers of small files, or working with a cluster of virtual machines. This is intended for use by packages that extend AzureRMR (and was originally implemented as part of the AzureStor package), but can also be called directly by the end-user. This functionality was originally implemented independently in the AzureStor and AzureVM packages, but has now been moved into AzureRMR. This removes the code duplication, and also makes it available for other packages that may benefit. ## Working with the pool A small API consisting of the following functions is currently provided for managing the pool. They pass their arguments down to the corresponding functions in the parallel package. - `init_pool` initialises the pool, creating it if necessary. The pool is created by calling `parallel::makeCluster` with the pool size and any additional arguments. If `init_pool` is called and the current pool is smaller than `size`, it is resized. - `delete_pool` shuts down the background processes and deletes the pool. - `pool_exists` checks for the existence of the pool, returning a TRUE/FALSE value. - `pool_size` returns the size of the pool, or zero if the pool does not exist. - `pool_export` exports variables to the pool nodes. It calls `parallel::clusterExport` with the given arguments. - `pool_lapply`, `pool_sapply` and `pool_map` carry out work on the pool. They call `parallel::parLapply`, `parallel::parSapply` and `parallel::clusterMap` with the given arguments. - `pool_call` and `pool_evalq` execute code on the pool nodes. They call `parallel::clusterCall` and `parallel::clusterEvalQ` with the given arguments. The pool is persistent for the session or until terminated by `delete_pool`. You should initialise the pool by calling `init_pool` before running any code on it. This restores the original state of the pool nodes by removing any objects that may be in memory, and resetting the working directory to the master working directory. The pool is a shared resource, and so packages that make use of it should not assume that they have sole control over its state. In particular, just because the pool exists at the end of one call doesn't mean it will still exist at the time of a subsequent call. Here is a simple example that shows how to initialise the pool, and then execute code on it. ```r # create the pool # by default, it contains 10 nodes init_pool() # send some data to the nodes x <- 42 pool_export("x") # run some code pool_sapply(1:10, function(y) x + y) #> [1] 43 44 45 46 47 48 49 50 51 52 ``` Here is a more realistic example using the AzureStor package. We create a connection to an Azure storage account, and then upload a number of files in parallel to a blob container. This is basically what the `storage_multiupload` function does under the hood. ```r init_pool() library(AzureStor) endp <- storage_endpoint("https://mystorageacct.blob.core.windows.net", key="key") cont <- storage_container(endp, "container") src_files <- c("file1.txt", "file2.txt", "file3.txt") dest_files <- src_files pool_export("cont") pool_map( function(src, dest) AzureStor::storage_upload(cont, src, dest), src=src_files, dest=dest_files ) ```
/scratch/gouwar.j/cran-all/cranData/AzureRMR/inst/doc/parallel.Rmd
--- title: "Working with templates" author: Hong Ooi output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Working with templates} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{utf8} --- An Azure [template](https://learn.microsoft.com/en-us/azure/azure-resource-manager/template-deployment-overview) is a JSON file that can be used to automate the deployment of a set of related resources. The template uses declarative syntax, which lets you state what you intend to deploy without having to write the sequence of programming commands to create it. In the template, you specify the resources to deploy and the properties for those resources. Deploying a template with AzureRMR is just a matter of calling a resource group object's `deploy_template` method. This takes two arguments, `template` and `parameters`. `deploy_template` is very flexible in how you can specify its arguments: - As character strings containing unparsed JSON text. - As a (nested) list of R objects, which will be converted to JSON via `jsonlite::toJSON`. - A filename or connection pointing to a JSON file. - A URL from which the template can be accessed. - For the `parameters` argument, this can also be a character vector containing the types of each parameter. ```r vm_tpl <- rg$deploy_template("myNewVirtualMachine", template="vm_template.json", parameters=list( os="Linux", size="Standard_DS2_v2", username="ruser", publickey=readLines("~/id_rsa.pub") )) ``` Normally, deleting a template doesn't touch the resources it creates: it only deletes the template itself. However, AzureRMR optionally allows you to free any resources created when you delete a template. This is useful when managing complex objects like VMs, which actually consist of multiple individual resources in Azure (storage account, disk, network interface, etc). When you are done with the VM, deleting the template lets you free all these resources with a single command. ```r vm_tpl$delete(free_resources=TRUE) ``` ## Template helper functions AzureRMR also provides the `build_template_definition` and `build_template_parameters` functions to help you construct or modify a template. Both of these are generics and can be extended by other packages to handle specific deployment scenarios, eg virtual machines. `build_template_definition` is used to generate the template JSON. The default method has 4 arguments `parameters`, `variables`, `resources` and `outputs`, which are the components of a template; these should be either strings containing the unparsed JSON text, or lists to be converted into JSON. `build_template_parameters` is for creating the list of parameters to be passed along with the template. Its arguments should all be named, and contain either the JSON text or an R list giving the parsed JSON. ```r # a storage account template storage_tpl <- build_template_definition( parameters=c( name="string", location="string", sku="string" ), variables=list( id="[resourceId('Microsoft.Storage/storageAccounts', parameters('name'))]" ), resources=list( list( name="[parameters('name')]", location="[parameters('location')]", type="Microsoft.Storage/storageAccounts", apiVersion="2018-07-01", sku=list( name="[parameters('sku')]" ), kind="Storage" ) ), outputs=list( storageId="[variables('id')]" ) ) # the corresponding parameters storage_pars <- build_template_parameters( name="mystorageacct", location="westus", sku="Standard_LRS" ) ``` Once created, the template defintion and parameters can be passed directly to `deploy_template`: ```r # deploying rg$deploy_template("mystorageacct", template=storage_tpl, parameters=storage_pars) ```
/scratch/gouwar.j/cran-all/cranData/AzureRMR/inst/doc/template.Rmd
--- title: "Authentication basics" author: Hong Ooi output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Authentication} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{utf8} --- There are a number of ways to authenticate to the Azure Resource Manager API with AzureRMR. This vignette goes through the most common scenarios. ## Interactive authentication This is the scenario where you're using R interactively, such as in your local desktop or laptop, or in a hosted RStudio Server, Jupyter notebook or ssh session. The first time you authenticate with AzureRMR, you run `create_azure_login()`: ```r # on first use library(AzureRMR) az <- create_azure_login() ``` Notice that you _don't_ enter your username and password. AzureRMR will attempt to detect which authentication flow to use, based on your session details. In most cases, it will bring up the Azure Active Directory (AAD) login page in your browser, which is where you enter your user credentials. This is also known as the "authorization code" flow. There are some complications to be aware of: - If you are running R in a hosted session, trying to start a browser will usually fail. In this case, specify the device code authentication flow, with the `auth_type` argument: ```r az <- create_azure_login(auth_type="device_code") ``` - If you have a personal account that is also a guest in an organisational tenant, you may have to specify your tenant explicitly: ```r az <- create_azure_login(tenant="yourtenant") ``` - By default, AzureRMR identifies itself using the Azure CLI app registration ID. You can also supply your own app ID if you have one, for example if you want to restrict access to a specific subscription or resource group. See "Creating a custom app registration" below for more information. ```r az <- create_azure_login(app="yourappid") ``` All of the above arguments can be combined, eg this will authenticate using the device code flow, with an explicit tenant name, and a custom app ID: ```r az <- create_azure_login(tenant="yourtenant", app="yourappid", auth_type="device_code") ``` If needed, you can also supply other arguments that will be passed to `AzureAuth::get_azure_token()`. Having created the login, in subsequent sessions you run `get_azure_login()`. This will load your previous authentication details, saving you from having to login again. If you specified the tenant in the `create_azure_login()` call, you'll also need to specify it for `get_azure_login()`; the other arguments don't have to be repeated. ```r az <- get_azure_login() # if you specified the tenant in create_azure_login az <- get_azure_login(tenant="yourtenant") ``` ## Non-interactive authentication This is the scenario where you want to use AzureRMR as part of an automated script or unattended session, for example in a deployment pipeline. The appropriate authentication flow in this case is the client credentials flow. For this scenario, you must have a custom app ID and client secret. On the client side, these are supplied in the `app` and `password` arguments. You must also specify your tenant as AAD won't be able to detect it from a user's credentials. ```r az <- create_azure_login(tenant="yourtenant", app="yourccappid", password="client_secret") ``` In the non-interactive scenario, you don't use `get_azure_login()`; instead, you simply call `create_azure_login()` as part of your script. ## Creating a custom app registration This part is meant mostly for Azure tenant administrators, or users who have the appropriate rights to create AAD app registrations. You can create your own app registration to authenticate with, if the default Azure CLI app ID is insufficient. In particular, you'll need a custom app ID if you are using AzureRMR in a non-interactive session. If security is a concern, a custom app ID also lets you restrict the scope of the resources that AzureRMR that manipulate. You can create a new app registration using any of the usual methods. For example to create an app registration in the Azure Portal (`https://portal.azure.com/`), click on "Azure Active Directory" in the menu bar down the left, go to "App registrations" and click on "New registration". Name the app something suitable, eg "AzureRMR custom app". - If you want your users to be able to login with the authorization code flow, you must add a **public client/native redirect URI** of `http://localhost:1410`. This is appropriate if your users will be running R on their local PCs, with an Internet browser available. - If you want your users to be able to login with the device code flow, you must **enable the "Allow public client flows" setting** for your app. In the Portal, you can find this setting in the "Authentication" pane once the app registration is complete. This is appropriate if your users are running R in a remote session. - If the app is meant for non-interactive use, you must give the app a **client secret**, which is much the same as a password (and should similarly be kept secure). In the Portal, you can set this in the "Certificates and Secrets" pane for your app registration. Once the app registration has been created, note the app ID and, if applicable, the client secret. The latter can't be viewed after app creation, so make sure you note its value now. It's also possible to authenticate with a **client certificate (public key)**, but this is more complex and we won't go into it here. For more details, see the [Azure Active Directory documentation](https://learn.microsoft.com/en-au/azure/active-directory/develop/v2-oauth2-client-creds-grant-flow) and the [AzureAuth intro vignette](https://cran.r-project.org/package=AzureAuth/vignettes/token.html). ### Set the app role and scope You'll also need to set the role assignment and scope(s) for your app ID. The former determines the kinds of actions that AzureRMR can take; the latter determines which resources those action can be applied to. The main role assignments are - **Owner**: can manage all aspects of resources, including role assignments - **Contributor**: can modify, create and delete resources, but cannot modify role assignments - **Reader**: can view resources but not make changes It's generally recommended to use the most restrictive role assignment that still lets you carry out your tasks. In the Portal, you can set the role assignment for your app ID by going to a specific subscription/resource group/resource and clicking on "Access Control (IAM)". Role assignments for subscriptions and resource groups will propagate to objects further down in the hierarchy. Any resources that don't have a role for your app will not be accessible.
/scratch/gouwar.j/cran-all/cranData/AzureRMR/vignettes/auth.Rmd
--- title: "Extending AzureRMR" Author: Hong Ooi output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Extending AzureRMR} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{utf8} --- AzureRMR provides a generic framework for managing Azure resources. While you can use it as provided to work with any Azure service, you may also want to extend it to provide more features for a particular service. This vignette describes the process of doing so. We'll use examples from some of the other AzureR packages to show how this works. ## Subclass resource/template classes Create subclasses of `az_resource` and/or `az_template` to represent the resources used by this service. For example, the AzureStor package provides a new class, `az_storage`, that inherits from `az_resource`. This class represents a storage accounts and has new methods specific to storage, such as listing access keys, generating a shared access signature (SAS), and creating a client endpoint object. Here is a simplified version of the `az_storage` class. ```{r, eval=FALSE} az_storage <- R6::R6Class("az_storage", inherit=AzureRMR::az_resource, public=list( list_keys=function() { keys <- named_list(private$res_op("listKeys", http_verb="POST")$keys, "keyName") sapply(keys, `[[`, "value") }, get_blob_endpoint=function(key=self$list_keys()[1], sas=NULL) { blob_endpoint(self$properties$primaryEndpoints$blob, key=key, sas=sas) }, get_file_endpoint=function(key=self$list_keys()[1], sas=NULL) { file_endpoint(self$properties$primaryEndpoints$file, key=key, sas=sas) } )) ``` In most cases, you can rely on the default `az_resource$initialize` method to handle object construction. You can override this method if your resource class contains new data fields that have to be initialised. A more complex example of a custom class is the `az_vm_template` class in the AzureVM package. This represents the resources used by a virtual machine, or cluster of virtual machines, in Azure. The initialisation code not only handles the details of deploying or getting the template used to create the VM(s), but also retrieves the individual resource objects themselves. ```{r, eval=FALSE} az_vm_template <- R6::R6Class("az_vm_template", inherit=AzureRMR::az_template, public=list( disks=NULL, status=NULL, ip_address=NULL, dns_name=NULL, clust_size=NULL, initialize=function(token, subscription, resource_group, name, ...) { super$initialize(token, subscription, resource_group, name, ...) # fill in fields that don't require querying the host num_instances <- self$properties$outputs$numInstances if(is_empty(num_instances)) { self$clust_size <- 1 vmnames <- self$name } else { self$clust_size <- as.numeric(num_instances$value) vmnames <- paste0(self$name, seq_len(self$clust_size) - 1) } private$vm <- sapply(vmnames, function(name) { az_vm_resource$new(self$token, self$subscription, self$resource_group, type="Microsoft.Compute/virtualMachines", name=name) }, simplify=FALSE) # get the hostname/IP address for the VM outputs <- unlist(self$properties$outputResources) ip_id <- grep("publicIPAddresses/.+$", outputs, ignore.case=TRUE, value=TRUE) ip <- lapply(ip_id, function(id) az_resource$new(self$token, self$subscription, id=id)$properties) self$ip_address <- sapply(ip, function(x) x$ipAddress) self$dns_name <- sapply(ip, function(x) x$dnsSettings$fqdn) lapply(private$vm, function(obj) obj$sync_vm_status()) self$disks <- lapply(private$vm, "[[", "disks") self$status <- lapply(private$vm, "[[", "status") NULL } # ... other VM-specific methods ... ), private=list( # will store a list of VM objects after initialisation vm=NULL # ... other private members ... ) )) ``` ## Add accessor functions Once you've created your new class(es), you should add accessor functions to `az_resource_group` (and optionally `az_subscription` as well, if your service has subscription-level API calls) to create, get and delete resources. This allows the convenience of _method chaining_: ```{r, eval=FALSE} res <- az_rm$new("tenant_id", "app_id", "secret") $ get_subscription("subscription_id") $ get_resource_group("resgroup") $ get_my_resource("myresource") ``` Note that if you are writing a package that extends AzureRMR, these methods _must_ be defined in the package's `.onLoad` function. This is because the methods must be added at runtime, when the user loads your package, rather than at compile time, when it is built or installed. The `create_storage_account`, `get_storage_account` and `delete_storage_account` methods from the AzureStor package are defined like this. Note that calls to your class methods should include the `pkgname::` qualifier, to ensure they will work even if your package is not attached. ```{r, eval=FALSE} # all methods adding methods to classes in external package must go in .onLoad .onLoad <- function(libname, pkgname) { AzureRMR::az_resource_group$set("public", "create_storage_account", overwrite=TRUE, function(name, location, kind="Storage", sku=list(name="Standard_LRS", tier="Standard"), ...) { AzureStor::az_storage$new(self$token, self$subscription, self$name, type="Microsoft.Storage/storageAccounts", name=name, location=location, kind=kind, sku=sku, ...) }) AzureRMR::az_resource_group$set("public", "get_storage_account", overwrite=TRUE, function(name) { AzureStor::az_storage$new(self$token, self$subscription, self$name, type="Microsoft.Storage/storageAccounts", name=name) }) AzureRMR::az_resource_group$set("public", "delete_storage_account", overwrite=TRUE, function(name, confirm=TRUE, wait=FALSE) { self$get_storage_account(name)$delete(confirm=confirm, wait=wait) }) # ... other startup code ... } ``` The corresponding accessor functions for AzureVM's `az_vm_template` class are more complex, as might be imagined. Here is a fragment of that package's `onLoad` function showing the `az_resource_group$create_vm_cluster` method. ```{r, eval=FALSE} .onLoad <- function(libname, pkgname) { AzureRMR::az_resource_group$set("public", "create_vm_cluster", overwrite=TRUE, function(name, location, os=c("Windows", "Ubuntu"), size="Standard_DS3_v2", username, passkey, userauth_type=c("password", "key"), ext_file_uris=NULL, inst_command=NULL, clust_size, template, parameters, ..., wait=TRUE) { os <- match.arg(os) userauth_type <- match.arg(userauth_type) if(missing(parameters) && (missing(username) || missing(passkey))) stop("Must supply login username and password/private key", call.=FALSE) # find template given input args if(missing(template)) template <- get_dsvm_template(os, userauth_type, clust_size, ext_file_uris, inst_command) # convert input args into parameter list for template if(missing(parameters)) parameters <- make_dsvm_param_list(name=name, size=size, username=username, userauth_type=userauth_type, passkey=passkey, ext_file_uris=ext_file_uris, inst_command=inst_command, clust_size=clust_size, template=template) AzureVM::az_vm_template$new(self$token, self$subscription, self$name, name, template=template, parameters=parameters, ..., wait=wait) }) # ... other startup code ... } ``` ### Adding documentation Documenting methods added to a class in this way can be problematic. R's .Rd help format is designed around traditional functions, and R6 classes and methods are usually not a good fit. The popular Roxygen format also (as of October 2018) doesn't deal very well with R6 classes. The fact that we are adding methods to a class defined in an external package is an additional complication. Here is an example documentation skeleton in Roxygen format, copied from AzureStor. You can add this as a separate block in the source file where you define the accessor method(s). The block uses Markdown formatting, so you will need to have installed roxygen2 version 6.0.1 or later. ```{r, eval=FALSE} #' Get existing Azure resource type 'foo' #' #' Methods for the [AzureRMR::az_resource_group] and [AzureRMR::az_subscription] classes. #' #' @rdname get_foo #' @name get_foo #' @aliases get_foo list_foos #' #' @section Usage: #' ``` #' get_foo(name) #' list_foos() #' ``` #' @section Arguments: #' - `name`: For `get_foo()`, the name of the resource. #' #' @section Details: #' The `AzureRMR::az_resource_group` class has both `get_foo()` and `list_foos()` methods, while the `AzureRMR::az_subscription` class only has the latter. #' #' @section Value: #' For `get_foo()`, an object of class `az_foo` representing the foo resource. #' #' For `list_foos()`, a list of such objects. #' #' @seealso #' [create_foo], [delete_foo], [az_foo] NULL ``` We note the following: - The `@aliases` tag includes all the names that will bring up this page when using the `?` command, _including_ the default name. - Rather than using the standard `@usage`, `@param`, `@details` and `@return` tags, the block uses `@section` to create sections with the appropriate titles (including one named 'Arguments'). - The usage block is explicitly formatted as fixed-width using Markdown backticks. - The arguments are formatted as a (bulleted) list rather than the usual table format for function arguments. These changes are necessary because what we're technically documenting is not a standalone function, but a method inside a class. The `@usage`, `@param` tags et al only apply to functions, and if you use them here, `R CMD check` will generate a warning when it can't find a function with the given name. This can be important if you want to publish your package on CRAN. ## Add client-facing interface The AzureRMR class framework allows you to work with resources at the _Azure_ level, via Azure Resource Manager. If a service exposes a _client_ endpoint that is independent of ARM, you may also want to create a separate R interface for the endpoint. As the client interface is independent of the ARM interface, you have flexibility to tailor its design. For example, rather than using R6, the AzureStor package uses S3 classes to represent storage endpoints and individual containers and shares within an endpoint. It further defines (S3) methods for these classes to perform common operations like listing directories, uploading and downloading files, and so on. This is consistent with most other data access and manipulation packages in R, which usually stick to S3. ```{r, eval=FALSE} # blob endpoint for a storage account blob_endpoint <- function(endpoint, key=NULL, sas=NULL, api_version=getOption("azure_storage_api_version")) { if(!is_endpoint_url(endpoint, "blob")) stop("Not a blob endpoint", call.=FALSE) obj <- list(url=endpoint, key=key, sas=sas, api_version=api_version) class(obj) <- c("blob_endpoint", "storage_endpoint") obj } # S3 generic and methods to create an object representing a blob container within an endpoint blob_container <- function(endpoint, ...) { UseMethod("blob_container") } blob_container.character <- function(endpoint, key=NULL, sas=NULL, api_version=getOption("azure_storage_api_version")) { do.call(blob_container, generate_endpoint_container(endpoint, key, sas, api_version)) } blob_container.blob_endpoint <- function(endpoint, name) { obj <- list(name=name, endpoint=endpoint) class(obj) <- "blob_container" obj } # download a file from a blob container download_blob <- function(container, src, dest, overwrite=FALSE, lease=NULL) { headers <- list() if(!is.null(lease)) headers[["x-ms-lease-id"]] <- as.character(lease) do_container_op(container, src, headers=headers, config=httr::write_disk(dest, overwrite)) } ```
/scratch/gouwar.j/cran-all/cranData/AzureRMR/vignettes/extend.Rmd
--- title: "Introduction to AzureRMR" author: Hong Ooi output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Introduction to AzureRMR} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{utf8} --- AzureRMR is a package for interacting with Azure Resource Manager: authenticate, list subscriptions, manage resource groups, deploy and delete templates and resources. It calls the Resource Manager [REST API](https://learn.microsoft.com/en-us/rest/api/resources) directly, so you don't need to have PowerShell or Python installed. As a general-purpose interface to Azure Resource Manager (ARM), you can use AzureRMR to work with nearly any Azure object that ARM can handle: subscriptions, resource groups, resources, templates and so on. The things you can do include: - Create a new resource - Carry out arbitrary operations on a resource - Delete a resource - Deploy a template - Delete a template, and, optionally, any resources that it created - Create and delete resource groups (if you gave your service principal subscription-level access) ## Authentication Under the hood, AzureRMR uses a similar authentication process to the [Azure CLI](https://learn.microsoft.com/en-us/cli/azure/?view=azure-cli-latest). The first time you authenticate with a given Azure Active Directory tenant, you call `create_azure_login()`, which will log you into Azure. R will prompt you for permission to create a special data directory in which to save your credentials. Once this information is saved on your machine, it can be retrieved in subsequent R sessions with `get_azure_login()`. Your credentials will be automatically refreshed so you don't have to reauthenticate. Unless you have a good reason otherwise, you should allow this caching directory to be created. Note that many other cloud engineering tools save credentials in this way, including the Azure CLI itself. You can see the location of the caching directory with the function `AzureR_dir()`. ```r library(AzureRMR) #> The AzureR packages can save your authentication credentials in the directory: #> #> C:\Users\hongooi\AppData\Local\AzureR #> #> This saves you having to reauthenticate with Azure in future sessions. Create this directory? (Y/n) y AzureR_dir() #> [1] "C:\\Users\\hongooi\\AppData\\Local\\AzureR" # if this is the first time you're logging in az <- create_azure_login() #> Creating Azure Resource Manager login for default tenant #> Waiting for authentication in browser... #> Press Esc/Ctrl + C to abort #> Authentication complete. # for subsequent sessions az <- get_azure_login() #> Loading Azure Resource Manager login for default tenant # you can also list the tenants that you've previously authenticated with list_azure_logins() ``` See the "Authentication basics" vignette for more details on how to authenticate with AzureRMR. ## Subscriptions and resource groups AzureRMR allows you to work with your subscriptions and resource groups. Note that if you created your service principal via the cloud shell, as described in this vignette, you probably only have access to one subscription. Regardless, you can list all subscriptions that you can work with: ```r # all subscriptions az$list_subscriptions() #> $`5710aa44-281f-49fe-bfa6-69e66bb55b11` #> <Azure subscription 5710aa44-281f-49fe-bfa6-69e66bb55b11> #> authorization_source: RoleBased #> name: Visual Studio Ultimate with MSDN #> policies: list(locationPlacementId, quotaId, spendingLimit) #> state: Enabled #> --- #> Methods: #> create_resource_group, delete_resource_group, get_provider_api_version, get_resource_group, #> list_locations, list_resource_groups, list_resources #> #> $`e26f4a80-370f-4a77-88df-5a8d291cd2f9` #> <Azure subscription e26f4a80-370f-4a77-88df-5a8d291cd2f9> #> authorization_source: RoleBased #> name: ADLTrainingMS #> policies: list(locationPlacementId, quotaId, spendingLimit) #> state: Enabled #> --- #> Methods: #> create_resource_group, delete_resource_group, get_provider_api_version, get_resource_group, #> list_locations, list_resource_groups, list_resources #> #> ... ``` Notice that AzureRMR is based on R6 classes, where methods are part of the object itself (much like objects in C++, C# and Java). Thus `list_subscriptions` is a member of the `az` object, and we call it with `az$list_subscriptions()`. R6 is used because it allows objects to have persistent state; in this case, the objects in R represent corresponding objects in Azure. The `list_subscriptions()` call returns a list of subscription objects. You can retrieve the details for a single subscription with `get_subscription`: ```r # get a subscription (sub1 <- az$get_subscription("5710aa44-281f-49fe-bfa6-69e66bb55b11")) #> <Azure subscription 5710aa44-281f-49fe-bfa6-69e66bb55b11> #> authorization_source: Legacy #> name: Visual Studio Ultimate with MSDN #> policies: list(locationPlacementId, quotaId, spendingLimit) #> state: Enabled #> --- #> Methods: #> create_resource_group, delete_resource_group, get_provider_api_version, get_resource_group, #> list_locations, list_resource_groups, list_resources ``` A subscription object in turn has methods to get, create and delete resource groups (and also list all resource groups): ```r (rg <- sub1$get_resource_group("rdev1")) #> <Azure resource group rdev1> #> id: /subscriptions/5710aa44-281f-49fe-bfa6-69e66bb55b11/resourceGroups/rdev1 #> location: australiaeast #> properties: list(provisioningState) #> --- #> Methods: #> check, create_resource, delete, delete_resource, delete_template, deploy_template, get_resource, #> get_template, list_resources, list_templates # create and delete a resource group test <- sub1$create_resource_group("test_group") test$delete(confirm=FALSE) ``` ## Resources and templates Methods for working with resources and templates are exposed as part of the `az_resource_group` class. You can retrieve an existing resource/template, create a new one, or delete an existing one. Below is a short introduction to resources; for templates, see the "Working with templates" vignette. ```r (stor <- rg$get_resource(type="Microsoft.Storage/storageServices", name="rdevstor1")) #> <Azure resource Microsoft.Storage/storageAccounts/rdevstor1> #> id: /subscriptions/5710aa44-281f-49fe-bfa6-69e66bb55b11/resourceGroups/rdev1/providers/Microsoft.Sto ... #> is_synced: TRUE #> kind: Storage #> location: australiasoutheast #> properties: list(networkAcls, trustedDirectories, supportsHttpsTrafficOnly, encryption, #> provisioningState, creationTime, primaryEndpoints, primaryLocation, statusOfPrimary) #> sku: list(name, tier) #> tags: list() #> --- #> Methods: #> check, delete, do_operation, set_api_version, sync_fields, update ``` One benefit of the syntax that AzureRMR uses is that _method chaining_ works. This is the OOP version of pipelines, which most R users will recognise from the tidyverse. ```r # use method chaining to get a resource without creating a bunch of intermediaries # same result as above stor <- az$ get_subscription("5710aa44-281f-49fe-bfa6-69e66bb55b11")$ get_resource_group("rdev1")$ get_resource(type="Microsoft.Storage/storageServices", name="rdevstor1") ``` Once we have a resource, we can do _things_ with it, via the `do_operation()` method. In this case, we have a storage account. One of the things we can do with a storage account is retrieve its access keys: ```r stor$do_operation("listKeys", http_verb="POST") #> $`keys` #> $`keys`[[1]] #> $`keys`[[1]]$`keyName` #> [1] "key1" #> #> $`keys`[[1]]$value #> [1] "k0gGFi8LirKcDNe73fzwDzhZ2+4oRKzvz+6+Pfn2ZCKO/JLnpyBSpVO7btLxBXQj+j8MZatDTGZ2NXUItye/vA==" #> #> $`keys`[[1]]$permissions #> [1] "FULL" #> ... ``` Here is another example. If we have a virtual machine, we can start it, execute shell commands, and then shut it down again: ```r vm <- rg$get_resource(type="Microsoft.Compute/virtualMachines", name="myVirtualMachine") vm$do_operation("start", http_verb="POST") # may take a while vm$do_operation("runCommand", body=list( commandId="RunShellScript", # RunPowerShellScript for Windows script=as.list("ifconfig > /tmp/ifconfig.out") ), encode="json", http_verb="POST") vm$do_operation("powerOff", http_verb="POST") ``` For the types of operations you can carry out on a resource, consult the [Azure REST API documentation](https://learn.microsoft.com/en-us/rest/api/?view=Azure). You can also interrogate the fields of a resource object; in particular the `properties` field can contain arbitrary information about an Azure resource. For example, a storage account's properties includes the endpoint URIs, and a virtual machine's properties includes its admin login details. ```r # file and blob storage endpoint stor$properties$primaryEndpoints$file stor$properties$primaryEndpoints$blob # OS profile for a VM: includes login details vm$properties$osProfile ``` ## Common methods The following types of functionality apply at multiple levels: resource, resource group and/or subscription. ### Tagging Resources and resource groups can be assigned _tags_. Tags are labels that help admins to organise and categorise Azure resources. To set and unset tags, use the `set_tags` method, and to view them, use `get_tags`. ```r rg$set_tags(comment1="hello world!", created_by="AzureRMR") # a name-only comment rg$set_tags(comment2) # to unset a tag, set it to NULL rg$set_tags(created_by=NULL) # see the tags rg$get_tags() #> $comment1 #> [1] "hello world!" #> #> $comment2 #> [1] "" # specify keep_existing=FALSE to unset all existing tags rg$set_tags(newcomment="my new comment", keep_existing=FALSE) ``` ### Locking As of version 2.0.0, AzureRMR includes the ability to lock and unlock subscriptions, resource groups and resources. The methods involved are: * `create_lock(name, level)`: Create a management lock on this object. The `level` argument can be either "cannotdelete" or "readonly". * `get_lock(name`): Returns a management lock object. * `delete_lock(name)`: Deletes a management lock object. * `list_locks()`: List all locks that apply to this object. Locks applied to a resource group also apply to all its resources, and similarly locks applied to a subscription also apply to all its resource groups (and resources). If you logged in via a custom service principal, it must have "Owner" or "User Access Administrator" access to manage locks. ```r # protect this resource group and its resources against deletion rg$create_lock("mylock", "cannotdelete") rg$list_locks() rg$delete_lock("mylock") ``` ### Role-based access control As of version 2.1.0, AzureRMR includes limited support for [role-based access control](https://learn.microsoft.com/en-us/azure/role-based-access-control/overview) (RBAC). You can read role definitions, and read, add and remove role assignments. This applies to subscription, resource group and resource objects. ```r rg$list_role_definitions() #> definition_id name #> 1 a7b1b19a-0e83-4fe5-935c-faaefbfd18c3 Avere Cluster Create #> 2 e078ab98-ef3a-4c9a-aba7-12f5172b45d0 Avere Cluster Runtime Operator #> 3 21d96096-b162-414a-8302-d8354f9d91b2 Azure Service Deploy Release Management Contributor #> 4 7b266cd7-0bba-4ae2-8423-90ede5e1e898 CAL-Custom-Role #> 5 b91f4c0b-46e3-47bb-a242-eecfe23b3b5b Dsms Role (deprecated) #> ... rg$get_role_definition("Reader") #> <Azure role definition> #> role: Reader #> description: Lets you view everything, but not make any changes. #> role definition ID: acdd72a7-3385-48ef-bd42-f606fba81ae7 # assign Reader role to the principal with the given ID rg$add_role_assignment("041ff2be-4eb0-11e9-8f38-394fbcd0b29d", "Reader") ``` You can assign roles to either a user or a service principal, although note that the ID of a service principal is _not_ the app ID of its corresponding registered app. The AzureGraph package can help you in specifying the principal to which to assign a role. ```r gr <- AzureGraph::get_graph_login() # can get a user by their email address usr <- gr$get_user("[email protected]") # get the service principal for an app by its app ID svc <- gr$get_service_principal(app_id="b9ed4812-4eba-11e9-9a1e-1fda262d9c77") rg$add_role_assignment(usr, "Reader") rg$add_role_assignment(svc, "Contributor") ``` Technically role definitions and assignments are _resources_ and could be manipulated as such, but AzureRMR currently treats them as independent classes. ## Conclusion This has been a quick introduction to the features of AzureRMR. Remember that this package is only meant to be a generic mechanism for working with Resource Manager. You can extend it to provide support for service-specific features; examples of packages that do this include [AzureVM](https://github.com/cloudyr/AzureVM) for [virtual machines](https://azure.microsoft.com/en-us/products/virtual-machines/), and [AzureStor](https://github.com/cloudyr/AzureStor) for [storage accounts](https://azure.microsoft.com/en-us/products/category/storage/). For more information, see the "Extending AzureRMR" vignette.
/scratch/gouwar.j/cran-all/cranData/AzureRMR/vignettes/intro.Rmd
--- title: "Parallel connections using a background process pool" author: Hong Ooi output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Parallel connections} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{utf8} --- AzureRMR provides the ability to parallelise communicating with Azure by utilising a pool of R processes in the background. This often leads to major speedups in scenarios like downloading large numbers of small files, or working with a cluster of virtual machines. This is intended for use by packages that extend AzureRMR (and was originally implemented as part of the AzureStor package), but can also be called directly by the end-user. This functionality was originally implemented independently in the AzureStor and AzureVM packages, but has now been moved into AzureRMR. This removes the code duplication, and also makes it available for other packages that may benefit. ## Working with the pool A small API consisting of the following functions is currently provided for managing the pool. They pass their arguments down to the corresponding functions in the parallel package. - `init_pool` initialises the pool, creating it if necessary. The pool is created by calling `parallel::makeCluster` with the pool size and any additional arguments. If `init_pool` is called and the current pool is smaller than `size`, it is resized. - `delete_pool` shuts down the background processes and deletes the pool. - `pool_exists` checks for the existence of the pool, returning a TRUE/FALSE value. - `pool_size` returns the size of the pool, or zero if the pool does not exist. - `pool_export` exports variables to the pool nodes. It calls `parallel::clusterExport` with the given arguments. - `pool_lapply`, `pool_sapply` and `pool_map` carry out work on the pool. They call `parallel::parLapply`, `parallel::parSapply` and `parallel::clusterMap` with the given arguments. - `pool_call` and `pool_evalq` execute code on the pool nodes. They call `parallel::clusterCall` and `parallel::clusterEvalQ` with the given arguments. The pool is persistent for the session or until terminated by `delete_pool`. You should initialise the pool by calling `init_pool` before running any code on it. This restores the original state of the pool nodes by removing any objects that may be in memory, and resetting the working directory to the master working directory. The pool is a shared resource, and so packages that make use of it should not assume that they have sole control over its state. In particular, just because the pool exists at the end of one call doesn't mean it will still exist at the time of a subsequent call. Here is a simple example that shows how to initialise the pool, and then execute code on it. ```r # create the pool # by default, it contains 10 nodes init_pool() # send some data to the nodes x <- 42 pool_export("x") # run some code pool_sapply(1:10, function(y) x + y) #> [1] 43 44 45 46 47 48 49 50 51 52 ``` Here is a more realistic example using the AzureStor package. We create a connection to an Azure storage account, and then upload a number of files in parallel to a blob container. This is basically what the `storage_multiupload` function does under the hood. ```r init_pool() library(AzureStor) endp <- storage_endpoint("https://mystorageacct.blob.core.windows.net", key="key") cont <- storage_container(endp, "container") src_files <- c("file1.txt", "file2.txt", "file3.txt") dest_files <- src_files pool_export("cont") pool_map( function(src, dest) AzureStor::storage_upload(cont, src, dest), src=src_files, dest=dest_files ) ```
/scratch/gouwar.j/cran-all/cranData/AzureRMR/vignettes/parallel.Rmd
--- title: "Working with templates" author: Hong Ooi output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Working with templates} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{utf8} --- An Azure [template](https://learn.microsoft.com/en-us/azure/azure-resource-manager/template-deployment-overview) is a JSON file that can be used to automate the deployment of a set of related resources. The template uses declarative syntax, which lets you state what you intend to deploy without having to write the sequence of programming commands to create it. In the template, you specify the resources to deploy and the properties for those resources. Deploying a template with AzureRMR is just a matter of calling a resource group object's `deploy_template` method. This takes two arguments, `template` and `parameters`. `deploy_template` is very flexible in how you can specify its arguments: - As character strings containing unparsed JSON text. - As a (nested) list of R objects, which will be converted to JSON via `jsonlite::toJSON`. - A filename or connection pointing to a JSON file. - A URL from which the template can be accessed. - For the `parameters` argument, this can also be a character vector containing the types of each parameter. ```r vm_tpl <- rg$deploy_template("myNewVirtualMachine", template="vm_template.json", parameters=list( os="Linux", size="Standard_DS2_v2", username="ruser", publickey=readLines("~/id_rsa.pub") )) ``` Normally, deleting a template doesn't touch the resources it creates: it only deletes the template itself. However, AzureRMR optionally allows you to free any resources created when you delete a template. This is useful when managing complex objects like VMs, which actually consist of multiple individual resources in Azure (storage account, disk, network interface, etc). When you are done with the VM, deleting the template lets you free all these resources with a single command. ```r vm_tpl$delete(free_resources=TRUE) ``` ## Template helper functions AzureRMR also provides the `build_template_definition` and `build_template_parameters` functions to help you construct or modify a template. Both of these are generics and can be extended by other packages to handle specific deployment scenarios, eg virtual machines. `build_template_definition` is used to generate the template JSON. The default method has 4 arguments `parameters`, `variables`, `resources` and `outputs`, which are the components of a template; these should be either strings containing the unparsed JSON text, or lists to be converted into JSON. `build_template_parameters` is for creating the list of parameters to be passed along with the template. Its arguments should all be named, and contain either the JSON text or an R list giving the parsed JSON. ```r # a storage account template storage_tpl <- build_template_definition( parameters=c( name="string", location="string", sku="string" ), variables=list( id="[resourceId('Microsoft.Storage/storageAccounts', parameters('name'))]" ), resources=list( list( name="[parameters('name')]", location="[parameters('location')]", type="Microsoft.Storage/storageAccounts", apiVersion="2018-07-01", sku=list( name="[parameters('sku')]" ), kind="Storage" ) ), outputs=list( storageId="[variables('id')]" ) ) # the corresponding parameters storage_pars <- build_template_parameters( name="mystorageacct", location="westus", sku="Standard_LRS" ) ``` Once created, the template defintion and parameters can be passed directly to `deploy_template`: ```r # deploying rg$deploy_template("mystorageacct", template=storage_tpl, parameters=storage_pars) ```
/scratch/gouwar.j/cran-all/cranData/AzureRMR/vignettes/template.Rmd
#' @import AzureRMR #' @importFrom utils URLencode modifyList packageVersion glob2rx NULL globalVariables(c("self", "pool"), "AzureStor") .AzureStor <- new.env() .onLoad <- function(libname, pkgname) { set_option <- function(name, value) { if(is.null(getOption(name))) options(structure(list(value), names=name)) } set_option("azure_storage_api_version", "2021-06-08") set_option("azure_storage_progress_bar", TRUE) set_option("azure_storage_retries", 10) # all methods extending classes in external package must be run from .onLoad add_methods() }
/scratch/gouwar.j/cran-all/cranData/AzureStor/R/AzureStor.R
# documentation is separate from implementation because roxygen still doesn't know how to handle R6 #' Create Azure storage account #' #' Method for the [AzureRMR::az_resource_group] class. #' #' @rdname create_storage_account #' @name create_storage_account #' @aliases create_storage_account #' @section Usage: #' ``` #' create_storage_account(name, location, kind = "StorageV2", replication = "Standard_LRS", #' access_tier = "hot"), https_only = TRUE, #' hierarchical_namespace_enabled = TRUE, properties = list(), ...) #' ``` #' @section Arguments: #' - `name`: The name of the storage account. #' - `location`: The location/region in which to create the account. Defaults to the resource group location. #' - `kind`: The type of account, either `"StorageV2"` (the default), `"FileStorage"` or `"BlobStorage"`. #' - `replication`: The replication strategy for the account. The default is locally-redundant storage (LRS). #' - `access_tier`: The access tier, either `"hot"` or `"cool"`, for blobs. #' - `https_only`: Whether a HTTPS connection is required to access the storage. #' - `hierarchical_namespace_enabled`: Whether to enable hierarchical namespaces, which are a feature of Azure Data Lake Storage Gen 2 and provide more a efficient way to manage storage. See 'Details' below. #' - `properties`: A list of other properties for the storage account. #' - ... Other named arguments to pass to the [az_storage] initialization function. #' #' @section Details: #' This method deploys a new storage account resource, with parameters given by the arguments. A storage account can host multiple types of storage: #' - blob storage #' - file storage #' - table storage #' - queue storage #' - Azure Data Lake Storage Gen2 #' #' Accounts created with `kind = "BlobStorage"` can only host blob storage, while those with `kind = "FileStorage"` can only host file storage. Accounts with `kind = "StorageV2"` can host all types of storage. AzureStor provides an R interface to ADLSgen2, blob and file storage, while the AzureQstor and AzureTableStor packages provide interfaces to queue and table storage respectively. #' #' @section Value: #' An object of class `az_storage` representing the created storage account. #' #' @seealso #' [get_storage_account], [delete_storage_account], [az_storage] #' #' [Azure Storage documentation](https://docs.microsoft.com/en-us/azure/storage/), #' [Azure Storage Provider API reference](https://docs.microsoft.com/en-us/rest/api/storagerp/), #' [Azure Data Lake Storage hierarchical namespaces](https://docs.microsoft.com/en-us/azure/storage/blobs/data-lake-storage-namespace) #' #' @examples #' \dontrun{ #' #' rg <- AzureRMR::az_rm$ #' new(tenant="myaadtenant.onmicrosoft.com", app="app_id", password="password")$ #' get_subscription("subscription_id")$ #' get_resource_group("rgname") #' #' # create a new storage account #' rg$create_storage_account("mystorage", kind="StorageV2") #' #' # create a blob storage account in a different region #' rg$create_storage_account("myblobstorage", #' location="australiasoutheast", #' kind="BlobStorage") #' #' } NULL #' Get existing Azure storage account(s) #' #' Methods for the [AzureRMR::az_resource_group] and [AzureRMR::az_subscription] classes. #' #' @rdname get_storage_account #' @name get_storage_account #' @aliases get_storage_account list_storage_accounts #' #' @section Usage: #' ``` #' get_storage_account(name) #' list_storage_accounts() #' ``` #' @section Arguments: #' - `name`: For `get_storage_account()`, the name of the storage account. #' #' @section Details: #' The `AzureRMR::az_resource_group` class has both `get_storage_account()` and `list_storage_accounts()` methods, while the `AzureRMR::az_subscription` class only has the latter. #' #' @section Value: #' For `get_storage_account()`, an object of class `az_storage` representing the storage account. #' #' For `list_storage_accounts()`, a list of such objects. #' #' @seealso #' [create_storage_account], [delete_storage_account], [az_storage], #' [Azure Storage Provider API reference](https://docs.microsoft.com/en-us/rest/api/storagerp/) #' #' @examples #' \dontrun{ #' #' rg <- AzureRMR::az_rm$ #' new(tenant="myaadtenant.onmicrosoft.com", app="app_id", password="password")$ #' get_subscription("subscription_id")$ #' get_resource_group("rgname") #' #' # get a storage account #' rg$get_storage_account("mystorage") #' #' } NULL #' Delete an Azure storage account #' #' Method for the [AzureRMR::az_resource_group] class. #' #' @rdname delete_storage_account #' @name delete_storage_account #' @aliases delete_storage_account #' #' @section Usage: #' ``` #' delete_storage_account(name, confirm=TRUE, wait=FALSE) #' ``` #' @section Arguments: #' - `name`: The name of the storage account. #' - `confirm`: Whether to ask for confirmation before deleting. #' - `wait`: Whether to wait until the deletion is complete. #' #' @section Value: #' NULL on successful deletion. #' #' @seealso #' [create_storage_account], [get_storage_account], [az_storage], #' [Azure Storage Provider API reference](https://docs.microsoft.com/en-us/rest/api/storagerp/) #' #' @examples #' \dontrun{ #' #' rg <- AzureRMR::az_rm$ #' new(tenant="myaadtenant.onmicrosoft.com", app="app_id", password="password")$ #' get_subscription("subscription_id")$ #' get_resource_group("rgname") #' #' # delete a storage account #' rg$delete_storage_account("mystorage") #' #' } NULL add_methods <- function() { ## extending AzureRMR classes AzureRMR::az_resource_group$set("public", "create_storage_account", overwrite=TRUE, function(name, location=self$location, kind="StorageV2", replication="Standard_LRS", access_tier="hot", https_only=TRUE, hierarchical_namespace_enabled=TRUE, properties=list(), ...) { properties <- modifyList(properties, list(accessTier=access_tier, supportsHttpsTrafficOnly=https_only, isHnsEnabled=hierarchical_namespace_enabled)) AzureStor::az_storage$new(self$token, self$subscription, self$name, type="Microsoft.Storage/storageAccounts", name=name, location=location, kind=kind, sku=list(name=replication), properties=properties, ...) }) AzureRMR::az_resource_group$set("public", "get_storage_account", overwrite=TRUE, function(name) { AzureStor::az_storage$new(self$token, self$subscription, self$name, type="Microsoft.Storage/storageAccounts", name=name) }) AzureRMR::az_resource_group$set("public", "delete_storage_account", overwrite=TRUE, function(name, confirm=TRUE, wait=FALSE) { self$get_storage_account(name)$delete(confirm=confirm, wait=wait) }) AzureRMR::az_resource_group$set("public", "list_storage_accounts", overwrite=TRUE, function(name) { provider <- "Microsoft.Storage" path <- "storageAccounts" api_version <- az_subscription$ new(self$token, self$subscription)$ get_provider_api_version(provider, path) op <- file.path("resourceGroups", self$name, "providers", provider, path) cont <- call_azure_rm(self$token, self$subscription, op, api_version=api_version) lst <- lapply(cont$value, function(parms) AzureStor::az_storage$new(self$token, self$subscription, deployed_properties=parms)) # keep going until paging is complete while(!is_empty(cont$nextLink)) { cont <- call_azure_url(self$token, cont$nextLink) lst <- lapply(cont$value, function(parms) AzureStor::az_storage$new(self$token, self$subscription, deployed_properties=parms)) } named_list(lst) }) AzureRMR::az_subscription$set("public", "list_storage_accounts", overwrite=TRUE, function(name) { provider <- "Microsoft.Storage" path <- "storageAccounts" api_version <- self$get_provider_api_version(provider, path) op <- file.path("providers", provider, path) cont <- call_azure_rm(self$token, self$id, op, api_version=api_version) lst <- lapply(cont$value, function(parms) AzureStor::az_storage$new(self$token, self$id, deployed_properties=parms)) # keep going until paging is complete while(!is_empty(cont$nextLink)) { cont <- call_azure_url(self$token, cont$nextLink) lst <- lapply(cont$value, function(parms) AzureStor::az_storage$new(self$token, self$id, deployed_properties=parms)) } named_list(lst) }) }
/scratch/gouwar.j/cran-all/cranData/AzureStor/R/add_methods.R
#' Operations on an Azure Data Lake Storage Gen2 endpoint #' #' Get, list, create, or delete ADLSgen2 filesystems. #' #' @param endpoint Either an ADLSgen2 endpoint object as created by [storage_endpoint] or [adls_endpoint], or a character string giving the URL of the endpoint. #' @param key,token,sas If an endpoint object is not supplied, authentication credentials: either an access key, an Azure Active Directory (AAD) token, or a SAS, in that order of priority. Currently the `sas` argument is unused. #' @param api_version If an endpoint object is not supplied, the storage API version to use when interacting with the host. Currently defaults to `"2019-07-07"`. #' @param name The name of the filesystem to get, create, or delete. #' @param confirm For deleting a filesystem, whether to ask for confirmation. #' @param x For the print method, a filesystem object. #' @param ... Further arguments passed to lower-level functions. #' #' @details #' You can call these functions in a couple of ways: by passing the full URL of the filesystem, or by passing the endpoint object and the name of the filesystem as a string. #' #' If authenticating via AAD, you can supply the token either as a string, or as an object of class AzureToken, created via [AzureRMR::get_azure_token]. The latter is the recommended way of doing it, as it allows for automatic refreshing of expired tokens. #' #' @return #' For `adls_filesystem` and `create_adls_filesystem`, an S3 object representing an existing or created filesystem respectively. #' #' For `list_adls_filesystems`, a list of such objects. #' #' @seealso #' [storage_endpoint], [az_storage], [storage_container] #' #' @examples #' \dontrun{ #' #' endp <- adls_endpoint("https://mystorage.dfs.core.windows.net/", key="access_key") #' #' # list ADLSgen2 filesystems #' list_adls_filesystems(endp) #' #' # get, create, and delete a filesystem #' adls_filesystem(endp, "myfs") #' create_adls_filesystem(endp, "newfs") #' delete_adls_filesystem(endp, "newfs") #' #' # alternative way to do the same #' adls_filesystem("https://mystorage.dfs.core.windows.net/myfs", key="access_key") #' create_adls_filesystem("https://mystorage.dfs.core.windows.net/newfs", key="access_key") #' delete_adls_filesystem("https://mystorage.dfs.core.windows.net/newfs", key="access_key") #' #' } #' @rdname adls_filesystem #' @export adls_filesystem <- function(endpoint, ...) { UseMethod("adls_filesystem") } #' @rdname adls_filesystem #' @export adls_filesystem.character <- function(endpoint, key=NULL, token=NULL, sas=NULL, api_version=getOption("azure_storage_api_version"), ...) { do.call(adls_filesystem, generate_endpoint_container(endpoint, key, token, sas, api_version)) } #' @rdname adls_filesystem #' @export adls_filesystem.adls_endpoint <- function(endpoint, name, ...) { obj <- list(name=name, endpoint=endpoint) class(obj) <- c("adls_filesystem", "storage_container") obj } #' @rdname adls_filesystem #' @export print.adls_filesystem <- function(x, ...) { cat("Azure Data Lake Storage Gen2 filesystem '", x$name, "'\n", sep="") url <- httr::parse_url(x$endpoint$url) url$path <- x$name cat(sprintf("URL: %s\n", httr::build_url(url))) if(!is_empty(x$endpoint$key)) cat("Access key: <hidden>\n") else cat("Access key: <none supplied>\n") if(!is_empty(x$endpoint$token)) { cat("Azure Active Directory token:\n") print(x$endpoint$token) } else cat("Azure Active Directory token: <none supplied>\n") if(!is_empty(x$endpoint$sas)) cat("Account shared access signature: <hidden>\n") else cat("Account shared access signature: <none supplied>\n") cat(sprintf("Storage API version: %s\n", x$endpoint$api_version)) invisible(x) } #' @rdname adls_filesystem #' @export list_adls_filesystems <- function(endpoint, ...) { UseMethod("list_adls_filesystems") } #' @rdname adls_filesystem #' @export list_adls_filesystems.character <- function(endpoint, key=NULL, token=NULL, sas=NULL, api_version=getOption("azure_storage_api_version"), ...) { do.call(list_adls_filesystems, generate_endpoint_container(endpoint, key, token, sas, api_version)) } #' @rdname adls_filesystem #' @export list_adls_filesystems.adls_endpoint <- function(endpoint, ...) { res <- call_storage_endpoint(endpoint, "/", options=list(resource="account"), http_status_handler="pass") httr::stop_for_status(res, storage_error_message((res))) continue <- httr::headers(res)$`x-ms-continuation` res <- httr::content(res, simplifyVector=TRUE) lst <- sapply(res$filesystems$name, function(fs) adls_filesystem(endpoint, fs), simplify=FALSE) while(!is_empty(continue) && nchar(continue) > 0) { res <- call_storage_endpoint( endpoint, "/", options=list(resource="account", continuation=continue), http_status_handler="pass" ) httr::stop_for_status(res, storage_error_message((res))) continue <- httr::headers(res)$`x-ms-continuation` res <- httr::content(res, simplifyVector=TRUE) lst <- c(lst, sapply(res$filesystems$name, function(fs) adls_filesystem(endpoint, fs), simplify=FALSE)) } lst } #' @rdname adls_filesystem #' @export create_adls_filesystem <- function(endpoint, ...) { UseMethod("create_adls_filesystem") } #' @rdname adls_filesystem #' @export create_adls_filesystem.character <- function(endpoint, key=NULL, token=NULL, sas=NULL, api_version=getOption("azure_storage_api_version"), ...) { endp <- generate_endpoint_container(endpoint, key, token, sas, api_version) create_adls_filesystem(endp$endpoint, endp$name, ...) } #' @rdname adls_filesystem #' @export create_adls_filesystem.adls_filesystem <- function(endpoint, ...) { create_adls_filesystem(endpoint$endpoint, endpoint$name) } #' @rdname adls_filesystem #' @export create_adls_filesystem.adls_endpoint <- function(endpoint, name, ...) { obj <- adls_filesystem(endpoint, name) do_container_op(obj, options=list(resource="filesystem"), http_verb="PUT") obj } #' @rdname adls_filesystem #' @export delete_adls_filesystem <- function(endpoint, ...) { UseMethod("delete_adls_filesystem") } #' @rdname adls_filesystem #' @export delete_adls_filesystem.character <- function(endpoint, key=NULL, token=NULL, sas=NULL, api_version=getOption("azure_storage_api_version"), ...) { endp <- generate_endpoint_container(endpoint, key, token, sas, api_version) delete_adls_filesystem(endp$endpoint, endp$name, ...) } #' @rdname adls_filesystem #' @export delete_adls_filesystem.adls_filesystem <- function(endpoint, ...) { delete_adls_filesystem(endpoint$endpoint, endpoint$name, ...) } #' @rdname adls_filesystem #' @export delete_adls_filesystem.adls_endpoint <- function(endpoint, name, confirm=TRUE, ...) { if(!delete_confirmed(confirm, paste0(endpoint$url, name), "filesystem")) return(invisible(NULL)) obj <- adls_filesystem(endpoint, name) invisible(do_container_op(obj, options=list(resource="filesystem"), http_verb="DELETE")) } #' Operations on an Azure Data Lake Storage Gen2 filesystem #' #' Upload, download, or delete a file; list files in a directory; create or delete directories; check file existence. #' #' @param filesystem An ADLSgen2 filesystem object. #' @param dir,file A string naming a directory or file respectively. #' @param info Whether to return names only, or all information in a directory listing. #' @param src,dest The source and destination paths/files for uploading and downloading. See 'Details' below. #' @param confirm Whether to ask for confirmation on deleting a file or directory. #' @param blocksize The number of bytes to upload/download per HTTP(S) request. #' @param recursive For the multiupload/download functions, whether to recursively transfer files in subdirectories. For `list_adls_files`, and `delete_adls_dir`, whether the operation should recurse through subdirectories. For `delete_adls_dir`, this must be TRUE to delete a non-empty directory. #' @param lease The lease for a file, if present. #' @param overwrite When downloading, whether to overwrite an existing destination file. #' @param use_azcopy Whether to use the AzCopy utility from Microsoft to do the transfer, rather than doing it in R. #' @param max_concurrent_transfers For `multiupload_adls_file` and `multidownload_adls_file`, the maximum number of concurrent file transfers. Each concurrent file transfer requires a separate R process, so limit this if you are low on memory. #' @param put_md5 For uploading, whether to compute the MD5 hash of the file(s). This will be stored as part of the file's properties. #' @param check_md5 For downloading, whether to verify the MD5 hash of the downloaded file(s). This requires that the file's `Content-MD5` property is set. If this is TRUE and the `Content-MD5` property is missing, a warning is generated. #' #' @details #' `upload_adls_file` and `download_adls_file` are the workhorse file transfer functions for ADLSgen2 storage. They each take as inputs a _single_ filename as the source for uploading/downloading, and a single filename as the destination. Alternatively, for uploading, `src` can be a [textConnection] or [rawConnection] object; and for downloading, `dest` can be NULL or a `rawConnection` object. If `dest` is NULL, the downloaded data is returned as a raw vector, and if a raw connection, it will be placed into the connection. See the examples below. #' #' `multiupload_adls_file` and `multidownload_adls_file` are functions for uploading and downloading _multiple_ files at once. They parallelise file transfers by using the background process pool provided by AzureRMR, which can lead to significant efficiency gains when transferring many small files. There are two ways to specify the source and destination for these functions: #' - Both `src` and `dest` can be vectors naming the individual source and destination pathnames. #' - The `src` argument can be a wildcard pattern expanding to one or more files, with `dest` naming a destination directory. In this case, if `recursive` is true, the file transfer will replicate the source directory structure at the destination. #' #' `upload_adls_file` and `download_adls_file` can display a progress bar to track the file transfer. You can control whether to display this with `options(azure_storage_progress_bar=TRUE|FALSE)`; the default is TRUE. #' #' `adls_file_exists` and `adls_dir_exists` test for the existence of a file and directory, respectively. #' #' ## AzCopy #' `upload_azure_file` and `download_azure_file` have the ability to use the AzCopy commandline utility to transfer files, instead of native R code. This can be useful if you want to take advantage of AzCopy's logging and recovery features; it may also be faster in the case of transferring a very large number of small files. To enable this, set the `use_azcopy` argument to TRUE. #' #' Note that AzCopy only supports SAS and AAD (OAuth) token as authentication methods. AzCopy also expects a single filename or wildcard spec as its source/destination argument, not a vector of filenames or a connection. #' #' @return #' For `list_adls_files`, if `info="name"`, a vector of file/directory names. If `info="all"`, a data frame giving the file size and whether each object is a file or directory. #' #' For `download_adls_file`, if `dest=NULL`, the contents of the downloaded file as a raw vector. #' #' For `adls_file_exists`, either TRUE or FALSE. #' #' @seealso #' [adls_filesystem], [az_storage], [storage_download], [call_azcopy] #' #' @examples #' \dontrun{ #' #' fs <- adls_filesystem("https://mystorage.dfs.core.windows.net/myfilesystem", key="access_key") #' #' list_adls_files(fs, "/") #' list_adls_files(fs, "/", recursive=TRUE) #' #' create_adls_dir(fs, "/newdir") #' #' upload_adls_file(fs, "~/bigfile.zip", dest="/newdir/bigfile.zip") #' download_adls_file(fs, "/newdir/bigfile.zip", dest="~/bigfile_downloaded.zip") #' #' delete_adls_file(fs, "/newdir/bigfile.zip") #' delete_adls_dir(fs, "/newdir") #' #' # uploading/downloading multiple files at once #' multiupload_adls_file(fs, "/data/logfiles/*.zip") #' multidownload_adls_file(fs, "/monthly/jan*.*", "/data/january") #' #' # you can also pass a vector of file/pathnames as the source and destination #' src <- c("file1.csv", "file2.csv", "file3.csv") #' dest <- paste0("uploaded_", src) #' multiupload_adls_file(share, src, dest) #' #' # uploading serialized R objects via connections #' json <- jsonlite::toJSON(iris, pretty=TRUE, auto_unbox=TRUE) #' con <- textConnection(json) #' upload_adls_file(fs, con, "iris.json") #' #' rds <- serialize(iris, NULL) #' con <- rawConnection(rds) #' upload_adls_file(fs, con, "iris.rds") #' #' # downloading files into memory: as a raw vector, and via a connection #' rawvec <- download_adls_file(fs, "iris.json", NULL) #' rawToChar(rawvec) #' #' con <- rawConnection(raw(0), "r+") #' download_adls_file(fs, "iris.rds", con) #' unserialize(con) #' #' } #' @rdname adls #' @export list_adls_files <- function(filesystem, dir="/", info=c("all", "name"), recursive=FALSE) { info <- match.arg(info) opts <- list( recursive=tolower(as.character(recursive)), resource="filesystem", directory=as.character(dir) ) out <- NULL repeat { res <- do_container_op(filesystem, "", options=opts, http_status_handler="pass") httr::stop_for_status(res, storage_error_message(res)) out <- vctrs::vec_rbind(out, httr::content(res, simplifyVector=TRUE)$paths) headers <- httr::headers(res) if(is_empty(headers$`x-ms-continuation`)) break else opts$continuation <- headers$`x-ms-continuation` } # cater for null output if(is_empty(out)) { out <- if(info == "name") character(0) else data.frame( name=character(0), size=numeric(0), isdir=logical(0), lastModified=structure(numeric(0), class=c("POSIXct", "POSIXt"), tzone="GMT"), permissions=character(0), etag=character(0)) return(out) } else if(info == "name") return(out$name) # normalise output if(is.null(out$isDirectory)) out$isDirectory <- FALSE else out$isDirectory <- !is.na(out$isDirectory) if(is.null(out$contentLength)) out$contentLength <- NA_real_ if(is.null(out$etag)) out$etag <- "" else out$etag[is.na(out$etag)] <- "" if(is.null(out$permissions)) out$permissions <- "" else out$permissions[is.na(out$permissions)] <- "" if(is.null(out$lastModified)) out$lastModified <- "" out <- out[c("name", "contentLength", "isDirectory", "lastModified", "permissions", "etag")] if(!is.null(out$contentLength)) out$contentLength <- as.numeric(out$contentLength) if(!is.null(out$lastModified)) out$lastModified <- as_datetime(out$lastModified) names(out)[c(2, 3)] <- c("size", "isdir") if(all(out$permissions == "")) out$permissions <- NULL if(all(out$etag == "")) out$etag <- NULL # needed when dir was created in a non-HNS enabled account out$size[out$isdir] <- NA out } #' @rdname adls #' @export multiupload_adls_file <- function(filesystem, src, dest, recursive=FALSE, blocksize=2^22, lease=NULL, put_md5=FALSE, use_azcopy=FALSE, max_concurrent_transfers=10) { if(use_azcopy) return(azcopy_upload(filesystem, src, dest, blocksize=blocksize, lease=lease, recursive=recursive, put_md5=put_md5)) multiupload_internal(filesystem, src, dest, recursive=recursive, blocksize=blocksize, lease=lease, put_md5=put_md5, max_concurrent_transfers=max_concurrent_transfers) } #' @rdname adls #' @export upload_adls_file <- function(filesystem, src, dest=basename(src), blocksize=2^24, lease=NULL, put_md5=FALSE, use_azcopy=FALSE) { if(use_azcopy) azcopy_upload(filesystem, src, dest, blocksize=blocksize, lease=lease, put_md5=put_md5) else upload_adls_file_internal(filesystem, src, dest, blocksize=blocksize, lease=lease, put_md5=put_md5) } #' @rdname adls #' @export multidownload_adls_file <- function(filesystem, src, dest, recursive=FALSE, blocksize=2^24, overwrite=FALSE, check_md5=FALSE, use_azcopy=FALSE, max_concurrent_transfers=10) { if(use_azcopy) return(azcopy_download(filesystem, src, dest, overwrite=overwrite, recursive=recursive, check_md5=check_md5)) multidownload_internal(filesystem, src, dest, recursive=recursive, blocksize=blocksize, overwrite=overwrite, check_md5=check_md5, max_concurrent_transfers=max_concurrent_transfers) } #' @rdname adls #' @export download_adls_file <- function(filesystem, src, dest=basename(src), blocksize=2^24, overwrite=FALSE, check_md5=FALSE, use_azcopy=FALSE) { if(use_azcopy) azcopy_download(filesystem, src, dest, overwrite=overwrite, check_md5=check_md5) else download_adls_file_internal(filesystem, src, dest, blocksize=blocksize, overwrite=overwrite, check_md5=check_md5) } #' @rdname adls #' @export delete_adls_file <- function(filesystem, file, confirm=TRUE) { if(!delete_confirmed(confirm, paste0(filesystem$endpoint$url, filesystem$name, "/", file), "file")) return(invisible(NULL)) invisible(do_container_op(filesystem, file, http_verb="DELETE")) } #' @rdname adls #' @export create_adls_dir <- function(filesystem, dir) { invisible(do_container_op(filesystem, dir, options=list(resource="directory"), http_verb="PUT")) } #' @rdname adls #' @export delete_adls_dir <- function(filesystem, dir, recursive=FALSE, confirm=TRUE) { if(!delete_confirmed(confirm, paste0(filesystem$endpoint$url, filesystem$name, "/", dir), "directory")) return(invisible(NULL)) # special-case handling of deletion of root dir if(dir == "/" && recursive) { lst <- list_adls_files(filesystem, "/", info="all") for(i in seq_len(nrow(lst))) { if(lst$isdir[i]) delete_adls_dir(filesystem, lst$name[i], recursive=TRUE, confirm=FALSE) else delete_adls_file(filesystem, lst$name[i], confirm=FALSE) } return(invisible(NULL)) } opts <- list(recursive=tolower(as.character(recursive))) invisible(do_container_op(filesystem, dir, options=opts, http_verb="DELETE")) } #' @rdname adls #' @export adls_file_exists <- function(filesystem, file) { res <- do_container_op(filesystem, file, headers = list(), http_verb = "HEAD", http_status_handler = "pass") if (httr::status_code(res) == 404L) return(FALSE) httr::stop_for_status(res, storage_error_message(res)) return(TRUE) } #' @rdname adls #' @export adls_dir_exists <- function(filesystem, dir) { if(dir == "/") return(TRUE) props <- try(get_storage_properties(filesystem, dir), silent=TRUE) if(inherits(props, "try-error")) return(FALSE) props[["x-ms-resource-type"]] == "directory" }
/scratch/gouwar.j/cran-all/cranData/AzureStor/R/adls_client_funcs.R
upload_adls_file_internal <- function(filesystem, src, dest, blocksize=2^24, lease=NULL, put_md5=FALSE) { src <- normalize_src(src, put_md5) on.exit(close(src$con)) headers <- list() if(!is.null(lease)) headers[["x-ms-lease-id"]] <- as.character(lease) do_container_op(filesystem, dest, options=list(resource="file"), headers=headers, http_verb="PUT") bar <- storage_progress_bar$new(src$size, "up") # transfer the contents blocklist <- list() pos <- 0 repeat { body <- readBin(src$con, "raw", blocksize) thisblock <- length(body) if(thisblock == 0) break opts <- list(action="append", position=sprintf("%.0f", pos)) headers <- list( `content-length`=sprintf("%.0f", thisblock), `content-md5`=encode_md5(body) ) if(!is.null(lease)) headers$`x-ms-lease-id` <- as.character(lease) do_container_op(filesystem, dest, headers=headers, body=body, options=opts, progress=bar$update(), http_verb="PATCH") bar$offset <- bar$offset + blocksize pos <- pos + thisblock } bar$close() # flush contents headers <- list(`content-type`=src$content_type) if(!is.null(src$md5)) headers$`x-ms-content-md5` <- src$md5 if(!is.null(lease)) headers$`x-ms-lease-id` <- as.character(lease) do_container_op(filesystem, dest, options=list(action="flush", position=sprintf("%.0f", pos)), headers=headers, http_verb="PATCH") invisible(NULL) } download_adls_file_internal <- function(filesystem, src, dest, blocksize=2^24, overwrite=FALSE, check_md5=FALSE) { headers <- list() dest <- init_download_dest(dest, overwrite) on.exit(dispose_download_dest(dest)) # get file size (for progress bar) and MD5 hash props <- get_storage_properties(filesystem, src) size <- as.numeric(props[["content-length"]]) src_md5 <- props[["content-md5"]] bar <- storage_progress_bar$new(size, "down") offset <- 0 while(offset < size) { headers$Range <- sprintf("bytes=%.0f-%.0f", offset, offset + blocksize - 1) res <- do_container_op(filesystem, src, headers=headers, progress=bar$update(), http_status_handler="pass") httr::stop_for_status(res, storage_error_message(res)) writeBin(httr::content(res, as="raw"), dest) offset <- offset + blocksize bar$offset <- offset } bar$close() if(check_md5) do_md5_check(dest, src_md5) if(inherits(dest, "null_dest")) rawConnectionValue(dest) else invisible(NULL) }
/scratch/gouwar.j/cran-all/cranData/AzureStor/R/adls_transfer_internal.R