Check docker container status if it is running using python - python

I have a repo in github and there are shared containers(folders) in the repo. I need to check if the shared containers are running by using python.
This is what I have tried:
import docker
DOCKER_CLIENT = docker.DockerClient(base_url="unix://var/run/docker.sock")
RUNNING = "running"
def is_running(container_name):
container = DOCKER_CLIENT.containers.get(container_name)
container_state = container.attrs["State"]
container_is_running = container_state["Status"] == RUNNING
return container_is_running
my_container_name = "myfolder1"
print(is_running(my_container_name))
If I run this script in VS code IDE terminal, Im not getting any errors or results.
Am I missing anything here? Can anyone suggest any other approach for this

Related

download from URL Kubeflow pipeline

I have been trying to create a kubeflow pipeline in my local machine and created a simple one component pipeline to download data from a given url.
import kfp
import kfp.components as comp
downloader_op = kfp.components.load_component_from_url(path)
def my_pipeline(url):
downloader_task = downloader_op(url = url)
This works fine if I execute this pipeline through python code
client = kfp.Client()
client.create_run_from_pipeline_func(my_pipeline,arguments=
{
'url': 'https://storage.googleapis.com/ml-pipeline-playground/iris-csv-files.tar.gz'
})
But It shows an error when I try to execute the same code through Kubeflow UI.
First I execute the above code which create a yaml file using below line and then upload the yaml file in kubeflow UI to create a new run.
kfp.compiler.Compiler().compile(pipeline_func=my_pipeline,package_path='pipeline.yaml')
It give below error
This step is in Error state with this message: Error (exit code 1): cannot enter chroot for container named "main": no PID known - maybe short running container
I am not able to understand why it creates problems through UI and what is the solution.

how to override downloader directory with local directory in polyglot in python

I run polyglot sentiment detection. When I upload it to the server I cannot run the downloader.download("TASK:sentiment2") command, so I downloaded the sentiment2 folder and saved it in the same folder as the python file.
I tried to set downloader.download_dir = os.path.join(os.getcwd(),'polyglot_data') pointing at the sentiment2 folder location as it says in the polyglot documentation but it doesnt work.
How do I override downloader directory so it will access the sentiment2 local folder when it executes the sentiment analysis?
Please see the full code below. This code works on my computer and localhost but returns zero when I run it on the server.
from polyglot.downloader import downloader
#downloader.download("TASK:sentiment2")
from polyglot.text import Text
downloader.download_dir = os.path.join(os.getcwd(),'polyglot_data')
def get_text_sentiment(text):
result = 0
ttext = Text(text)
for w in ttext.words:
try:
result += w.polarity
except ValueError:
pass
if result:
return result/ len(ttext.words)
else:
return 0
text = "he is feeling proud with ❤"
print(get_text_sentiment(text))
my localhost returns - 0.1666
the server returns - 0.0
after looking at the polyglot git init function. Its an env. issue. data_path = os.environ.get('POLYGLOT_DATA_PATH', data_path)
So I removed the downloader.download_dir = os.path.join(os.getcwd(),'polyglot_data')
and simply define the local POLYGLOT_DATA_PATH in the env. path.
It worked.

NameError: name 'AnsibleModule' is not defined in PyCharm

I am having a python script along with ansible modules integrated. While executing in PyCharm, getting AnsibleModule not defined and it is not recognizing any ansible keywords. Any idea? Do I need to install any additional plugins for PyCharm to execute ansible based Python scripts? Here is my code
def main():
module = AnsibleModule(
argument_spec = dict(
hostvars = dict(required=True, type='dict'),
topology = dict(required=True, type='list'),
my_hostname = dict(required=True)
)
)
try:
hostvars = module.params['hostvars']
topology = module.params['topology']
my_hostname = module.params['my_hostname']
facts = get_facts(hostvars, topology, my_hostname)
module.exit_json(changed=False, ansible_facts=facts)
except Exception as error:
module.fail_json(msg=str(error))
Thanks,
Sridhar A
You have to set up your project interpreter in pycharm. IIRC, this may be a feature only available in pycharm pro. You should point the interpreter at your virtualenv and that will get you up and moving.

pyinstaller Error starting service: The service did not respond to the start or control request in a timely fashion

