README.org 17.9 KB
Newer Older
1 2 3 4 5 6 7 8
#+TITLE: python-grid5000
#+AUTHOR: Matthieu Simonin
#+EMAIL: {firstname.lastname}@inria.fr

#+LANGUAGE: en
#+OPTIONS: ':t author:nil email:nil date:nil toc:nil


SIMONIN Matthieu's avatar
SIMONIN Matthieu committed
9 10 11
~python-grid5000~ is a python package wrapping the Grid'5000 REST API. You can
use it as a library in your python project or you can explore the Grid'5000
resources interactively using the embedded shell.
12 13

#+BEGIN_warning
SIMONIN Matthieu's avatar
SIMONIN Matthieu committed
14 15
The code is currently being developed heavily. Jump to the contributing section
if you want to be involved.
16 17 18 19 20
#+END_warning

* Thanks

The core code is borrowed from [[https://github.com/python-gitlab/python-gitlab][python-gitlab]] with small adaptations to
SIMONIN Matthieu's avatar
SIMONIN Matthieu committed
21
conform with the Grid5000 API models (with an 's'!)
22

SIMONIN Matthieu's avatar
SIMONIN Matthieu committed
23 24 25 26 27 28 29 30 31 32 33
* Contributing

- To contribute, you can drop me an email or open an issue for a bug report, or feature request.
- There are many areas where this can be improved some of them are listed here:

  + The complete coverage of the API isn't finished (yet) but this should be fairly easy to reach.
    Most of the logic go in [[https://gitlab.inria.fr/msimonin/python-grid5000/blob/master/grid5000/objects.py][~grid5000.objects~]]. And to be honnest I only
    implemented the feature that I needed the most.

  + Returned [[https://www.grid5000.fr/mediawiki/index.php/API#Status_Codes][status code]] aren't yet well treated.

SIMONIN Matthieu's avatar
SIMONIN Matthieu committed
34 35 36
* Comparison with ...

- [[https://api.grid5000.fr/doc/4.0/tools/restfully.html][RESTfully]]: 
SIMONIN Matthieu's avatar
SIMONIN Matthieu committed
37 38 39 40 41 42
  It consumes REST API following the [[https://en.m.wikipedia.org/wiki/HATEOAS][HATEOAS]] principles. This allows the client
  to fully discover the resources and actions available. Most of the G5K API
  follow theses principles but, for instance the [[https://www.grid5000.fr/mediawiki/index.php/Storage_Manager][Storage API]] don't. Thus
  RESTfully isn't compatible with all the features offered by the Grid'5000 API.
  It's a ruby library. Python-grid5000 borrows the friendly syntax for resource
  browsing, but in python.
SIMONIN Matthieu's avatar
SIMONIN Matthieu committed
43 44 45 46 47

- [[http://execo.gforge.inria.fr][Execo]]: 
  Written in Python. The api module gathers a lot of utils functions leveraging
  the Grid'5000 API. Resources aren't exposed in a syntax friendly manner,
  instead functions for some classical operations are exposed (mainly getters).
SIMONIN Matthieu's avatar
SIMONIN Matthieu committed
48
  It has a convenient way of caching the reference API. Python-grid5000 is a
SIMONIN Matthieu's avatar
SIMONIN Matthieu committed
49 50
  wrapper around the Grid'5000 that seeks 100% coverage. Python-grid5000 is
  resource oriented.
SIMONIN Matthieu's avatar
SIMONIN Matthieu committed
51 52 53

- [[http://docs.python-requests.org][Raw requests]]: 
 *The* reference for HTTP library in python. Good for prototyping but low-level.
54
 python-grid5000 encapsulates this library.
SIMONIN Matthieu's avatar
SIMONIN Matthieu committed
55

SIMONIN Matthieu's avatar
SIMONIN Matthieu committed
56
* Installation and examples
57

SIMONIN Matthieu's avatar
SIMONIN Matthieu committed
58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
- Please refer to [[https://api.grid5000.fr/doc/4.0/reference/spec.html]] for 
  the complete specification.

- All the examples are exported in the examples subdirectory so you can
  easily test and adapt them.

- The configuration is read from a configuration file located in the home
  directory (should be compatible with the restfully one). 
  It can be created with the following:

#+BEGIN_EXAMPLE
echo '
username: MYLOGIN
password: MYPASSWORD
' > ~/.python-grid5000.yaml
#+END_EXAMPLE
74

SIMONIN Matthieu's avatar
SIMONIN Matthieu committed
75
#+BEGIN_hint
76 77
From a Grid'5000 frontend this file is optionnal. In all other cases the
configuration file is mandatory.
SIMONIN Matthieu's avatar
SIMONIN Matthieu committed
78
#+END_hint
SIMONIN Matthieu's avatar
SIMONIN Matthieu committed
79

SIMONIN Matthieu's avatar
SIMONIN Matthieu committed
80 81 82 83 84 85 86
- Using a virtualenv is recommended (python 3.5+ is required)

#+BEGIN_EXAMPLE
virtualenv -p python3 venv
source venv/bin/activate
pip install python-grid5000
#+END_EXAMPLE
SIMONIN Matthieu's avatar
SIMONIN Matthieu committed
87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113
** Grid'5000 shell

   If you call ~grid5000~ on the command line you should land in a ipython shell.
   Before starting, the file ~$HOME/.python-grid5000.yaml~ will be loaded.

#+BEGIN_EXAMPLE
$) grid5000

Python 3.6.5 (default, Jun 17 2018, 21:32:15) 
Type 'copyright', 'credits' or 'license' for more information
IPython 7.3.0 -- An enhanced Interactive Python. Type '?' for help.

In [1]: gk.sites.list()                                                                                                                                                                                            
Out[1]: 
[<Site uid:grenoble>,
 <Site uid:lille>,
 <Site uid:luxembourg>,
 <Site uid:lyon>,
 <Site uid:nancy>,
 <Site uid:nantes>,
 <Site uid:rennes>,
 <Site uid:sophia>]

In [2]: # gk is your entry point    
#+END_EXAMPLE


114 115
** Reference API
*** Get node information
SIMONIN Matthieu's avatar
SIMONIN Matthieu committed
116

SIMONIN Matthieu's avatar
SIMONIN Matthieu committed
117 118 119 120 121 122
  #+BEGIN_SRC python :exports code :tangle examples/node_information.py
  import logging
  import os

  from grid5000 import Grid5000

SIMONIN Matthieu's avatar
SIMONIN Matthieu committed
123

SIMONIN Matthieu's avatar
SIMONIN Matthieu committed
124
  logging.basicConfig(level=logging.DEBUG)
SIMONIN Matthieu's avatar
SIMONIN Matthieu committed
125

SIMONIN Matthieu's avatar
SIMONIN Matthieu committed
126 127
  conf_file = os.path.join(os.environ.get("HOME"), ".python-grid5000.yaml")
  gk = Grid5000.from_yaml(conf_file)
SIMONIN Matthieu's avatar
SIMONIN Matthieu committed
128

SIMONIN Matthieu's avatar
SIMONIN Matthieu committed
129 130 131 132 133
  node_info = gk.sites["nancy"].clusters["grisou"].nodes["grisou-1"]
  print("grisou-1 has {threads} threads and has {ram} bytes of RAM".format(
      threads=node_info.architecture["nb_threads"],
      ram=node_info.main_memory["ram_size"]))
  #+END_SRC
SIMONIN Matthieu's avatar
SIMONIN Matthieu committed
134

135
*** Get Versions of resources
136

137
  #+BEGIN_SRC python :exports code :tangle examples/versions.py
SIMONIN Matthieu's avatar
SIMONIN Matthieu committed
138 139 140 141
  import logging
  import os

  from grid5000 import Grid5000
142 143


SIMONIN Matthieu's avatar
SIMONIN Matthieu committed
144
  logging.basicConfig(level=logging.DEBUG)
145

SIMONIN Matthieu's avatar
SIMONIN Matthieu committed
146 147
  conf_file = os.path.join(os.environ.get("HOME"), ".python-grid5000.yaml")
  gk = Grid5000.from_yaml(conf_file)
148

149 150
  root_versions = gk.root.get().versions.list()
  print(root_versions)
151

152 153 154
  rennes = gk.sites["rennes"]
  site_versions = rennes.versions.list()
  print(site_versions)
155

156 157 158 159 160 161
  cluster = rennes.clusters["paravance"]
  cluster_versions = cluster.versions.list()
  print(cluster_versions)

  node_versions = cluster.nodes["paravance-1"]
  print(node_versions)
162

SIMONIN Matthieu's avatar
SIMONIN Matthieu committed
163
  #+END_SRC
164

165 166 167
** Monitoring API

*** Get Statuses of resources
168

169
  #+BEGIN_SRC python :exports code :tangle examples/statuses.py
SIMONIN Matthieu's avatar
SIMONIN Matthieu committed
170 171
  import logging
  import os
172

SIMONIN Matthieu's avatar
SIMONIN Matthieu committed
173 174 175 176 177 178 179
  from grid5000 import Grid5000


  logging.basicConfig(level=logging.DEBUG)

  conf_file = os.path.join(os.environ.get("HOME"), ".python-grid5000.yaml")
  gk = Grid5000.from_yaml(conf_file)
180

181 182 183
  rennes = gk.sites["rennes"]
  site_statuses = rennes.status.list()
  print(site_statuses)
184

185 186
  cluster = rennes.clusters["paravance"]
  cluster_statuses = cluster.status.list()
187

SIMONIN Matthieu's avatar
SIMONIN Matthieu committed
188
  #+END_SRC
189

190 191
  #+RESULTS:
  : None
SIMONIN Matthieu's avatar
SIMONIN Matthieu committed
192

193 194
** Job API
*** Job filtering
195

196 197 198
   #+BEGIN_SRC python :exports code :tangle examples/jobs_filtering.py
   import logging
   import os
199

200
   from grid5000 import Grid5000
201

SIMONIN Matthieu's avatar
SIMONIN Matthieu committed
202

203
   logging.basicConfig(level=logging.DEBUG)
SIMONIN Matthieu's avatar
SIMONIN Matthieu committed
204

205 206
   conf_file = os.path.join(os.environ.get("HOME"), ".python-grid5000.yaml")
   gk = Grid5000.from_yaml(conf_file)
SIMONIN Matthieu's avatar
SIMONIN Matthieu committed
207

208 209 210
   # state=running will be placed in the query params
   running_jobs = gk.sites["rennes"].jobs.list(state="running")
   print(running_jobs)
SIMONIN Matthieu's avatar
SIMONIN Matthieu committed
211

212 213 214 215 216 217
   # get a specific job by its uid
   job = gk.sites["rennes"].jobs.get("424242")
   print(job)
   # or using the bracket notation
   job = gk.sites["rennes"].jobs["424242"]
   print(job)
218

SIMONIN Matthieu's avatar
SIMONIN Matthieu committed
219

220
   #+END_SRC
SIMONIN Matthieu's avatar
SIMONIN Matthieu committed
221

222
*** Submit a job
SIMONIN Matthieu's avatar
SIMONIN Matthieu committed
223

224 225 226 227
   #+BEGIN_SRC python :exports code :tangle examples/job_submission.py
   import logging
   import os
   import time
228

229
   from grid5000 import Grid5000
SIMONIN Matthieu's avatar
SIMONIN Matthieu committed
230

231

232
   logging.basicConfig(level=logging.DEBUG)
233

234 235
   conf_file = os.path.join(os.environ.get("HOME"), ".python-grid5000.yaml")
   gk = Grid5000.from_yaml(conf_file)
236

237 238
   # This is equivalent to gk.sites.get("rennes")
   site = gk.sites["rennes"]
239

240 241
   job = site.jobs.create({"name": "pyg5k",
                           "command": "sleep 3600"})
242

243 244 245 246
   while job.state != "running":
       job.refresh()
       print("Waiting for the job [%s] to be running" % job.uid)
       time.sleep(10)
SIMONIN Matthieu's avatar
SIMONIN Matthieu committed
247

248 249 250
   print(job)
   print("Assigned nodes : %s" % job.assigned_nodes)
   #+END_SRC
251

252 253
** Deployment API
*** Deploy an environment
254

255 256 257 258
   #+BEGIN_SRC python :exports code :tangle examples/deploy.py
   import logging
   import os
   import time
259

260
   from grid5000 import Grid5000
261 262


263
   logging.basicConfig(level=logging.DEBUG)
264

265 266
   conf_file = os.path.join(os.environ.get("HOME"), ".python-grid5000.yaml")
   gk = Grid5000.from_yaml(conf_file)
267

268 269
   # This is equivalent to gk.sites.get("rennes")
   site = gk.sites["rennes"]
SIMONIN Matthieu's avatar
SIMONIN Matthieu committed
270

271 272 273
   job = site.jobs.create({"name": "pyg5k",
                           "command": "sleep 3600",
                           "types": ["deploy"]})
274

275 276 277 278
   while job.state != "running":
       job.refresh()
       print("Waiting the job [%s] to be running" % job.uid)
       time.sleep(10)
279

280
   print("Assigned nodes : %s" % job.assigned_nodes)
281

282 283
   deployment = site.deployments.create({"nodes": job.assigned_nodes,
                                         "environment": "debian9-x64-min"})
SIMONIN Matthieu's avatar
SIMONIN Matthieu committed
284 285 286 287 288 289 290 291 292 293
   # To get SSH access to your nodes you can pass your public key
   #
   # from pathlib import Path
   #
   # key_path = Path.home().joinpath(".ssh", "id_rsa.pub")
   #
   #
   # deployment = site.deployments.create({"nodes": job.assigned_nodes,
   #                                       "environment": "debian9-x64-min"
   #                                       "key": key_path.read_text()})
294

295 296 297 298
   while deployment.status != "terminated":
       deployment.refresh()
       print("Waiting for the deployment [%s] to be finished" % deployment.uid)
       time.sleep(10)
299

300 301
   print(deployment.result)
   #+END_SRC
302

303 304
** Storage API
*** Get Storage accesses
305

306 307 308
   #+BEGIN_SRC python :exports code :tangle examples/storage_accesses.py
   import logging
   import os
309

310
   from grid5000 import Grid5000
SIMONIN Matthieu's avatar
SIMONIN Matthieu committed
311

312

313
   logging.basicConfig(level=logging.DEBUG)
314

315 316
   conf_file = os.path.join(os.environ.get("HOME"), ".python-grid5000.yaml")
   gk = Grid5000.from_yaml(conf_file)
SIMONIN Matthieu's avatar
SIMONIN Matthieu committed
317

318 319
   print(gk.sites["rennes"].storage["msimonin"].access.list())
   #+END_SRC
SIMONIN Matthieu's avatar
SIMONIN Matthieu committed
320

321
*** Set storage accesses (e.g for vms)
SIMONIN Matthieu's avatar
SIMONIN Matthieu committed
322

323 324 325 326 327
   #+BEGIN_SRC python :exports code :tangle examples/storage_set.py
   from netaddr import IPNetwork
   import logging
   import os
   import time
SIMONIN Matthieu's avatar
SIMONIN Matthieu committed
328

329
   from grid5000 import Grid5000
330

SIMONIN Matthieu's avatar
SIMONIN Matthieu committed
331

332
   logging.basicConfig(level=logging.DEBUG)
333

334 335 336
   conf_file = os.path.join(os.environ.get("HOME"), ".python-grid5000.yaml")
   gk = Grid5000.from_yaml(conf_file)
   site = gk.sites["rennes"]
337

338 339 340
   job = site.jobs.create({"name": "pyg5k",
                           "command": "sleep 3600",
                           "resources": "slash_22=1+nodes=1"})
341

342 343 344 345
   while job.state != "running":
       job.refresh()
       print("Waiting the job [%s] to be running" % job.uid)
       time.sleep(5)
346

347 348
   subnet = job.resources_by_type['subnets'][0]
   ip_network = [str(ip) for ip in IPNetwork(subnet)]
349

350 351 352 353 354
   # create acces for all ips in the subnet
   access = site.storage["msimonin"].access.create({"ipv4": ip_network,
                                                     "termination": {"job": job.uid,
                                                                     "site": site.uid}})
   #+END_SRC
SIMONIN Matthieu's avatar
SIMONIN Matthieu committed
355

356 357
** Vlan API
*** Get vlan(s)
358

359 360 361
   #+BEGIN_SRC python :exports code :tangle examples/vlans_get.py
   import logging
   import os
362

363
   from grid5000 import Grid5000
364 365


366
   logging.basicConfig(level=logging.DEBUG)
367

368 369
   conf_file = os.path.join(os.environ.get("HOME"), ".python-grid5000.yaml")
   gk = Grid5000.from_yaml(conf_file)
SIMONIN Matthieu's avatar
SIMONIN Matthieu committed
370

371
   site = gk.sites["rennes"]
SIMONIN Matthieu's avatar
SIMONIN Matthieu committed
372

373 374 375
   # Get all vlans
   vlans = site.vlans.list()
   print(vlans)
SIMONIN Matthieu's avatar
SIMONIN Matthieu committed
376

377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440
   # Get on specific
   vlan = site.vlans.get("4")
   print(vlan)

   vlan = site.vlans["4"]
   print(vlan)

   # Get vlan of some nodes
   print(site.vlansnodes.submit({"nodes": ["paravance-1.rennes.grid5000.fr", "paravance-2.rennes.grid5000.fr"]}))


   # Get nodes in vlan
   print(site.vlans["4"].nodes.list())

   #+END_SRC

*** Set nodes in vlan

 - Putting primary interface in a vlan

   #+BEGIN_SRC python :exports code :tangle examples/vlan_set_1.py
   import logging
   import os
   import time

   from grid5000 import Grid5000


   logging.basicConfig(level=logging.DEBUG)

   conf_file = os.path.join(os.environ.get("HOME"), ".python-grid5000.yaml")
   gk = Grid5000.from_yaml(conf_file)
   site = gk.sites["rennes"]

   job = site.jobs.create({"name": "pyg5k",
                           "command": "sleep 3600",
                           "resources": "{type='kavlan'}/vlan=1+nodes=1",
                           "types": ["deploy"]})

   while job.state != "running":
       job.refresh()
       print("Waiting the job [%s] to be runnning" % job.uid)
       time.sleep(5)

   deployment = site.deployments.create({"nodes": job.assigned_nodes,
                                         "environment": "debian9-x64-min",
                                         "vlan": job.resources_by_type["vlans"][0]})

   while deployment.status != "terminated":
       deployment.refresh()
       print("Waiting for the deployment [%s] to be finished" % deployment.uid)
       time.sleep(10)

   print(deployment.result)
   #+END_SRC

 - Putting the secondary interface in a vlan

   #+BEGIN_SRC python :exports code :tangle examples/vlan_set_2.py
   import logging
   import os
   import time

   from grid5000 import Grid5000
SIMONIN Matthieu's avatar
SIMONIN Matthieu committed
441

SIMONIN Matthieu's avatar
SIMONIN Matthieu committed
442
  
443
   logging.basicConfig(level=logging.DEBUG)
SIMONIN Matthieu's avatar
SIMONIN Matthieu committed
444 445


446 447 448 449 450 451 452
   def _to_network_address(host, interface):
       """Translate a host to a network address
       e.g:
       paranoia-20.rennes.grid5000.fr -> paranoia-20-eth2.rennes.grid5000.fr
       """
       splitted = host.split('.')
       splitted[0] = splitted[0] + "-" + interface
SIMONIN Matthieu's avatar
SIMONIN Matthieu committed
453

454
       return ".".join(splitted)
SIMONIN Matthieu's avatar
SIMONIN Matthieu committed
455 456


457 458
   conf_file = os.path.join(os.environ.get("HOME"), ".python-grid5000.yaml")
   gk = Grid5000.from_yaml(conf_file)
SIMONIN Matthieu's avatar
SIMONIN Matthieu committed
459

460
   site = gk.sites["rennes"]
SIMONIN Matthieu's avatar
SIMONIN Matthieu committed
461

462 463 464 465 466
   job = site.jobs.create({"name": "pyg5k",
                           "command": "sleep 3600",
                           "resources": "{type='kavlan'}/vlan=1+{cluster='paranoia'}nodes=1",
                           "types": ["deploy"]
   })
SIMONIN Matthieu's avatar
SIMONIN Matthieu committed
467

468 469 470 471
   while job.state != "running":
       job.refresh()
       print("Waiting the job [%s] to be runnning" % job.uid)
       time.sleep(5)
SIMONIN Matthieu's avatar
SIMONIN Matthieu committed
472
      
473
   vlanid = job.resources_by_type["vlans"][0]
SIMONIN Matthieu's avatar
SIMONIN Matthieu committed
474

475 476 477 478
   # we hard code the interface but this can be discovered in the node info
   # TODO: write the code here to discover
   nodes = [_to_network_address(n, "eth2") for n in job.assigned_nodes]
   print(nodes)
SIMONIN Matthieu's avatar
SIMONIN Matthieu committed
479

480 481 482
   # set in vlan
   site.vlans[vlanid].submit({"nodes": nodes})
   #+END_SRC
483

484 485
** More snippets
*** Site of a cluster
SIMONIN Matthieu's avatar
SIMONIN Matthieu committed
486

487 488 489
   #+BEGIN_SRC python :exports code :tangle examples/site_of_cluster.py
   import logging
   import os
SIMONIN Matthieu's avatar
SIMONIN Matthieu committed
490

491
   from grid5000 import Grid5000
SIMONIN Matthieu's avatar
SIMONIN Matthieu committed
492 493


494
   logging.basicConfig(level=logging.DEBUG)
SIMONIN Matthieu's avatar
SIMONIN Matthieu committed
495

496
   clusters = ["dahu", "parasilo", "chetemi"]
SIMONIN Matthieu's avatar
SIMONIN Matthieu committed
497

498 499
   conf_file = os.path.join(os.environ.get("HOME"), ".python-grid5000.yaml")
   gk = Grid5000.from_yaml(conf_file)
SIMONIN Matthieu's avatar
SIMONIN Matthieu committed
500

501 502 503 504 505 506 507 508 509 510
   sites = gk.sites.list()
   matches = []
   for site in sites:
       candidates = site.clusters.list()
       matching = [c.uid for c in candidates if c.uid in clusters]
       if len(matching) == 1:
           matches.append((site, matching[0]))
           clusters.remove(matching[0])
   print("We found the following matches %s" % matches)
   #+END_SRC
SIMONIN Matthieu's avatar
SIMONIN Matthieu committed
511

512
*** Get all job with a given name on all the sites
SIMONIN Matthieu's avatar
SIMONIN Matthieu committed
513

514
   #+BEGIN_SRC python :exports code :tangle examples/api_oargrid.py
SIMONIN Matthieu's avatar
SIMONIN Matthieu committed
515

516 517
   import logging
   import os
SIMONIN Matthieu's avatar
SIMONIN Matthieu committed
518

519
   from grid5000 import Grid5000
SIMONIN Matthieu's avatar
SIMONIN Matthieu committed
520 521


522
   logging.basicConfig(level=logging.DEBUG)
SIMONIN Matthieu's avatar
SIMONIN Matthieu committed
523

524
   NAME = "pyg5k"
SIMONIN Matthieu's avatar
SIMONIN Matthieu committed
525
  
526 527
   conf_file = os.path.join(os.environ.get("HOME"), ".python-grid5000.yaml")
   gk = Grid5000.from_yaml(conf_file)
SIMONIN Matthieu's avatar
SIMONIN Matthieu committed
528

529 530 531
   sites = gk.sites.list()
   site = gk.sites["rennes"]
   sites = [gk.sites["rennes"], gk.sites["nancy"], gk.sites["grenoble"]]
SIMONIN Matthieu's avatar
SIMONIN Matthieu committed
532
  
533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550
   # creates some jobs
   jobs = []
   for site in sites:
       job = site.jobs.create({"name": "pyg5k",
                               "command": "sleep 3600"})
       jobs.append(job)

   _jobs = []
   for site in sites:
       _jobs.append((site.uid, site.jobs.list(name=NAME,
                                              state="waiting,launching,running")))

   print("We found %s" % _jobs)

   # deleting the jobs
   for job in jobs:
       job.delete()
   #+END_SRC
551

552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 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 610 611 612 613 614 615 616 617 618 619 620 621 622 623
*** Caching API responses

    The Grid'5000 reference API is static. In this situation to speed up the
    requests, one could leverage heavily on caching. Currently
    ~python-grid5000~ doesn't do caching out-of the box but defers that to the
    consuming application. There are many solutions to implement a cache.
    Amongst them LRU cache
    (https://docs.python.org/3/library/functools.html#functools.lru_cache)
    provides an in-memory caching facilities but doesn't give you control on the
    cache. The ring library (https://ring-cache.readthedocs.io/en/stable/) is
    great as it implements different backends for your cache (esp.
    cross-processes cache) and give you control on the cached object. Enough talking:


   #+BEGIN_SRC python :exports code :tangle examples/caching.py
    import logging
    import threading
    import os

    import diskcache
    from grid5000 import Grid5000
    import ring


    _api_lock = threading.Lock()
    # Keep track of the api client
    _api_client = None

    storage = diskcache.Cache('cachedir')

    def get_api_client():
        """Gets the reference to the API cient (singleton)."""
        with _api_lock:
            global _api_client
            if not _api_client:
                conf_file = os.path.join(os.environ.get("HOME"),
                                        ".python-grid5000.yaml")
                _api_client = Grid5000.from_yaml(conf_file)

            return _api_client


    @ring.disk(storage)
    def get_sites_obj():
        """Get all the sites."""
        gk = get_api_client()
        return gk.sites.list()


    @ring.disk(storage)
    def get_all_clusters_obj():
        """Get all the clusters."""
        sites = get_sites_obj()
        clusters = []
        for site in sites:
            # should we cache the list aswell ?
            clusters.extend(site.clusters.list())
        return clusters


    if __name__ == "__main__":
        logging.basicConfig(level=logging.DEBUG)
        clusters = get_all_clusters_obj()
        print(clusters)
        print("Known key in the cache")
        print(get_all_clusters_obj.get())
        print("Calling again the function is now faster")
        clusters = get_all_clusters_obj()
        print(clusters)
   #+END_SRC


624 625 626 627 628 629 630 631 632 633 634 635 636
* Appendix                                                         :noexport:
** How to export this file

- Produce ~README.rst~.
  To generate the rst file, load the ~ox-rst.el~ file from
  https://github.com/msnoigrs/ox-rst into emacs. Then do, ~C-c C-e r r~ or ~M-x
  org-rst-export-to-rst~.

- Produce python example scripts.
  Do ~C-c C-v t~ or ~M-x
  org-babel-tangle~. The scripts are available under available under ~examples~.