Class: Cute::G5K::API

Inherits:
Object
  • Object
show all
Defined in:
lib/cute/g5k_api.rb

Overview

This class helps you to access Grid’5000 REST API. Thus, the most common actions such as reservation of nodes and deployment can be easily scripted. If you are using this module outside Grid’5000 you should created a configuration file with the following contents:

$ cat > ~/.grid5000_api.yml << EOF
  uri: https://api.grid5000.fr/
  username: user
  password: **********
  version: stable
  EOF

You can take a look at the G5K::API constructor to see more details of this configuration.

Getting started

As already said, the goal of G5K::API class is to present a high level abstraction to manage the most common activities in Grid’5000 such as: the reservation of resources and the deployment of environments. Consequently, these activities can be easily scripted using Ruby. The advantage of this is that you can use all Ruby constructs (e.g., loops, conditionals, blocks, iterators, etc) to script your experiments. In the presence of error, G5K::API raises exceptions (see G5K exceptions), that you can handle to decide the workflow of your experiment (see wait_for_deploy and wait_for_job). In the following example it is shown how G5K::API is used. The example represents the reservation of 3 nodes in Nancy site for 1 hour:

require 'cute'

g5k = Cute::G5K::API.new()

job = g5k.reserve(:nodes => 3, :site => 'nancy', :walltime => '01:00:00')

puts "Assigned nodes : #{job['assigned_nodes']}"

If that is all you want to do, you can write that into a file, let’s say example.rb and execute it using the Ruby interpreter.

$ ruby example.rb

The execution will block until you got the reservation. Then, you can interact with the nodes you reserved in the way you used to or add more code to the previous script for controlling your experiment with Ruby-Cute as shown in this example. We have just used the method reserve that allow us to reserve resources in Grid’5000. This method can be used to reserve resources in deployment mode and deploy our own software environment on them using / Kadeploy. For this we use the option :env of the reserve method. Therefore, it will first reserve the resources and then deploy the specified environment. The method reserve will block until the deployment is done. The following Ruby script illustrates all we have just said.

require 'cute'

g5k = Cute::G5K::API.new()

job = g5k.reserve(:nodes => 1, :site => 'grenoble', :walltime => '00:40:00', :env => 'wheezy-x64-base')

puts "Assigned nodes : #{job['assigned_nodes']}"

By default your public ssh key ‘~/.ssh/id_rsa.pub’ will be copied on the deployed machines, you can specify another path for your keys with the option :keys. In order to deploy your own environment, you have to put the tar file that contains the operating system you want to deploy and the environment description file, under the public directory of a given site. VLANS are supported by adding the parameter :vlan => type where type can be: kavlan, kavlan-global, kavlan-local. The following example, reserves 10 nodes in the Lille site, starts the deployment of a custom environment over the nodes and puts the nodes under a routed VLAN. The different types of VLANs are described in KaVLAN We used the method get_vlan_nodes to get the new hostnames assigned to your nodes.

require 'cute'

g5k = Cute::G5K::API.new()

job = g5k.reserve(:site => "lille", :nodes => 10,
                  :env => 'http://public.lyon.grid5000.fr/~user/debian_custom_img.yaml',
                  :vlan => "kavlan", :keys => "~/my_ssh_key")

puts "Log in into the nodes using the following hostnames: #{g5k.get_vlan_nodes(job)}"

You should make sure when using custom environments that in the Kadeploy description file, you use an URL to specify the path to the tarball. Otherwise, you will get the error ‘Invalid client’s export’. If you do not want that the method reserve perform the deployment for you, you have to use the option :type => :deploy. This can be useful when deploying different environments in your reserved nodes, for example: deploying the environments for a small HPC cluster. You have to use the method deploy for performing the deploy. This method do not block by default, that is why you have to use the method wait_for_deploy in order to block the execution until the deployment is done.

require 'cute'

g5k = Cute::G5K::API.new()

job = g5k.reserve(:site => "lyon", :nodes => 5, :walltime => "03:00:00", :type => :deploy)

nodes = job["assigned_nodes"]

slaves = nodes[1..4]
master = nodes-slaves

g5k.deploy(job,:nodes => master, :env => 'http://public.lyon.grid5000.fr/~user/debian_master_img.yaml')
g5k.deploy(job,:nodes => slaves, :env => 'http://public.lyon.grid5000.fr/~user/debian_slaves_img.yaml')

g5k.wait_for_deploy(job)

puts "master node: #{master}"
puts "slaves nodes: #{slaves}"

You can check out the documentation of reserve and deploy methods to know all the parameters supported and more complex uses.

Another useful methods

Let’s use pry to show other useful methods. As shown in Ruby Cute the cute command will open a pry shell with some modules preloaded and it will create the variable $g5k to access G5K::API class. Therefore, we can consult the name of the cluster available in a specific site.

[4] pry(main)> $g5k.cluster_uids("grenoble")
=> ["adonis", "edel", "genepi"]

As well as the deployable environments:

[6] pry(main)> $g5k.environment_uids("grenoble")
=> ["squeeze-x64-base", "squeeze-x64-big", "squeeze-x64-nfs", "wheezy-x64-base", "wheezy-x64-big", "wheezy-x64-min", "wheezy-x64-nfs", "wheezy-x64-xen"]

For getting a list of sites available in Grid’5000 you can use:

[7] pry(main)> $g5k.site_uids()
=> ["grenoble", "lille", "luxembourg", "lyon",...]

We can get the status of nodes in a given site by using:

