GithubHelp home page GithubHelp logo

agaveplatform / r-sdk Goto Github PK

View Code? Open in Web Editor NEW
0.0 2.0 1.0 691 KB

Official R client SDK to the Agave Platform -- EARLY ALPHA

Home Page: https://agaveapi.co/

License: Other

R 97.58% Shell 0.40% HTML 1.80% Dockerfile 0.21%

r-sdk's Introduction

R client SDK for the Agave Platform

Power your digital lab and reduce the time from theory to discovery using the Agave Science-as-a-Service API Platform. Agave provides hosted services that allow researchers to manage data, conduct experiments, and publish and share results from anywhere at any time.

Overview

The Agave R client SDK is based off the vanilla REST API client code generated by the swagger-codegen project. Additional scripts were added to ease authentication and authorization, session management, serialization, and improve syntax.

  • API version: 2.2.14
  • Package version: 1.0.0
  • Build package: io.swagger.codegen.languages.RClientCodegen

Installation

You'll need the devtools package in order to build the API. Make sure you have a proper CRAN repository from which you can download packages.

Prerequisites

Install the devtools package with the following command.

> if(!require(devtools)) { install.packages("devtools") }
> if(!require(devtools)) { install.packages("plyr") }

If you would like to rebuild the documentation, you will need to install roxygen2.

> if(!require(roxygen2)) { install.packages("roxygen2") }

Installation from Github

To install the package directly from the master branch in Github

> library(devtools)
> install_github("agaveplatform/r-sdk")

Installation from source

Make sure you set the working directory to the repository home directory. Then execute

> library(devtools)
> install(".")

Using rAgave in Docker

========================

This repository includes a Dockerfile and a docker-compose.yml file, which allows a zero installation version of rAgave in RStudio.

The only requirement is Docker and Docker Compose. Please consult the official Docker website for installation instructions for your system.

To bring up your development environment, clone this repository and execute docker-compose as follows:

$ git clone https://github.com/agaveplatform/r-sdk.git agave-r-sdk
$ cd agave-r-sdk
$ docker-compose build
$ docker-compose up

Navigate to http://localhost:8787 and access the RStudio server with username and password "rstudio". The notebook R-example.Rmd contains a full example of use.

Quickstart

Import the library into your current session namespace.

> library(rAgave)

Now we can create an Agave instance pointing to your tenant:

> library(rAgave)
> api = Agave$new(baseUrl="https://public.agaveapi.org",
                  username="myusername",
                  password="mypassword")

Once the object is instantiated, interact with it according to the methods in the API documentation.

For example, create a new client with:

> clientData <- Client$new(clientName="my_client")
> api$clientInfo <- api$clients$create(body=clientData)
> api$store()

You may also pass in a list, if preferred, over the object model

> api$clientInfo <- api$clients$create(body=list(clientName="my_client"))
> api$store()

Access any endpoint with:

> api$systems$listSystems()
> api$jobs$submitJob(body=Job$new(appId="head-1.0u1"))

Once a client is created, it is used by default to access the API.

To make use of an existing client, pass the client's credentials into the Agave constructor:

> library("rAgave")
> api = Agave$new(baseUrl="https://public.agaveapi.co",
              username="myusername", password="mypassword",
              clientKey="123", clientSecret="abc")

If you do not pass in any client, credential, token, or tenant information in your constructor, the SDK will look for those values in your runtime environment. The following table lists the environment variables corresponding to each constructor argument in the SDK.

Argument Environment Variable
baseUrl AGAVE_BASE_URL, AGAVE_TENANT_BASE_URL
username AGAVE_USERNAME
password AGAVE_PASSWORD
clientKey AGAVE_CLIENT_KEY
clientSecret AGAVE_CLIENT_SECRET
tenant AGAVE_TENANT
cacheDir AGAVE_CACHE_DIR
accessToken AGAVE_ACCESS_TOKEN
refreshToken AGAVE_REFRESH_TOKEN

The following code would produce the identical result as the previous example.

> library("rAgave")
> Sys.setenv(AGAVE_BASE_URL = "https://public.agaveapi.co",
+            AGAVE_USERNAME = "myusername",
+            AGAVE_PASSWORD = "mypassword",
+            AGAVE_CLIENT_KEY = "123",
+            AGAVE_CLIENT_SECRET = "abc")
> api = Agave$new()

If you do not know the baseUrl of your tenant, you can simply provide the tenant code. The following example will initialize instances of the SDK for the Agave Public tenant, Cyverse Tenant, and DesignSafe tenants respectively.

