4

I am building a shiny app that scores the data of the deep learning model using h2o engine.

I could achieve my goal by simply placing my predicting operation into the function. In this function I would typically start my deep learning machine, make calculations and stop it. This is unfortunately slow.

My goal is to start h2o in the beginning, when user starts shiny app from R-Server and then to make sure the h2o virtual machine will shutdown when user closes the browser.

I would ask to suggest the most optimal way to do that because I am not fully satisfied with this method taken from here where I just placed these lines of code into global.R script:

#global.R
library(h2o)
h2o.init(nthreads = 2)
onStop(function() {
  # shut down the h2o on app exit see 
  h2o.shutdown(prompt = FALSE)
})

It seems that sometimes my h2o instance is stopped before as I got an error Error in h2o.shutdown(prompt = FALSE) : There is no H2O instance running.

... I am now testing it in the browser but I just want to make sure there would be no consequences on the R-Server

Any help is appreciated!

topchef
  • 19,091
  • 9
  • 63
  • 102
vlad1490
  • 355
  • 2
  • 8

2 Answers2

2

You could try using try-catch to prevent that error message. This is how I initialize from my local machine:

  # Try to connect to existing cluster. If it does not exist then initialize.
  errorStatus <- tryCatch({
    h2o.init(startH2O = FALSE)
  }, error = function(err) {
    errorStatus <- err[1]$message
    message(paste0(errorStatus,"\n Initializing new H2O cluster..."))
    # Inititialize H2o cluster
    try({h2o.shutdown(prompt = FALSE)}, silent=TRUE)
    h2o.init(ip = 'localhost', port = 54321, nthreads= -1, max_mem_size = '4g')
    return(errorStatus)
  }) # END tryCatch

  # Shut down H2O cluster on app exit
  onStop(function() {
    try({h2o.shutdown(prompt = FALSE)}, silent=TRUE)
  })
1

When you get the error "There is no H2O instance running" it really means there is nothing to shut down so in your case it's not an error. Of course, you should test that by logging into your R-Server and when you get the error checking if the h2o process running or not:

ps -eaf | grep h2o

The method using global.R is completely legitimate for Shiny app.

UPDATE: Beware that if you run multiple Shiny apps each of them may start their own h2o instance, or they may share the same instance and run into conflicts. So test this in advance not to run into unexpected conflicts/errors/

topchef
  • 19,091
  • 9
  • 63
  • 102