[8] pry(main)> $g5k.nodes_status("lyon")
 => {"taurus-2.lyon.grid5000.fr"=>"besteffort", "taurus-16.lyon.grid5000.fr"=>"besteffort", "taurus-15.lyon.grid5000.fr"=>"besteffort", ...}

We can get information about our submitted jobs by using:

[11] pry(main)> $g5k.get_my_jobs("grenoble")
=> [{"uid"=>1679094,
     "user_uid"=>"cruizsanabria",
     "user"=>"cruizsanabria",
     "walltime"=>3600,
     "queue"=>"default",
     "state"=>"running", ...}, ...]

If we are done with our experiment, we can release the submitted job or all jobs in a given site as follows:

[12] pry(main)> $g5k.release(job)
[13] pry(main)> $g5k.release_all("grenoble")

How to debug

There are two ways for debugging: (1) by using the option :debug when initializing the G5K::API object or (2) by enabling the RestClient’s logging:

RESTCLIENT_LOG=stdout cute
RESTCLIENT_LOG=stdout path/to/my/script

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(params = {}) ⇒ API

Initializes a REST connection for Grid’5000 API

Example

You can specify another configuration file using the option :conf_file, for example:

g5k = Cute::G5K::API.new(:conf_file =>"config file path")

You can specify other parameters to use:

g5k = Cute::G5K::API.new(:uri => "https://api.grid5000.fr", :version => "sid")

If you want to ignore ResquestFailed exceptions you can use:

g5k = Cute::G5K::API.new(:on_error => :ignore)

To activate debugging mode you can use the option :debug:

g5k =  Cute::G5K::API.new(:debug => true)

This will provide you with a curl command to try by hand the same request the library is trying to perform. For example:

2016-09-27 11:25:34.039 => CMD debug: curl -kn https://api.grid5000.fr/3.0/sites/nancy/deployments/?user=cruizsanabria

Parameters:

  • params (Hash) (defaults to: {})

    Contains initialization parameters.

Options Hash (params):

  • :conf_file (String)

    Path for configuration file

  • :uri (String)

    REST API URI to contact

  • :version (String)

    Version of the REST API to use

  • :username (String)

    Username to access the REST API

  • :password (String)

    Password to access the REST API

  • :on_error (Symbol)

    Set to :ignore if you want to ignore ResquestFailed exceptions.

  • :debug (Boolean)

    Activate the debug mode

  • :timeout (Integer)

    Set the timeout in sec, default is 30 sec



573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
# File 'lib/cute/g5k_api.rb', line 573

def initialize(params={})
  config = {}
  default_file = "#{ENV['HOME']}/.grid5000_api.yml"

  if params[:conf_file].nil? then
    params[:conf_file] =  default_file if File.exist?(default_file)
  end

  params[:username] ||= params[:user]
  params[:password] ||= params[:pass] # backward compatibility

  config = YAML.load(File.open(params[:conf_file],'r')) unless params[:conf_file].nil?
  @user = params[:username] || config["username"]
  @pass = params[:password] || config["password"]
  @uri = params[:uri] || config["uri"] || "https://api.grid5000.fr/"
  @api_version = params[:version] || config["version"] || "stable"
  @logger = nil
  @debug = params[:debug] || false
  @timeout = params[:timeout] || 30

  begin
    @g5k_connection = G5KRest.new(@uri,@api_version,@user,@pass,params[:on_error], @timeout)
  rescue => e

    msg_create_file = ""
    if (not File.exist?(default_file)) && params[:conf_file].nil? then
      msg_create_file = "Please create the file: ~/.grid5000_api.yml and
                    put the necessary credentials or use the option
                    :conf_file to indicate another file for the credentials"
    end
    raise "Unable to authorize against the Grid'5000 API.
          #{e.message}
          #{msg_create_file}"


  end
end

Instance Attribute Details

#loggerObject

Assigns a logger

Examples

You can use this attribute to control how to log all messages produce by G5K::API. For example, below we use the logger available in Ruby standard library.

require 'cute'
require 'logger'

g5k = Cute::G5K::API.new()

g5k.logger = Logger.new(File.new('experiment_1.log'))


539
540
541
# File 'lib/cute/g5k_api.rb', line 539

def logger
  @logger
end

Instance Method Details

#api_uri(path) ⇒ String

Returns a valid URI using the current G5K API version.

Returns:



1378
1379
1380
1381
# File 'lib/cute/g5k_api.rb', line 1378

def api_uri(path)
  path = path[1..-1] if path.start_with?('/')
  return "#{@api_version}/#{path}"
end

#check_deployment(deploy_info) ⇒ Array

It returns an array of machines that did not deploy successfully

Example

It can be used to try a new deploy:

badnodes = g5k.check_deployment(job["deploy"].last)
g5k.deploy(job,:nodes => badnodes, :env => 'wheezy-x64-base')
g5k.wait_for_deploy(job)

Parameters:

  • deploy_info (Hash)

    deployment structure information

Returns:

  • (Array)

    machines that did not deploy successfully



1372
1373
1374
# File 'lib/cute/g5k_api.rb', line 1372

def check_deployment(deploy_info)
  deploy_info["result"].select{ |_p,v|  v["state"] == "KO"}.keys
end

#cluster_uids(site) ⇒ Array

Returns all cluster identifiers

Example:

cluster_uids("grenoble") #=> ["adonis", "edel", "genepi"]

Returns:

  • (Array)

    cluster identifiers



657
658
659
# File 'lib/cute/g5k_api.rb', line 657

def cluster_uids(site)
  return clusters(site).uids
end

