SlideShare a Scribd company logo
Maxym Kharchenko
Manage ORACLE databases
with Python
Whoami
■ Started as a database kernel developer with C and C++
■ ORACLE DBA for ~ 14 years: + SQL, PL/SQL and Perl
■ Persistence Engineer for the last 4: + Python, R and Scala
■ OCM, ORACLE Ace Associate
■ Blog: http://intermediatesql.com
■ Twitter: @maxymkh
Agenda
■ Talk about why Python is awesome
■ Design ORACLE multi db “ping” in Python
■ (hopefully) Demo it
The job of an engineer is
to make complex things simple
Why script outside the database ?
Do I have a good datafilebackup ?
SELECT …
FROM v$backup_datafile
 v$backup_datafile
 Backup files actually exist
 and can be validated
 Backup size is plausible
 On the end storage
 Network transfer as well
 No critical errors in logs
 Etc
Some things are
just difficult to do in a database
You will, generally, get better Zen
i := i + 1 i += 1
You will, generally, get better Zen
You will, generally, get better Zen
You, probably, have >1 database
ORACLE ORACLE
ORACLE ORACLE ORACLE
ORACLE ORACLE ORACLE
ORACLE MySql MySql
Postgres Cassandra
S3 S3
So, why Python ?
There should be one way to do it
And it should be obvious
Python enforces good coding practices
Python enforces good coding practices
foreach my $p (keys %$p1) {if(exists($p1->{$p})
and exists($p2->{$p})) {
if(uc($p1->{$p}) eq uc($p2->{$p})) {$diff-
>{SAME}->{$p} = 1;
} else {$diff->{DIFF}->{$p} = 1;
}}} elsif(! exists($p2->{$p})) {$diff-
>{ONLY_IN_1}->{$p} = 1;}}
Python enforces good coding practices
for p in db1_params:
if p in db2_params:
if db1_params[p] == db2_params[p]:
same_parameters.append(p)
else:
diff_parameters.append(p)
else:
only_in_1.append(p)
Python should come
with all the batteries included
Python interfaces to everything
import urllib
import json
url =
"http://api.openweathermap.org/data/2.5/weather?q=Seattle
,WA"
url_obj = urllib.urlopen(url)
data = url_obj.read().strip()
data = json.loads(data)
print(data['weather'])
Python interfaces to everything
import cx_Oracle
sql = "SELECT user FROM dual"
conn = cx_Oracle.connect('scott/tiger@orcl')
cursor = conn.cursor()
cursor.execute(sql)
db_user = cursor.fetchall()
Python interfaces to everything
import boto
from boto.s3.key import Key
s3 = boto.connect_s3()
bucket = s3.get_bucket('my_cats')
k.key = 'lazy_cat.jpg'
k.set_contents_from_filename('/tmp/lazy_cat.jpg')
Python is pretty popular
Python is pretty popular
If you know any scripting language
you (almost) know Python
Python is similar to other languages
def is_accessible(db_name):
""" Check if database is accessible """
ret = False
db_status = ping_db(db_name)
if "ACTIVE" == db_status:
ret = True
return ret
But: Spaces are first class citizens
def print_databases():
""" Print all databases from /etc/oratab """
with open("/etc/oratab") as file:
for line in file:
if line:
print line.strip().split(':')[0]
But: Spaces are first class citizens
def print_databases():
""" Print all databases from /etc/oratab ""“
with open("/etc/oratab") as file:
for line in file:
if line:
print line.strip().split(':')[0]
File "./a.py", line 7
print line.strip().split(':')[0]
^
IndentationError:
expected an indented block
Compare to Perl
sub print_databases() {
open(my $f, "<", "/etc/oratab")
or die ("Unable to open: $!");
while(my $line = <$f>) {
if ($line =~ /S+/) {
my @aItems = split(':', $line);
print $aItems[0] . "n";
}
}
close($f);
}
Compare to Perl
sub print_databases(){open(my $f, "<", "/etc/oratab") or
die ("Unable to open: $!"); while(my $line = <$f>) {
if ($line =~ /S+/) {my @aItems = split(':', $line);
print $aItems[0] . "n";}} close($f);}
Functions are first class citizens too
Fun with functions
def outer_function(parameter_function):
""" This function accepts function as a parameter """
def inner_function(inner_parameter):
""" This is a nested function """
return inner_parameter
# This returns a function from a function
return inner_function(parameter_function)
# This "calls" function return value as a function
print outer_function(external_function)()
Fun with functions: Decorators
def do_stuff():
result = heavy_processing()
def do_stuff():
start = time()
result = heavy_processing()
end = time()
print "Elapsed: %f" % (end-start)
def do_stuff2():
…
def do_stuff3076():
Fun with functions: Decorators
def timeit(func):
""" Generic time profiling function """
def time_exec(*args, **kwargs):
start_time = time()
ret = func(*args, **kwargs)
end = time()
print "Elapsed: %f" % (end-start)
return ret
return time_exec
Fun with functions: Decorators
do_stuff = timeit(do_stuff)
@timeit
def do_stuff():
…
@timeit
def do_stuff2():
…
@timeit
def do_stuff3076():
…
Learn to think Pythonian. It helps!
def print_databases():
file = open('/etc/oratab', 'r')
while True:
line = file.readline()
if len(line) == 0 and not line.endswith('n'):
break
print line.strip().split(':')[0]
file.close()
def print_databases():
with open('/etc/oratab') as file:
for line in file:
print line.strip().split(':')[0]
Python and ORACLE
Database “multi ping” tool
■ Ping ORACLE database
▪ Report AVAILABLE / NOT AVAILABLE status
■ Option to ping multiple databases
▪ Preferably in parallel
■ Bonus: track execution timing
Demo
cx_Oracle: Running SQL
import cx_Oracle
def is_db_alive(db_name):
is_alive = False
try:
conn = cx_Oracle.connect("user/password@%s" % db_name)
cursor = conn.cursor()
cursor.execute("SELECT user FROM dual")
except:
is_alive = False
else:
is_alive = True
return is_alive
Database ping
> dbping.py c15lv1
PING [c15lv1]: OK
> dbping.py c15lv2
PING [c15lv2]: UNAVAILABLE
Database “multi ping”
import dbping
def multi_dbping(db_list, ping_routine):
""" Ping all databases in a list """
for db in db_list:
ping_routine(db)
> dbping_list.py c15lv1 c15lv2 c15lv3
PING [c15lv1]: OK
PING [c15lv2]: UNAVAILABLE
PING [c15lv3]: OK
Parallel database “multi ping”
import multiprocessing
def parallel_ping(db_list, target=dbping.print_dbping):
""" Ping db_list databases in parallel """
jobs = []
for d in db_list:
p = multiprocessing.Process(
target=target, args=(d,)
)
jobs.append(p)
p.start()
for p in jobs:
p.join()
Parallel database “multi ping”
> dbping_parallel.py c15lv1 c15lv2 c15lv3 c15lv4
PING [c15lv1]: OK
PING [c15lv3]: OK
PING [c15lv4]: OK
PING [c15lv2]: UNAVAILABLE
Decorator: Execution Timing
def timeit(func):
""" Generic time profiling function """
def time_exec(*args, **kwargs):
start_time = time()
ret = func(*args, **kwargs)
ela = time() - start_time
print “tElapsed: %.3f seconds" % ela
return ret
return time_exec
Execution Timing:
> dbping_parallel_timing.py c15lv1 c15lv2 c15lv3
PING [c15lv3]: OK
Elapsed: 1.186 seconds
PING [c15lv1]: OK
Elapsed: 2.309 seconds
PING [c15lv2]: UNAVAILABLE
Elapsed: 22.511 seconds
@timeit
def print_dbping_with_timing(db_name):
return dbping.print_dbping(db_name)
How to start with Python
■ Lots of free resources on the web
▪ Tutorials
▪ Documentation
▪ Stackoverflow.com
▪ “Play” environments
▪ Even books
■ Python self documentation:
▪ dir()
▪ help()
Thank you!

More Related Content

What's hot

KubeCon EU 2016: Custom Volume Plugins
KubeCon EU 2016: Custom Volume PluginsKubeCon EU 2016: Custom Volume Plugins
KubeCon EU 2016: Custom Volume Plugins
KubeAcademy
 
Shell Script to Extract IP Address, MAC Address Information
Shell Script to Extract IP Address, MAC Address InformationShell Script to Extract IP Address, MAC Address Information
Shell Script to Extract IP Address, MAC Address Information
VCP Muthukrishna
 
PuppetDB, Puppet Explorer and puppetdbquery
PuppetDB, Puppet Explorer and puppetdbqueryPuppetDB, Puppet Explorer and puppetdbquery
PuppetDB, Puppet Explorer and puppetdbquery
Puppet
 
File Space Usage Information and EMail Report - Shell Script
File Space Usage Information and EMail Report - Shell ScriptFile Space Usage Information and EMail Report - Shell Script
File Space Usage Information and EMail Report - Shell Script
VCP Muthukrishna
 
Redis as a message queue
Redis as a message queueRedis as a message queue
Redis as a message queue
Brandon Lamb
 
Bash Script Disk Space Utilization Report and EMail
Bash Script Disk Space Utilization Report and EMailBash Script Disk Space Utilization Report and EMail
Bash Script Disk Space Utilization Report and EMail
VCP Muthukrishna
 
Parse, scale to millions
Parse, scale to millionsParse, scale to millions
Parse, scale to millions
Florent Vilmart
 
Go memory
Go memoryGo memory
Go memory
jgrahamc
 
并发模型介绍
并发模型介绍并发模型介绍
并发模型介绍
qiang
 
Value protocols and codables
Value protocols and codablesValue protocols and codables
Value protocols and codables
Florent Vilmart
 
R Data Analysis/Rを使った人事データ分析入門
R Data Analysis/Rを使った人事データ分析入門R Data Analysis/Rを使った人事データ分析入門
R Data Analysis/Rを使った人事データ分析入門
Takanori Omote
 
All you need to know about the JavaScript event loop
All you need to know about the JavaScript event loopAll you need to know about the JavaScript event loop
All you need to know about the JavaScript event loop
Saša Tatar
 
CouchDB Day NYC 2017: Full Text Search
CouchDB Day NYC 2017: Full Text SearchCouchDB Day NYC 2017: Full Text Search
CouchDB Day NYC 2017: Full Text Search
IBM Cloud Data Services
 
MySQL Slow Query log Monitoring using Beats & ELK
MySQL Slow Query log Monitoring using Beats & ELKMySQL Slow Query log Monitoring using Beats & ELK
MySQL Slow Query log Monitoring using Beats & ELK
YoungHeon (Roy) Kim
 
Go Profiling - John Graham-Cumming
Go Profiling - John Graham-Cumming Go Profiling - John Graham-Cumming
Go Profiling - John Graham-Cumming Cloudflare
 
Go debugging and troubleshooting tips - from real life lessons at SignalFx
Go debugging and troubleshooting tips - from real life lessons at SignalFxGo debugging and troubleshooting tips - from real life lessons at SignalFx
Go debugging and troubleshooting tips - from real life lessons at SignalFx
SignalFx
 
node ffi
node ffinode ffi
node ffi
偉格 高
 
App-o-Lockalypse now!
App-o-Lockalypse now!App-o-Lockalypse now!
App-o-Lockalypse now!
Oddvar Moe
 
Impala: A Modern, Open-Source SQL Engine for Hadoop
Impala: A Modern, Open-Source SQL Engine for HadoopImpala: A Modern, Open-Source SQL Engine for Hadoop
Impala: A Modern, Open-Source SQL Engine for Hadoop
All Things Open
 

What's hot (20)

KubeCon EU 2016: Custom Volume Plugins
KubeCon EU 2016: Custom Volume PluginsKubeCon EU 2016: Custom Volume Plugins
KubeCon EU 2016: Custom Volume Plugins
 
Shell Script to Extract IP Address, MAC Address Information
Shell Script to Extract IP Address, MAC Address InformationShell Script to Extract IP Address, MAC Address Information
Shell Script to Extract IP Address, MAC Address Information
 
PuppetDB, Puppet Explorer and puppetdbquery
PuppetDB, Puppet Explorer and puppetdbqueryPuppetDB, Puppet Explorer and puppetdbquery
PuppetDB, Puppet Explorer and puppetdbquery
 
File Space Usage Information and EMail Report - Shell Script
File Space Usage Information and EMail Report - Shell ScriptFile Space Usage Information and EMail Report - Shell Script
File Space Usage Information and EMail Report - Shell Script
 
Redis as a message queue
Redis as a message queueRedis as a message queue
Redis as a message queue
 
Bash Script Disk Space Utilization Report and EMail
Bash Script Disk Space Utilization Report and EMailBash Script Disk Space Utilization Report and EMail
Bash Script Disk Space Utilization Report and EMail
 
Parse, scale to millions
Parse, scale to millionsParse, scale to millions
Parse, scale to millions
 
Go memory
Go memoryGo memory
Go memory
 
并发模型介绍
并发模型介绍并发模型介绍
并发模型介绍
 
Value protocols and codables
Value protocols and codablesValue protocols and codables
Value protocols and codables
 
R Data Analysis/Rを使った人事データ分析入門
R Data Analysis/Rを使った人事データ分析入門R Data Analysis/Rを使った人事データ分析入門
R Data Analysis/Rを使った人事データ分析入門
 
All you need to know about the JavaScript event loop
All you need to know about the JavaScript event loopAll you need to know about the JavaScript event loop
All you need to know about the JavaScript event loop
 
Go Memory
Go MemoryGo Memory
Go Memory
 
CouchDB Day NYC 2017: Full Text Search
CouchDB Day NYC 2017: Full Text SearchCouchDB Day NYC 2017: Full Text Search
CouchDB Day NYC 2017: Full Text Search
 
MySQL Slow Query log Monitoring using Beats & ELK
MySQL Slow Query log Monitoring using Beats & ELKMySQL Slow Query log Monitoring using Beats & ELK
MySQL Slow Query log Monitoring using Beats & ELK
 
Go Profiling - John Graham-Cumming
Go Profiling - John Graham-Cumming Go Profiling - John Graham-Cumming
Go Profiling - John Graham-Cumming
 
Go debugging and troubleshooting tips - from real life lessons at SignalFx
Go debugging and troubleshooting tips - from real life lessons at SignalFxGo debugging and troubleshooting tips - from real life lessons at SignalFx
Go debugging and troubleshooting tips - from real life lessons at SignalFx
 
node ffi
node ffinode ffi
node ffi
 
App-o-Lockalypse now!
App-o-Lockalypse now!App-o-Lockalypse now!
App-o-Lockalypse now!
 
Impala: A Modern, Open-Source SQL Engine for Hadoop
Impala: A Modern, Open-Source SQL Engine for HadoopImpala: A Modern, Open-Source SQL Engine for Hadoop
Impala: A Modern, Open-Source SQL Engine for Hadoop
 

Similar to 2015 555 kharchenko_ppt

Apache Spark Workshop, Apr. 2016, Euangelos Linardos
Apache Spark Workshop, Apr. 2016, Euangelos LinardosApache Spark Workshop, Apr. 2016, Euangelos Linardos
Apache Spark Workshop, Apr. 2016, Euangelos Linardos
Euangelos Linardos
 
Python for Linux System Administration
Python for Linux System AdministrationPython for Linux System Administration
Python for Linux System Administration
vceder
 
File and directories in python
File and directories in pythonFile and directories in python
File and directories in python
Lifna C.S
 
Apache Flink internals
Apache Flink internalsApache Flink internals
Apache Flink internals
Kostas Tzoumas
 
File mangement
File mangementFile mangement
File mangement
Jigarthacker
 
Will iPython replace bash?
Will iPython replace bash?Will iPython replace bash?
Will iPython replace bash?
Roberto Polli
 
Will iPython replace Bash?
Will iPython replace Bash?Will iPython replace Bash?
Will iPython replace Bash?
Babel
 
Why and How Powershell will rule the Command Line - Barcamp LA 4
Why and How Powershell will rule the Command Line - Barcamp LA 4Why and How Powershell will rule the Command Line - Barcamp LA 4
Why and How Powershell will rule the Command Line - Barcamp LA 4
Ilya Haykinson
 
The Essential Perl Hacker's Toolkit
The Essential Perl Hacker's ToolkitThe Essential Perl Hacker's Toolkit
The Essential Perl Hacker's Toolkit
Stephen Scaffidi
 
Coding in Kotlin with Arrow NIDC 2018
Coding in Kotlin with Arrow NIDC 2018Coding in Kotlin with Arrow NIDC 2018
Coding in Kotlin with Arrow NIDC 2018
Garth Gilmour
 
Python utan-stodhjul-motorsag
Python utan-stodhjul-motorsagPython utan-stodhjul-motorsag
Python utan-stodhjul-motorsagniklal
 
Script up your application with Lua! -- RyanE -- OpenWest 2014
Script up your application with Lua! -- RyanE -- OpenWest 2014Script up your application with Lua! -- RyanE -- OpenWest 2014
Script up your application with Lua! -- RyanE -- OpenWest 2014ryanerickson
 
비윈도우즈 환경의 기술 서적 번역 도구 경험 공유
비윈도우즈 환경의 기술 서적 번역 도구 경험 공유비윈도우즈 환경의 기술 서적 번역 도구 경험 공유
비윈도우즈 환경의 기술 서적 번역 도구 경험 공유
Younggun Kim
 
How to create a non managed standby database
How to create a non managed  standby databaseHow to create a non managed  standby database
How to create a non managed standby databaseJorge Batista
 
Introduction to clojure
Introduction to clojureIntroduction to clojure
Introduction to clojure
Abbas Raza
 
Reading and Writing Files
Reading and Writing FilesReading and Writing Files
Reading and Writing Files
primeteacher32
 
Python 3000
Python 3000Python 3000
Python 3000
Bob Chao
 
あなたのScalaを爆速にする7つの方法
あなたのScalaを爆速にする7つの方法あなたのScalaを爆速にする7つの方法
あなたのScalaを爆速にする7つの方法
x1 ichi
 

Similar to 2015 555 kharchenko_ppt (20)

Apache Spark Workshop, Apr. 2016, Euangelos Linardos
Apache Spark Workshop, Apr. 2016, Euangelos LinardosApache Spark Workshop, Apr. 2016, Euangelos Linardos
Apache Spark Workshop, Apr. 2016, Euangelos Linardos
 
Python for Linux System Administration
Python for Linux System AdministrationPython for Linux System Administration
Python for Linux System Administration
 
File and directories in python
File and directories in pythonFile and directories in python
File and directories in python
 
Apache Flink internals
Apache Flink internalsApache Flink internals
Apache Flink internals
 
File mangement
File mangementFile mangement
File mangement
 
Having Fun Programming!
Having Fun Programming!Having Fun Programming!
Having Fun Programming!
 
Will iPython replace bash?
Will iPython replace bash?Will iPython replace bash?
Will iPython replace bash?
 
Will iPython replace Bash?
Will iPython replace Bash?Will iPython replace Bash?
Will iPython replace Bash?
 
Why and How Powershell will rule the Command Line - Barcamp LA 4
Why and How Powershell will rule the Command Line - Barcamp LA 4Why and How Powershell will rule the Command Line - Barcamp LA 4
Why and How Powershell will rule the Command Line - Barcamp LA 4
 
The Essential Perl Hacker's Toolkit
The Essential Perl Hacker's ToolkitThe Essential Perl Hacker's Toolkit
The Essential Perl Hacker's Toolkit
 
Coding in Kotlin with Arrow NIDC 2018
Coding in Kotlin with Arrow NIDC 2018Coding in Kotlin with Arrow NIDC 2018
Coding in Kotlin with Arrow NIDC 2018
 
Python utan-stodhjul-motorsag
Python utan-stodhjul-motorsagPython utan-stodhjul-motorsag
Python utan-stodhjul-motorsag
 
Script up your application with Lua! -- RyanE -- OpenWest 2014
Script up your application with Lua! -- RyanE -- OpenWest 2014Script up your application with Lua! -- RyanE -- OpenWest 2014
Script up your application with Lua! -- RyanE -- OpenWest 2014
 
비윈도우즈 환경의 기술 서적 번역 도구 경험 공유
비윈도우즈 환경의 기술 서적 번역 도구 경험 공유비윈도우즈 환경의 기술 서적 번역 도구 경험 공유
비윈도우즈 환경의 기술 서적 번역 도구 경험 공유
 
How to create a non managed standby database
How to create a non managed  standby databaseHow to create a non managed  standby database
How to create a non managed standby database
 
Introduction to clojure
Introduction to clojureIntroduction to clojure
Introduction to clojure
 
Reading and Writing Files
Reading and Writing FilesReading and Writing Files
Reading and Writing Files
 
Flink internals web
Flink internals web Flink internals web
Flink internals web
 
Python 3000
Python 3000Python 3000
Python 3000
 
あなたのScalaを爆速にする7つの方法
あなたのScalaを爆速にする7つの方法あなたのScalaを爆速にする7つの方法
あなたのScalaを爆速にする7つの方法
 

Recently uploaded

Large Language Models and the End of Programming
Large Language Models and the End of ProgrammingLarge Language Models and the End of Programming
Large Language Models and the End of Programming
Matt Welsh
 
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Anthony Dahanne
 
Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024
Globus
 
Strategies for Successful Data Migration Tools.pptx
Strategies for Successful Data Migration Tools.pptxStrategies for Successful Data Migration Tools.pptx
Strategies for Successful Data Migration Tools.pptx
varshanayak241
 
Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus
 
Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024
Paco van Beckhoven
 
top nidhi software solution freedownload
top nidhi software solution freedownloadtop nidhi software solution freedownload
top nidhi software solution freedownload
vrstrong314
 
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Globus
 
A Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdfA Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdf
kalichargn70th171
 
Enhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdfEnhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdf
Globus
 
SOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBrokerSOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar
 
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
Juraj Vysvader
 
Advanced Flow Concepts Every Developer Should Know
Advanced Flow Concepts Every Developer Should KnowAdvanced Flow Concepts Every Developer Should Know
Advanced Flow Concepts Every Developer Should Know
Peter Caitens
 
Corporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMSCorporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMS
Tendenci - The Open Source AMS (Association Management Software)
 
How to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good PracticesHow to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good Practices
Globus
 
First Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User EndpointsFirst Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User Endpoints
Globus
 
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoamOpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
takuyayamamoto1800
 
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data AnalysisProviding Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
Globus
 
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.ILBeyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Natan Silnitsky
 
Explore Modern SharePoint Templates for 2024
Explore Modern SharePoint Templates for 2024Explore Modern SharePoint Templates for 2024
Explore Modern SharePoint Templates for 2024
Sharepoint Designs
 

Recently uploaded (20)

Large Language Models and the End of Programming
Large Language Models and the End of ProgrammingLarge Language Models and the End of Programming
Large Language Models and the End of Programming
 
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
 
Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024
 
Strategies for Successful Data Migration Tools.pptx
Strategies for Successful Data Migration Tools.pptxStrategies for Successful Data Migration Tools.pptx
Strategies for Successful Data Migration Tools.pptx
 
Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024
 
Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024
 
top nidhi software solution freedownload
top nidhi software solution freedownloadtop nidhi software solution freedownload
top nidhi software solution freedownload
 
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
 
A Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdfA Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdf
 
Enhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdfEnhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdf
 
SOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBrokerSOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBroker
 
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
 
Advanced Flow Concepts Every Developer Should Know
Advanced Flow Concepts Every Developer Should KnowAdvanced Flow Concepts Every Developer Should Know
Advanced Flow Concepts Every Developer Should Know
 
Corporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMSCorporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMS
 
How to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good PracticesHow to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good Practices
 
First Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User EndpointsFirst Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User Endpoints
 
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoamOpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
 
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data AnalysisProviding Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
 
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.ILBeyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
 
Explore Modern SharePoint Templates for 2024
Explore Modern SharePoint Templates for 2024Explore Modern SharePoint Templates for 2024
Explore Modern SharePoint Templates for 2024
 

2015 555 kharchenko_ppt

  • 1. Maxym Kharchenko Manage ORACLE databases with Python
  • 2. Whoami ■ Started as a database kernel developer with C and C++ ■ ORACLE DBA for ~ 14 years: + SQL, PL/SQL and Perl ■ Persistence Engineer for the last 4: + Python, R and Scala ■ OCM, ORACLE Ace Associate ■ Blog: http://intermediatesql.com ■ Twitter: @maxymkh
  • 3. Agenda ■ Talk about why Python is awesome ■ Design ORACLE multi db “ping” in Python ■ (hopefully) Demo it
  • 4. The job of an engineer is to make complex things simple
  • 5. Why script outside the database ?
  • 6. Do I have a good datafilebackup ? SELECT … FROM v$backup_datafile  v$backup_datafile  Backup files actually exist  and can be validated  Backup size is plausible  On the end storage  Network transfer as well  No critical errors in logs  Etc
  • 7. Some things are just difficult to do in a database
  • 8. You will, generally, get better Zen i := i + 1 i += 1
  • 9. You will, generally, get better Zen
  • 10. You will, generally, get better Zen
  • 11. You, probably, have >1 database ORACLE ORACLE ORACLE ORACLE ORACLE ORACLE ORACLE ORACLE ORACLE MySql MySql Postgres Cassandra S3 S3
  • 13. There should be one way to do it And it should be obvious
  • 14. Python enforces good coding practices
  • 15. Python enforces good coding practices foreach my $p (keys %$p1) {if(exists($p1->{$p}) and exists($p2->{$p})) { if(uc($p1->{$p}) eq uc($p2->{$p})) {$diff- >{SAME}->{$p} = 1; } else {$diff->{DIFF}->{$p} = 1; }}} elsif(! exists($p2->{$p})) {$diff- >{ONLY_IN_1}->{$p} = 1;}}
  • 16. Python enforces good coding practices for p in db1_params: if p in db2_params: if db1_params[p] == db2_params[p]: same_parameters.append(p) else: diff_parameters.append(p) else: only_in_1.append(p)
  • 17. Python should come with all the batteries included
  • 18. Python interfaces to everything import urllib import json url = "http://api.openweathermap.org/data/2.5/weather?q=Seattle ,WA" url_obj = urllib.urlopen(url) data = url_obj.read().strip() data = json.loads(data) print(data['weather'])
  • 19. Python interfaces to everything import cx_Oracle sql = "SELECT user FROM dual" conn = cx_Oracle.connect('scott/tiger@orcl') cursor = conn.cursor() cursor.execute(sql) db_user = cursor.fetchall()
  • 20. Python interfaces to everything import boto from boto.s3.key import Key s3 = boto.connect_s3() bucket = s3.get_bucket('my_cats') k.key = 'lazy_cat.jpg' k.set_contents_from_filename('/tmp/lazy_cat.jpg')
  • 21. Python is pretty popular
  • 22. Python is pretty popular
  • 23. If you know any scripting language you (almost) know Python
  • 24. Python is similar to other languages def is_accessible(db_name): """ Check if database is accessible """ ret = False db_status = ping_db(db_name) if "ACTIVE" == db_status: ret = True return ret
  • 25. But: Spaces are first class citizens def print_databases(): """ Print all databases from /etc/oratab """ with open("/etc/oratab") as file: for line in file: if line: print line.strip().split(':')[0]
  • 26. But: Spaces are first class citizens def print_databases(): """ Print all databases from /etc/oratab ""“ with open("/etc/oratab") as file: for line in file: if line: print line.strip().split(':')[0] File "./a.py", line 7 print line.strip().split(':')[0] ^ IndentationError: expected an indented block
  • 27. Compare to Perl sub print_databases() { open(my $f, "<", "/etc/oratab") or die ("Unable to open: $!"); while(my $line = <$f>) { if ($line =~ /S+/) { my @aItems = split(':', $line); print $aItems[0] . "n"; } } close($f); }
  • 28. Compare to Perl sub print_databases(){open(my $f, "<", "/etc/oratab") or die ("Unable to open: $!"); while(my $line = <$f>) { if ($line =~ /S+/) {my @aItems = split(':', $line); print $aItems[0] . "n";}} close($f);}
  • 29. Functions are first class citizens too
  • 30. Fun with functions def outer_function(parameter_function): """ This function accepts function as a parameter """ def inner_function(inner_parameter): """ This is a nested function """ return inner_parameter # This returns a function from a function return inner_function(parameter_function) # This "calls" function return value as a function print outer_function(external_function)()
  • 31. Fun with functions: Decorators def do_stuff(): result = heavy_processing() def do_stuff(): start = time() result = heavy_processing() end = time() print "Elapsed: %f" % (end-start) def do_stuff2(): … def do_stuff3076():
  • 32. Fun with functions: Decorators def timeit(func): """ Generic time profiling function """ def time_exec(*args, **kwargs): start_time = time() ret = func(*args, **kwargs) end = time() print "Elapsed: %f" % (end-start) return ret return time_exec
  • 33. Fun with functions: Decorators do_stuff = timeit(do_stuff) @timeit def do_stuff(): … @timeit def do_stuff2(): … @timeit def do_stuff3076(): …
  • 34. Learn to think Pythonian. It helps! def print_databases(): file = open('/etc/oratab', 'r') while True: line = file.readline() if len(line) == 0 and not line.endswith('n'): break print line.strip().split(':')[0] file.close() def print_databases(): with open('/etc/oratab') as file: for line in file: print line.strip().split(':')[0]
  • 36. Database “multi ping” tool ■ Ping ORACLE database ▪ Report AVAILABLE / NOT AVAILABLE status ■ Option to ping multiple databases ▪ Preferably in parallel ■ Bonus: track execution timing
  • 37. Demo
  • 38. cx_Oracle: Running SQL import cx_Oracle def is_db_alive(db_name): is_alive = False try: conn = cx_Oracle.connect("user/password@%s" % db_name) cursor = conn.cursor() cursor.execute("SELECT user FROM dual") except: is_alive = False else: is_alive = True return is_alive
  • 39. Database ping > dbping.py c15lv1 PING [c15lv1]: OK > dbping.py c15lv2 PING [c15lv2]: UNAVAILABLE
  • 40. Database “multi ping” import dbping def multi_dbping(db_list, ping_routine): """ Ping all databases in a list """ for db in db_list: ping_routine(db) > dbping_list.py c15lv1 c15lv2 c15lv3 PING [c15lv1]: OK PING [c15lv2]: UNAVAILABLE PING [c15lv3]: OK
  • 41. Parallel database “multi ping” import multiprocessing def parallel_ping(db_list, target=dbping.print_dbping): """ Ping db_list databases in parallel """ jobs = [] for d in db_list: p = multiprocessing.Process( target=target, args=(d,) ) jobs.append(p) p.start() for p in jobs: p.join()
  • 42. Parallel database “multi ping” > dbping_parallel.py c15lv1 c15lv2 c15lv3 c15lv4 PING [c15lv1]: OK PING [c15lv3]: OK PING [c15lv4]: OK PING [c15lv2]: UNAVAILABLE
  • 43. Decorator: Execution Timing def timeit(func): """ Generic time profiling function """ def time_exec(*args, **kwargs): start_time = time() ret = func(*args, **kwargs) ela = time() - start_time print “tElapsed: %.3f seconds" % ela return ret return time_exec
  • 44. Execution Timing: > dbping_parallel_timing.py c15lv1 c15lv2 c15lv3 PING [c15lv3]: OK Elapsed: 1.186 seconds PING [c15lv1]: OK Elapsed: 2.309 seconds PING [c15lv2]: UNAVAILABLE Elapsed: 22.511 seconds @timeit def print_dbping_with_timing(db_name): return dbping.print_dbping(db_name)
  • 45. How to start with Python ■ Lots of free resources on the web ▪ Tutorials ▪ Documentation ▪ Stackoverflow.com ▪ “Play” environments ▪ Even books ■ Python self documentation: ▪ dir() ▪ help()

Editor's Notes

  1. Rupe Goldberg machine