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
A website application running in Google app engine, deliver rss news to your kindle. generate mobi using python, multilanguages supported.

Readme of english version refers to Readme_EN.md 简介 这是一个运行在Google App Engine(GAE)上的Kindle个人推送服务应用,生成排版精美的杂志模式mobi/epub格式自动每天推送至您的Kindle或其他邮箱。 此应用目前的主要

2.6k Jan 06, 2023
Chorok - High quality Discord music bot

Chorok - High quality Discord music bot Rewrite with dico Config guide

Chorok Opensource project 10 May 03, 2022
OpenQuake's Engine for Seismic Hazard and Risk Analysis

OpenQuake Engine The OpenQuake Engine is an open source application that allows users to compute seismic hazard and seismic risk of earthquakes on a g

Global Earthquake Model 281 Dec 21, 2022
Monitoring plugin for MikroTik devices

check_routeros - Monitoring MikroTik devices This is a monitoring plugin for Icinga, Nagios and other compatible monitoring solutions to check MikroTi

DinoTools 6 Dec 24, 2022
My telegram bot to download Instagram Profiles

Instagram Profile Get for Telegram My telegram bot to download Instagram Profiles First you have to get a telegrm bot api key from @BotFather Then you

Ali Yoonesi 2 Sep 22, 2022
Python Library to Extract youtube video Tags without Youtube API

YoutubeTags Python Library to Extract youtube video Tags without Youtube API Installation pip install YoutubeTags Example import YoutubeTags from Yout

Nuhman Pk 17 Nov 12, 2022
Please Do Not Throw Sausage Pizza Away - Side Scrolling Up The OSI Stack

Please Do Not Throw Sausage Pizza Away - Side Scrolling Up The OSI Stack

John Capobianco 2 Jan 25, 2022
Battle Pass farming tft bot

Tft bot Bot para farmar pontos do Passe de Batalha do TFT Descrição A cada partida de tft jogada você ganha 100 pontos no passe, porém você não precis

Leonardo Gonçalves 4 Jan 27, 2022
Nowadays we don't have time to listen to each and every song that we come across in a playlist.

Nowadays we don't have time to listen to each and every song that we come across in a playlist. so, this project helps you. we used Spotify API for collecting the dataset information and able to do E

3 Apr 26, 2022
Cryptocurrency Trading Bot - A trading bot to automate cryptocurrency trading strategies using Python, equipped with a basic GUI

Cryptocurrency Trading Bot - A trading bot to automate cryptocurrency trading strategies using Python, equipped with a basic GUI. Used REST and WebSocket API to connect to two of the most popular cry

Francis 8 Sep 15, 2022
Minimal API for the COVID Booking System of the Offices at the UniPD Math Dep

Simple and easy to use python BOT for the COVID registration booking system of the math department @ unipd (torre archimede). This API creates an interface with the official website, with more useful

Guglielmo Camporese 4 Dec 24, 2021
This tool is created by Shahzain and is one of the best self bots out there!

Shahzain SelfBot This tool is created by Shahzain and is one of the best self bots out there! Features Token Destroyer! Server Nuker(50-100 Bans Per S

Shahzain 6 Apr 02, 2022
Low-level, feature rich and easy to use discord python wrapper

PWRCord Low-level, feature rich and easy to use discord python wrapper Important Note: At this point, this library API is considered unstable and can

MIguel Lopes 1 Dec 26, 2021
SEMID - OSINT module with lots of discord functions

SEMID Framework About Semid is a framework with different Discord functions and

Hima 20 Sep 23, 2022
Skyscanner Python SDK

Skyscanner Python SDK Important As of May 1st, 2020, the project is deprecated and no longer maintained. The latest update in v1.1.5 includes changing

Skyscanner 118 Sep 23, 2022
A python package that fetches tweets and user information in a very pythonic manner.

Tweetsy Tweetsy uses Twitter's underlying API to fetch user information and tweets and present it in a human-friendly way. What makes Tweetsy special

Sakirul Alam 5 Nov 12, 2022
This is an Advanced Calculator maybe with Discord Buttons in python.

Welcome! This is an Advanced Calculator maybe with Discord Buttons in python. This was the first version of the calculator, made for my discord bot, P

Polsulpicien 18 Dec 24, 2022
A python based all-in-one tool for Google Drive

gdrive-tools A python based all-in-one tool for Google Drive Uses For Gdrive-Tools ✓ generate SA ✓ Add the SA and Add them to TD automatically ✓ Gener

XcodersHub 32 Feb 09, 2022
🥀 Find the start of the token !

Discord Token Finder Find half of your target's token with just their ID. Install 🔧 pip install -r requeriments.txt Gui Usage 💻 Go to Discord Setti

zeytroxxx 2 Dec 22, 2021
4 Oct 28, 2021