Cloudshell-sandbox-reporter - Helper modules and classes for writing to Cloudshell sandbox console

Overview

Python 3.7 Lint and Test PyPI version

Cloudshell Sandbox Reporter

This project provides utility classes for formatting and sending html messages to the cloudshell sandbox console. These methods help to semantically color the text and generate custom html elements (headers / anchors / etc.).

The SandboxReporter class is used to chunk together logging messages with the sandbox console print actions into single commands. This reduces duplication in your script if you typically log and print the same messages. There are granular flags for message instances that you only want to log and not print.

The SandboxReporter is also a "logger adapter" - which means it can be passed into functions in place of the original logger. You just instantiate the reporter with your logger instance, and log messages will be delegated to the original logger.

Sample Output

alt text

Installation

pip install cloudshell-sandbox-reporter

General Usage Samples

import logging
from cloudshell.helpers.sandbox_reporter.reporter import SandboxReporter, SandboxConsole
from cloudshell.api.cloudshell_api import CloudShellAPISession

LIVE_SANDBOX_ID = "16df1ea8-27b3-491d-89b9-10d1076f99c5"
logger = logging.Logger("test logger")
api = CloudShellAPISession("localhost", "admin", "admin", "Global")

reporter = SandboxReporter(api, LIVE_SANDBOX_ID, logger)

reporter.warning_header("Add a yellow, italic header to get attention")

reporter.info("standard INFO level message to logs and console")
reporter.debug("DEBUG message to logs and purple text to console ")
reporter.error("ERROR log and red text to console")
reporter.warning("WARNING log and yellow text to console")
reporter.success("INFO log and green text to console")

# generate a clickable anchor tag in console
reporter.console.anchor_tag_print(url="https://www.google.com", text="click to to go to google!")

# pass reporter into functions expecting logger
def some_func(logger: logging.Logger):
    logger.info("running func")
    
some_func(reporter)

# if you want to avoid noise in the console, just pass along internal logger
some_func(reporter.logger)

# if you only care about console without logging, instantiate console independently
console = SandboxConsole(api, LIVE_SANDBOX_ID)
console.sb_print("write to sandbox console only")
  • NOTE: In orchestration scripts the SandboxReporter init dependencies are generally provided (api, sandbox id, logger)
    • (examples in next section)

Orchestration Sample

In cloudshell Orchestration scripts, the sandbox object will provide the sandbox id, api session and logger.

from cloudshell.workflow.orchestration.setup.default_setup_orchestrator import DefaultSetupWorkflow
from cloudshell.workflow.orchestration.sandbox import Sandbox
from cloudshell.helpers.sandbox_reporter.reporter import SandboxReporter


def custom_config_function(sandbox, components=None):
    """
    Functions passed into orchestration flow MUST have (sandbox, components) signature
    :param Sandbox sandbox:
    :param components
    :return:
    """
    sb_id = sandbox.id
    api = sandbox.automation_api
    logger = sandbox.logger
    
    # instantiate reporter
    reporter = SandboxReporter(api, sb_id, logger)
    reporter.info("starting custom config function!!!")
    
    # some more business logic .........

sandbox = Sandbox()

DefaultSetupWorkflow().register(sandbox, enable_configuration=False)
sandbox.workflow.add_to_configuration(custom_config_function, None)
sandbox.execute_setup()

Shell Command Sample

In shell methods, the ResourceCommandContext object will help produce the api, sandbox id, and logger that are passed to SandboxReporter

from cloudshell.shell.core.resource_driver_interface import ResourceDriverInterface
from cloudshell.shell.core.driver_context import InitCommandContext, ResourceCommandContext
from cloudshell.shell.core.session.cloudshell_session import CloudShellSessionContext
from cloudshell.shell.core.session.logging_session import LoggingSessionContext
from cloudshell.helpers.sandbox_reporter.reporter import SandboxReporter
import time