I have been searching since a couple of days for a solution without success.
We have a windows service build to copy some files from one location to another one.
So I build the code shown below with Python 3.7.
The full coding can be found on Github.
When I run the service using python all is working fine, I can install the service and also start the service.
This using commands:
Install the service:
python jis53_backup.py install
Run the service:
python jis53_backup.py start
When I now compile this code using pyinstaller with command:
pyinstaller -F --hidden-import=win32timezone jis53_backup.py
After the exe is created, I can install the service but when trying to start the service I get the error:
Error starting service: The service did not respond to the start or
control request in a timely fashion
I have gone through multiple posts on Stackoverflow and on Google related to this error however, without success. I don't have the option to install the python 3.7 programs on the PC's that would need to run this service. That's why we are trying to get a .exe build.
I have made sure to have the path updated according to the information that I found in the different questions.
Image of path definitions:
I also copied the pywintypes37.dll file.
From -> Python37\Lib\site-packages\pywin32_system32
To -> Python37\Lib\site-packages\win32
Does anyone have any other suggestions on how to get this working?
'''
Windows service to copy a file from one location to another
at a certain interval.
'''
import sys
import time
from distutils.dir_util import copy_tree
import servicemanager
import win32serviceutil
import win32service
from HelperModules.CheckFileExistance import check_folder_exists, create_folder
from HelperModules.ReadConfig import (check_config_file_exists,
create_config_file, read_config_file)
from ServiceBaseClass.SMWinService import SMWinservice
sys.path += ['filecopy_service/ServiceBaseClass',
'filecopy_service/HelperModules']
class Jis53Backup(SMWinservice):
_svc_name_ = "Jis53Backup"
_svc_display_name_ = "JIS53 backup copy"
_svc_description_ = "Service to copy files from server to local drive"
def start(self):
self.conf = read_config_file()
if not check_folder_exists(self.conf['dest']):
create_folder(self.conf['dest'])
self.isrunning = True
def stop(self):
self.isrunning = False
def main(self):
self.ReportServiceStatus(win32service.SERVICE_RUNNING)
while self.isrunning:
# Copy the files from the server to a local folder
# TODO: build function to trigger only when a file is changed.
copy_tree(self.conf['origin'], self.conf['dest'], update=1)
time.sleep(30)
if __name__ == '__main__':
if sys.argv[1] == 'install':
if not check_config_file_exists():
create_config_file()
if len(sys.argv) == 1:
servicemanager.Initialize()
servicemanager.PrepareToHostSingle(Jis53Backup)
servicemanager.StartServiceCtrlDispatcher()
else:
win32serviceutil.HandleCommandLine(Jis53Backup)
I was also facing this issue after compiling using pyinstaller. For me, the issue was that I was using the paths to configs and logs file in dynamic way, for ex:
curr_path = os.path.dirname(os.path.abspath(__file__))
configs_path = os.path.join(curr_path, 'configs', 'app_config.json')
opc_configs_path = os.path.join(curr_path, 'configs', 'opc.json')
log_file_path = os.path.join(curr_path, 'logs', 'application.log')
This was working fine when I was starting the service using python service.py install/start. But after compiling it using pyinstaller, it always gave me error of not starting in timely fashion.
To resolve this, I made all the dynamic paths to static, for ex:
configs_path = 'C:\\Program Files (x86)\\ScantechOPC\\configs\\app_config.json'
opc_configs_path = 'C:\\Program Files (x86)\\ScantechOPC\\configs\\opc.json'
debug_file = 'C:\\Program Files (x86)\\ScantechOPC\\logs\\application.log'
After compiling via pyinstaller, it is now working fine without any error. Looks like when we do dynamic path, it doesn't get the actual path to files and thus it gives error.
Hope this solves your problem too. Thanks

OpenERP on uWSGI?

How do I run OpenERP on uWSGI?
I found this wsgi script online, but I'm not sure where to place it?
import openerp
try:
import uwsgi
uwsgi.port_fork_hook = openerp.wsgi.core.on_starting
except:
openerp.wsgi.core.on_starting()
# Equivalent of --load command-line option
openerp.conf.server_wide_modules = ['web']
# internal TODO: use openerp.conf.xxx when available
conf = openerp.tools.config
# Path to the OpenERP Addons repository (comma-separated for
# multiple locations)
conf['addons_path'] = '/home/openerp/addons/trunk,/home/openerp/web/trunk/addons'
# Optional database config if not using local socket
#conf['db_name'] = 'mycompany'
#conf['db_host'] = 'localhost'
#conf['db_user'] = 'foo'
#conf['db_port'] = 5432
#conf['db_password'] = 'secret'
# OpenERP Log Level
# DEBUG=10, DEBUG_RPC=8, DEBUG_RPC_ANSWER=6, DEBUG_SQL=5, INFO=20,
# WARNING=30, ERROR=40, CRITICAL=50
# conf['log_level'] = 20
# If --static-http-enable is used, path for the static web directory
#conf['static_http_document_root'] = '/var/www'
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
application = openerp.wsgi.core.application
I installed OpenERP in a virtual environment in /var/www/openerp/venv and I can run it by calling $ openerp-server.
Thanks in advance.
you can just put the script file in the same directory with the openerp-server.py file.
however when I test it it doesnot work since gunicorn cannot find the openerp in the
import openerp sentence. the reason is that openerp is not installed as a python module to the system with the installation procedures around.
I think it will work when you do a openerp install with the DEB package. (when you make such install you should disable the start script so it will just work from gunicorn.
let me also make a test install and share the result.

Categories

Resources