> library("rAgave")
> api = Agave$new(tenant="agave.prod")
> api = Agave$new(tenant="iplantc.org")
> api = Agave$new(tenant="designsafe")

If you do not know the code or url of your tenant, you can query the Tenants API to find a list of all the available tenants.

> library("rAgave")
> api <- Agave$new()
> tenants <- api$tenants$list(responseType="df")
> tenants$code
 [1] agave.prod    araport.org   designsafe    iplantc.org   irec         
 [6] irmacs        sd2e          sgci          tacc.prod     vdjserver.org
> api$tenantInfo <- tenants[[1]]

Alternatively, the SDK will attempt to recover the client credentials from a predictable location disk. The default cache directory is $HOME/.agave. You can configure the location of the cache directory when instantiating a new Agave object:

> library("rAgave")
> api = Agave$new(cacheDir="/Dropbox/agave/cache")

The format of the cache file is recognized by all Agave SDK, so you can freely move across multiple SDK without having to reauthenticate each time.

Your password will never be written to the cache file.

rAgave will automatically update the cache file any time you create or update your client or authenticate. Thus, subsequent instantiations can be streamlined to use the no-arg constructor as rAgave will automatically refresh your access token for you.

> api = Agave$new()

rAgave leverages the futile.logger package to provide a custom logging output similar to log4j. You can enabled logging at runtime by specifying the logLevel parameter in the constructor. The following log levels are predefined as constants: TRACE, DEBUG, INFO, WARN, FATAL. The log level is set to FATAL by default.

> api = Agave$new(logLevel = INFO)

You can also change the log level at runtime by upating the logLevel attibute of an Agave class instance.

> api = Agave$new()
> api$logLevel <- TRACE
> profile <- api$profiles$getDetails()
> api$logLevel <- DEBUG
> profile <- api$jobs$listJobs()
> api$logLevel <- FATAL

When enabled, logs will be written to agave.log in the currrent directory (getwd()). You can specify an alternative location by specifying the logFilePath parameter in the constructor.

> api = Agave$new(logFilePath = "/var/log/rAgave.log", logLevel = INFO)

References

License

The Agave Platform and rAgave are licensed under the BSD 3-Clause license.

r-sdk's People

Contributors

deardooley avatar

Watchers

 avatar  avatar

Forkers

dhbrand

r-sdk's Issues

Could not install from NAMESPACE error

Tried to install the package via clone repo change working directory in R to repo directory and follow

library(devtools)
install(".")

Generated the following error:

> setwd("~/Stapleton_Lab/agave-rlang-sdk")
> install(".")
Installing swagger
'/Library/Frameworks/R.framework/Resources/bin/R' --no-site-file --no-environ --no-save --no-restore --quiet CMD INSTALL  \
  '/Users/d3r3zz3d/Stapleton_Lab/agave-rlang-sdk'  \
  --library='/Library/Frameworks/R.framework/Versions/3.4/Resources/library' --install-tests 

* installing *source* package ‘swagger’ ...
ERROR: a 'NAMESPACE' file is required
* removing ‘/Library/Frameworks/R.framework/Versions/3.4/Resources/library/swagger’
 Show Traceback
 
 Rerun with Debug
 Error: Command failed (1) 

Opened terminal and cd to repo directory. Issued command:
echo 'exportPattern( "." )' > NAMESPACE
and then reattempted install(".") with success.

Cannot Instantiate using the Example

Running through the example using the Docker environment and receiving an error when running the
ag <-Agave$new command.
The console output is below. In the instructions you might mention to the user to change their working directory to the examples folder and the install("..") to install("../rAgave")