#clusters(site) ⇒ Array

Returns the description of clusters that belong to a given Grid’5000 site.

Parameters:

  • site (String)

    a valid Grid’5000 site name

Returns:

  • (Array)

    the description of clusters that belong to a given Grid’5000 site



706
707
708
# File 'lib/cute/g5k_api.rb', line 706

def clusters(site)
  @g5k_connection.get_json(api_uri("sites/#{site}/clusters")).items
end

#deploy(job, opts = {}) ⇒ G5KJSON

Deploys an environment in a set of reserved nodes using / Kadeploy. A job structure returned by reserve or get_my_jobs methods is mandatory as a parameter as well as the environment to deploy. By default this method does not block, for that you have to set the option :wait to true.

Examples

Deploying the production environment wheezy-x64-base on all the reserved nodes and wait until the deployment is done:

deploy(job, :env => "wheezy-x64-base", :wait => true)

Other parameters you can specify are :nodes [Array] for deploying on specific nodes within a job and :keys [String] to specify the public key to use during the deployment.

deploy(job, :nodes => ["genepi-2.grid5000.fr"], :env => "wheezy-x64-xen", :keys => "~/my_key")

The parameter :keys [String] can be a string specifying the path of the key (as the previous case) or the contents of the public ssh key as the example given below:

deploy(job,:env => "jessie-x64-big", :keys =>  File.read("/tmp/test_key/test_key.pub"))

Parameters:

  • job (G5KJSON)

    as described in job

  • opts (Hash) (defaults to: {})

    Deploy options

Options Hash (opts):

  • :env (String)

    / Kadeploy environment to deploy

  • :user (String)

    User owning the Kadeploy environment

  • :nodes (Array)

    Specifies the nodes to deploy on

  • :keys (String)

    Specifies the SSH keys to copy for the deployment. By default, the content of ~/.ssh/id_rsa.pub is used.

  • :wait (Boolean)

    Whether or not to wait until the deployment is done (default is false)

  • :vlan (Boolean)

    VLAN id (number) to use (default is none)

Returns:

  • (G5KJSON)

    a job with deploy information as described in job

Raises:

  • (ArgumentError)


1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
# File 'lib/cute/g5k_api.rb', line 1211

def deploy(job, opts = {})

  # checking valid options, same as reserve option even though some option dont make any sense
  valid_opts = [:site, :cluster, :switches, :cpus, :cores, :nodes, :walltime, :cmd,
                :type, :name, :subnets, :env, :vlan_id, :properties, :resources,
                :reservation, :wait, :keys, :queue, :env_user]

  unre_opts = opts.keys - valid_opts
  raise ArgumentError, "Unrecognized option #{unre_opts}" unless unre_opts.empty?

  raise ArgumentError, "Unrecognized job format" unless job.is_a?(G5KJSON)

  env = opts[:env]
  raise ArgumentError, "Environment must be given" if env.nil?

  nodes = opts[:nodes].nil? ? job['assigned_nodes'] : opts[:nodes]
  raise "Unrecognized nodes format, use an Array" unless nodes.is_a?(Array)

  site = @g5k_connection.follow_parent(job).uid

  if opts[:keys].nil? then
    public_key_path = File.expand_path("~/.ssh/id_rsa.pub")
    if File.exist?(public_key_path) then
      public_key_file = File.read(public_key_path)
    else
      raise ArgumentError, "No public ssh key found"
    end

  else
    # We check if the string passed contains the ssh public key
    if (opts[:keys].length < 300 && (opts[:keys] =~ /^ssh.*/).nil?)
      public_key_file = File.read("#{File.expand_path(opts[:keys])}.pub").chop
    else
      public_key_file = opts[:keys]
    end
  end

  payload = {
             'nodes' => nodes,
             'environment' => env,
             'key' => public_key_file,
            }

  payload['vlan'] = opts[:vlan_id] if opts[:vlan_id]

  payload['user'] = opts[:env_user] unless opts[:env_user].nil?

  info "Creating deployment"

  begin
    info debug_cmd(api_uri("sites/#{site}/deployments"),"POST",payload.to_json), :debug
    r = @g5k_connection.post_json(api_uri("sites/#{site}/deployments"), payload)
  rescue Error => e
    info "Fail to deploy"
    info e.message
    e.http_body.split("\\n").each{ |line| info line}
    raise
  end

  job["deploy"] = [] if job["deploy"].nil?

  job["deploy"].push(r)

  job = wait_for_deploy(job) if opts[:wait] == true

  return job

end

#deploy_status(job, filter = {}) ⇒ Array

Returns the status of all deployments performed within a job. The results can be filtered using a Hash with valid deployment properties described in Grid’5000 API spec.

Example

deploy_status(job, :nodes => ["adonis-10.grenoble.grid5000.fr"], :status => "terminated")

Parameters:

  • job (G5KJSON)

    as described in job

  • filter (Hash) (defaults to: {})

    filter the deployments to be returned.

Returns:

  • (Array)

    status of deploys within a job



1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
# File 'lib/cute/g5k_api.rb', line 1291

def deploy_status(job,filter = {})

  job["deploy"].map!{  |d| d.refresh(@g5k_connection) }

  filter.keep_if{ |_k,v| v} # removes nil values
  if filter.empty?
    status = job["deploy"].map{ |d| d["status"] }
  else
    status = job["deploy"].map{ |d| d["status"] if filter.select{ |k,v| d[k.to_s] != v }.empty? }
  end
  return status.compact

end

#environment_uids(site) ⇒ Array

