Backend.AI Client Library for Python

Overview

Backend.AI Client

PyPI version Python Versions SDK Documentation Build Status (Linux) Build Status (Windows) Code Coverage

The official API client library for Backend.AI

Usage (KeyPair mode)

You should set the access key and secret key as environment variables to use the API. Grab your keypair from cloud.backend.ai or your cluster admin.

On Linux/macOS, create a shell script as my-backend-ai.sh and run it before using the backend.ai command:

export BACKEND_ACCESS_KEY=...
export BACKEND_SECRET_KEY=...
export BACKEND_ENDPOINT=https://my-precious-cluster
export BACKEND_ENDPOINT_TYPE=api

On Windows, create a batch file as my-backend-ai.bat and run it before using the backend.ai command:

chcp 65001
set PYTHONIOENCODING=UTF-8
set BACKEND_ACCESS_KEY=...
set BACKEND_SECRET_KEY=...
set BACKEND_ENDPOINT=https://my-precious-cluster
set BACKEND_ENDPOINT_TYPE=api

Note that you need to switch to the UTF-8 codepage for correct display of special characters used in the console logs.

Usage (Session mode)

Change BACKEND_ENDPOINT_TYPE to "session" and set the endpoint to the URL of your console server.

export BACKEND_ENDPOINT=https://my-precious-cluster
export BACKEND_ENDPOINT_TYPE=session
$ backend.ai login
User ID: [email protected]
Password:
✔ Login succeeded!

$ backend.ai ...  # run any command

$ backend.ai logout
✔ Logout done.

The session expiration timeout is set by the console server.

Command-line Interface

backend.ai command is the entry point of all sub commands. (Alternatively you can use a verbosely long version: python -m ai.backend.client.cli)

Highlight: run command

The run command execute a code snippet or code source files on a Backend.AI compute session created on-the-fly.

To run the code specified in the command line directly, use -c option to pass the code string (like a shell).

$ backend.ai run python:3.6-ubuntu18.04 -c "print('hello world')"
∙ Client session token: d3694dda6e5a9f1e5c718e07bba291a9
✔ Kernel (ID: zuF1OzMIhFknyjUl7Apbvg) is ready.
hello world

By default, you need to specify language with full version tag like python:3.6-ubuntu18.04. Depending on the Backend.AI admin's language alias settings, this can be shortened just as python. If you want to know defined language aliases, contact the admin of Backend.AI server.

You can even run a C code on-the-fly. (Note that we put a dollar sign before the single-quoted code argument so that the shell to interpret '\n' as actual newlines.)

$ backend.ai run gcc:gcc6.4-alpine3.8 -c $'#include <stdio.h>\nint main() {printf("hello world\\n");}'
∙ Client session token: abc06ee5e03fce60c51148c6d2dd6126
✔ Kernel (ID: d1YXvee-uAJTx4AKYyeksA) is ready.
hello world

For larger programs, you may upload multiple files and then build & execute them. The below is a simple example to run a sample C program.

$ git clone https://gist.github.com/achimnol/df464c6a3fe05b21e9b06d5b80e986c5 c-example
Cloning into 'c-example'...
Unpacking objects: 100% (5/5), done.
$ cd c-example
$ backend.ai run gcc:gcc6.4-alpine3.8 main.c mylib.c mylib.h
∙ Client session token: 1c352a572bc751a81d1f812186093c47
✔ Kernel (ID: kJ6CgWR7Tz3_v2WsDHOwLQ) is ready.
✔ Uploading done.
✔ Build finished.
myvalue is 42
your name? LABLUP
hello, LABLUP!

Please refer the --help manual provided by the run command.

Highlight: start and app command

backend.ai start is simliar to the run command in that it creates a new compute session, but it does not execute anything there. You can subsequently call backend.ai run -t <sessionId> ... to execute codes snippets or use backend.ai app command to start a local proxy to a container service such as Jupyter which runs inside the compute session.

$ backend.ai start -t mysess -r cpu=1 -r mem=2g lablup/python:3.6-ubuntu18.04
∙ Session ID mysess is created and ready.
∙ This session provides the following app services: ipython, jupyter, jupyterlab
$ backend.ai app mysess jupyter
∙ A local proxy to the application "jupyter" provided by the session "mysess" is available at: http://127.0.0.1:8080