class ReporterTesterDriver (ResourceDriverInterface):

    def __init__(self):
        pass

    def initialize(self, context):
        pass

    def cleanup(self):
        pass
    
    def _some_business_logic(self):
        time.sleep(10)
        
    def cool_service_command(self, context):
        """
        :param ResourceCommandContext context:
        """
        api = CloudShellSessionContext(context).get_api()
        sandbox_id = context.reservation.reservation_id
        with LoggingSessionContext(context) as logger:
            reporter = SandboxReporter(api, sandbox_id, logger)
            reporter.info("Starting Service Command, this may take a while...")
            
            try:
                # simulate long running  action
                self._some_business_logic()
            except Exception as e:
                # logs error and sends red text message to sandbox
                err_msg = f"Error caught during command. {type(e).__name__}: {str(e)}"
                reporter.error(err_msg)
                raise Exception(err_msg)

        return "Service Flow SUCCESSFUL"

License

Free Software: MIT License

You might also like...
Set of classes and tools to communicate with a Noso wallet using NosoP

NosoPy Set of classes and tools to communicate with a Noso wallet using NosoP(Noso Protocol). The data that can be retrieved consist of: Node informat

Stop writing scripts to interact with your APIs. Call them as CLIs instead.
Stop writing scripts to interact with your APIs. Call them as CLIs instead.