Returns the name of the environments deployable in a given site. These can be used with reserve and deploy methods

Example:

environment_uids("nancy") #=> ["squeeze-x64-base", "squeeze-x64-big", "squeeze-x64-nfs", ...]

Returns:

  • (Array)

    environment identifiers



668
669
670
671
672
673
674
675
676
677
678
# File 'lib/cute/g5k_api.rb', line 668

def environment_uids(site)
  # environments are returned by the API following the format squeeze-x64-big-1.8
  # it returns environments without the version
  environment_uids = environments(site).uids.map{ |e|
    e_match = /(.*)-(.*)/.match(e)
    new_name = e_match.nil? ? "" : e_match[1]
    new_name
  }

  return environment_uids.uniq
end

#environments(site) ⇒ Array

Returns the description of all environments registered in a Grid’5000 site.

Returns:

  • (Array)

    the description of all environments registered in a Grid’5000 site



711
712
713
# File 'lib/cute/g5k_api.rb', line 711

def environments(site)
  @g5k_connection.get_json(api_uri("sites/#{site}/environments")).items
end

#g5k_userString

Returns Grid’5000 user.

Returns:

  • (String)

    Grid’5000 user



637
638
639
# File 'lib/cute/g5k_api.rb', line 637

def g5k_user
  return @user.nil? ? ENV['USER'] : @user
end

#get_deployments(site, uid = nil) ⇒ Hash

Returns the last 50 deployments performed in a Grid’5000 site.

Parameters:

  • site (String)

    a valid Grid’5000 site name

  • uid (String) (defaults to: nil)

    user name in Grid’5000

Returns:

  • (Hash)

    the last 50 deployments performed in a Grid’5000 site



747
748
749
750
# File 'lib/cute/g5k_api.rb', line 747

def get_deployments(site, uid = nil)
  info(debug_cmd(api_uri("sites/#{site}/deployments/?user=#{uid}"),"GET"), :debug)
  @g5k_connection.get_json(api_uri("sites/#{site}/deployments/?user=#{uid}")).items
end

#get_job(site, jid) ⇒ Hash

Returns information concerning a given job submitted in a Grid’5000 site.

Parameters:

  • site (String)

    a valid Grid’5000 site name

  • jid (Fixnum)

    a valid job identifier

Returns:

  • (Hash)

    information concerning a given job submitted in a Grid’5000 site



755
756
757
758
# File 'lib/cute/g5k_api.rb', line 755

def get_job(site, jid)
  info(debug_cmd(api_uri("/sites/#{site}/jobs/#{jid}"),"GET"), :debug)
  @g5k_connection.get_json(api_uri("/sites/#{site}/jobs/#{jid}"))
end

#get_jobs(site, uid = nil, states = nil, details = false, recurse = true) ⇒ Hash

Returns all the jobs submitted in a given Grid’5000 site, if a uid is provided only the jobs owned by the user are shown.

Parameters:

  • site (String)

    a valid Grid’5000 site name

  • uid (String) (defaults to: nil)

    user name in Grid’5000

  • states (Array) (defaults to: nil)

    or [String] jobs state: running, waiting (multiple states can be specified)

  • details (String) (defaults to: false)

    pass “resources=yes to the query to get the list of resources

  • recurse (String) (defaults to: true)

    after fetching the list of jobs, fetch details about each job individualy

Returns:

  • (Hash)

    all the jobs submitted in a given Grid’5000 site, if a uid is provided only the jobs owned by the user are shown.



722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
# File 'lib/cute/g5k_api.rb', line 722

def get_jobs(site, uid = nil, states = nil, details = false, recurse = true)

  parameters = []
  if states then
    states = [states] if states.is_a?(String)
    parameters.push("state=#{states.join(",")}")
  end
  parameters.push("user=#{uid}") if uid
  parameters.push("limit=1000000")
  parameters.push("resources=yes") if details

  info(debug_cmd(api_uri("/sites/#{site}/jobs?#{parameters.join("&")}"),"GET"), :debug)
  jobs = @g5k_connection.get_json(api_uri("/sites/#{site}/jobs?#{parameters.join("&")}")).items
  if recurse
    jobs.map! do |j|
      info(debug_cmd(j.rel_self, "GET"), :debug)
      @g5k_connection.get_json(j.rel_self)
    end
  end
  jobs.to_a
end

#get_metric(site, opts = {}) ⇒ Array

Returns information using the Metrology API.

Example

You can get detailed information of available metrics in a given site:

get_metric("rennes")

If you are only interested in the names of the available metrics:

get_metric("rennes").uids #=> ["cpu_nice", "boottime", "bytes_in", ...]

Then, you can get information about the probes available for a specific metric:

get_metric("rennes",:metric => "network_in")

Finally, you can query on a specific probe:

get_metric("rennes",:metric => "network_in",:query => {:from => 1450374553, :to => 1450374553, :only => "parasilo-11-eth0"})

Parameters:

  • site (String)

    a valid Grid’5000 site name

  • opts (Hash) (defaults to: {})

    Options for metric query

Options Hash (opts):

  • :metric (String)

    specific metric to query on

  • :query (Hash)

    timeseries parameters (e.g. only, resolution, from, to)

Returns:

  • (Array)

    information of a specific metric in a given Grid’5000 site.



811
812
813
814
815
816
817
818
819
# File 'lib/cute/g5k_api.rb', line 811