Highlight: ps and rm command

You can see the list of currently running sessions using your API keypair.

$ backend.ai ps
Session ID    Lang/runtime              Tag    Created At                        Terminated At    Status      CPU Cores    CPU Used (ms)    Total Memory (MiB)    Used Memory (MiB)    GPU Cores
------------  ------------------------  -----  --------------------------------  ---------------  --------  -----------  ---------------  --------------------  -------------------  -----------
88ee10a027    lablup/python:3.6-ubuntu         2018-12-11T03:53:14.802206+00:00                   RUNNING             1            16314                  1024                 39.2            0
fce7830826    lablup/python:3.6-ubuntu         2018-12-11T03:50:10.150740+00:00                   RUNNING             1            15391                  1024                 39.2            0

If you set -t option in the run command, it will be used as the session ID—you may use it to assign a human-readable, easy-to-type alias for your sessions. These session IDs can be reused after the current session using the same ID terminates.

To terminate a session, you can use terminate or rm command.

$ backend.ai rm 5baafb2136029228ca9d873e1f2b4f6a
✔ Done.

Highlight: proxy command

To use API development tools such as GraphiQL for the admin API, run an insecure local API proxy. This will attach all the necessary authorization headers to your vanilla HTTP API requests.

$ backend.ai proxy
∙ Starting an insecure API proxy at http://localhost:8084

More commands?

Please run backend.ai --help to see more commands.

Troubleshooting (FAQ)

  • There are error reports related to simplejson with Anaconda on Windows. This package no longer depends on simplejson since v1.0.5, so you may uninstall it safely since Python 3.5+ offers almost identical json module in the standard library.

    If you really need to keep the simplejson package, uninstall the existing simplejson package manually and try reinstallation of it by downloading a pre-built binary wheel from here.

