SlideShare uma empresa Scribd logo
1 de 46
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!

Mais conteúdo relacionado

Mais procurados

KubeCon EU 2016: Custom Volume Plugins
KubeCon EU 2016: Custom Volume PluginsKubeCon EU 2016: Custom Volume Plugins
KubeCon EU 2016: Custom Volume PluginsKubeAcademy
 
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 InformationVCP Muthukrishna
 
PuppetDB, Puppet Explorer and puppetdbquery
PuppetDB, Puppet Explorer and puppetdbqueryPuppetDB, Puppet Explorer and puppetdbquery
PuppetDB, Puppet Explorer and puppetdbqueryPuppet
 
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 ScriptVCP Muthukrishna
 
Redis as a message queue
Redis as a message queueRedis as a message queue
Redis as a message queueBrandon 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 EMailVCP Muthukrishna
 
Parse, scale to millions
Parse, scale to millionsParse, scale to millions
Parse, scale to millionsFlorent Vilmart
 
并发模型介绍
并发模型介绍并发模型介绍
并发模型介绍qiang
 
Value protocols and codables
Value protocols and codablesValue protocols and codables
Value protocols and codablesFlorent 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 loopSaša Tatar
 
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 & ELKYoungHeon (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 SignalFxSignalFx
 
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 HadoopAll Things Open
 

Mais procurados (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
 

Semelhante a 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 LinardosEuangelos Linardos
 
Python for Linux System Administration
Python for Linux System AdministrationPython for Linux System Administration
Python for Linux System Administrationvceder
 
File and directories in python
File and directories in pythonFile and directories in python
File and directories in pythonLifna C.S
 
Apache Flink internals
Apache Flink internalsApache Flink internals
Apache Flink internalsKostas Tzoumas
 
Will iPython replace Bash?
Will iPython replace Bash?Will iPython replace Bash?
Will iPython replace Bash?Babel
 
Will iPython replace bash?
Will iPython replace bash?Will iPython replace bash?
Will iPython replace bash?Roberto Polli
 
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 4Ilya Haykinson
 
The Essential Perl Hacker's Toolkit
The Essential Perl Hacker's ToolkitThe Essential Perl Hacker's Toolkit
The Essential Perl Hacker's ToolkitStephen 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 2018Garth 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 clojureAbbas Raza
 
Reading and Writing Files
Reading and Writing FilesReading and Writing Files
Reading and Writing Filesprimeteacher32
 
Python 3000
Python 3000Python 3000
Python 3000Bob Chao
 
あなたのScalaを爆速にする7つの方法
あなたのScalaを爆速にする7つの方法あなたのScalaを爆速にする7つの方法
あなたのScalaを爆速にする7つの方法x1 ichi
 

Semelhante a 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つの方法
 

Último

Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Matt Ray
 
Large Language Models for Test Case Evolution and Repair
Large Language Models for Test Case Evolution and RepairLarge Language Models for Test Case Evolution and Repair
Large Language Models for Test Case Evolution and RepairLionel Briand
 
What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...Technogeeks
 
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptxReal-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptxRTS corp
 
Odoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 EnterpriseOdoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 Enterprisepreethippts
 
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...OnePlan Solutions
 
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanyChristoph Pohl
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtimeandrehoraa
 
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Angel Borroy López
 
Precise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalPrecise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalLionel Briand
 
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...Akihiro Suda
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEEVICTOR MAESTRE RAMIREZ
 
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...confluent
 
Patterns for automating API delivery. API conference
Patterns for automating API delivery. API conferencePatterns for automating API delivery. API conference
Patterns for automating API delivery. API conferencessuser9e7c64
 
Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...Rob Geurden
 
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdfExploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdfkalichargn70th171
 
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Natan Silnitsky
 
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company OdishaBalasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odishasmiwainfosol
 
Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesŁukasz Chruściel
 

Último (20)

Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
 
Large Language Models for Test Case Evolution and Repair
Large Language Models for Test Case Evolution and RepairLarge Language Models for Test Case Evolution and Repair
Large Language Models for Test Case Evolution and Repair
 
What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...
 
Advantages of Odoo ERP 17 for Your Business
Advantages of Odoo ERP 17 for Your BusinessAdvantages of Odoo ERP 17 for Your Business
Advantages of Odoo ERP 17 for Your Business
 
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptxReal-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
Real-time Tracking and Monitoring with Cargo Cloud Solutions.pptx
 
Odoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 EnterpriseOdoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 Enterprise
 
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
 
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtime
 
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
 
Precise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalPrecise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive Goal
 
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...
20240415 [Container Plumbing Days] Usernetes Gen2 - Kubernetes in Rootless Do...
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEE
 
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
 
Patterns for automating API delivery. API conference
Patterns for automating API delivery. API conferencePatterns for automating API delivery. API conference
Patterns for automating API delivery. API conference
 
Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...
 
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdfExploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
Exploring Selenium_Appium Frameworks for Seamless Integration with HeadSpin.pdf
 
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
 
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company OdishaBalasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
 
Unveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New FeaturesUnveiling the Future: Sylius 2.0 New Features
Unveiling the Future: Sylius 2.0 New Features
 

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()

Notas do Editor

  1. Rupe Goldberg machine