def get_metric(site,opts ={})
  params = opts[:metric].nil? ? "" : "/#{opts[:metric]}/timeseries"
  if opts[:query]
    params+="?"
    opts[:query].each{ |k,v| params+="#{k}=#{v}&"}
  end
  info debug_cmd(api_uri("sites/#{site}/metrics#{params}"),"GET"), :debug
  @g5k_connection.get_json(api_uri("sites/#{site}/metrics#{params}")).items
end

#get_my_jobs(site, states = "running") ⇒ Array

Returns information of all my jobs submitted in a given site. By default it only shows the jobs in state running. You can specify another state like this:

Examples

get_my_jobs("nancy", "waiting")

Getting several states:

get_my_jobs("nancy", ["waiting","running"])

Valid states are specified in Grid’5000 API spec

Parameters:

  • site (String)

    a valid Grid’5000 site name

  • states (String/Array) (defaults to: "running")

    possible job state values (waiting, launching, running, hold, error, terminated)

Returns:

  • (Array)

    all my submitted jobs to a given site and their associated deployments.



833
834
835
836
837
838
839
840
841
# File 'lib/cute/g5k_api.rb', line 833

def get_my_jobs(site, states = "running")

#        raise ArgumentError,"States parameter should be an Array" unless states.is_a?(Array)
  jobs = get_jobs(site, g5k_user, states)
  deployments = get_deployments(site, g5k_user)
  # filtering deployments only the job in state running make sense
  jobs.map{ |j| j["deploy"] = deployments.select{ |d| d["created_at"] > j["started_at"]} if j["state"] == "running"}
  return jobs
end

#get_subnets(job) ⇒ Array

Returns an Array with all subnets reserved by a given job. Each element of the Array is a IPAddress::IPv4 object which we can interact with to obtain the details of our reserved subnets:

Example

require 'cute'

  g5k = Cute::G5K::API.new()

  job = g5k.reserve(:site => "lyon", :resources => "/slash_22=1+{virtual!='none'}/nodes=1")

  subnet = g5k.get_subnets(job).first #=> we use 'first' because it is an array and we only reserved one subnet.

  ips = subnet.map{ |ip| ip.to_s }

Parameters:

Returns:

  • (Array)

    all the subnets defined in a given job



860
861
862
863
864
865
866
867
# File 'lib/cute/g5k_api.rb', line 860

def get_subnets(job)
  if job.resources["subnets"].nil?
    return nil
  else
    subnets = job.resources["subnets"]
  end
  subnets.map{|s| IPAddress::IPv4.new s }
end

#get_switch(site, name) ⇒ Hash

Returns information of a specific switch available in a given Grid’5000 site.

Parameters:

  • site (String)

    a valid Grid’5000 site name

  • name (String)

    a valid switch name

Returns:

  • (Hash)

    information of a specific switch available in a given Grid’5000 site.



783
784
785
786
787
# File 'lib/cute/g5k_api.rb', line 783

def get_switch(site, name)
  s = get_switches(site).detect { |x| x.uid == name }
  raise "Unknown switch '#{name}'" if s.nil?
  return s
end

#get_switches(site) ⇒ Hash

Returns switches information available in a given Grid’5000 site.

Parameters:

  • site (String)

    a valid Grid’5000 site name

Returns:

  • (Hash)

    switches information available in a given Grid’5000 site.



762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
# File 'lib/cute/g5k_api.rb', line 762

def get_switches(site)
  info(debug_cmd(api_uri("/sites/#{site}/network_equipments"),"GET"), :debug)
  items = @g5k_connection.get_json(api_uri("/sites/#{site}/network_equipments")).items
  items = items.select { |x| x['kind'] == 'switch' }
  # extract nodes connected to those switches
  items.each { |switch|
    conns = switch['linecards'].detect { |c| c['kind'] == 'node' }
    next if conns.nil?  # IB switches for example
    nodes = conns['ports'] \
      .select { |x| x != {} } \
      .map { |x| x['uid'] } \
      .map { |x| "#{x}.#{site}.grid5000.fr"}
    switch['nodes'] = nodes
  }

  return items
end

#get_vlan_nodes(job) ⇒ Array

Returns all the nodes in the VLAN.

Parameters:

Returns:

  • (Array)

    all the nodes in the VLAN



871
872
873
874
875
876
877
878
879
880
881
882
# File 'lib/cute/g5k_api.rb', line 871

def get_vlan_nodes(job)
  if job.resources["vlans"].nil?
    return nil
  else
    vlan_id = job.resources["vlans"].first
  end
  nodes = job["assigned_nodes"]
  reg = /^(\w+-\d+)(\..*)$/
  nodes.map {
    |name| reg.match(name)[1]+"-kavlan-"+vlan_id.to_s+reg.match(name)[2] unless reg.match(name).nil?
  }
end

#nodes_status(site) ⇒ Hash

Returns the nodes state (e.g, free, busy, etc) that belong to a given Grid’5000 site.

Parameters:

  • site (String)

    a valid Grid’5000 site name

Returns:

  • (Hash)

    the nodes state (e.g, free, busy, etc) that belong to a given Grid’5000 site



689
690
691
692
693
694
695
696
697
# File 'lib/cute/g5k_api.rb', line 689

def nodes_status(site)
  nodes = {}
  site_status(site).nodes.each do |node|
    name = node[0]
    status = node[1]["soft"]
    nodes[name] = status
  end
  return nodes
end

#release(resource) ⇒ Object

Releases a resource, it can be a job or a deploy.

Parameters:

Raises:

  • (ArgumentError)


902
903
904
905
906
907
908
909
# File 'lib/cute/g5k_api.rb', line 902