Comments
  • Argument parsing error when specifying

    Argument parsing error when specifying "--exec" option to "run" command

    argparse module is not working as expected.

    $ backend.ai run python --exec "python hello.py" hello.py
    usage: backend.ai [-h] {help,config,run,proxy,admin,ps} ...
    backend.ai: error: unrecognized arguments: hello.py
    
    bug 
    opened by achimnol 5
  • Client py tus-draft

    Client py tus-draft

    This is draft version.

    • The client implemented at func/vfolder.py under @api_function async def upload_tus

    • To test client capabilities the file func/mytus.py is used.

    • The package client-tus is located under func/tusclient. It is based on tus-py-client. It was refactored by adding backend.ai session creation and making request to generate a new id for a file.

    • It has the following issues such that aiohttp server on received request produces uncaught exception 400.

    • The server function create_tus_session cannot be executed after the exception occurred. So, fully functionality of tus client is not tested

    feature 
    opened by leksikov 4
  • 버츄얼 폴더에 get 메소드 버그

    버츄얼 폴더에 get 메소드 버그

    session = Session()
    vf = session.VFolder
    name = "first_vf"
    vf.create(name)
    vf.get(name)
    

    을 할경우 아래와 같이 에러가 발생합니다.

    ---------------------------------------------------------------------------
    TypeError                                 Traceback (most recent call last)
    <ipython-input-24-586f79b79e3d> in <module>
    ----> 1 vf.get('first_vf')
    
    ~/code/brgg/CodeLion/.venv/lib/python3.6/site-packages/ai/backend/client/base.py in _caller(cls, *args, **kwargs)
         63                    'You must use API wrapper functions via a Session object.'
         64             gen = meth(*args, **kwargs)
    ---> 65             resp = cls._make_request(gen)
         66             return cls._handle_response(resp, gen)
         67 
    
    ~/code/brgg/CodeLion/.venv/lib/python3.6/site-packages/ai/backend/client/base.py in _make_request(gen)
         49     @staticmethod
         50     def _make_request(gen):
    ---> 51         rqst = next(gen)
         52         resp = rqst.fetch()
         53         return resp
    
    TypeError: 'VFolder' object is not an iterator
    

    get메소드는 다른 메소드와 달리 별도의 처리가 되지 않아 발생한 상황인듯 하여 확인 부탁드립니다.

    opened by like-sinsky 4
  • Tunneling proxy to access service ports (e.g., TensorBoard)

    Tunneling proxy to access service ports (e.g., TensorBoard)

    Configuring a network is often painful for end-users. Let's provide a better way in the CLI of sorna client, and let the users just open "localhost:8081" to magically connect to a web page served by the kernel session. We could use the SSH socks proxy or just some custom-built ones via WebSockets.

    feature 
    opened by achimnol 4
  • Feature/audit_logs

    Feature/audit_logs

    This pull request refers to: https://github.com/lablup/backend.ai-internal/issues/17

    This is the implementation of the audit log feature in client side, which includes admin cli commands

    List

    This command list audit logs of a user by user_id

    Screenshot 2022-05-04 at 18 30 52 Screenshot 2022-05-09 at 21 09 03
    opened by hydroxyde 3
  • Feature/filebrowser in storage proxy

    Feature/filebrowser in storage proxy

    A CLI implementation for starting File Browser in storage proxy. After File Browser starts the CLI opens the web browser tab with url of FileBrowser UI interface.

    feature cli client 
    opened by leksikov 3
  • refactor: Make CLI commands consistent

    refactor: Make CLI commands consistent

    Let's make command arguments and options to be consistent and update to Click 8.0.x.

    • refs https://github.com/lablup/backend.ai-test
    • refs lablup/backend.ai#240

    The client SDK consists of: low-level API (auth, request) + functional API (wrappers around REST and GraphQL) + CLI commands. This PR will rewrite the CLI commands, and this will not be backward compatible due to ambiguity of command parsing. (Just imagine that etcdctl requires ETCDCTL_API environment variable to switch between v2 and v3 command sets.)

    What's included in this PR:

    • API v4 or older support is removed with an explicit warning during version negotiation.
    • Python 3.7 support is removed and now it requires 3.8 or later.
    • New consistent CLI command hierarchy with backend.ai admin? <entity> {info,list,...}. e.g.,
      • Before
        • backend.ai admin agents
        • backend.ai admin agent i-dgx001 (😞 mix of plural and singular "agent" and "agents")
        • backend.ai admin scaling-group -n default (😞 some individual item query commands just accept an argument but some accept an arbitrarily named option -- inconsistent!!)
      • After
        • backend.ai admin agent list
        • backend.ai admin agent info i-dgx001 (💯 now consistent singular name followed by list, info)
        • backend.ai admin scaling-group info default (💯 now consistently accept the key as a sole argument)
      • Still it preserves many frequently-used shortcuts such as run, ps, rm, etc., but they are now the pure duplicate, by generating the command handler function twice for different command groups and thus removing potential of missing new options/arguments due to manual copy-and-paste of codes.
    • Global --output=console (the default) or --output=json option to control the output format of CLI list and info commands. e.g.,
      • backend.ai --output=json ps --dead
      • backend.ai --output=json admin agent list
      • This introduces a new "output" framework as ai.backend.client.output subpackage.
        • Now all functional list/detail APIs must be called with a list of FieldSpec as fields arguments, instead of a list of str.
        • You may refer the predefined FieldSpec instances from ai.backend.client.output.fields and each functional API module's _default_list_fields and _default_detail_fields variables.
        • It standardizes the error output and exit code so that users may write more sophisticated automation scripts using the CLI with jq command and shell scripts.
    • --limit and --offset to control pagination of paginated list commands (NOTE: Not all list commands support this...)
      • e.g., backend.ai ps --dead --offset=30 --limit=20
      • All JSON output of list commands now include count (the number of items in the current page result), total_count (the number of all items in the server), items (the list of item objects) fields so that client may perform its own pagination as needed, in a consistent way.

    Left as future work:

    • This PR does not implement the --output=json support for mutation and session execution commands. They currently work like before, just printing out console messages regardless of the output option.
    feature refactor cli client 
    opened by achimnol 3
  • backend.ai ssh/scp commands

    backend.ai ssh/scp commands

    Completed Backend.AI SSH client which can connect to the existing backend.ai session SSH server for the Issue #228

    After session is started. It is possible to directly initialize ssh connection. backend.ai ssh mysess

    Or with port specification for that session: backend.ai ssh mysess -p 9922

    File upload and download. Scp client was implemented to upload and download files. (session name, local file, host file/dir, flag to reverse) backend.ai scp mysess vfolder.py [email protected]:tmp/

    To download file from localhost reverse the src and dest: backend.ai scp mysess [email protected]:tmp/ vfolder.py

    Directories upload and download support. Add -r option. upload: backend.ai scp mysess -r tmp/ [email protected]:tmp/ download: backend.ai scp mysess -r [email protected]:tmp/ tmp/

    cli usability client 
    opened by leksikov 3
  • Added --format and --plain options to the 'backend.ai ps' command

    Added --format and --plain options to the 'backend.ai ps' command

    lablup/backend.ai#87 @achimnol

    • Added --format/-f options for "backend.ai ps"/"backend.ai admin session" commands

    • Added --plain option to see process status info in plain tabular format

    • [x] I will update the documentation file as soon as possible

    feature 
    opened by miraliahmadli 3
  • 쿼리 요청이 불가능합니다.

    쿼리 요청이 불가능합니다.

    from ai.backend.client import Kernel로 되있으나 실제로는 from ai.backend.client.kernel import Kernel해야 작동이 됩니다. 또한 위와 같이 변경하여 아래와 같이 요청을 시도하여도

    from ai.backend.client.kernel import Kernel
    
    kern = Kernel.get_or_create('python', client_token='abcdef')
    result = kern.execute('print("hello world")', mode='query')
    print(result['console'])
    kern.destroy()
    

    AssertionError: You must use API wrapper functions via a Session object. 에러가 발생합니다. get_or_create가 클래스 메소드이다보니 세션을 어느시점에 어떻게 넣어줘야 하는지 궁금합니다.

    마지막으로 사소한 부분이긴 하나 실세 샘플 코드에서는 클라이언트 토큰이 'abc'로 적혀있는데 실제로 그대로 돌려볼경우 assert 4 <= len(client_token) <= 64, 'Client session token should be 4 to 64 characters long.' 에러가 막히지 않을까 싶습니다. 그래서 4자 이상으로 변경하시면 처음 시도하시는 분이 에러없이 테스트 해보실수 있지 않을까 싶습니다.

    help wanted 
    opened by like-sinsky 3
  • Cannot download file(s) from compute session

    Cannot download file(s) from compute session

    backend.ai download <sess-id> <filepath> command is broken with following traceback:

    Traceback (most recent call last):c51362187f653ee5745d6906b...
      File "/Users/adrysn/.pyenv/versions/playground/bin/backend.ai", line 11, in <module>
        sys.exit(main())
      File "/Users/adrysn/.pyenv/versions/3.7.0/envs/playground/lib/python3.7/site-packages/ai/backend/client/cli/__init__.py", line 104, in main
        args.function(args)
      File "/Users/adrysn/.pyenv/versions/3.7.0/envs/playground/lib/python3.7/site-packages/ai/backend/client/cli/__init__.py", line 40, in wrapped
        handler(args)
      File "/Users/adrysn/.pyenv/versions/3.7.0/envs/playground/lib/python3.7/site-packages/ai/backend/client/cli/files.py", line 44, in download
        kernel.download(args.files, show_progress=True)
      File "/Users/adrysn/.pyenv/versions/3.7.0/envs/playground/lib/python3.7/site-packages/ai/backend/client/base.py", line 79, in _caller
        return self._handle_response(resp, gen)
      File "/Users/adrysn/.pyenv/versions/3.7.0/envs/playground/lib/python3.7/site-packages/ai/backend/client/base.py", line 37, in _handle_response
        meth_gen.send(resp)
      File "/Users/adrysn/.pyenv/versions/3.7.0/envs/playground/lib/python3.7/site-packages/ai/backend/client/kernel.py", line 191, in _download
        total=resp.stream_reader.total_bytes,
    AttributeError: 'Response' object has no attribute 'stream_reader'
    

    Meanwhile, downloading from vfolders is working.

    bug 
    opened by adrysn 3
  • refactor: remove dependency of tqdm in vfolder function progress

    refactor: remove dependency of tqdm in vfolder function progress

    resolves https://github.com/lablup/backend.ai/issues/344

    add abstraction in vfolder function and remove tqdm dependency

    upload function still uses tqdm because aiotusclient uses tqdm directly.

    refactor cli client 
    opened by fregataa 0
  • feat: Display kernel-pull-progress

    feat: Display kernel-pull-progress

    backend.ai-issue#227

    Client (Python & Javascript) Task

    • [x] Check the existence of the task ID in the create-kernel API response.

    • [x] If it exists, show a progress bar reflecting its progress stream.

    Using response from manager, client obtains background-task pulling kernel and displays progress bar reflecting kernel-pulling. But, I do request twice.

    • From first request, client obtains kernel_id and background task.

    • From second request, client gets all the information from existed session.

    But, I think we need another way to get all the information(contains background-task id) from manager with a single request.

    feature cli client 
    opened by youngjun0627 4
  • Docs/cli 2009

    Docs/cli 2009

    Configuration

    • API Mode

    • Session Mode

    • Checking out current configuration

    • Command reference 
 Code Execution
    • ComputeSessions

    • Container Apps

    • Adv. Code Execution

    • Session Templates

    • Command reference


    Storage Management

    • VFolder Basics -> 생성·삭제·업로드·다운로드·파일조회 관련 설명

    • VFolder Sharing -> invitation 관련 기능 설명(새로운 내용 추가)

    • Command reference


    의 구조로 docs를 정리했습니다. review 부탁드립니다!

    docs cli 
    opened by kmkwon94 3
