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

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



498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
# File 'lib/cute/g5k_api.rb', line 498

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"]
  @api_version = params[:version] || config["version"] || "sid"
  @logger = nil

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


475
476
477
# File 'lib/cute/g5k_api.rb', line 475

def logger
  @logger
end

Instance Method Details

#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



1237
1238
1239
# File 'lib/cute/g5k_api.rb', line 1237

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



572
573
574
# File 'lib/cute/g5k_api.rb', line 572

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



619
620
621
# File 'lib/cute/g5k_api.rb', line 619

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)


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
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
# File 'lib/cute/g5k_api.rb', line 1083

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

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

  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



1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
# File 'lib/cute/g5k_api.rb', line 1156

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



583
584
585
586
587
588
589
590
591
592
# File 'lib/cute/g5k_api.rb', line 583

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



624
625
626
# File 'lib/cute/g5k_api.rb', line 624

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



552
553
554
# File 'lib/cute/g5k_api.rb', line 552

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



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

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



654
655
656
# File 'lib/cute/g5k_api.rb', line 654

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.



633
634
635
636
637
638
639
640
641
642
# File 'lib/cute/g5k_api.rb', line 633

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_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.



708
709
710
711
712
713
714
715
# File 'lib/cute/g5k_api.rb', line 708

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
  @g5k_connection.get_json(api_uri("sites/#{site}/metrics#{params}")).items
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.



726
727
728
729
730
731
732
# File 'lib/cute/g5k_api.rb', line 726

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



751
752
753
754
755
756
757
758
# File 'lib/cute/g5k_api.rb', line 751

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.



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

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.



660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
# File 'lib/cute/g5k_api.rb', line 660

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
end

#get_vlan_nodes(job) ⇒ Array

Returns all the nodes in the VLAN.

Parameters:

Returns:

  • (Array)

    all the nodes in the VLAN



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

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



602
603
604
605
606
607
608
609
610
# File 'lib/cute/g5k_api.rb', line 602

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)


793
794
795
796
797
798
799
800
# File 'lib/cute/g5k_api.rb', line 793

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)


777
778
779
780
781
782
783
784
785
786
787
788
789
# File 'lib/cute/g5k_api.rb', line 777

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 => "~/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

  • :queue (String)

    A specific job queue

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


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
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
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 893

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, :queue, :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.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]
  queue = opts[:queue]

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

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

  secs = walltime.to_secs
  walltime = walltime.to_time

  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?
  payload['queue'] = queue if queue

  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

      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



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

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



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

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



596
597
598
# File 'lib/cute/g5k_api.rb', line 596

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



562
563
564
# File 'lib/cute/g5k_api.rb', line 562

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



613
614
615
# File 'lib/cute/g5k_api.rb', line 613

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



1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
# File 'lib/cute/g5k_api.rb', line 1202

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



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

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