def release(resource)
  raise ArgumentError, "parameter should be a G5KJSON data type" unless resource.is_a?(Cute::G5K::G5KJSON)
  begin
    return @g5k_connection.delete_json(resource.rel_self)
  rescue Cute::G5K::RequestFailed => e
    raise unless e.response.include?('already killed')
  end
end

#release_all(site) ⇒ Object

Releases all jobs on a site

Parameters:

  • site (String)

    a valid Grid’5000 site name

Raises:

  • (ArgumentError)


886
887
888
889
890
891
892
893
894
895
896
897
898
# File 'lib/cute/g5k_api.rb', line 886

def release_all(site)
  raise ArgumentError, "parameter should be a string" unless site.is_a?(String)
  Timeout.timeout(20) do
    jobs = get_my_jobs(site,"running") + get_my_jobs(site,"waiting")
    break if jobs.empty?
    begin
      jobs.each { |j| release(j) }
    rescue Cute::G5K::RequestFailed => e
      raise unless e.response.include?('already killed')
    end
  end
  return true
end

#reserve(opts) ⇒ G5KJSON

Performs a reservation in Grid’5000.

Examples

By default this method blocks until the reservation is ready, if we want this method to return after creating the reservation we set the option :wait to false. Then, you can use the method wait_for_job to wait for the reservation.

job = g5k.reserve(:nodes => 25, :site => 'luxembourg', :walltime => '01:00:00', :wait => false)

job = g5k.wait_for_job(job, :wait_time => 100)

Reserving with properties

job = g5k.reserve(:site => 'lyon', :nodes => 2, :properties => "wattmeter='YES'")

job = g5k.reserve(:site => 'nancy', :nodes => 1, :properties => "switch='sgraphene1'")

job = g5k.reserve(:site => 'nancy', :nodes => 1, :properties => "cputype='Intel Xeon E5-2650'")

Subnet reservation

The example below reserves 2 nodes in the cluster chirloute located in Lille for 1 hour as well as 2 /22 subnets. We will get 2048 IP addresses that can be used, for example, in virtual machines. If walltime is not specified, 1 hour walltime will be assigned to the reservation.

job = g5k.reserve(:site => 'lille', :cluster => 'chirloute', :nodes => 2,
                       :env => 'wheezy-x64-xen', :keys => "path/to/my_ssh_jobkey",
                       :subnets => [22,2])

Multiple types

The option :type accepts an array for specifying multiple types. For example, if we want to submit a job deploy and destructive, we will type:

job = g5k.reserve(:site => "nancy", :nodes => 1, :walltime => "2:00:00", :type => [:deploy,:destructive])

Before using OAR hierarchy

In order to take advantage of this capability, SSH keys have to be specified at the moment of reserving resources. This has to be used whenever we perform a reservation with cpu and core hierarchy. Given that OAR needs access to both keys private and public users are encouraged to create a pair of SSH keys for managing jobs, for instance the following command can be used:

ssh-keygen -N "" -t rsa -f ~/my_ssh_jobkey

The reserved nodes can be accessed using “oarsh” or by configuring the SSH connection as shown in OAR2. You have to specify different keys per reservation if you want several jobs running at the same time in the same site. Example using the OAR hierarchy:

job = g5k.reserve(:site => "grenoble", :switches => 3, :nodes => 1, :cpus => 1, :cores => 1, :keys => "path/to/my_ssh_jobkey")

Remember that the path passed in the :keys parameter corresponds to the path in the Grid’5000 site frontend where you are submitting the job. This is because OAR needs to access to both keys (private and public) locally. For deployments the path corresponds to the local path from where the script is being executed (See deploy method).

Using OAR syntax

The parameter :resources can be used instead of parameters such as: :cluster, :nodes, :cpus, :walltime, :vlan, :subnets, :properties, etc, which are shortcuts for OAR syntax. These shortcuts are ignored if the the parameter :resources is used. Using the parameter :resources allows to express more flexible and complex reservations by using directly the OAR syntax. Therefore, the two examples shown below are equivalent:

job = g5k.reserve(:site => "grenoble", :switches => 3, :nodes => 1, :cpus => 1, :cores => 1, :keys => "~/my_ssh_jobkey")
job = g5k.reserve(:site => "grenoble", :resources => "/switch=3/nodes=1/cpu=1/core=1", :keys => "~/my_ssh_jobkey")

Combining OAR hierarchy with properties:

job = g5k.reserve(:site => "grenoble", :resources => "{ib10g='YES' and memnode=24160}/cluster=1/nodes=2/core=1", :keys => "~/my_ssh_jobkey")

If we want 2 nodes with the following constraints: 1) nodes on 2 different clusters of the same site, 2) nodes with virtualization capability enabled 3) 1 /22 subnet. The reservation will be like:

job = g5k.reserve(:site => "rennes", :resources => "/slash_22=1+{virtual!='none'}/cluster=2/nodes=1")

Another reservation for two clusters:

job = g5k.reserve(:site => "nancy", :resources => "{cluster='graphene'}/nodes=2+{cluster='griffon'}/nodes=3")

Reservation using a local VLAN

job = g5k.reserve(:site => 'nancy', :resources => "{type='kavlan-local'}/vlan=1,nodes=1", :env => 'wheezy-x64-xen')

Parameters:

  • opts (Hash)

    Options for reservation in Grid’5000