Zum Stop writing scripts to interact with your APIs. Call them as CLIs instead. Zum (German word roughly meaning "to the" or "to" depending on the con

❤️ Hi There Im EzilaX ❤️ A next gen powerful telegram group manager bot 😱 for manage your groups and have fun with other cool modules Made By Sadew Jayasekara 🔥
❤️ Hi There Im EzilaX ❤️ A next gen powerful telegram group manager bot 😱 for manage your groups and have fun with other cool modules Made By Sadew Jayasekara 🔥

❤️ EzilaX v1 ❤️ Unmaintained. The new repo of @EzilaXBot is Public. (It is no longer based on this source code. The completely rewritten bot available

❤️A next gen powerful telegram group manager bot for manage your groups and have fun with other cool modules
❤️A next gen powerful telegram group manager bot for manage your groups and have fun with other cool modules

Natsuki Based on Python Telegram Bot Contributors Video Tutorial: Complete guide on deploying @TheNatsukiBot's clone on Heroku. ☆ Video by Sadew Jayas

Amanda-A next gen powerful telegram group manager bot for manage your groups and have fun with other cool modules.
Amanda-A next gen powerful telegram group manager bot for manage your groups and have fun with other cool modules.

Amanda-A next gen powerful telegram group manager bot for manage your groups and have fun with other cool modules.

This Is A Python Program To Showcase Two Modules (Gratient And Fade)

Hellooo, It's PndaBoi Here! This Is A Python Program To Showcase Two Modules (Gratient And Fade). I Really Like Both Of These Modules So I Decided To

Botto - A discord bot written in python that uses the hikari and lightbulb modules to make this bot

❓ About Botto Hi! This is botto, a discord bot written in python that uses the h

Async boto3 with Autogenerated Data Classes

awspydk Async boto3 with Autogenerated JIT Data Classes Motivation This library is forked from an internal project that works with a lot of backend AW

A simple discord bot named atticus that sends you the timetable of your classes upon request
A simple discord bot named atticus that sends you the timetable of your classes upon request

A simple discord bot named atticus that sends you the timetable of your classes upon request. Soon, it would you ping you before classes too!

Owner
QualiLab
Automating the DevOps lifecycle with Cloud Sandboxes
QualiLab
𝗖𝝠𝝦𝝩𝝠𝝞𝝥 𝝦𝗥𝝞𝗖𝝽°™️ 🇱🇰 Is An All In One Media Inline Bot Made For Inline Your Media Effectively With Some Advance Security Tools♥️

𝗖𝝠𝝦𝝩𝝠𝝞𝝥 𝝦𝗥𝝞𝗖𝝽° ™️ 🇱🇰 𝗙𝗘𝝠𝝩𝗨𝗥𝗘𝗦 Auto Filter IMDB Admin Commands Broadcast Index IMDB Search Inline Search Random Pics Ids & User I

Kɪꜱᴀʀᴀ Pᴇꜱᴀɴᴊɪᴛʜ Pᴇʀᴇʀᴀ 〄 13 Jun 21, 2022
Hack WhatsApp Account Easily(Android)

X-Whatsapp Hack WhatsApp Account Easily(Android) HOW TO RUN 👇 (Termux) pkg update && pkg upgrade pkg install python pkg install git git clone https:/

KiLL3R_xRO 72 Dec 21, 2022
vk.com API python wrapper

Python vk.com API wrapper This is a vk.com (the largest Russian social network) python API wrapper. The goal is to support all API methods (current an

Dmitry Voronin 371 Dec 29, 2022
QR-Code-Grabber - A python script that allows a person to create a qr code token grabber

Qr Code Grabber Description Un script python qui permet a une personne de creer

5 Jun 28, 2022
Telegram File to Link Fastest Bot , also used for movies streaming

Telegram File Stream Bot ! A Telegram bot to stream files to web. Report a Bug | Request Feature About This Bot This bot will give you stream links fo

Avishkar Patil 194 Jan 07, 2023
a Disqus alternative

Isso – a commenting server similar to Disqus Isso – Ich schrei sonst – is a lightweight commenting server written in Python and JavaScript. It aims to

Martin Zimmermann 4.7k Jan 02, 2023
A userbot made for telegram

𝚃𝙷𝙴 𝙼𝙰𝙵𝙸𝙰𝙱𝙾𝚃 This is a userbot made for telegram. I made this userbot with help of all other userbots available in telegram. All credits go

MafiaBotOP 8 Apr 08, 2022
A Telegram bot that can stream Telegram files to users over HTTP.

T.ME_FILE_TO_LINK Hi iam a file to link bot....best Bot telegram Telegram File To Link Generation Bot A Telegram bot that can stream Telegram files to

1 Oct 24, 2021
A Telegram bot to extracting text from images. All languages supported.

OCR Bot A Telegram bot to extracting text from images. All languages supported. Deploy to Heroku Local Deploying Clone the repo git clone https://gith

6 Oct 21, 2022
A simple bot to upload file to various cloud servers.

Cloudsy Bot A simple bot to upload file to various cloud servers. Variables API_HASH Your API Hash from my.telegram.org API_ID Your API ID from my.tel

Flying Santas 8 Oct 31, 2022
A Very Simple Telegram Files Rename Bot by @AbirHasan2005

Rename-Bot This is a very simple Telegram Files Rename Bot by @AbirHasan2005. Features Rename Videos, Files or Audios. Permanent Custom Thumbnail Supp

Abir Hasan 124 Dec 25, 2022
Python wrapper to simplify calls to AncestryDNA API.

AncestryDNA API wrapper Ancestry exposes an undocumented REST API for its DNA features. This Python wrapper inventories the available calls, and expos

Matt 2 Jun 10, 2022
Практическая работа 6 - Документирование кода

Практическая работа №6 ПСП – правильная скобочная последовательность – последовательность из открывающих «(« и закрывающих «)» круглых скобок. Програм

0 Apr 14, 2022
Want to play What Would Rather on your Server? Invite the bot now!😏

What is this Bot? 👀 What You Would Rather? is a Guessing game where you guess one thing. Long Description short Take this example: You typed r!rather

丂ㄚ么乙ツ 2 Nov 17, 2021
Webb-Tracker-Bot - This is a discord bot that displays current progress of the James Webb Space Telescope.

Webb-Tracker-Bot - This is a discord bot that displays current progress of the James Webb Space Telescope.

Copperbotte 1 Jan 05, 2022
A Discord bot written in Python that can be used to control event management on a server.

Event Management Discord Bot A Discord bot written in Python that can be used to control event management on a Discord server. Made originally for GDS

Suvaditya Mukherjee 2 Dec 07, 2021
Google Drive, OneDrive and Youtube as covert-channels - Control systems remotely by uploading files to Google Drive, OneDrive, Youtube or Telegram

covert-control Control systems remotely by uploading files to Google Drive, OneDrive, Youtube or Telegram using Python to create the files and the lis

Ricardo Ruiz 52 Dec 06, 2022
Discord opsiyonel detaylı hava durumu botu

WeatherBot Discord opsiyonel detaylı hava durumu botu önümüzdeki Perşembe ──► önümüzdeki Çarşamba ┌─────────┐┌─────────┐┌─────────┐┌───────

DejaVu 16 Dec 19, 2022
Innocent-Bot - A Discord client self-bot for destroying, nuking and causing mischief in servers

Innocent-bot A Discord client self-bot for destroying, nuking and causing mischi

†† 5 Jan 26, 2022
GTK3-based panel for sway window manager

nwg-panel I have been using sway since 2019 and find it the most comfortable working environment, but... Have you ever missed all the graphical bells

Piotr Miller 290 Jan 07, 2023