Releases(20.03.0a1)
  • 20.03.0a1(Apr 6, 2020)

    Breaking Changes

    • Breaking Changes without explicit PR/issue numbers
      • Now the client SDK runs on Python 3.6, 3.7, and 3.8 and dropped support for Python 3.5.
    • All functional API classes are moved into the ai.backend.client.func sub-package. (#82)
      • Kernel is changed to Session.
      • The session ID field name in the response of Session objects is now session_id instead of kernel_id.
      • Except above, this would not introduce big changes in the SDK user codes since they use AsyncSession and Session in the ai.backend.client.session module.

    Features

    • Features without explicit PR/issue numbers
      • Add SDK API (SessionTemplate) and CLI command set (backend.ai sesstpl)
    • Support for unmanaged vfolders and token-based download API (#77)
    • backend.ai config command now displays the server/client component and API versions with negotiated API version if available. (#79)
    • Add --format and --plain options to backend.ai ps command to customize the output table format (#80)
    • Perform automatic API version negotiation when entering session contexts while keeping the functional API same (#82)
    • Support dotfiles management API and CLI (#85)

    Fixes

    • Refine details of the app command such as error handling (#90)
    • Improve exception handling in backend.ai app command and update backend.ai-cli package (#94)

    Miscellaneous

    Source code(tar.gz)
    Source code(zip)
Owner
Lablup
lab | up: Make AI Accessible - A start-up to innovate research / education processes.
Lablup
Celestial - a Python regex Discord chatbot who can talk with you.

Celestial a Python regex Discord chat bot who can talk with you. Invite url: https://discord.com/api/oauth2/authorize?client_id=927573556961869825&per

Jirayu Kaewsing 3 Jan 01, 2023
Automates the process to obtain an appointment for NIE in spain.

get-nie-appointment A Python script that automates the process of getting an appointment for NIE assignation. It can be modified in order to change th

Ezequiel Aceto 39 Nov 28, 2022
A multi exploit instagram exploitation framework

Instagram Exploitation Framework About IEF Is an open source Instagram Exploitation Framework with various Exploits that could be used to mod your pro

Instagram Exploitation Framework - BirdSecurity 1 May 23, 2022
Bitcoin tracker hecho con python.

Bitcoin Tracker Precio del Bitcoin en tiempo real. Script simple hecho con python. Rollercoin RollerCoin es un juego en el que puedes ganar bitcoin (y

biyivi 3 Jan 04, 2022
Texting service to receive current air quality conditions and maps, powered by AirNow, Twilio, and AWS

The Air Quality Bot is generally available by texting a zip code (and optionally the word "map") to (415) 212-4229. The bot will respond with the late

Alex Laird 8 Oct 16, 2022
Simple yet efficient tool used to check and sort tokens in terms of there validation.

Discord Token Checker Simple yet efficient tool used to check and sort tokens in terms of there validation.When the program is done,go to the "output"

Robotnik 15 Dec 27, 2022
Build a better understanding of your data in PostgreSQL.

Data Fluent for PostgreSQL Build a better understanding of your data in PostgreSQL. The following shows an example report generated by this tool. It g

Mark Litwintschik 28 Aug 30, 2022
Elemeno.ai standard development kit in Python

Overview A set of glue code and utilities to make using elemeno AI platform a smooth experience Free software: Apache Software License 2.0 Installatio

Elemeno AI 3 Dec 14, 2022
This automation protect against subdomain takeover on AWS env which also send alerts on slack.

AWS_Subdomain_Takeover_Detector Purpose The purpose of this automation is to detect misconfigured Route53 entries which are vulnerable to subdomain ta

Puneet Kumar Maurya 8 May 18, 2022
A delivery protection and notification system

DeliveryProtect This project builds a delivery protection and notification system, based on integration of Arduino Uno and Raspberry Pi 4. The codes a

2 Dec 13, 2021
RequestTrackerBot - Request Tracker Bot With Python

Request Tracker Bot This is a Request Tracker Bot repo, It is for those who uplo

Prince Jaiswal 1 Dec 30, 2021
The aim is to contain multiple models for materials discovery under a common interface

Aviary The aviary contains: - roost, - wren, cgcnn. The aim is to contain multiple models for materials discovery under a common interface Environment

Rhys Goodall 20 Jan 06, 2023
A multifunctional bot for Discord

Um bot multifuncional e divertido para Discord Estive desenvolvendo o BotDaora desde o começo de outubro de 2021 e agora ele é open-source! tomei essa

Ruan 4 Dec 28, 2021
A taskbar clock for secondary taskbars on Windows 11

ElevenClock A taskbar clock for secondary taskbars on Windows 11. When microsoft's engineers were creating Windows 11, they forgot to add a clock on t

Martí Climent 1.7k Jan 07, 2023
Repositório para a Live Coding do dia 22/12/2021 sobre AWS Step Functions

DIO Live Step Functions - 22/12/2021 Serviços AWS utilizados AWS Step Functions AWS Lambda Amazon S3 Amazon Rekognition Amazon DynamoDB Amazon Cloudwa

Cassiano Ricardo de Oliveira Peres 5 Mar 01, 2022
Cogs for RedDiscord-Bot V3

Cogs v3 Disclaimer: This is an unapproved repo, meaning no one has formally reviewed this repo yet and any loss of data in your bot isn't my fault (An

Honkertonken 5 Nov 17, 2022
Bot-moderator for Telegram group chats

Project title A little info about your project and/ or overview that explains what the project is about. 🌟 Hello everyone! This is the repository of

Maxim Zavalniuk 6 Nov 01, 2022
A Pythonic wrapper for the Wikipedia API

Wikipedia Wikipedia is a Python library that makes it easy to access and parse data from Wikipedia. Search Wikipedia, get article summaries, get data

Jonathan Goldsmith 2.5k Dec 28, 2022
Track to Detect and Segment: An Online Multi-Object Tracker (CVPR 2021)

Track to Detect and Segment: An Online Multi-Object Tracker (CVPR 2021) Track to Detect and Segment: An Online Multi-Object Tracker Jialian Wu, Jiale

Jialian Wu 520 Dec 31, 2022
A free, minimal, lightweight, cross-platform, easily expandable Twitch IRC/API bot.

parky's twitch bot A free, minimal, lightweight, cross-platform, easily expandable Twitch IRC/API bot. Features 🔌 Connect to Twitch IRC chat! 🔌 Conn

Andreas Schneider 10 Dec 30, 2022