Options Hash (opts):

  • :nodes (Numeric)

    Number of nodes to reserve

  • :walltime (String)

    Walltime of the reservation

  • :site (String)

    Grid’5000 site

  • :type (Array or Symbol)

    Type of reservation: :deploy, :allow_classic_ssh, [:deploy,:destructive]

  • :name (String)

    Reservation name

  • :cmd (String)

    The command to execute when the job starts (e.g. ./my-script.sh).

  • :cluster (String)

    Valid Grid’5000 cluster

  • :queue (String)

    A specific job queue

  • :project (String)

    A specific OAR project

  • :subnets (Array)

    1) prefix_size, 2) number of subnets

  • :env (String)

    Environment name for / Kadeploy

  • :vlan (String)

    VLAN type and number: kavlan-local, kavlan, kavlan-topo, etc

  • :num_vlan (Numeric)

    Number of VLANs

  • :properties (String)

    OAR properties defined in the cluster

  • :resources (String)

    OAR syntax for complex submissions

  • :reservation (String)

    Request a job to be scheduled a specific date. The date format is “YYYY-MM-DD HH:MM:SS”.

  • :wait (Boolean)

    Whether or not to wait until the job is running (default is true)

Returns:

Raises:

  • (ArgumentError)


1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
# File 'lib/cute/g5k_api.rb', line 1013

def reserve(opts)

  # checking valid options
  valid_opts = [:site, :cluster, :switches, :cpus, :cores, :nodes, :walltime, :cmd,
                :type, :name, :subnets, :env, :vlan, :num_vlan,:properties, :resources,
                :reservation, :wait, :keys, :queue, :project, :env_user]
  unre_opts = opts.keys - valid_opts
  raise ArgumentError, "Unrecognized option #{unre_opts}" unless unre_opts.empty?

  nodes = opts.fetch(:nodes, 1)
  walltime = opts[:walltime]
  site = opts[:site]
  type = opts.fetch(:type, [])
  name = opts.fetch(:name, 'rubyCute job')
  command = opts[:cmd]
  opts[:wait] = true if opts[:wait].nil?
  cluster = opts[:cluster]
  switches = opts[:switches]
  cpus = opts[:cpus]
  cores = opts[:cores]
  subnets = opts[:subnets]
  properties = opts[:properties]
  reservation = opts[:reservation]
  resources = opts.fetch(:resources, "")
  type = [:deploy] if opts[:env]
  type = [type] if type.is_a?(Symbol)
  keys = opts[:keys]
  queue = opts[:queue]
  project = opts[:project]
  vlan = opts[:vlan]
  num_vlan = opts.fetch(:num_vlan, 1)


  available_vlans = nil
  if opts[:vlan]
    available_vlans = @g5k_connection.get_json(api_uri("sites/#{site}/vlans")).items.map{ |item| item["type"]}.uniq
    available_vlans.delete("NULL")
  end

  unless opts[:vlan].nil?
    raise ArgumentError, "VLAN type not available in site #{site}" unless available_vlans.include?(vlan)
  end

  raise 'At least nodes and site must be given'  if [nodes, site].any? { |x| x.nil? }

  raise 'nodes should be an integer or a string containing either ALL or BEST' unless (nodes.is_a?(Integer) or ["ALL","BEST"].include?(nodes))

  command = "sleep infinity" if command.nil?

  if resources == ""
    resources = "/switch=#{switches}" unless switches.nil?
    resources += "/nodes=#{nodes}"
    resources += "/cpu=#{cpus}" unless cpus.nil?
    resources += "/core=#{cores}" unless cores.nil?

    if cluster
      resources = (cluster.is_a?(Integer) ? "/cluster=#{cluster}" : "{cluster='#{cluster}'}") + resources
    end

    resources = "{type='#{vlan}'}/vlan=#{num_vlan}+" + resources unless vlan.nil?
    resources = "slash_#{subnets[0]}=#{subnets[1]}+" + resources unless subnets.nil?
  end

  if walltime
    resources += ",walltime=#{walltime}" unless resources.include?("walltime")
  end

  payload = {
             'resources' => resources,
             'name' => name,
             'command' => command
            }

  info "Reserving resources: #{resources} (types: #{type.join(' ')}) (in #{site})"

  payload['properties'] = properties unless properties.nil?
  payload['types'] = type.map{ |t| t.to_s} unless type.nil?
  type.map!{|t| t.to_sym}  unless type.nil?
  payload['queue'] = queue if queue
  payload['project'] = project if project

  unless type.include?(:deploy)
    if opts[:keys]
      payload['import-job-key-from-file'] = [ File.expand_path(keys) ]
    end
  end

  if reservation
    payload['reservation'] = reservation
  end

  info debug_cmd(api_uri("sites/#{site}/jobs"),"POST",payload.to_json), :debug
  r = @g5k_connection.post_json(api_uri("sites/#{site}/jobs"),payload)  # This makes reference to the same class

  job = @g5k_connection.get_json(r.rel_self)
  job = wait_for_job(job) if opts[:wait] == true
  opts.delete(:nodes) # to not collapse with deploy options
  opts.delete(:vlan)
  opts.delete(:num_vlan)
  if opts[:env]
    if opts[:vlan]
      vlan_id = job.resources["vlans"].first
      deploy(job,opts.merge!({:vlan_id => vlan_id}))
    else
      deploy(job,opts) #type == :deploy
    end
  end

  return job

end

#restObject

It returns the RestClient::Resource object which provides you the get_json and post_json methods. This enables to perform low level REST requests. This method is intended to be used along with the api_uri method for generating valid URI.

Example:

require 'cute'

