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. To simplify the use of the module, it is better to create a file with the following information:

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

The username and password are not necessary if you are using the module from inside Grid’5000. You can take a look at the G5K::API constructor to see more details for 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). Let’s show how G5K::API is used through an example, suppose we want to reserve 3 nodes in Nancy site for 1 hour. In order to do that we would write something like this:

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 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']}"

Your public ssh key located in ~/.ssh will be copied by default 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: :routed, :local, :global. 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. 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 => 'https://public.lyon.grid5000.fr/~user/debian_custom_img.yaml',
                  :vlan => :routed, :keys => "~/my_ssh_key")

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

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 => 'https://public.lyon.grid5000.fr/~user/debian_master_img.yaml')
g5k.deploy(job,:nodes => slaves, :env => 'https://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")

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 parameter 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)

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

  • :user (String)

    Username to access the REST API

  • :pass (String)

    Password to access the REST API

  • :on_error (Symbol)

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



490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
# File 'lib/cute/g5k_api.rb', line 490

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

  config = YAML.load(File.open(params[:conf_file],'r')) unless params[:conf_file].nil?
  @user = params[:user] || config["username"]
  @pass = params[:pass] || config["password"]
  @uri = params[:uri] || config["uri"]
  @api_version = params[:version] || config["version"] || "sid"
  @logger = nil

  begin
    @g5k_connection = G5KRest.new(@uri,@api_version,@user,@pass,params[:on_error])
  rescue
    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.
         #{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'))


467
468
469
# File 'lib/cute/g5k_api.rb', line 467

def logger
  @logger
end

Instance Method Details

#cluster_uids(site) ⇒ Array

Returns all cluster identifiers

Example:

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

Returns:

  • (Array)

    cluster identifiers



558
559
560
# File 'lib/cute/g5k_api.rb', line 558

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



605
606
607
# File 'lib/cute/g5k_api.rb', line 605

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")

Parameters:

  • job (G5KJSON)

    as described in job

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

    Deploy options

Options Hash (opts):

  • :env (String)

    / Kadeploy environment to deploy

  • :nodes (String)

    Specifies the nodes to deploy on

  • :keys (String)

    Specifies the SSH keys to copy for the deployment

  • :wait (Boolean)

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

Returns:

  • (G5KJSON)

    a job with deploy information as described in job

Raises:

  • (ArgumentError)


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
# File 'lib/cute/g5k_api.rb', line 1027

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, :properties, :resources, :reservation, :wait, :keys]

  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")
    public_key_file = File.exist?(public_key_path) ? File.read(public_key_path) : ""
  else
    public_key_file = File.read("#{File.expand_path(opts[:keys])}.pub")
  end

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

  if !job.resources["vlans"].nil?
    vlan = job.resources["vlans"].first
    payload['vlan'] = vlan
    info "Found VLAN with uid = #{vlan}"
  end

  info "Creating deployment"

  begin
    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



1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
# File 'lib/cute/g5k_api.rb', line 1097

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



569
570
571
572
573
574
575
576
577
578
# File 'lib/cute/g5k_api.rb', line 569

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]
  }

  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



610
611
612
# File 'lib/cute/g5k_api.rb', line 610

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



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

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



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

def get_deployments(site, uid = nil)
  @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



640
641
642
# File 'lib/cute/g5k_api.rb', line 640

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

#get_jobs(site, uid = nil, state = nil) ⇒ 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

  • state (String) (defaults to: nil)

    jobs state: running, waiting

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.



619
620
621
622
623
624
625
626
627
628
# File 'lib/cute/g5k_api.rb', line 619

def get_jobs(site, uid = nil, state = nil)
  filter = "?"
  filter += state.nil? ? "" : "state=#{state}"
  filter += uid.nil? ? "" : "&user=#{uid}"
  filter += "limit=25" if (state.nil? and uid.nil?)
  jobs = @g5k_connection.get_json(api_uri("/sites/#{site}/jobs/#{filter}")).items
  jobs.map{ |j| @g5k_connection.get_json(j.rel_self)}
  # This request sometime is could take a little long when all jobs are requested
  # The API return by default 50 the limit was set to 25 (e.g., 23 seconds).
end

#get_my_jobs(site, state = "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:

Example

get_my_jobs("nancy", state="waiting")

Valid states are specified in Grid’5000 API spec

Parameters:

  • site (String)

    a valid Grid’5000 site name

Returns:

  • (Array)

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



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

def get_my_jobs(site, state = "running")
  jobs = get_jobs(site, g5k_user, state)
  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



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

def get_subnets(job)
  subnets = job.resources["subnets"]
  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.



665
666
667
668
669
# File 'lib/cute/g5k_api.rb', line 665

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.



646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
# File 'lib/cute/g5k_api.rb', line 646

def get_switches(site)
  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.select { |it| it.key?('nodes') }
end

#get_vlan_nodes(job) ⇒ Array

Returns all the nodes in the VLAN.