`R version 3.4.3 (2017-11-30) -- "Kite-Eating Tree"
Copyright (C) 2017 The R Foundation for Statistical Computing
Platform: x86_64-pc-linux-gnu (64-bit)

R is free software and comes with ABSOLUTELY NO WARRANTY.
You are welcome to redistribute it under certain conditions.
Type 'license()' or 'licence()' for distribution details.

R is a collaborative project with many contributors.
Type 'contributors()' for more information and
'citation()' on how to cite R or R packages in publications.

Type 'demo()' for some demos, 'help()' for on-line help, or
'help.start()' for an HTML browser interface to help.
Type 'q()' to quit R.

Error in loadNamespace(name) : there is no package called ‘rmarkdown’
31 Jan 2018 17:34:20 [rsession-rstudio] ERROR r error 4 (R code execution error) [errormsg=Error in loadNamespace(name) : there is no package called ‘rmarkdown’
]; OCCURRED AT: rstudio::core::Error rstudio::r::exec::{anonymous}::evaluateExpressionsUnsafe(SEXP, SEXP, SEXPREC**, rstudio::r::sexp::Protect*, rstudio::r::exec::{anonymous}::EvalType) /home/ubuntu/rstudio/src/cpp/r/RExec.cpp:159; LOGGED FROM: void rstudio::session::modules::rmarkdown:📓:{anonymous}::onDocAdded(const string&) /home/ubuntu/rstudio/src/cpp/session/modules/rmarkdown/NotebookCache.cpp:341

library("rAgave")

For security, we'll pull our variables from the environment rather than enter them directly.

myCreds <- Sys.getenv( c("AGAVE_USERNAME", "AGAVE_PASSWORD", "AGAVE_TENANT", "AGAVE_BASE_URL"), names = TRUE )

Prompt for them if not present, and store them in the environment in case we rerun this later.

if (is.null(myCreds[["AGAVE_USERNAME"]]) || nchar(myCreds[["AGAVE_USERNAME"]]) == 0) {

  • myCreds[["AGAVE_USERNAME"]] <- readline("Agave username:")
  • Sys.setenv(AGAVE_USERNAME = myCreds[["AGAVE_USERNAME"]])
  • }
    Agave username:dhbrand

if (is.null(myCreds[["AGAVE_PASSWORD"]]) || nchar(myCreds[["AGAVE_PASSWORD"]]) == 0) {

  • myCreds[["AGAVE_PASSWORD"]] <- readline("Agave password:")
  • Sys.setenv(AGAVE_PASSWORD = myCreds[["AGAVE_PASSWORD"]])
  • }
    Agave password:Engaged1001

if (is.null(myCreds[["AGAVE_BASE_URL"]]) || nchar(myCreds[["AGAVE_BASE_URL"]]) == 0) {

#detach("package:futile.logger", unload=TRUE)
#detach("package:rAgave", unload=TRUE)
install("..")
Error: Could not find package root.
getwd()
[1] "/home/rstudio"
setwd("~/examples")
library("rAgave")

For security, we'll pull our variables from the environment rather than enter them directly.

myCreds <- Sys.getenv( c("AGAVE_USERNAME", "AGAVE_PASSWORD", "AGAVE_TENANT", "AGAVE_BASE_URL"), names = TRUE )
#detach("package:futile.logger", unload=TRUE)
#detach("package:rAgave", unload=TRUE)
install("..")
Error: Could not find package root.
getwd()
[1] "/home/rstudio/examples"
#detach("package:futile.logger", unload=TRUE)
#detach("package:rAgave", unload=TRUE)
install("../rAgave")
Installing rAgave
'/usr/local/lib/R/bin/R' --no-site-file --no-environ --no-save --no-restore --quiet CMD INSTALL
'/home/rstudio/rAgave' --library='/usr/local/lib/R/site-library' --install-tests

  • installing source package ‘rAgave’ ...
    ** R
    ** preparing package for lazy loading
    ** help
    No man pages found in package ‘rAgave’
    *** installing help indices
    ** building package indices
    ** testing if installed package can be loaded
  • DONE (rAgave)
    Reloading installed rAgave

ag <-Agave$new( baseUrl = myCreds[["AGAVE_BASE_URL"]],

  •             username = myCreds[["AGAVE_USERNAME"]], 
    
  •             password = myCreds[["AGAVE_PASSWORD"]])
    

cannot open file 'agave.log': Permission deniedError in file(file, ifelse(append, "a", "w")) :
cannot open the connection`

Coding style recommendations

Using the SDK a bit, I'm wondering about what people prefer with respect to coding style. I see a few common recommendations showing up in Google searches:

The current syntax is akin to Google's style guide, but feels a little non-idiomatic for a scripting language. Would it be more helpful for existing users if the R SDK mirrored the agavepy syntax, or would it be more helpful to adhere to the existing structure which more closely reflects the Java, PHP, and AngularJS syntax?

Current/Google

library("rAgave")
api <- Agave$new()
system <- api$systems$getDetails(id = "example.com")
print(system$storage$rootDir)

tidyverse

library("r_agave")
api <- agave$new()
system <- api$systems$get_details(id = "example.com")
print(system$storage$root_dir)

We might also consider use S3 classes instead of S6 classes, which would allow for a pythonic dot notation that reads a bit more like core R

library("agave")
api <- new_agave()
system <- api.systems.get_details(id = "example.com")

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.