g5k = Cute::G5K::API.new()
g5k.rest.get_json(g5k.api_uri("/sites/grenoble/clusters")

Returns:

  • the rest point for performing low level REST requests



632
633
634
# File 'lib/cute/g5k_api.rb', line 632

def rest
  @g5k_connection
end

#siteString

It returns the site name. Example:

site #=> "rennes"

This will only work when G5K::API is used within Grid’5000. In the other cases it will return nil

Returns:

  • (String)

    the site name where the method is called on



616
617
618
619
620
# File 'lib/cute/g5k_api.rb', line 616

def site
  p = `hostname`.chop
  res = /^.*\.(.*).*\.grid5000.fr/.match(p)
  res[1] unless res.nil?
end

#site_status(site) ⇒ Hash

Returns all the status information of a given Grid’5000 site.

Parameters:

  • site (String)

    a valid Grid’5000 site name

Returns:

  • (Hash)

    all the status information of a given Grid’5000 site



682
683
684
685
# File 'lib/cute/g5k_api.rb', line 682

def site_status(site)
  info(debug_cmd(api_uri("sites/#{site}/status"),"GET"), :debug)
  @g5k_connection.get_json(api_uri("sites/#{site}/status"))
end

#site_uidsArray

Returns all sites identifiers

Example:

site_uids #=> ["grenoble", "lille", "luxembourg", "lyon",...]

Returns:

  • (Array)

    all site identifiers



647
648
649
# File 'lib/cute/g5k_api.rb', line 647

def site_uids
  return sites.uids
end

#sitesArray

Returns the description of all Grid’5000 sites.

Returns:

  • (Array)

    the description of all Grid’5000 sites



700
701
702
# File 'lib/cute/g5k_api.rb', line 700

def sites
  @g5k_connection.get_json(api_uri("sites")).items
end

#wait_for_deploy(job, opts = {}) ⇒ Object

Blocks until deployments have terminated status

Examples

This method requires a job as a parameter and it will blocks by default until all deployments within the job pass form processing status to terminated status.

wait_for_deploy(job)

You can wait for specific deployments using the option :nodes. This can be useful when performing different deployments on the reserved resources.

wait_for_deploy(job, :nodes => ["adonis-10.grenoble.grid5000.fr"])

Another parameter you can specify is :wait_time that allows you to timeout the deployment (by default is 10h). The method will throw a Timeout exception that you can catch and react upon. This example illustrates how this can be used.

require 'cute'

g5k = Cute::G5K::API.new()

job = g5k.reserve(:nodes => 1, :site => 'lyon', :type => :deploy)

begin
  g5k.deploy(job,:env => 'wheezy-x64-base')
  g5k.wait_for_deploy(job,:wait_time => 100)
  rescue  Cute::G5K::EventTimeout
  puts "We waited too long let's release the job"
  g5k.release(job)
end

Parameters:

  • job (G5KJSON)

    as described in job

  • opts (Hash) (defaults to: {})

    options



1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
# File 'lib/cute/g5k_api.rb', line 1337

def wait_for_deploy(job,opts = {})

  raise "Deploy information not present in the given job" if job["deploy"].nil?

  opts.merge!({:wait_time => 36000}) if opts[:wait_time].nil?
  nodes = opts[:nodes]

  begin
    Timeout.timeout(opts[:wait_time]) do
      # it will ask just for processing status
      status = deploy_status(job,{:nodes => nodes, :status => "processing"})
      until status.empty? do
        info "Waiting for #{status.length} deployment"
        sleep 4
        status = deploy_status(job,{:nodes => nodes, :status => "processing"})
      end
      info "Deployment finished"
      return job
    end
  rescue Timeout::Error
    raise EventTimeout.new("Timeout triggered")
  end

end

#wait_for_job(job, opts = {}) ⇒ Object

Blocks until job is in running state

Example

You can pass the parameter :wait_time that allows you to timeout the submission (by default is 10h). The method will throw a Timeout exception that you can catch and react upon. The following example shows how can be used, let’s suppose we want to find 5 nodes available for 3 hours. We can try in each site using the script below.

require 'cute'

 g5k = Cute::G5K::API.new()

 sites = g5k.site_uids

 sites.each{ |site|
    job = g5k.reserve(:site => site, :nodes => 5, :wait => false, :walltime => "03:00:00")
    begin
      job = g5k.wait_for_job(job, :wait_time => 60)
      puts "Nodes assigned #{job['assigned_nodes']}"
      break
    rescue  Cute::G5K::EventTimeout
      puts "We waited too long in site #{site} let's release the job and try in another site"
      g5k.release(job)
    end
 }

Parameters:

  • job (G5KJSON)

    as described in job

  • opts (Hash) (defaults to: {})

    Options

Options Hash (opts):

  • :wait_time (Numeric)

    Number of seconds to wait before triggering a timeout



1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
# File 'lib/cute/g5k_api.rb', line 1155

def wait_for_job(job,opts={})
  opts[:wait_time] = 36000 if opts[:wait_time].nil?
  jid = job['uid']
  info "Waiting for reservation #{jid}"
  begin
    Timeout.timeout(opts[:wait_time]) do
      while true
        job = job.refresh(@g5k_connection)
        t = job['scheduled_at']
        if !t.nil?
          t = Time.at(t)
          secs = [ t - Time.now, 0 ].max.to_i
          info "Reservation #{jid} should be available at #{t} (#{secs} s)"
        end
        break if job['state'] == 'running'
        raise "Job is finishing." if job['state'] == 'finishing'
        Kernel.sleep(5)
      end
    end
  rescue Timeout::Error
    raise EventTimeout.new("Event timeout")
  end

  info "Reservation #{jid} ready"
  return job
end