Parameters:

Returns:

  • (Array)

    all the nodes in the VLAN



712
713
714
715
716
717
718
719
720
721
722
723
# File 'lib/cute/g5k_api.rb', line 712

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



588
589
590
591
592
593
594
595
596
# File 'lib/cute/g5k_api.rb', line 588

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(r) ⇒ Object

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



741
742
743
744
745
746
747
# File 'lib/cute/g5k_api.rb', line 741

def release(r)
  begin
    return @g5k_connection.delete_json(r.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



727
728
729
730
731
732
733
734
735
736
737
738
# File 'lib/cute/g5k_api.rb', line 727

def release_all(site)
  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 => "~/my_ssh_jobkey",
                       :subnets => [22,2])

Before using OAR hierarchy

All non-deploy reservations are submitted by default with the OAR option “-allow_classic_ssh” which does not take advantage of the CPU/core management level. Therefore, 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. 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 => "~/my_ssh_jobkey")

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 (Symbol)

    Type of reservation: :deploy, :allow_classic

  • :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

  • :subnets (Array)

    1) prefix_size, 2) number of subnets

  • :env (String)

    Environment name for / Kadeploy

  • :vlan (Symbol)

    Vlan type: :routed, :local, :global

  • :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)


839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
# File 'lib/cute/g5k_api.rb', line 839

def reserve(opts)

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

  nodes = opts.fetch(:nodes, 1)
  walltime = opts.fetch(:walltime, '01:00:00')
  site = opts[:site]
  type = opts[: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]
  keys = opts[:keys]

  vlan_opts = {:routed => "kavlan",:global => "kavlan-global",:local => "kavlan-local"}
  vlan = nil
  unless opts[:vlan].nil?
    if vlan_opts.include?(opts[:vlan]) then
      vlan = vlan_opts.fetch(opts[:vlan])
    else
      raise ArgumentError, 'Option for vlan not recognized'
    end
  end

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

  secs = walltime.to_secs
  walltime = walltime.to_time

  raise 'Nodes must be an integer.' unless nodes.is_a?(Integer)

  command = "sleep #{secs}" if command.nil?
  type = type.to_sym unless type.nil?

  if resources == ""
    resources = "/switch=#{switches}" unless switches.nil?
    resources += "/nodes=#{nodes}"
    resources += "/cpu=#{cpus}" unless cpus.nil?
    resources += "/core=#{cores}" unless cores.nil?
    resources = "{cluster='#{cluster}'}" + resources unless cluster.nil?
    resources = "{type='#{vlan}'}/vlan=1+" + resources unless vlan.nil?
    resources = "slash_#{subnets[0]}=#{subnets[1]}+" + resources unless subnets.nil?
  end

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

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

  info "Reserving resources: #{resources} (type: #{type}) (in #{site})"

  payload['properties'] = properties unless properties.nil?
  payload['types'] = [ type.to_s ] unless type.nil?

  if not type == :deploy
    if opts[:keys]
      payload['import-job-key-from-file'] = [ File.expand_path(keys) ]
    else
      payload['types'] = [ 'allow_classic_ssh' ]
    end
  end

  if reservation
    payload['reservation'] = reservation
    info "Starting this reservation at #{reservation}"
  end

  begin
    # Support for the option "import-job-key-from-file"
    # The request has to be redirected to the OAR API given that Grid'5000 API
    # does not support some OAR options.
    if payload['import-job-key-from-file'] then
      # Adding double quotes otherwise we have a syntax error from OAR API
      payload["resources"] = "\"#{payload["resources"]}\""
      temp = @g5k_connection.post_json(api_uri("sites/#{site}/internal/oarapi/jobs"),payload)
      sleep 1 # This is for being sure that our job appears on the list
      r = get_my_jobs(site,nil).select{ |j| j["uid"] == temp["id"] }.first
    else
      r = @g5k_connection.post_json(api_uri("sites/#{site}/jobs"),payload)  # This makes reference to the same class
    end
  rescue Error => e
    info "Fail to submit job"
    info e.message
    e.http_body.split("\\n").each{ |line| info line}
    raise
  end

  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
  deploy(job,opts) unless opts[:env].nil? #type == :deploy
  return job

end

#restObject

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Returns the rest point for performing low level REST requests.

Returns:

  • the rest point for performing low level REST requests



533
534
535
# File 'lib/cute/g5k_api.rb', line 533

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



525
526
527
528
529
# File 'lib/cute/g5k_api.rb', line 525

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



582
583
584
# File 'lib/cute/g5k_api.rb', line 582

def site_status(site)
  @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



548
549
550
# File 'lib/cute/g5k_api.rb', line 548

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



599
600
601
# File 'lib/cute/g5k_api.rb', line 599

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', :env => 'wheezy-x64-base')

begin
  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



1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
# File 'lib/cute/g5k_api.rb', line 1142

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



978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
# File 'lib/cute/g5k_api.rb', line 978

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