Skip to content
Projects
Groups
Snippets
Help
Loading...
Help
Support
Keyboard shortcuts
?
Submit feedback
Contribute to GitLab
Sign in / Register
Toggle navigation
S
slapos.toolbox
Project overview
Project overview
Details
Activity
Releases
Repository
Repository
Files
Commits
Branches
Tags
Contributors
Graph
Compare
Issues
0
Issues
0
List
Boards
Labels
Milestones
Merge Requests
0
Merge Requests
0
CI / CD
CI / CD
Pipelines
Jobs
Schedules
Analytics
Analytics
CI / CD
Repository
Value Stream
Wiki
Wiki
Snippets
Snippets
Members
Members
Collapse sidebar
Close sidebar
Activity
Graph
Create a new issue
Jobs
Commits
Issue Boards
Open sidebar
Xiaowu Zhang
slapos.toolbox
Commits
5ceae36b
Commit
5ceae36b
authored
Sep 26, 2018
by
Bryton Lacquement
🚪
Browse files
Options
Browse Files
Download
Email Patches
Plain Diff
wip
parent
f873f59d
Changes
39
Show whitespace changes
Inline
Side-by-side
Showing
39 changed files
with
275 additions
and
233 deletions
+275
-233
slapos/agent/agent.py
slapos/agent/agent.py
+2
-2
slapos/agent/tester.py
slapos/agent/tester.py
+13
-11
slapos/apachedex.py
slapos/apachedex.py
+7
-5
slapos/container/__init__.py
slapos/container/__init__.py
+5
-5
slapos/equeue/__init__.py
slapos/equeue/__init__.py
+8
-8
slapos/generatefeed.py
slapos/generatefeed.py
+1
-1
slapos/lamp/__init__.py
slapos/lamp/__init__.py
+12
-11
slapos/monitor/collect.py
slapos/monitor/collect.py
+6
-4
slapos/monitor/globalstate.py
slapos/monitor/globalstate.py
+6
-4
slapos/monitor/monitor.py
slapos/monitor/monitor.py
+30
-28
slapos/monitor/monitor_config_write.py
slapos/monitor/monitor_config_write.py
+19
-17
slapos/monitor/runpromise.py
slapos/monitor/runpromise.py
+3
-3
slapos/networkbench/__init__.py
slapos/networkbench/__init__.py
+8
-6
slapos/networkbench/http.py
slapos/networkbench/http.py
+1
-1
slapos/networkbench/ping.py
slapos/networkbench/ping.py
+2
-1
slapos/onetimeupload/__init__.py
slapos/onetimeupload/__init__.py
+1
-1
slapos/promise/apache_mpm_watchdog/__init__.py
slapos/promise/apache_mpm_watchdog/__init__.py
+4
-2
slapos/promise/check_apachedex_result/__init__.py
slapos/promise/check_apachedex_result/__init__.py
+1
-1
slapos/promise/check_computer_memory/__init__.py
slapos/promise/check_computer_memory/__init__.py
+8
-4
slapos/promise/check_error_on_apache_log/__init__.py
slapos/promise/check_error_on_apache_log/__init__.py
+4
-2
slapos/promise/check_re6st_optimal_status/__init__.py
slapos/promise/check_re6st_optimal_status/__init__.py
+6
-4
slapos/promise/check_slow_queries_digest_result/__init__.py
slapos/promise/check_slow_queries_digest_result/__init__.py
+4
-2
slapos/promise/check_user_memory/__init__.py
slapos/promise/check_user_memory/__init__.py
+4
-2
slapos/promise/check_web_page_http_cache_hit/__init__.py
slapos/promise/check_web_page_http_cache_hit/__init__.py
+8
-6
slapos/promise/is_icmp_packet_lost/__init__.py
slapos/promise/is_icmp_packet_lost/__init__.py
+5
-3
slapos/promise/is_process_older_than_dependency_set/__init__.py
.../promise/is_process_older_than_dependency_set/__init__.py
+7
-5
slapos/pubsub/__init__.py
slapos/pubsub/__init__.py
+1
-1
slapos/qemuqmpclient/__init__.py
slapos/qemuqmpclient/__init__.py
+41
-39
slapos/runner/sup_process.py
slapos/runner/sup_process.py
+1
-1
slapos/runner/utils.py
slapos/runner/utils.py
+12
-12
slapos/securedelete.py
slapos/securedelete.py
+3
-1
slapos/systool.py
slapos/systool.py
+4
-2
slapos/test/monitor/test_config_document.py
slapos/test/monitor/test_config_document.py
+2
-2
slapos/test/monitor/testbootstrap.py
slapos/test/monitor/testbootstrap.py
+2
-2
slapos/test/monitor/testglobalstate.py
slapos/test/monitor/testglobalstate.py
+2
-2
slapos/test/monitor/testrunpromise.py
slapos/test/monitor/testrunpromise.py
+15
-15
slapos/test/test_qemuqmpclient.py
slapos/test/test_qemuqmpclient.py
+2
-2
slapos/test/test_runner.py
slapos/test/test_runner.py
+2
-2
slapos/test/test_securedelete.py
slapos/test/test_securedelete.py
+13
-13
No files found.
slapos/agent/agent.py
View file @
5ceae36b
...
@@ -25,7 +25,7 @@
...
@@ -25,7 +25,7 @@
#
#
##############################################################################
##############################################################################
import
ConfigP
arser
from
six.moves
import
configp
arser
import
argparse
import
argparse
import
collections
import
collections
import
json
import
json
...
@@ -214,7 +214,7 @@ def main():
...
@@ -214,7 +214,7 @@ def main():
logger
,
log_file
=
getLogger
(
log
,
args
.
verbose
)
logger
,
log_file
=
getLogger
(
log
,
args
.
verbose
)
configuration
=
ConfigP
arser
.
SafeConfigParser
()
configuration
=
configp
arser
.
SafeConfigParser
()
configuration
.
readfp
(
args
.
configuration_file
)
configuration
.
readfp
(
args
.
configuration_file
)
pidfile
=
args
.
pidfile
pidfile
=
args
.
pidfile
...
...
slapos/agent/tester.py
View file @
5ceae36b
from
__future__
import
print_function
import
datetime
import
datetime
import
json
import
json
import
sys
import
sys
...
@@ -50,16 +52,16 @@ def retryOnNetworkFailure(func):
...
@@ -50,16 +52,16 @@ def retryOnNetworkFailure(func):
while
True
:
while
True
:
try
:
try
:
return
func
(
*
args
,
**
kwargs
)
return
func
(
*
args
,
**
kwargs
)
except
SAFE_RPC_EXCEPTION_LIST
,
e
:
except
SAFE_RPC_EXCEPTION_LIST
as
e
:
print
'Network failure: %s , %s'
%
(
sys
.
exc_info
(),
e
)
print
(
'Network failure: %s , %s'
%
(
sys
.
exc_info
(),
e
)
)
except
HTTPError
,
e
:
except
HTTPError
as
e
:
print
'Network failure: %s , %s'
%
(
sys
.
exc_info
(),
e
)
print
(
'Network failure: %s , %s'
%
(
sys
.
exc_info
(),
e
)
)
except
ConnectionError
,
e
:
except
ConnectionError
as
e
:
print
'Network failure: %s , %s'
%
(
sys
.
exc_info
(),
e
)
print
(
'Network failure: %s , %s'
%
(
sys
.
exc_info
(),
e
)
)
except
slapos
.
slap
.
ConnectionError
,
e
:
except
slapos
.
slap
.
ConnectionError
as
e
:
print
'Network failure: %s , %s'
%
(
sys
.
exc_info
(),
e
)
print
(
'Network failure: %s , %s'
%
(
sys
.
exc_info
(),
e
)
)
print
'Retry method %s in %i seconds'
%
(
func
,
retry_time
)
print
(
'Retry method %s in %i seconds'
%
(
func
,
retry_time
)
)
time
.
sleep
(
retry_time
)
time
.
sleep
(
retry_time
)
retry_time
=
min
(
retry_time
*
1.5
,
640
)
retry_time
=
min
(
retry_time
*
1.5
,
640
)
...
@@ -218,7 +220,7 @@ class SlapOSMasterCommunicator(object):
...
@@ -218,7 +220,7 @@ class SlapOSMasterCommunicator(object):
result
=
self
.
hateoas_navigator
.
GET
(
url
)
result
=
self
.
hateoas_navigator
.
GET
(
url
)
result
=
json
.
loads
(
result
)
result
=
json
.
loads
(
result
)
if
result
[
'_links'
].
get
(
'action_object_slap'
,
None
)
is
None
:
if
result
[
'_links'
].
get
(
'action_object_slap'
,
None
)
is
None
:
print
result
[
'links'
]
print
(
result
[
'links'
])
return
None
return
None
object_link
=
self
.
hateoas_navigator
.
hateoasGetLinkFromLinks
(
object_link
=
self
.
hateoas_navigator
.
hateoasGetLinkFromLinks
(
...
...
slapos/apachedex.py
View file @
5ceae36b
...
@@ -27,6 +27,8 @@
...
@@ -27,6 +27,8 @@
#
#
##############################################################################
##############################################################################
from
__future__
import
print_function
import
os
,
errno
import
os
,
errno
import
subprocess
import
subprocess
import
argparse
import
argparse
...
@@ -52,7 +54,7 @@ def build_command(apachedex_executable, output_file,
...
@@ -52,7 +54,7 @@ def build_command(apachedex_executable, output_file,
# Automaticaly replace variable 'date'.
# Automaticaly replace variable 'date'.
apache_log
=
logfile
.
strip
()
%
{
'date'
:
today
}
apache_log
=
logfile
.
strip
()
%
{
'date'
:
today
}
if
not
os
.
path
.
exists
(
apache_log
):
if
not
os
.
path
.
exists
(
apache_log
):
print
"WARNING: File %s not found..."
%
apache_log
print
(
"WARNING: File %s not found..."
%
apache_log
)
continue
continue
log_list
.
append
(
apache_log
)
log_list
.
append
(
apache_log
)
if
not
log_list
:
if
not
log_list
:
...
@@ -81,7 +83,7 @@ def main():
...
@@ -81,7 +83,7 @@ def main():
base_url
=
args
.
base_url
.
strip
()
base_url
=
args
.
base_url
.
strip
()
if
not
os
.
path
.
exists
(
output_folder
)
or
not
os
.
path
.
isdir
(
output_folder
):
if
not
os
.
path
.
exists
(
output_folder
)
or
not
os
.
path
.
isdir
(
output_folder
):
print
"ERROR: Output folder is not a directory. Exiting..."
print
(
"ERROR: Output folder is not a directory. Exiting..."
)
return
1
return
1
today
=
date
.
today
().
strftime
(
"%Y-%m-%d"
)
today
=
date
.
today
().
strftime
(
"%Y-%m-%d"
)
...
@@ -93,7 +95,7 @@ def main():
...
@@ -93,7 +95,7 @@ def main():
args
.
apache_log_list
,
args
.
apache_log_list
,
config
)
config
)
except
ValueError
as
e
:
except
ValueError
as
e
:
print
e
print
(
e
)
return
1
return
1
process_handler
=
subprocess
.
Popen
(
argument_list
,
process_handler
=
subprocess
.
Popen
(
argument_list
,
stdout
=
subprocess
.
PIPE
,
stdout
=
subprocess
.
PIPE
,
...
@@ -103,11 +105,11 @@ def main():
...
@@ -103,11 +105,11 @@ def main():
stdout
,
stderr
=
process_handler
.
communicate
()
stdout
,
stderr
=
process_handler
.
communicate
()
if
process_handler
.
returncode
!=
0
:
if
process_handler
.
returncode
!=
0
:
if
stderr
:
if
stderr
:
print
stderr
print
(
stderr
)
return
1
return
1
with
open
(
output_file
,
'r'
)
as
f
:
with
open
(
output_file
,
'r'
)
as
f
:
print
base_url
+
'/ApacheDex-%s.html'
%
today
print
(
base_url
+
'/ApacheDex-%s.html'
%
today
)
return
0
return
0
if
__name__
==
"__main__"
:
if
__name__
==
"__main__"
:
...
...
slapos/container/__init__.py
View file @
5ceae36b
# -*- coding: utf-8 -*-
# -*- coding: utf-8 -*-
import
ConfigP
arser
from
six.moves
import
configp
arser
import
argparse
import
argparse
import
gdbm
from
six.moves
import
dbm_gnu
as
gdbm
import
sys
import
sys
import
os
import
os
...
@@ -41,7 +41,7 @@ def main():
...
@@ -41,7 +41,7 @@ def main():
run
(
args
)
run
(
args
)
def
run
(
args
):
def
run
(
args
):
slapos_conf
=
ConfigP
arser
.
ConfigParser
()
slapos_conf
=
configp
arser
.
ConfigParser
()
slapos_conf
.
read
(
args
.
configuration_file
)
slapos_conf
.
read
(
args
.
configuration_file
)
current_binary
=
os
.
path
.
join
(
os
.
getcwd
(),
sys
.
argv
[
0
])
current_binary
=
os
.
path
.
join
(
os
.
getcwd
(),
sys
.
argv
[
0
])
...
@@ -52,7 +52,7 @@ def run(args):
...
@@ -52,7 +52,7 @@ def run(args):
partition_base_name
=
slapos_conf
.
get
(
'slapformat'
,
'partition_base_name'
)
partition_base_name
=
slapos_conf
.
get
(
'slapformat'
,
'partition_base_name'
)
try
:
try
:
bridge_name
=
slapos_conf
.
get
(
'slapformat'
,
'interface_name'
)
bridge_name
=
slapos_conf
.
get
(
'slapformat'
,
'interface_name'
)
except
ConfigP
arser
.
NoOptionError
:
except
configp
arser
.
NoOptionError
:
bridge_name
=
slapos_conf
.
get
(
'slapformat'
,
'bridge_name'
)
bridge_name
=
slapos_conf
.
get
(
'slapformat'
,
'bridge_name'
)
instance_root
=
slapos_conf
.
get
(
'slapos'
,
'instance_root'
)
instance_root
=
slapos_conf
.
get
(
'slapos'
,
'instance_root'
)
partition_base_path
=
os
.
path
.
join
(
instance_root
,
partition_base_name
)
partition_base_path
=
os
.
path
.
join
(
instance_root
,
partition_base_name
)
...
@@ -61,7 +61,7 @@ def run(args):
...
@@ -61,7 +61,7 @@ def run(args):
logging
.
basicConfig
(
level
=
logging
.
getLevelName
(
args
.
log
[
0
]))
logging
.
basicConfig
(
level
=
logging
.
getLevelName
(
args
.
log
[
0
]))
database
=
gdbm
.
open
(
args
.
database
,
'c'
,
0600
)
database
=
gdbm
.
open
(
args
.
database
,
'c'
,
0
o
600
)
try
:
try
:
process
.
main
(
sr_directory
,
partition_list
,
database
,
bridge_name
)
process
.
main
(
sr_directory
,
partition_list
,
database
,
bridge_name
)
finally
:
finally
:
...
...
slapos/equeue/__init__.py
View file @
5ceae36b
...
@@ -28,7 +28,7 @@
...
@@ -28,7 +28,7 @@
import
argparse
import
argparse
import
errno
import
errno
import
gdbm
from
six.moves
import
dbm_gnu
as
gdbm
import
json
import
json
from
lockfile
import
LockFile
from
lockfile
import
LockFile
import
logging
import
logging
...
@@ -38,8 +38,8 @@ import signal
...
@@ -38,8 +38,8 @@ import signal
import
socket
import
socket
import
subprocess
import
subprocess
import
sys
import
sys
import
SocketS
erver
from
six.moves
import
sockets
erver
import
StringIO
import
six
import
threading
import
threading
# Copied from erp5.util:erp5/util/testnode/ProcessManager.py
# Copied from erp5.util:erp5/util/testnode/ProcessManager.py
...
@@ -75,13 +75,13 @@ def subprocess_capture(p, log, log_prefix, get_output=True):
...
@@ -75,13 +75,13 @@ def subprocess_capture(p, log, log_prefix, get_output=True):
return
(
p
.
stdout
and
''
.
join
(
stdout
),
return
(
p
.
stdout
and
''
.
join
(
stdout
),
p
.
stderr
and
''
.
join
(
stderr
))
p
.
stderr
and
''
.
join
(
stderr
))
class
EqueueServer
(
SocketS
erver
.
ThreadingUnixStreamServer
):
class
EqueueServer
(
sockets
erver
.
ThreadingUnixStreamServer
):
daemon_threads
=
True
daemon_threads
=
True
def
__init__
(
self
,
*
args
,
**
kw
):
def
__init__
(
self
,
*
args
,
**
kw
):
self
.
options
=
kw
.
pop
(
'equeue_options'
)
self
.
options
=
kw
.
pop
(
'equeue_options'
)
SocketS
erver
.
ThreadingUnixStreamServer
.
__init__
(
self
,
sockets
erver
.
ThreadingUnixStreamServer
.
__init__
(
self
,
RequestHandlerClass
=
None
,
RequestHandlerClass
=
None
,
*
args
,
**
kw
)
*
args
,
**
kw
)
# Equeue Specific elements
# Equeue Specific elements
...
@@ -106,7 +106,7 @@ class EqueueServer(SocketServer.ThreadingUnixStreamServer):
...
@@ -106,7 +106,7 @@ class EqueueServer(SocketServer.ThreadingUnixStreamServer):
self
.
logger
.
addHandler
(
handler
)
self
.
logger
.
addHandler
(
handler
)
def
setDB
(
self
,
database
):
def
setDB
(
self
,
database
):
self
.
db
=
gdbm
.
open
(
database
,
'cs'
,
0700
)
self
.
db
=
gdbm
.
open
(
database
,
'cs'
,
0
o
700
)
def
_hasTakeoverBeenTriggered
(
self
):
def
_hasTakeoverBeenTriggered
(
self
):
if
hasattr
(
self
,
'takeover_triggered_file_path'
)
and
\
if
hasattr
(
self
,
'takeover_triggered_file_path'
)
and
\
...
@@ -149,7 +149,7 @@ class EqueueServer(SocketServer.ThreadingUnixStreamServer):
...
@@ -149,7 +149,7 @@ class EqueueServer(SocketServer.ThreadingUnixStreamServer):
# Handle request
# Handle request
self
.
logger
.
debug
(
"Connection with file descriptor %d"
,
request
.
fileno
())
self
.
logger
.
debug
(
"Connection with file descriptor %d"
,
request
.
fileno
())
request
.
settimeout
(
self
.
options
.
timeout
)
request
.
settimeout
(
self
.
options
.
timeout
)
request_string
=
StringIO
.
StringIO
()
request_string
=
six
.
StringIO
()
segment
=
None
segment
=
None
try
:
try
:
while
segment
!=
''
:
while
segment
!=
''
:
...
@@ -181,7 +181,7 @@ class EqueueServer(SocketServer.ThreadingUnixStreamServer):
...
@@ -181,7 +181,7 @@ class EqueueServer(SocketServer.ThreadingUnixStreamServer):
def
remove_existing_file
(
path
):
def
remove_existing_file
(
path
):
try
:
try
:
os
.
remove
(
path
)
os
.
remove
(
path
)
except
OSError
,
e
:
except
OSError
as
e
:
if
e
.
errno
!=
errno
.
ENOENT
:
if
e
.
errno
!=
errno
.
ENOENT
:
raise
raise
...
...
slapos/generatefeed.py
View file @
5ceae36b
...
@@ -76,7 +76,7 @@ def generateFeed(option):
...
@@ -76,7 +76,7 @@ def generateFeed(option):
# Reduces feed if number of items exceeds max_item
# Reduces feed if number of items exceeds max_item
if
len
(
item_dict
)
>
option
.
max_item
:
if
len
(
item_dict
)
>
option
.
max_item
:
outdated_key_list
=
sorted_item_dict
.
keys
(
)[:
-
option
.
max_item
]
outdated_key_list
=
list
(
sorted_item_dict
)[:
-
option
.
max_item
]
for
outdated_key
in
outdated_key_list
:
for
outdated_key
in
outdated_key_list
:
del
sorted_item_dict
[
outdated_key
]
del
sorted_item_dict
[
outdated_key
]
deleteFileList
(
outdated_key_list
)
deleteFileList
(
outdated_key_list
)
...
...
slapos/lamp/__init__.py
View file @
5ceae36b
...
@@ -12,6 +12,7 @@
...
@@ -12,6 +12,7 @@
#
#
##############################################################################
##############################################################################
from
__future__
import
print_function
import
os
import
os
import
time
import
time
...
@@ -76,7 +77,7 @@ def run():
...
@@ -76,7 +77,7 @@ def run():
result
=
parser
.
parse_args
()
result
=
parser
.
parse_args
()
arguments
=
dict
(
result
.
_get_kwargs
())
arguments
=
dict
(
result
.
_get_kwargs
())
if
arguments
[
'token'
]
==
None
and
arguments
[
'file_token'
]
==
None
:
if
arguments
[
'token'
]
==
None
and
arguments
[
'file_token'
]
==
None
:
print
"lampconfigure: Error: Please specify where condition will be taken, use -d or -f option"
print
(
"lampconfigure: Error: Please specify where condition will be taken, use -d or -f option"
)
return
return
setup
(
arguments
)
setup
(
arguments
)
...
@@ -84,7 +85,7 @@ def setup(arguments):
...
@@ -84,7 +85,7 @@ def setup(arguments):
timeout
=
5
;
timeout
=
5
;
while
True
:
while
True
:
if
not
checkAction
(
arguments
):
if
not
checkAction
(
arguments
):
print
"Waiting for 3s and retrying"
print
(
"Waiting for 3s and retrying"
)
time
.
sleep
(
3
)
time
.
sleep
(
3
)
continue
continue
time
.
sleep
(
timeout
)
time
.
sleep
(
timeout
)
...
@@ -115,9 +116,9 @@ def checkAction(arguments):
...
@@ -115,9 +116,9 @@ def checkAction(arguments):
user
=
arguments
[
'mysql_user'
],
user
=
arguments
[
'mysql_user'
],
passwd
=
arguments
[
'mysql_password'
],
passwd
=
arguments
[
'mysql_password'
],
db
=
arguments
[
'token'
])
db
=
arguments
[
'token'
])
except
Exception
,
ex
:
except
Exception
as
e
:
#Mysql is not ready yet?...
#Mysql is not ready yet?...
print
ex
.
message
print
(
e
)
return
False
return
False
if
arguments
[
'table'
]
==
"**"
:
if
arguments
[
'table'
]
==
"**"
:
#only detect if mysql has been started
#only detect if mysql has been started
...
@@ -145,7 +146,7 @@ def rename(arguments):
...
@@ -145,7 +146,7 @@ def rename(arguments):
source
=
os
.
path
.
join
(
arguments
[
'target_directory'
],
arguments
[
'source'
])
source
=
os
.
path
.
join
(
arguments
[
'target_directory'
],
arguments
[
'source'
])
destination
=
os
.
path
.
join
(
arguments
[
'target_directory'
],
arguments
[
'destination'
])
destination
=
os
.
path
.
join
(
arguments
[
'target_directory'
],
arguments
[
'destination'
])
if
not
os
.
path
.
exists
(
source
):
if
not
os
.
path
.
exists
(
source
):
print
"Error when moving: '%s': no such file or directory"
%
source
print
(
"Error when moving: '%s': no such file or directory"
%
source
)
return
return
os
.
rename
(
source
,
destination
)
os
.
rename
(
source
,
destination
)
if
arguments
[
'mode'
]
!=
None
:
if
arguments
[
'mode'
]
!=
None
:
...
@@ -155,7 +156,7 @@ def delete(arguments):
...
@@ -155,7 +156,7 @@ def delete(arguments):
for
path
in
arguments
[
'delete_target'
]:
for
path
in
arguments
[
'delete_target'
]:
path
=
os
.
path
.
join
(
arguments
[
'target_directory'
],
path
)
path
=
os
.
path
.
join
(
arguments
[
'target_directory'
],
path
)
if
not
os
.
path
.
exists
(
path
):
if
not
os
.
path
.
exists
(
path
):
print
"Error when deleting: '%s': no such file or directory"
%
path
print
(
"Error when deleting: '%s': no such file or directory"
%
path
)
continue
continue
if
os
.
path
.
isdir
(
path
):
if
os
.
path
.
isdir
(
path
):
shutil
.
rmtree
(
path
)
shutil
.
rmtree
(
path
)
...
@@ -164,7 +165,7 @@ def delete(arguments):
...
@@ -164,7 +165,7 @@ def delete(arguments):
def
run_script
(
arguments
):
def
run_script
(
arguments
):
script
=
os
.
path
.
join
(
arguments
[
'target_directory'
],
arguments
[
'script'
])
script
=
os
.
path
.
join
(
arguments
[
'target_directory'
],
arguments
[
'script'
])
print
'Running script: %s'
%
script
print
(
'Running script: %s'
%
script
)
if
os
.
path
.
exists
(
script
):
if
os
.
path
.
exists
(
script
):
import
subprocess
import
subprocess
#run python script with predefined data
#run python script with predefined data
...
@@ -176,12 +177,12 @@ def run_script(arguments):
...
@@ -176,12 +177,12 @@ def run_script(arguments):
result
=
subprocess
.
Popen
(
data
,
env
=
{
'PYTHONPATH'
:
':'
.
join
(
sys
.
path
)})
result
=
subprocess
.
Popen
(
data
,
env
=
{
'PYTHONPATH'
:
':'
.
join
(
sys
.
path
)})
result
.
wait
()
result
.
wait
()
else
:
else
:
print
"Error: can not read file '%s'"
%
script
print
(
"Error: can not read file '%s'"
%
script
)
def
run_sql_script
(
arguments
):
def
run_sql_script
(
arguments
):
script
=
os
.
path
.
join
(
arguments
[
'target_directory'
],
arguments
[
'sql_script'
])
script
=
os
.
path
.
join
(
arguments
[
'target_directory'
],
arguments
[
'sql_script'
])
print
'Running SQL script: %s'
%
script
print
(
'Running SQL script: %s'
%
script
)
if
os
.
path
.
exists
(
script
):
if
os
.
path
.
exists
(
script
):
conn
=
MySQLdb
.
connect
(
host
=
arguments
[
'mysql_host'
],
conn
=
MySQLdb
.
connect
(
host
=
arguments
[
'mysql_host'
],
port
=
int
(
arguments
[
'mysql_port'
]),
port
=
int
(
arguments
[
'mysql_port'
]),
...
@@ -196,7 +197,7 @@ def run_sql_script(arguments):
...
@@ -196,7 +197,7 @@ def run_sql_script(arguments):
conn
.
close
()
conn
.
close
()
else
:
else
:
print
"Error: can not read file '%s'"
%
script
print
(
"Error: can not read file '%s'"
%
script
)
...
@@ -204,6 +205,6 @@ def chmod(arguments):
...
@@ -204,6 +205,6 @@ def chmod(arguments):
for
path
in
arguments
[
'chmod_target'
]:
for
path
in
arguments
[
'chmod_target'
]:
path
=
os
.
path
.
join
(
arguments
[
'target_directory'
],
path
)
path
=
os
.
path
.
join
(
arguments
[
'target_directory'
],
path
)
if
not
os
.
path
.
exists
(
path
):
if
not
os
.
path
.
exists
(
path
):
print
"Error when changing mode: '%s': no such file or directory"
%
path
print
(
"Error when changing mode: '%s': no such file or directory"
%
path
)
continue
continue
os
.
chmod
(
path
,
int
(
arguments
[
'mode'
],
8
))
os
.
chmod
(
path
,
int
(
arguments
[
'mode'
],
8
))
slapos/monitor/collect.py
View file @
5ceae36b
...
@@ -27,6 +27,8 @@
...
@@ -27,6 +27,8 @@
#
#
##############################################################################
##############################################################################
from
six.moves
import
zip
import
sqlite3
import
sqlite3
import
os
import
os
import
pwd
import
pwd
...
@@ -80,7 +82,7 @@ class ResourceCollect:
...
@@ -80,7 +82,7 @@ class ResourceCollect:
table
=
"sqlite_master"
,
table
=
"sqlite_master"
,
columns
=
'name'
,
columns
=
'name'
,
where
=
"type='table' AND name='%s'"
%
name
)
where
=
"type='table' AND name='%s'"
%
name
)
table_exists_result
=
zip
(
*
check_result_cursor
)
table_exists_result
=
list
(
zip
(
*
check_result_cursor
)
)
if
not
len
(
table_exists_result
)
or
table_exists_result
[
0
][
0
]
is
None
:
if
not
len
(
table_exists_result
)
or
table_exists_result
[
0
][
0
]
is
None
:
return
False
return
False
return
True
return
True
...
@@ -159,7 +161,7 @@ class ResourceCollect:
...
@@ -159,7 +161,7 @@ class ResourceCollect:
query_result
=
self
.
db
.
select
(
'user'
,
date_scope
,
colums
,
query_result
=
self
.
db
.
select
(
'user'
,
date_scope
,
colums
,
where
=
"partition='%s' and (time between '%s' and '%s') %s"
%
where
=
"partition='%s' and (time between '%s' and '%s') %s"
%
(
partition_id
,
min_time
,
max_time
,
where
))
(
partition_id
,
min_time
,
max_time
,
where
))
result_list
=
zip
(
*
query_result
)
result_list
=
list
(
zip
(
*
query_result
)
)
process_dict
=
memory_dict
=
io_dict
=
{}
process_dict
=
memory_dict
=
io_dict
=
{}
if
len
(
result_list
):
if
len
(
result_list
):
...
@@ -188,7 +190,7 @@ class ResourceCollect:
...
@@ -188,7 +190,7 @@ class ResourceCollect:
)
)
)
)
disk_used_sum
=
zip
(
*
disk_result_cursor
)
disk_used_sum
=
list
(
zip
(
*
disk_result_cursor
)
)
if
len
(
disk_used_sum
)
and
disk_used_sum
[
0
][
0
]
is
not
None
:
if
len
(
disk_used_sum
)
and
disk_used_sum
[
0
][
0
]
is
not
None
:
io_dict
[
'disk_used'
]
=
round
(
disk_used_sum
[
0
][
0
]
/
1024.0
,
2
)
io_dict
[
'disk_used'
]
=
round
(
disk_used_sum
[
0
][
0
]
/
1024.0
,
2
)
self
.
db
.
close
()
self
.
db
.
close
()
...
@@ -252,7 +254,7 @@ def main():
...
@@ -252,7 +254,7 @@ def main():
status_file
=
os
.
path
.
join
(
parser
.
output_folder
,
'monitor_resource.status.json'
)
status_file
=
os
.
path
.
join
(
parser
.
output_folder
,
'monitor_resource.status.json'
)
if
not
os
.
path
.
exists
(
parser
.
collector_db
):
if
not
os
.
path
.
exists
(
parser
.
collector_db
):
print
"Collector database not found..."
print
(
"Collector database not found..."
)
initProcessDataFile
(
process_file
)
initProcessDataFile
(
process_file
)
initMemoryDataFile
(
mem_file
)
initMemoryDataFile
(
mem_file
)
initIODataFile
(
io_file
)
initIODataFile
(
io_file
)
...
...
slapos/monitor/globalstate.py
View file @
5ceae36b
#!/usr/bin/env python
#!/usr/bin/env python
from
__future__
import
print_function
import
sys
import
sys
import
os
import
os
import
glob
import
glob
import
json
import
json
import
ConfigP
arser
from
six.moves
import
configp
arser
import
time
import
time
from
datetime
import
datetime
from
datetime
import
datetime
import
base64
import
base64
...
@@ -150,9 +152,9 @@ def generateMonitoringData(config, public_folder, private_folder, public_url,
...
@@ -150,9 +152,9 @@ def generateMonitoringData(config, public_folder, private_folder, public_url,
previous_state_dict
.
get
(
tmp_json
[
'name'
]),
previous_state_dict
.
get
(
tmp_json
[
'name'
]),
public_folder
public_folder
)
)
except
ValueError
,
e
:
except
ValueError
as
e
:
# bad json file
# bad json file
print
"ERROR: Bad json file at: %s
\
n
%s"
%
(
file
,
str
(
e
))
print
(
"ERROR: Bad json file at: %s
\
n
%s"
%
(
file
,
str
(
e
)
))
continue
continue
with
open
(
promises_status_file
,
"w"
)
as
f
:
with
open
(
promises_status_file
,
"w"
)
as
f
:
...
@@ -202,7 +204,7 @@ def savePromiseHistory(promise_name, state_dict, previous_state_list,
...
@@ -202,7 +204,7 @@ def savePromiseHistory(promise_name, state_dict, previous_state_list,
def
run
(
monitor_conf_file
):
def
run
(
monitor_conf_file
):
config
=
ConfigP
arser
.
ConfigParser
()
config
=
configp
arser
.
ConfigParser
()
config
.
read
(
monitor_conf_file
)
config
.
read
(
monitor_conf_file
)
base_folder
=
config
.
get
(
'monitor'
,
'private-folder'
)
base_folder
=
config
.
get
(
'monitor'
,
'private-folder'
)
...
...
slapos/monitor/monitor.py
View file @
5ceae36b
#!/usr/bin/env python
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# -*- coding: utf-8 -*-
from
__future__
import
print_function
import
sys
import
sys
import
os
import
os
import
stat
import
stat
import
json
import
json
import
ConfigP
arser
from
six.moves
import
configp
arser
import
traceback
import
traceback
import
argparse
import
argparse
import
urllib2
from
six.moves
import
urllib
import
ssl
import
ssl
import
glob
import
glob
import
socket
import
socket
...
@@ -46,7 +48,7 @@ def parseArguments():
...
@@ -46,7 +48,7 @@ def parseArguments():
def
mkdirAll
(
path
):
def
mkdirAll
(
path
):
try
:
try
:
os
.
makedirs
(
path
)
os
.
makedirs
(
path
)
except
OSError
,
e
:
except
OSError
as
e
:
if
e
.
errno
==
os
.
errno
.
EEXIST
and
os
.
path
.
isdir
(
path
):
if
e
.
errno
==
os
.
errno
.
EEXIST
and
os
.
path
.
isdir
(
path
):
pass
pass
else
:
raise
else
:
raise
...
@@ -54,13 +56,13 @@ def mkdirAll(path):
...
@@ -54,13 +56,13 @@ def mkdirAll(path):
def
softConfigGet
(
config
,
*
args
,
**
kwargs
):
def
softConfigGet
(
config
,
*
args
,
**
kwargs
):
try
:
try
:
return
config
.
get
(
*
args
,
**
kwargs
)
return
config
.
get
(
*
args
,
**
kwargs
)
except
(
ConfigParser
.
NoOptionError
,
ConfigP
arser
.
NoSectionError
):
except
(
configparser
.
NoOptionError
,
configp
arser
.
NoSectionError
):
return
None
return
None
def
createSymlink
(
source
,
destination
):
def
createSymlink
(
source
,
destination
):
try
:
try
:
os
.
symlink
(
source
,
destination
)
os
.
symlink
(
source
,
destination
)
except
OSError
,
e
:
except
OSError
as
e
:
if
e
.
errno
!=
os
.
errno
.
EEXIST
:
if
e
.
errno
!=
os
.
errno
.
EEXIST
:
raise
raise
...
@@ -98,10 +100,10 @@ class Monitoring(object):
...
@@ -98,10 +100,10 @@ class Monitoring(object):
def
loadConfig
(
self
,
pathes
,
config
=
None
):
def
loadConfig
(
self
,
pathes
,
config
=
None
):
if
config
is
None
:
if
config
is
None
:
config
=
ConfigP
arser
.
ConfigParser
()
config
=
configp
arser
.
ConfigParser
()
try
:
try
:
config
.
read
(
pathes
)
config
.
read
(
pathes
)
except
ConfigP
arser
.
MissingSectionHeaderError
:
except
configp
arser
.
MissingSectionHeaderError
:
traceback
.
print_exc
()
traceback
.
print_exc
()
return
config
return
config
...
@@ -130,8 +132,8 @@ class Monitoring(object):
...
@@ -130,8 +132,8 @@ class Monitoring(object):
try
:
try
:
with
open
(
config_list
[
2
])
as
cfile
:
with
open
(
config_list
[
2
])
as
cfile
:
param_value
=
cfile
.
read
()
param_value
=
cfile
.
read
()
except
OSError
,
e
:
except
OSError
as
e
:
print
'Cannot read file %s, Error is: %s'
%
(
config_list
[
2
],
str
(
e
))
print
(
'Cannot read file %s, Error is: %s'
%
(
config_list
[
2
],
str
(
e
)
))
pass
pass
else
:
else
:
param_value
=
""
param_value
=
""
...
@@ -146,7 +148,7 @@ class Monitoring(object):
...
@@ -146,7 +148,7 @@ class Monitoring(object):
)
)
if
config_list
[
0
]
==
'htpasswd'
:
if
config_list
[
0
]
==
'htpasswd'
:
if
len
(
config_list
)
!=
5
or
not
os
.
path
.
exists
(
config_list
[
4
]):
if
len
(
config_list
)
!=
5
or
not
os
.
path
.
exists
(
config_list
[
4
]):
print
'htpasswd file is not specified: %s'
%
str
(
config_list
)
print
(
'htpasswd file is not specified: %s'
%
str
(
config_list
)
)
continue
continue
parameter
[
'description'
][
'user'
]
=
config_list
[
3
]
parameter
[
'description'
][
'user'
]
=
config_list
[
3
]
parameter
[
'description'
][
'htpasswd'
]
=
config_list
[
4
]
parameter
[
'description'
][
'htpasswd'
]
=
config_list
[
4
]
...
@@ -177,8 +179,8 @@ class Monitoring(object):
...
@@ -177,8 +179,8 @@ class Monitoring(object):
}
}
)
)
configuration_list
.
append
(
parameter
)
configuration_list
.
append
(
parameter
)
except
OSError
,
e
:
except
OSError
as
e
:
print
'Cannot read file at %s, Error is: %s'
%
(
old_cors_file
,
str
(
e
))
print
(
'Cannot read file at %s, Error is: %s'
%
(
old_cors_file
,
str
(
e
)
))
pass
pass
return
configuration_list
return
configuration_list
...
@@ -191,7 +193,7 @@ class Monitoring(object):
...
@@ -191,7 +193,7 @@ class Monitoring(object):
try
:
try
:
mkdirAll
(
dirname
)
# could also raise OSError
mkdirAll
(
dirname
)
# could also raise OSError
os
.
symlink
(
path
,
os
.
path
.
join
(
dirname
,
os
.
path
.
basename
(
path
)))
os
.
symlink
(
path
,
os
.
path
.
join
(
dirname
,
os
.
path
.
basename
(
path
)))
except
OSError
,
e
:
except
OSError
as
e
:
if
e
.
errno
!=
os
.
errno
.
EEXIST
:
if
e
.
errno
!=
os
.
errno
.
EEXIST
:
raise
raise
...
@@ -211,20 +213,20 @@ class Monitoring(object):
...
@@ -211,20 +213,20 @@ class Monitoring(object):
# XXX - working here with public url
# XXX - working here with public url
if
hasattr
(
ssl
,
'_create_unverified_context'
):
if
hasattr
(
ssl
,
'_create_unverified_context'
):
context
=
ssl
.
_create_unverified_context
()
context
=
ssl
.
_create_unverified_context
()
response
=
urllib
2
.
urlopen
(
url
,
context
=
context
,
timeout
=
timeout
)
response
=
urllib
.
urlopen
(
url
,
context
=
context
,
timeout
=
timeout
)
else
:
else
:
response
=
urllib
2
.
urlopen
(
url
,
timeout
=
timeout
)
response
=
urllib
.
urlopen
(
url
,
timeout
=
timeout
)
except
urllib
2
.
HTTPError
:
except
urllib
.
HTTPError
:
print
"ERROR: Failed to get Monitor configuration file at %s "
%
url
print
(
"ERROR: Failed to get Monitor configuration file at %s "
%
url
)
except
socket
.
timeout
,
e
:
except
socket
.
timeout
as
e
:
print
"ERROR: Timeout while downloading monitor config at %s "
%
url
print
(
"ERROR: Timeout while downloading monitor config at %s "
%
url
)
else
:
else
:
try
:
try
:
monitor_dict
=
json
.
loads
(
response
.
read
())
monitor_dict
=
json
.
loads
(
response
.
read
())
monitor_title
=
monitor_dict
.
get
(
'title'
,
'Unknown Instance'
)
monitor_title
=
monitor_dict
.
get
(
'title'
,
'Unknown Instance'
)
success
=
True
success
=
True
except
ValueError
,
e
:
except
ValueError
as
e
:
print
"ERROR: Json file at %s is not valid"
%
url
print
(
"ERROR: Json file at %s is not valid"
%
url
)
self
.
bootstrap_is_ok
=
success
self
.
bootstrap_is_ok
=
success
return
monitor_title
return
monitor_title
...
@@ -266,8 +268,8 @@ class Monitoring(object):
...
@@ -266,8 +268,8 @@ class Monitoring(object):
for
parameter
in
parameter_list
:
for
parameter
in
parameter_list
:
if
parameter
[
'key'
]:
if
parameter
[
'key'
]:
pfile
.
write
(
'%s = %s
\
n
'
%
(
parameter
[
'key'
],
parameter
[
'value'
]))
pfile
.
write
(
'%s = %s
\
n
'
%
(
parameter
[
'key'
],
parameter
[
'value'
]))
except
OSError
,
e
:
except
OSError
as
e
:
print
"Error failed to create file %s"
%
self
.
parameter_cfg_file
print
(
"Error failed to create file %s"
%
self
.
parameter_cfg_file
)
pass
pass
...
@@ -316,8 +318,8 @@ class Monitoring(object):
...
@@ -316,8 +318,8 @@ class Monitoring(object):
try
:
try
:
if
os
.
path
.
exists
(
file
):
if
os
.
path
.
exists
(
file
):
os
.
unlink
(
file
)
os
.
unlink
(
file
)
except
OSError
,
e
:
except
OSError
as
e
:
print
"failed to remove file %s."
%
file
,
str
(
e
)
print
(
"failed to remove file %s."
%
file
,
str
(
e
)
)
# cleanup result of promises that was removed
# cleanup result of promises that was removed
promise_list
=
os
.
listdir
(
self
.
legacy_promise_folder
)
promise_list
=
os
.
listdir
(
self
.
legacy_promise_folder
)
...
@@ -335,8 +337,8 @@ class Monitoring(object):
...
@@ -335,8 +337,8 @@ class Monitoring(object):
if
os
.
path
.
exists
(
status_path
):
if
os
.
path
.
exists
(
status_path
):
try
:
try
:
os
.
unlink
(
status_path
)
os
.
unlink
(
status_path
)
except
OSError
,
e
:
except
OSError
as
e
:
print
"Error: Failed to delete %s"
%
status_path
,
str
(
e
)
print
(
"Error: Failed to delete %s"
%
status_path
,
str
(
e
)
)
else
:
else
:
promise_list
.
pop
(
position
)
promise_list
.
pop
(
position
)
...
@@ -365,7 +367,7 @@ class Monitoring(object):
...
@@ -365,7 +367,7 @@ class Monitoring(object):
if
self
.
bootstrap_is_ok
:
if
self
.
bootstrap_is_ok
:
with
open
(
self
.
promise_output_file
,
'w'
)
as
promise_file
:
with
open
(
self
.
promise_output_file
,
'w'
)
as
promise_file
:
promise_file
.
write
(
""
)
promise_file
.
write
(
""
)
print
"SUCCESS: bootstrap is OK"
print
(
"SUCCESS: bootstrap is OK"
)
return
0
return
0
...
...
slapos/monitor/monitor_config_write.py
View file @
5ceae36b
#!/usr/bin/env python
#!/usr/bin/env python
from
__future__
import
print_function
import
sys
import
sys
import
os
import
os
import
re
import
re
...
@@ -38,11 +40,11 @@ class MonitorConfigWrite(object):
...
@@ -38,11 +40,11 @@ class MonitorConfigWrite(object):
def
_fileWrite
(
self
,
file_path
,
content
):
def
_fileWrite
(
self
,
file_path
,
content
):
try
:
try
:
with
open
(
file_path
,
'w'
)
as
wf
:
with
open
(
file_path
,
'w'
)
as
wf
:
print
file_path
,
content
print
(
file_path
,
content
)
wf
.
write
(
content
.
strip
())
wf
.
write
(
content
.
strip
())
return
True
return
True
except
OSError
,
e
:
except
OSError
as
e
:
print
"ERROR while writing changes to %s.
\
n
%s"
%
(
file_path
,
str
(
e
))
print
(
"ERROR while writing changes to %s.
\
n
%s"
%
(
file_path
,
str
(
e
)
))
return
False
return
False
def
_htpasswdWrite
(
self
,
htpasswd_bin
,
parameter_dict
,
value
):
def
_htpasswdWrite
(
self
,
htpasswd_bin
,
parameter_dict
,
value
):
...
@@ -55,7 +57,7 @@ class MonitorConfigWrite(object):
...
@@ -55,7 +57,7 @@ class MonitorConfigWrite(object):
)
)
result
=
process
.
communicate
()[
0
]
result
=
process
.
communicate
()[
0
]
if
process
.
returncode
!=
0
:
if
process
.
returncode
!=
0
:
print
result
print
(
result
)
return
False
return
False
with
open
(
parameter_dict
[
'file'
],
'w'
)
as
pfile
:
with
open
(
parameter_dict
[
'file'
],
'w'
)
as
pfile
:
pfile
.
write
(
value
)
pfile
.
write
(
value
)
...
@@ -76,31 +78,31 @@ class MonitorConfigWrite(object):
...
@@ -76,31 +78,31 @@ class MonitorConfigWrite(object):
or
(
cors_domain
==
""
and
os
.
stat
(
httpd_cors_file
).
st_size
==
0
)):
or
(
cors_domain
==
""
and
os
.
stat
(
httpd_cors_file
).
st_size
==
0
)):
# Skip if cors file is not empty
# Skip if cors file is not empty
return
True
return
True
except
OSError
,
e
:
except
OSError
as
e
:
print
"Failed to open file at %s.
\
n
%s"
%
(
old_httpd_cors_file
,
str
(
e
))
print
(
"Failed to open file at %s.
\
n
%s"
%
(
old_httpd_cors_file
,
str
(
e
)
))
try
:
try
:
with
open
(
self
.
monitor_https_cors
,
'r'
)
as
cors_template
:
with
open
(
self
.
monitor_https_cors
,
'r'
)
as
cors_template
:
template
=
jinja2
.
Template
(
cors_template
.
read
())
template
=
jinja2
.
Template
(
cors_template
.
read
())
rendered_string
=
template
.
render
(
domain
=
cors_domain
)
rendered_string
=
template
.
render
(
domain
=
cors_domain
)
with
open
(
httpd_cors_file
,
'w'
)
as
file
:
with
open
(
httpd_cors_file
,
'w'
)
as
file
:
file
.
write
(
rendered_string
)
file
.
write
(
rendered_string
)
except
OSError
,
e
:
except
OSError
as
e
:
print
"ERROR while writing CORS changes to %s.
\
n
%s"
%
(
httpd_cors_file
,
str
(
e
))
print
(
"ERROR while writing CORS changes to %s.
\
n
%s"
%
(
httpd_cors_file
,
str
(
e
)
))
return
False
return
False
# Save current cors domain list
# Save current cors domain list
try
:
try
:
with
open
(
old_httpd_cors_file
,
'w'
)
as
cors_file
:
with
open
(
old_httpd_cors_file
,
'w'
)
as
cors_file
:
cors_file
.
write
(
cors_domain
)
cors_file
.
write
(
cors_domain
)
except
OSError
,
e
:
except
OSError
as
e
:
print
"Failed to open file at %s.
\
n
%s"
%
(
old_httpd_cors_file
,
str
(
e
))
print
(
"Failed to open file at %s.
\
n
%s"
%
(
old_httpd_cors_file
,
str
(
e
)
))
return
False
return
False
# Restart httpd process
# Restart httpd process
try
:
try
:
subprocess
.
call
(
httpd_gracefull_bin
)
subprocess
.
call
(
httpd_gracefull_bin
)
except
OSError
,
e
:
except
OSError
as
e
:
print
"Failed to execute command %s.
\
n
%s"
%
(
httpd_gracefull_bin
,
str
(
e
))
print
(
"Failed to execute command %s.
\
n
%s"
%
(
httpd_gracefull_bin
,
str
(
e
)
))
return
False
return
False
return
True
return
True
...
@@ -122,7 +124,7 @@ class MonitorConfigWrite(object):
...
@@ -122,7 +124,7 @@ class MonitorConfigWrite(object):
with
open
(
self
.
config_json_file
)
as
tmpfile
:
with
open
(
self
.
config_json_file
)
as
tmpfile
:
new_parameter_list
=
json
.
loads
(
tmpfile
.
read
())
new_parameter_list
=
json
.
loads
(
tmpfile
.
read
())
except
ValueError
:
except
ValueError
:
print
"Error: Couldn't parse json file %s"
%
self
.
config_json_file
print
(
"Error: Couldn't parse json file %s"
%
self
.
config_json_file
)
with
open
(
parameter_config_file
)
as
tmpfile
:
with
open
(
parameter_config_file
)
as
tmpfile
:
description_dict
=
json
.
loads
(
tmpfile
.
read
())
description_dict
=
json
.
loads
(
tmpfile
.
read
())
...
@@ -156,8 +158,8 @@ class MonitorConfigWrite(object):
...
@@ -156,8 +158,8 @@ class MonitorConfigWrite(object):
for
parameter
in
new_parameter_list
:
for
parameter
in
new_parameter_list
:
if
parameter
[
'key'
]:
if
parameter
[
'key'
]:
pfile
.
write
(
'%s = %s
\
n
'
%
(
parameter
[
'key'
],
parameter
[
'value'
]))
pfile
.
write
(
'%s = %s
\
n
'
%
(
parameter
[
'key'
],
parameter
[
'value'
]))
except
OSError
,
e
:
except
OSError
as
e
:
print
"Error failed to create file %s"
%
self
.
output_cfg_file
print
(
"Error failed to create file %s"
%
self
.
output_cfg_file
)
pass
pass
return
result_dict
return
result_dict
...
@@ -190,8 +192,8 @@ def main():
...
@@ -190,8 +192,8 @@ def main():
if
status
and
os
.
path
.
exists
(
parameter_tmp_file
):
if
status
and
os
.
path
.
exists
(
parameter_tmp_file
):
try
:
try
:
os
.
unlink
(
config_file
)
os
.
unlink
(
config_file
)
except
OSError
,
e
:
except
OSError
as
e
:
print
"ERROR cannot remove file: %s"
%
parameter_tmp_file
print
(
"ERROR cannot remove file: %s"
%
parameter_tmp_file
)
else
:
else
:
os
.
rename
(
parameter_tmp_file
,
config_file
)
os
.
rename
(
parameter_tmp_file
,
config_file
)
if
run_counter
==
max_runn
:
if
run_counter
==
max_runn
:
...
...
slapos/monitor/runpromise.py
View file @
5ceae36b
...
@@ -13,7 +13,7 @@ import glob
...
@@ -13,7 +13,7 @@ import glob
import
argparse
import
argparse
import
traceback
import
traceback
import
logging
import
logging
import
ConfigP
arser
from
six.moves
import
configp
arser
from
slapos.grid.promise
import
PromiseLauncher
,
PromiseQueueResult
,
PromiseError
from
slapos.grid.promise
import
PromiseLauncher
,
PromiseQueueResult
,
PromiseError
from
slapos.grid.promise.generic
import
PROMISE_LOG_FOLDER_NAME
from
slapos.grid.promise.generic
import
PROMISE_LOG_FOLDER_NAME
from
slapos.util
import
mkdir_p
from
slapos.util
import
mkdir_p
...
@@ -92,7 +92,7 @@ class MonitorPromiseLauncher(object):
...
@@ -92,7 +92,7 @@ class MonitorPromiseLauncher(object):
def
_loadConfigFromFile
(
self
,
config_file
):
def
_loadConfigFromFile
(
self
,
config_file
):
config
=
ConfigP
arser
.
ConfigParser
()
config
=
configp
arser
.
ConfigParser
()
config
.
read
([
config_file
])
config
.
read
([
config_file
])
known_key_list
=
[
'partition-cert'
,
'partition-key'
,
'partition-id'
,
known_key_list
=
[
'partition-cert'
,
'partition-key'
,
'partition-id'
,
'pid-path'
,
'computer-id'
,
'check-anomaly'
,
'pid-path'
,
'computer-id'
,
'check-anomaly'
,
...
@@ -158,7 +158,7 @@ class MonitorPromiseLauncher(object):
...
@@ -158,7 +158,7 @@ class MonitorPromiseLauncher(object):
self
.
logger
.
info
(
"Checking promises..."
)
self
.
logger
.
info
(
"Checking promises..."
)
try
:
try
:
promise_launcher
.
run
()
promise_launcher
.
run
()
except
PromiseError
,
e
:
except
PromiseError
as
e
:
#self.logger.exception(e)
#self.logger.exception(e)
# error was already logged
# error was already logged
pass
pass
...
...
slapos/networkbench/__init__.py
View file @
5ceae36b
from
__future__
import
print_function
import
socket
import
socket
import
logging
import
logging
import
time
import
time
...
@@ -11,10 +13,10 @@ import random
...
@@ -11,10 +13,10 @@ import random
import
pycurl
import
pycurl
import
argparse
import
argparse
import
json
import
json
from
StringIO
import
StringIO
from
six
import
StringIO
from
ping
import
ping
,
ping6
from
.
ping
import
ping
,
ping6
from
dnsbench
import
resolve
from
.
dnsbench
import
resolve
from
http
import
get_curl
,
request
from
.
http
import
get_curl
,
request
import
textwrap
import
textwrap
class
HelpFormatter
(
argparse
.
ArgumentDefaultsHelpFormatter
):
class
HelpFormatter
(
argparse
.
ArgumentDefaultsHelpFormatter
):
...
@@ -62,11 +64,11 @@ def download_external_configuration(url):
...
@@ -62,11 +64,11 @@ def download_external_configuration(url):
try
:
try
:
return
json
.
loads
(
buffer
.
getvalue
())
return
json
.
loads
(
buffer
.
getvalue
())
except
ValueError
:
except
ValueError
:
print
"Unable to parse external configuration, error:"
print
(
"Unable to parse external configuration, error:"
)
import
traceback
import
traceback
traceback
.
print_exc
(
file
=
sys
.
stderr
)
traceback
.
print_exc
(
file
=
sys
.
stderr
)
sys
.
stderr
.
flush
()
sys
.
stderr
.
flush
()
print
"Ignoring external configuration"
print
(
"Ignoring external configuration"
)
finally
:
finally
:
curl
.
close
()
curl
.
close
()
...
...
slapos/networkbench/http.py
View file @
5ceae36b
import
sys
import
sys
import
pycurl
import
pycurl
from
StringIO
import
StringIO
from
six
import
StringIO
def
get_curl
(
buffer
,
url
):
def
get_curl
(
buffer
,
url
):
curl
=
pycurl
.
Curl
()
curl
=
pycurl
.
Curl
()
...
...
slapos/networkbench/ping.py
View file @
5ceae36b
...
@@ -22,6 +22,7 @@ def ping(host, timeout=10, protocol="4", count=10):
...
@@ -22,6 +22,7 @@ def ping(host, timeout=10, protocol="4", count=10):
test_title
=
'PING6'
test_title
=
'PING6'
proc
=
subprocess
.
Popen
((
ping_bin
,
'-c'
,
str
(
count
),
'-w'
,
str
(
timeout
),
host
),
proc
=
subprocess
.
Popen
((
ping_bin
,
'-c'
,
str
(
count
),
'-w'
,
str
(
timeout
),
host
),
universal_newlines
=
True
,
stdout
=
subprocess
.
PIPE
,
stderr
=
subprocess
.
PIPE
)
stdout
=
subprocess
.
PIPE
,
stderr
=
subprocess
.
PIPE
)
out
,
err
=
proc
.
communicate
()
out
,
err
=
proc
.
communicate
()
...
@@ -29,7 +30,7 @@ def ping(host, timeout=10, protocol="4", count=10):
...
@@ -29,7 +30,7 @@ def ping(host, timeout=10, protocol="4", count=10):
return
(
test_title
,
host
,
600
,
'failed'
,
100
,
"Network is unreachable"
)
return
(
test_title
,
host
,
600
,
'failed'
,
100
,
"Network is unreachable"
)
try
:
try
:
packet_loss_line
,
summary_line
=
(
out
.
splitlines
()
or
[
''
])[
-
2
:]
packet_loss_line
,
summary_line
=
(
out
.
splitlines
()
or
[
''
])[
-
2
:]
except
:
except
Exception
:
return
(
test_title
,
host
,
600
,
'failed'
,
-
1
,
"Fail to parser ping output"
)
return
(
test_title
,
host
,
600
,
'failed'
,
-
1
,
"Fail to parser ping output"
)
m
=
ping_re
.
match
(
summary_line
)
m
=
ping_re
.
match
(
summary_line
)
match
=
re
.
search
(
'(
\
d*)% p
a
cket loss'
,
packet_loss_line
)
match
=
re
.
search
(
'(
\
d*)% p
a
cket loss'
,
packet_loss_line
)
...
...
slapos/onetimeupload/__init__.py
View file @
5ceae36b
...
@@ -124,7 +124,7 @@ def main():
...
@@ -124,7 +124,7 @@ def main():
run
(
config
)
run
(
config
)
return_code
=
0
return_code
=
0
except
SystemExit
,
err
:
except
SystemExit
as
err
:
# Catch exception raise by optparse
# Catch exception raise by optparse
return_code
=
err
return_code
=
err
...
...
slapos/promise/apache_mpm_watchdog/__init__.py
View file @
5ceae36b
from
__future__
import
print_function
import
requests
import
requests
import
re
import
re
import
signal
import
signal
...
@@ -56,11 +58,11 @@ def watchServerStatus(pid_dict, server_status, timeout):
...
@@ -56,11 +58,11 @@ def watchServerStatus(pid_dict, server_status, timeout):
if
process
.
cmdline
()[
0
].
endswith
(
"/httpd"
):
if
process
.
cmdline
()[
0
].
endswith
(
"/httpd"
):
_pid_dict
.
setdefault
(
i
,
time
.
time
()
+
timeout
)
_pid_dict
.
setdefault
(
i
,
time
.
time
()
+
timeout
)
if
_pid_dict
[
i
]
<
time
.
time
():
if
_pid_dict
[
i
]
<
time
.
time
():
print
"Sending signal -%s to %s"
%
(
signal
.
SIGKILL
,
i
)
print
(
"Sending signal -%s to %s"
%
(
signal
.
SIGKILL
,
i
)
)
try
:
try
:
process
.
kill
()
process
.
kill
()
except
psutil
.
NoSuchProcess
:
except
psutil
.
NoSuchProcess
:
print
"Process is not there anymore"
print
(
"Process is not there anymore"
)
continue
continue
return
_pid_dict
return
_pid_dict
...
...
slapos/promise/check_apachedex_result/__init__.py
View file @
5ceae36b
...
@@ -47,7 +47,7 @@ def checkApachedexResult(apachedex_path, apachedex_report_status_file, desired_t
...
@@ -47,7 +47,7 @@ def checkApachedexResult(apachedex_path, apachedex_report_status_file, desired_t
with
open
(
apachedex_report_status_file
)
as
f
:
with
open
(
apachedex_report_status_file
)
as
f
:
try
:
try
:
json_content
=
json
.
load
(
f
)
json_content
=
json
.
load
(
f
)
except
ValueError
,
e
:
except
ValueError
as
e
:
json_content
=
''
json_content
=
''
if
json_content
:
if
json_content
:
message
+=
"
\
n
"
+
json_content
[
"message"
]
message
+=
"
\
n
"
+
json_content
[
"message"
]
...
...
slapos/promise/check_computer_memory/__init__.py
View file @
5ceae36b
...
@@ -7,6 +7,8 @@ Uses:
...
@@ -7,6 +7,8 @@ Uses:
- /proc/meminfo
- /proc/meminfo
"""
"""
from
__future__
import
print_function
import
sys
import
sys
import
sqlite3
import
sqlite3
import
argparse
import
argparse
...
@@ -14,6 +16,8 @@ import datetime
...
@@ -14,6 +16,8 @@ import datetime
from
slapos.collect.db
import
Database
from
slapos.collect.db
import
Database
from
six.moves
import
zip
def
getMemoryInfo
(
database
,
time
,
date
):
def
getMemoryInfo
(
database
,
time
,
date
):
memory_info
=
{}
memory_info
=
{}
...
@@ -21,7 +25,7 @@ def getMemoryInfo(database, time, date):
...
@@ -21,7 +25,7 @@ def getMemoryInfo(database, time, date):
try
:
try
:
database
.
connect
()
database
.
connect
()
query_result
=
database
.
select
(
"computer"
,
date
,
"memory_size"
,
limit
=
1
)
query_result
=
database
.
select
(
"computer"
,
date
,
"memory_size"
,
limit
=
1
)
result
=
zip
(
*
query_result
)
result
=
list
(
zip
(
*
query_result
)
)
if
not
result
or
not
result
[
0
][
0
]:
if
not
result
or
not
result
[
0
][
0
]:
return
(
None
,
"couldn't fetch total memory, collectordb is empty?"
)
return
(
None
,
"couldn't fetch total memory, collectordb is empty?"
)
memory_info
[
'total'
]
=
int
(
result
[
0
][
0
])
# in byte
memory_info
[
'total'
]
=
int
(
result
[
0
][
0
])
# in byte
...
@@ -29,7 +33,7 @@ def getMemoryInfo(database, time, date):
...
@@ -29,7 +33,7 @@ def getMemoryInfo(database, time, date):
# fetch free and used memory
# fetch free and used memory
where_query
=
"time between '%s:00' and '%s:30' "
%
(
time
,
time
)
where_query
=
"time between '%s:00' and '%s:30' "
%
(
time
,
time
)
query_result
=
database
.
select
(
"system"
,
date
,
"memory_free, memory_used"
,
where
=
where_query
)
query_result
=
database
.
select
(
"system"
,
date
,
"memory_free, memory_used"
,
where
=
where_query
)
result
=
zip
(
*
query_result
)
result
=
list
(
zip
(
*
query_result
)
)
if
not
result
or
not
result
[
0
][
0
]:
if
not
result
or
not
result
[
0
][
0
]:
return
(
None
,
"couldn't fetch free memory"
)
return
(
None
,
"couldn't fetch free memory"
)
memory_info
[
'free'
]
=
int
(
result
[
0
][
0
])
# in byte
memory_info
[
'free'
]
=
int
(
result
[
0
][
0
])
# in byte
...
@@ -95,9 +99,9 @@ def main():
...
@@ -95,9 +99,9 @@ def main():
unit
=
args
.
unit
,
unit
=
args
.
unit
,
)
)
if
error
:
if
error
:
print
error
print
(
error
)
return
0
return
0
print
message
print
(
message
)
return
0
if
result
else
1
return
0
if
result
else
1
if
__name__
==
"__main__"
:
if
__name__
==
"__main__"
:
...
...
slapos/promise/check_error_on_apache_log/__init__.py
View file @
5ceae36b
from
__future__
import
print_function
import
re
import
re
import
time
import
time
import
sys
import
sys
...
@@ -21,7 +23,7 @@ def test(log_file, maximum_delay):
...
@@ -21,7 +23,7 @@ def test(log_file, maximum_delay):
f
.
seek
(
0
,
2
)
f
.
seek
(
0
,
2
)
block_end_byte
=
f
.
tell
()
block_end_byte
=
f
.
tell
()
f
.
seek
(
-
min
(
block_end_byte
,
4096
),
1
)
f
.
seek
(
block_end_byte
-
min
(
block_end_byte
,
4096
),
0
)
data
=
f
.
read
()
data
=
f
.
read
()
for
line
in
reversed
(
data
.
splitlines
()):
for
line
in
reversed
(
data
.
splitlines
()):
...
@@ -76,7 +78,7 @@ def main():
...
@@ -76,7 +78,7 @@ def main():
result
=
test
(
args
.
log_file
,
args
.
maximum_delay
)
result
=
test
(
args
.
log_file
,
args
.
maximum_delay
)
print
result
print
(
result
)
if
result
!=
"OK"
:
if
result
!=
"OK"
:
sys
.
exit
(
1
)
sys
.
exit
(
1
)
slapos/promise/check_re6st_optimal_status/__init__.py
View file @
5ceae36b
from
__future__
import
print_function
import
argparse
import
argparse
import
re
import
re
import
time
import
time
...
@@ -7,10 +9,10 @@ from slapos.networkbench.ping import ping, ping6
...
@@ -7,10 +9,10 @@ from slapos.networkbench.ping import ping, ping6
def
test
(
ipv6
,
ipv4
,
count
):
def
test
(
ipv6
,
ipv4
,
count
):
result_ipv4
=
ping
(
ipv4
,
count
=
count
)
result_ipv4
=
ping
(
ipv4
,
count
=
count
)
print
"%s host=%s code=%s, result=%s, packet_lost_ratio=%s msg=%s"
%
result_ipv4
print
(
"%s host=%s code=%s, result=%s, packet_lost_ratio=%s msg=%s"
%
result_ipv4
)
result_ipv6
=
ping6
(
ipv6
,
count
=
count
)
result_ipv6
=
ping6
(
ipv6
,
count
=
count
)
print
"%s host=%s code=%s, result=%s, packet_lost_ratio=%s msg=%s"
%
result_ipv6
print
(
"%s host=%s code=%s, result=%s, packet_lost_ratio=%s msg=%s"
%
result_ipv6
)
if
result_ipv4
[
3
]
==
"failed"
and
result_ipv6
[
3
]
!=
"failed"
:
if
result_ipv4
[
3
]
==
"failed"
and
result_ipv6
[
3
]
!=
"failed"
:
# IPv4 is unreacheable
# IPv4 is unreacheable
...
@@ -34,7 +36,7 @@ def test(ipv6, ipv4, count):
...
@@ -34,7 +36,7 @@ def test(ipv6, ipv4, count):
# Increase latency with the value.
# Increase latency with the value.
latency4
+=
acceptable_delay
+
latency4
*
acceptable_lost
latency4
+=
acceptable_delay
+
latency4
*
acceptable_lost
if
latency4
<
latency6
:
if
latency4
<
latency6
:
print
"Fail %s (latency4) > %s (latence6)"
%
(
latency4
,
latency6
)
print
(
"Fail %s (latency4) > %s (latence6)"
%
(
latency4
,
latency6
)
)
return
"FAIL"
return
"FAIL"
# Compare if both has Same working rate
# Compare if both has Same working rate
...
@@ -51,7 +53,7 @@ def main():
...
@@ -51,7 +53,7 @@ def main():
result
=
test
(
args
.
ipv6
,
args
.
ipv4
,
args
.
count
)
result
=
test
(
args
.
ipv6
,
args
.
ipv4
,
args
.
count
)
print
result
print
(
result
)
if
result
!=
"OK"
:
if
result
!=
"OK"
:
# re6st is not on an optimal state.
# re6st is not on an optimal state.
sys
.
exit
(
1
)
sys
.
exit
(
1
)
...
...
slapos/promise/check_slow_queries_digest_result/__init__.py
View file @
5ceae36b
...
@@ -4,6 +4,8 @@
...
@@ -4,6 +4,8 @@
Check if a mariadb result matches the desired threshold or raises an error.
Check if a mariadb result matches the desired threshold or raises an error.
"""
"""
from
__future__
import
print_function
import
json
import
json
import
os
import
os
import
re
import
re
...
@@ -58,7 +60,7 @@ def checkMariadbDigestResult(mariadbdex_path, mariadbdex_report_status_file,
...
@@ -58,7 +60,7 @@ def checkMariadbDigestResult(mariadbdex_path, mariadbdex_report_status_file,
with
open
(
mariadbdex_report_status_file
)
as
f
:
with
open
(
mariadbdex_report_status_file
)
as
f
:
try
:
try
:
json_content
=
json
.
load
(
f
)
json_content
=
json
.
load
(
f
)
except
ValueError
,
e
:
except
ValueError
as
e
:
json_content
=
''
json_content
=
''
if
json_content
:
if
json_content
:
message
+=
"
\
n
"
+
json_content
[
"message"
]
message
+=
"
\
n
"
+
json_content
[
"message"
]
...
@@ -76,5 +78,5 @@ def main():
...
@@ -76,5 +78,5 @@ def main():
args
.
max_queries_threshold
,
args
.
slowest_query_threshold
args
.
max_queries_threshold
,
args
.
slowest_query_threshold
)
)
print
message
print
(
message
)
sys
.
exit
(
status
)
sys
.
exit
(
status
)
slapos/promise/check_user_memory/__init__.py
View file @
5ceae36b
...
@@ -4,6 +4,8 @@
...
@@ -4,6 +4,8 @@
Check user memory usage according to a given threshold.
Check user memory usage according to a given threshold.
"""
"""
from
__future__
import
print_function
import
sys
import
sys
import
os
import
os
import
argparse
import
argparse
...
@@ -87,9 +89,9 @@ def main():
...
@@ -87,9 +89,9 @@ def main():
unit
=
args
.
unit
,
unit
=
args
.
unit
,
)
)
if
error
:
if
error
:
print
error
print
(
error
)
return
0
return
0
print
message
print
(
message
)
return
0
if
result
else
1
return
0
if
result
else
1
if
__name__
==
"__main__"
:
if
__name__
==
"__main__"
:
...
...
slapos/promise/check_web_page_http_cache_hit/__init__.py
View file @
5ceae36b
...
@@ -7,14 +7,16 @@ import sys
...
@@ -7,14 +7,16 @@ import sys
import
tempfile
import
tempfile
import
os
import
os
import
argparse
import
argparse
import
ConfigP
arser
from
six.moves
import
configp
arser
import
re
import
re
import
pycurl
import
pycurl
from
mimetools
import
Message
from
email.message
import
Message
from
cStringIO
import
StringIO
from
six.moves
import
(
from
HTMLParser
import
HTMLParser
cStringIO
as
StringIO
,
html_parser
as
HTMLParser
,
)
begins_by_known_protocol_re
=
re
.
compile
(
"^https?://"
)
begins_by_known_protocol_re
=
re
.
compile
(
"^https?://"
)
get_protocol_re
=
re
.
compile
(
"^([a-z]+)://"
)
get_protocol_re
=
re
.
compile
(
"^([a-z]+)://"
)
...
@@ -119,7 +121,7 @@ def checkWebpageHttpCacheHit(url_list, resolve_list=[], cookie_jar_path=None):
...
@@ -119,7 +121,7 @@ def checkWebpageHttpCacheHit(url_list, resolve_list=[], cookie_jar_path=None):
def
getConfig
(
config_parser
,
section
,
option
,
default
=
None
,
raw
=
False
,
vars
=
None
):
def
getConfig
(
config_parser
,
section
,
option
,
default
=
None
,
raw
=
False
,
vars
=
None
):
try
:
try
:
return
config_parser
.
get
(
section
,
option
,
raw
=
raw
,
vars
=
vars
)
return
config_parser
.
get
(
section
,
option
,
raw
=
raw
,
vars
=
vars
)
except
ConfigP
arser
.
NoOptionError
:
except
configp
arser
.
NoOptionError
:
return
default
return
default
def
main
():
def
main
():
...
@@ -132,7 +134,7 @@ def main():
...
@@ -132,7 +134,7 @@ def main():
args
.
url_list
=
getattr
(
args
,
"url-list"
)
args
.
url_list
=
getattr
(
args
,
"url-list"
)
if
args
.
config
is
not
None
:
if
args
.
config
is
not
None
:
parser
=
ConfigP
arser
.
ConfigParser
()
parser
=
configp
arser
.
ConfigParser
()
parser
.
read
(
args
.
config
)
parser
.
read
(
args
.
config
)
if
args
.
url_list
==
[]:
if
args
.
url_list
==
[]:
args
.
url_list
=
getConfig
(
parser
,
"public"
,
"url-list"
,
""
).
split
()
args
.
url_list
=
getConfig
(
parser
,
"public"
,
"url-list"
,
""
).
split
()
...
...
slapos/promise/is_icmp_packet_lost/__init__.py
View file @
5ceae36b
from
__future__
import
print_function
import
argparse
import
argparse
import
re
import
re
import
time
import
time
...
@@ -22,10 +24,10 @@ def main():
...
@@ -22,10 +24,10 @@ def main():
result
=
test
(
args
.
address
,
args
.
ipv4
,
args
.
count
)
result
=
test
(
args
.
address
,
args
.
ipv4
,
args
.
count
)
print
"%s host=%s code=%s, result=%s, packet_lost_ratio=%s msg=%s"
%
result
print
(
"%s host=%s code=%s, result=%s, packet_lost_ratio=%s msg=%s"
%
result
)
if
result
[
4
]
!=
"0"
:
if
result
[
4
]
!=
"0"
:
# Packet lost occurred
# Packet lost occurred
print
"FAIL"
print
(
"FAIL"
)
sys
.
exit
(
1
)
sys
.
exit
(
1
)
print
"OK"
print
(
"OK"
)
slapos/promise/is_process_older_than_dependency_set/__init__.py
View file @
5ceae36b
...
@@ -8,6 +8,8 @@ a file modification date is greater than the start date of the
...
@@ -8,6 +8,8 @@ a file modification date is greater than the start date of the
process.
process.
"""
"""
from
__future__
import
print_function
import
sys
import
sys
import
os
import
os
import
errno
import
errno
...
@@ -29,10 +31,10 @@ def moduleIsModifiedSince(top, since, followlinks=False):
...
@@ -29,10 +31,10 @@ def moduleIsModifiedSince(top, since, followlinks=False):
if
ext
in
ignored_extension_set
:
if
ext
in
ignored_extension_set
:
continue
continue
if
since
<
os
.
stat
(
os
.
path
.
join
(
root
,
name
)).
st_mtime
:
if
since
<
os
.
stat
(
os
.
path
.
join
(
root
,
name
)).
st_mtime
:
print
"%s was modified since the process started."
%
\
print
(
"%s was modified since the process started."
%
\
os
.
path
.
join
(
root
,
name
)
os
.
path
.
join
(
root
,
name
)
)
print
"Process Time %s < Last modidified file %s"
%
(
time
.
ctime
(
since
),
print
(
"Process Time %s < Last modidified file %s"
%
(
time
.
ctime
(
since
),
time
.
ctime
(
os
.
stat
(
os
.
path
.
join
(
root
,
name
)).
st_mtime
))
time
.
ctime
(
os
.
stat
(
os
.
path
.
join
(
root
,
name
)).
st_mtime
))
)
return
True
return
True
return
False
return
False
...
@@ -41,7 +43,7 @@ def isProcessOlderThanDependencySet(pid, python_path_list, kill=False):
...
@@ -41,7 +43,7 @@ def isProcessOlderThanDependencySet(pid, python_path_list, kill=False):
start_time
=
process
.
create_time
()
start_time
=
process
.
create_time
()
if
any
(
moduleIsModifiedSince
(
product_path
,
start_time
)
for
product_path
in
python_path_list
):
if
any
(
moduleIsModifiedSince
(
product_path
,
start_time
)
for
product_path
in
python_path_list
):
if
kill
:
if
kill
:
print
"Terminating process %s with pid %s"
%
(
process
.
name
(),
pid
)
print
(
"Terminating process %s with pid %s"
%
(
process
.
name
(),
pid
)
)
process
.
terminate
()
process
.
terminate
()
return
True
return
True
return
False
return
False
...
...
slapos/pubsub/__init__.py
View file @
5ceae36b
import
argparse
import
argparse
import
csv
import
csv
import
feedparser
import
feedparser
import
httplib
# To avoid magic numbers
from
six.moves
import
http_client
as
httplib
# To avoid magic numbers
import
io
import
io
import
json
import
json
import
logging
import
logging
...
...
slapos/qemuqmpclient/__init__.py
View file @
5ceae36b
...
@@ -25,6 +25,8 @@
...
@@ -25,6 +25,8 @@
#
#
##############################################################################
##############################################################################
from
__future__
import
print_function
import
argparse
import
argparse
import
json
import
json
import
os
import
os
...
@@ -71,7 +73,7 @@ def getInitialQemuResourceDict(pid_file):
...
@@ -71,7 +73,7 @@ def getInitialQemuResourceDict(pid_file):
with
open
(
pid_file
)
as
f
:
with
open
(
pid_file
)
as
f
:
try
:
try
:
pid
=
int
(
f
.
read
())
pid
=
int
(
f
.
read
())
except
ValueError
,
e
:
except
ValueError
as
e
:
raise
ValueError
(
"%r is empty or doesn't contain a valid pid number: %s"
%
(
raise
ValueError
(
"%r is empty or doesn't contain a valid pid number: %s"
%
(
pid_file
,
str
(
e
)))
pid_file
,
str
(
e
)))
...
@@ -81,7 +83,7 @@ def getInitialQemuResourceDict(pid_file):
...
@@ -81,7 +83,7 @@ def getInitialQemuResourceDict(pid_file):
process
=
psutil
.
Process
(
pid
)
process
=
psutil
.
Process
(
pid
)
break
break
except
psutil
.
NoSuchProcess
:
except
psutil
.
NoSuchProcess
:
print
"Qemu process is not started yet..."
print
(
"Qemu process is not started yet..."
)
wait_count
-=
1
wait_count
-=
1
time
.
sleep
(
0.5
)
time
.
sleep
(
0.5
)
else
:
else
:
...
@@ -130,7 +132,7 @@ class QemuQMPWrapper(object):
...
@@ -130,7 +132,7 @@ class QemuQMPWrapper(object):
if
not
os
.
path
.
exists
(
unix_socket_location
):
if
not
os
.
path
.
exists
(
unix_socket_location
):
raise
Exception
(
'unix socket %s does not exist.'
%
unix_socket_location
)
raise
Exception
(
'unix socket %s does not exist.'
%
unix_socket_location
)
print
'Connecting to qemu...'
print
(
'Connecting to qemu...'
)
so
=
socket
.
socket
(
socket
.
AF_UNIX
,
socket
.
SOCK_STREAM
)
so
=
socket
.
socket
(
socket
.
AF_UNIX
,
socket
.
SOCK_STREAM
)
connected
=
False
connected
=
False
while
not
connected
:
while
not
connected
:
...
@@ -138,7 +140,7 @@ class QemuQMPWrapper(object):
...
@@ -138,7 +140,7 @@ class QemuQMPWrapper(object):
so
.
connect
(
unix_socket_location
)
so
.
connect
(
unix_socket_location
)
except
socket
.
error
:
except
socket
.
error
:
time
.
sleep
(
1
)
time
.
sleep
(
1
)
print
'Could not connect, retrying...'
print
(
'Could not connect, retrying...'
)
else
:
else
:
connected
=
True
connected
=
True
so
.
recv
(
1024
)
so
.
recv
(
1024
)
...
@@ -159,7 +161,7 @@ class QemuQMPWrapper(object):
...
@@ -159,7 +161,7 @@ class QemuQMPWrapper(object):
raise
QmpCommandError
(
response
[
"error"
][
"desc"
])
raise
QmpCommandError
(
response
[
"error"
][
"desc"
])
if
'event'
in
response
:
if
'event'
in
response
:
self
.
_event_list
.
append
(
response
)
self
.
_event_list
.
append
(
response
)
print
response
print
(
response
)
if
not
only_event
:
if
not
only_event
:
continue
continue
...
@@ -171,7 +173,7 @@ class QemuQMPWrapper(object):
...
@@ -171,7 +173,7 @@ class QemuQMPWrapper(object):
for
i
in
range
(
0
,
retry
):
for
i
in
range
(
0
,
retry
):
if
response
is
not
None
:
if
response
is
not
None
:
break
break
print
"Retrying send command after %s second(s)..."
%
sleep
print
(
"Retrying send command after %s second(s)..."
%
sleep
)
time
.
sleep
(
sleep
)
time
.
sleep
(
sleep
)
self
.
socket
.
sendall
(
json
.
dumps
(
message
))
self
.
socket
.
sendall
(
json
.
dumps
(
message
))
response
=
self
.
_readResponse
()
response
=
self
.
_readResponse
()
...
@@ -191,14 +193,14 @@ class QemuQMPWrapper(object):
...
@@ -191,14 +193,14 @@ class QemuQMPWrapper(object):
if
actual_status
==
wanted_status
:
if
actual_status
==
wanted_status
:
return
return
else
:
else
:
print
'VM in %s status, wanting it to be %s, retrying...'
%
(
print
(
'VM in %s status, wanting it to be %s, retrying...'
%
(
actual_status
,
wanted_status
)
actual_status
,
wanted_status
)
)
time
.
sleep
(
1
)
time
.
sleep
(
1
)
except
IOError
:
except
IOError
:
print
'VM not ready, retrying...'
print
(
'VM not ready, retrying...'
)
def
capabilities
(
self
):
def
capabilities
(
self
):
print
'Asking for capabilities...'
print
(
'Asking for capabilities...'
)
self
.
_send
({
'execute'
:
'qmp_capabilities'
})
self
.
_send
({
'execute'
:
'qmp_capabilities'
})
def
getEventList
(
self
,
timeout
=
0
,
cleanup
=
False
):
def
getEventList
(
self
,
timeout
=
0
,
cleanup
=
False
):
...
@@ -223,7 +225,7 @@ class QemuQMPWrapper(object):
...
@@ -223,7 +225,7 @@ class QemuQMPWrapper(object):
self
.
socket
.
setblocking
(
0
)
self
.
socket
.
setblocking
(
0
)
try
:
try
:
self
.
_readResponse
(
only_event
=
True
)
self
.
_readResponse
(
only_event
=
True
)
except
socket
.
error
,
err
:
except
socket
.
error
as
err
:
if
err
[
0
]
==
errno
.
EAGAIN
:
if
err
[
0
]
==
errno
.
EAGAIN
:
# No data available
# No data available
pass
pass
...
@@ -240,7 +242,7 @@ class QemuQMPWrapper(object):
...
@@ -240,7 +242,7 @@ class QemuQMPWrapper(object):
def
setVNCPassword
(
self
,
password
):
def
setVNCPassword
(
self
,
password
):
# Set VNC password
# Set VNC password
print
'Setting VNC password...'
print
(
'Setting VNC password...'
)
result
=
self
.
_send
({
result
=
self
.
_send
({
"execute"
:
"change"
,
"execute"
:
"change"
,
"arguments"
:
{
"arguments"
:
{
...
@@ -251,19 +253,19 @@ class QemuQMPWrapper(object):
...
@@ -251,19 +253,19 @@ class QemuQMPWrapper(object):
})
})
if
result
and
result
.
get
(
'return'
,
None
)
!=
{}:
if
result
and
result
.
get
(
'return'
,
None
)
!=
{}:
raise
ValueError
(
result
)
raise
ValueError
(
result
)
print
'Done.'
print
(
'Done.'
)
def
powerdown
(
self
):
def
powerdown
(
self
):
print
'Stopping the VM...'
print
(
'Stopping the VM...'
)
self
.
_send
({
'execute'
:
'system_powerdown'
})
self
.
_send
({
'execute'
:
'system_powerdown'
})
def
suspend
(
self
):
def
suspend
(
self
):
print
'Suspending VM...'
print
(
'Suspending VM...'
)
self
.
_send
({
'execute'
:
'stop'
})
self
.
_send
({
'execute'
:
'stop'
})
self
.
_waitForVMStatus
(
'paused'
)
self
.
_waitForVMStatus
(
'paused'
)
def
resume
(
self
):
def
resume
(
self
):
print
'Resuming VM...'
print
(
'Resuming VM...'
)
self
.
_send
({
'execute'
:
'cont'
})
self
.
_send
({
'execute'
:
'cont'
})
self
.
_waitForVMStatus
(
'running'
)
self
.
_waitForVMStatus
(
'running'
)
...
@@ -285,7 +287,7 @@ class QemuQMPWrapper(object):
...
@@ -285,7 +287,7 @@ class QemuQMPWrapper(object):
return
return
def
driveBackup
(
self
,
backup_target
,
source_device
=
'virtio0'
,
sync_type
=
'full'
):
def
driveBackup
(
self
,
backup_target
,
source_device
=
'virtio0'
,
sync_type
=
'full'
):
print
'Asking Qemu to perform backup to %s'
%
backup_target
print
(
'Asking Qemu to perform backup to %s'
%
backup_target
)
# XXX: check for error
# XXX: check for error
self
.
_send
({
self
.
_send
({
'execute'
:
'drive-backup'
,
'execute'
:
'drive-backup'
,
...
@@ -296,17 +298,17 @@ class QemuQMPWrapper(object):
...
@@ -296,17 +298,17 @@ class QemuQMPWrapper(object):
}
}
})
})
while
self
.
_getRunningJobList
(
backup_target
):
while
self
.
_getRunningJobList
(
backup_target
):
print
'Job is not finished yet.'
print
(
'Job is not finished yet.'
)
time
.
sleep
(
20
)
time
.
sleep
(
20
)
def
createSnapshot
(
self
,
snapshot_file
,
device
=
'virtio0'
):
def
createSnapshot
(
self
,
snapshot_file
,
device
=
'virtio0'
):
print
self
.
_send
({
print
(
self
.
_send
({
'execute'
:
'blockdev-snapshot-sync'
,
'execute'
:
'blockdev-snapshot-sync'
,
'arguments'
:
{
'arguments'
:
{
'device'
:
device
,
'device'
:
device
,
'snapshot-file'
:
snapshot_file
,
'snapshot-file'
:
snapshot_file
,
}
}
})
})
)
def
createInternalSnapshot
(
self
,
name
=
None
,
device
=
'virtio0'
):
def
createInternalSnapshot
(
self
,
name
=
None
,
device
=
'virtio0'
):
if
name
is
None
:
if
name
is
None
:
...
@@ -372,9 +374,9 @@ class QemuQMPWrapper(object):
...
@@ -372,9 +374,9 @@ class QemuQMPWrapper(object):
try
:
try
:
if
resend
:
if
resend
:
result
=
self
.
_send
(
command_dict
)
result
=
self
.
_send
(
command_dict
)
except
QmpCommandError
,
e
:
except
QmpCommandError
as
e
:
print
"ERROR: "
,
str
(
e
)
print
(
"ERROR: "
,
str
(
e
)
)
print
"%s
\
n
Retry remove %r in few seconds..."
%
(
result
,
dev_id
)
print
(
"%s
\
n
Retry remove %r in few seconds..."
%
(
result
,
dev_id
)
)
resend
=
True
resend
=
True
else
:
else
:
for
event
in
self
.
getEventList
(
timeout
=
2
,
cleanup
=
True
):
for
event
in
self
.
getEventList
(
timeout
=
2
,
cleanup
=
True
):
...
@@ -388,13 +390,13 @@ class QemuQMPWrapper(object):
...
@@ -388,13 +390,13 @@ class QemuQMPWrapper(object):
if
stop_retry
:
if
stop_retry
:
break
break
elif
result
is
None
and
max_retry
>
0
:
elif
result
is
None
and
max_retry
>
0
:
print
"Retry remove %r in few seconds..."
%
dev_id
print
(
"Retry remove %r in few seconds..."
%
dev_id
)
time
.
sleep
(
2
)
time
.
sleep
(
2
)
if
result
is
not
None
:
if
result
is
not
None
:
if
result
.
get
(
'return'
,
None
)
==
{}
or
(
'error'
in
result
and
\
if
result
.
get
(
'return'
,
None
)
==
{}
or
(
'error'
in
result
and
\
result
[
'error'
].
get
(
'class'
,
''
)
==
'DeviceNotFound'
):
result
[
'error'
].
get
(
'class'
,
''
)
==
'DeviceNotFound'
):
print
'Device %s was removed.'
%
dev_id
print
(
'Device %s was removed.'
%
dev_id
)
return
return
# device was not remove after retries
# device was not remove after retries
...
@@ -417,7 +419,7 @@ class QemuQMPWrapper(object):
...
@@ -417,7 +419,7 @@ class QemuQMPWrapper(object):
if
not
system_exited
:
if
not
system_exited
:
# hard reset the VM
# hard reset the VM
print
"Trying hard shutdown of the VM..."
print
(
"Trying hard shutdown of the VM..."
)
self
.
_send
({
"execute"
:
"quit"
})
self
.
_send
({
"execute"
:
"quit"
})
raise
QmpDeviceRemoveError
(
"Stopped Qemu in order to remove the device %r"
%
dev_id
)
raise
QmpDeviceRemoveError
(
"Stopped Qemu in order to remove the device %r"
%
dev_id
)
...
@@ -459,14 +461,14 @@ class QemuQMPWrapper(object):
...
@@ -459,14 +461,14 @@ class QemuQMPWrapper(object):
if
cpu_amount
==
hotplug_amount
:
if
cpu_amount
==
hotplug_amount
:
# no chanches
# no chanches
print
"Hotplug CPU is up to date."
print
(
"Hotplug CPU is up to date."
)
return
return
if
cpu_amount
>
hotplug_amount
:
if
cpu_amount
>
hotplug_amount
:
# we will remove CPU
# we will remove CPU
cpu_diff
=
-
1
*
cpu_diff
cpu_diff
=
-
1
*
cpu_diff
if
cpu_diff
>=
1
:
if
cpu_diff
>=
1
:
print
"Request remove %s CPUs..."
%
cpu_diff
print
(
"Request remove %s CPUs..."
%
cpu_diff
)
used_socket_id_list
.
reverse
()
used_socket_id_list
.
reverse
()
for
i
in
range
(
0
,
cpu_diff
):
for
i
in
range
(
0
,
cpu_diff
):
self
.
_removeDevice
(
used_socket_id_list
[
i
],
{
self
.
_removeDevice
(
used_socket_id_list
[
i
],
{
...
@@ -478,7 +480,7 @@ class QemuQMPWrapper(object):
...
@@ -478,7 +480,7 @@ class QemuQMPWrapper(object):
# no hotplugable cpu socket found for Add
# no hotplugable cpu socket found for Add
raise
ValueError
(
"Cannot Configure %s CPUs, the maximum amount of "
\
raise
ValueError
(
"Cannot Configure %s CPUs, the maximum amount of "
\
"hotplugable CPU is %s!"
%
(
hotplug_amount
,
max_hotplug_cpu
))
"hotplugable CPU is %s!"
%
(
hotplug_amount
,
max_hotplug_cpu
))
print
"Adding %s CPUs..."
%
cpu_diff
print
(
"Adding %s CPUs..."
%
cpu_diff
)
for
i
in
range
(
0
,
cpu_diff
):
for
i
in
range
(
0
,
cpu_diff
):
self
.
_send
({
self
.
_send
({
'execute'
:
'device_add'
,
'execute'
:
'device_add'
,
...
@@ -491,10 +493,10 @@ class QemuQMPWrapper(object):
...
@@ -491,10 +493,10 @@ class QemuQMPWrapper(object):
if
hotplug_amount
!=
final_cpu_count
:
if
hotplug_amount
!=
final_cpu_count
:
raise
ValueError
(
"Consistency error: Expected %s hotplugged CPU(s) but"
\
raise
ValueError
(
"Consistency error: Expected %s hotplugged CPU(s) but"
\
" current CPU amount is %s"
%
(
hotplug_amount
,
final_cpu_count
))
" current CPU amount is %s"
%
(
hotplug_amount
,
final_cpu_count
))
print
"Done."
print
(
"Done."
)
def
_removeMemory
(
self
,
id_dict
,
auto_reboot
=
False
):
def
_removeMemory
(
self
,
id_dict
,
auto_reboot
=
False
):
print
"Trying to remove devices %s, %s..."
%
(
id_dict
[
'id'
],
id_dict
[
'memdev'
]
)
print
(
"Trying to remove devices %s, %s..."
%
(
id_dict
[
'id'
],
id_dict
[
'memdev'
])
)
self
.
_removeDevice
(
id_dict
[
'id'
]
,{
self
.
_removeDevice
(
id_dict
[
'id'
]
,{
'execute'
:
'device_del'
,
'execute'
:
'device_del'
,
'arguments'
:
{
'id'
:
id_dict
[
'id'
]}
'arguments'
:
{
'id'
:
id_dict
[
'id'
]}
...
@@ -544,7 +546,7 @@ class QemuQMPWrapper(object):
...
@@ -544,7 +546,7 @@ class QemuQMPWrapper(object):
# cleanup memdev that was not removed because of failure
# cleanup memdev that was not removed because of failure
for
memdev
in
cleanup_memdev_id_dict
.
keys
():
for
memdev
in
cleanup_memdev_id_dict
.
keys
():
print
"Cleaning up memdev %s..."
%
memdev
print
(
"Cleaning up memdev %s..."
%
memdev
)
self
.
_removeDevice
(
memdev
,
{
self
.
_removeDevice
(
memdev
,
{
'execute'
:
'object-del'
,
'execute'
:
'object-del'
,
'arguments'
:
{
'arguments'
:
{
...
@@ -559,9 +561,9 @@ class QemuQMPWrapper(object):
...
@@ -559,9 +561,9 @@ class QemuQMPWrapper(object):
if
(
mem_size
/
slot_size
)
>
slot_amount
:
if
(
mem_size
/
slot_size
)
>
slot_amount
:
raise
ValueError
(
"No enough slots available to add %sMB of RAM"
%
mem_size
)
raise
ValueError
(
"No enough slots available to add %sMB of RAM"
%
mem_size
)
current_size
=
current_size
/
(
1024
*
1024
)
current_size
=
current_size
//
(
1024
*
1024
)
if
current_size
==
mem_size
:
if
current_size
==
mem_size
:
print
"Hotplug Memory size is up to date."
print
(
"Hotplug Memory size is up to date."
)
return
return
if
mem_size
<
0
:
if
mem_size
<
0
:
...
@@ -569,7 +571,7 @@ class QemuQMPWrapper(object):
...
@@ -569,7 +571,7 @@ class QemuQMPWrapper(object):
elif
current_size
>
mem_size
:
elif
current_size
>
mem_size
:
# Request to remove memory
# Request to remove memory
to_remove_size
=
current_size
-
mem_size
to_remove_size
=
current_size
-
mem_size
print
"Removing %s MB of memory..."
%
to_remove_size
print
(
"Removing %s MB of memory..."
%
to_remove_size
)
for
i
in
range
(
num_slot_used
,
0
,
-
1
):
for
i
in
range
(
num_slot_used
,
0
,
-
1
):
# remove all slots that won't be used
# remove all slots that won't be used
...
@@ -587,9 +589,9 @@ class QemuQMPWrapper(object):
...
@@ -587,9 +589,9 @@ class QemuQMPWrapper(object):
)
)
elif
current_size
<
mem_size
:
elif
current_size
<
mem_size
:
# ask for increase memory
# ask for increase memory
slot_add
=
(
mem_size
-
current_size
)
/
slot_size
slot_add
=
(
mem_size
-
current_size
)
/
/
slot_size
print
"Adding %s memory slot(s) of %s MB..."
%
(
slot_add
,
slot_size
)
print
(
"Adding %s memory slot(s) of %s MB..."
%
(
slot_add
,
slot_size
)
)
for
i
in
range
(
0
,
slot_add
):
for
i
in
range
(
0
,
slot_add
):
index
=
num_slot_used
+
i
+
1
index
=
num_slot_used
+
i
+
1
self
.
_send
({
self
.
_send
({
...
@@ -618,11 +620,11 @@ class QemuQMPWrapper(object):
...
@@ -618,11 +620,11 @@ class QemuQMPWrapper(object):
if
mem_size
!=
final_mem_size
:
if
mem_size
!=
final_mem_size
:
raise
ValueError
(
"Consistency error: Expected %s MB of hotplugged RAM "
\
raise
ValueError
(
"Consistency error: Expected %s MB of hotplugged RAM "
\
"but current RAM size is %s MB"
%
(
mem_size
,
final_mem_size
))
"but current RAM size is %s MB"
%
(
mem_size
,
final_mem_size
))
print
"Done."
print
(
"Done."
)
def
updateDevice
(
self
,
option_dict
):
def
updateDevice
(
self
,
option_dict
):
argument_dict
=
{}
argument_dict
=
{}
if
option_dict
.
has_key
(
'device'
)
:
if
'device'
in
option_dict
:
if
option_dict
[
'device'
]
==
'cpu'
:
if
option_dict
[
'device'
]
==
'cpu'
:
return
self
.
_updateCPU
(
return
self
.
_updateCPU
(
amount
=
int
(
option_dict
[
'amount'
]),
amount
=
int
(
option_dict
[
'amount'
]),
...
...
slapos/runner/sup_process.py
View file @
5ceae36b
...
@@ -3,7 +3,7 @@
...
@@ -3,7 +3,7 @@
import
os
import
os
import
signal
import
signal
import
time
import
time
import
xmlrpclib
import
six.moves.xmlrpc_client
as
xmlrpclib
# This mini-library is used to communicate with supervisord process
# This mini-library is used to communicate with supervisord process
# It aims to replace the file "process.py"
# It aims to replace the file "process.py"
...
...
slapos/runner/utils.py
View file @
5ceae36b
...
@@ -2,20 +2,20 @@
...
@@ -2,20 +2,20 @@
# vim: set et sts=2:
# vim: set et sts=2:
# pylint: disable-msg=W0311,C0301,C0103,C0111,W0141,W0142
# pylint: disable-msg=W0311,C0301,C0103,C0111,W0141,W0142
import
ConfigP
arser
from
six.moves
import
configp
arser
import
datetime
import
datetime
import
json
import
json
import
logging
import
logging
import
md5
import
hashlib
import
os
import
os
import
sup_process
from
.
import
sup_process
import
re
import
re
import
shutil
import
shutil
import
stat
import
stat
import
thread
from
six.moves
import
_
thread
import
time
import
time
import
urllib
import
urllib
import
xmlrpclib
import
six.moves.xmlrpc_client
as
xmlrpclib
from
xml.dom
import
minidom
from
xml.dom
import
minidom
import
xml_marshaller
import
xml_marshaller
...
@@ -92,11 +92,11 @@ def updateUserCredential(config, username, password):
...
@@ -92,11 +92,11 @@ def updateUserCredential(config, username, password):
def
getRcode
(
config
):
def
getRcode
(
config
):
parser
=
ConfigP
arser
.
ConfigParser
()
parser
=
configp
arser
.
ConfigParser
()
try
:
try
:
parser
.
read
(
config
[
'knowledge0_cfg'
])
parser
.
read
(
config
[
'knowledge0_cfg'
])
return
parser
.
get
(
'public'
,
'recovery-code'
)
return
parser
.
get
(
'public'
,
'recovery-code'
)
except
(
ConfigP
arser
.
NoSectionError
,
IOError
)
as
e
:
except
(
configp
arser
.
NoSectionError
,
IOError
)
as
e
:
return
None
return
None
def
getUsernameList
(
config
):
def
getUsernameList
(
config
):
...
@@ -193,7 +193,7 @@ def updateProxy(config):
...
@@ -193,7 +193,7 @@ def updateProxy(config):
partition_path
=
os
.
path
.
join
(
config
[
'instance_root'
],
partition_reference
)
partition_path
=
os
.
path
.
join
(
config
[
'instance_root'
],
partition_reference
)
if
not
os
.
path
.
exists
(
partition_path
):
if
not
os
.
path
.
exists
(
partition_path
):
os
.
mkdir
(
partition_path
)
os
.
mkdir
(
partition_path
)
os
.
chmod
(
partition_path
,
0750
)
os
.
chmod
(
partition_path
,
0
o
750
)
slap_config
[
'partition_list'
].
append
({
slap_config
[
'partition_list'
].
append
({
'address_list'
:
[
'address_list'
:
[
{
{
...
@@ -461,7 +461,7 @@ def removeInstanceRootDirectory(config):
...
@@ -461,7 +461,7 @@ def removeInstanceRootDirectory(config):
fullPath
=
os
.
path
.
join
(
root
,
fname
)
fullPath
=
os
.
path
.
join
(
root
,
fname
)
if
not
os
.
access
(
fullPath
,
os
.
W_OK
):
if
not
os
.
access
(
fullPath
,
os
.
W_OK
):
# Some directories may be read-only, preventing to remove files in it
# Some directories may be read-only, preventing to remove files in it
os
.
chmod
(
fullPath
,
0744
)
os
.
chmod
(
fullPath
,
0
o
744
)
shutil
.
rmtree
(
instance_directory
)
shutil
.
rmtree
(
instance_directory
)
def
removeCurrentInstance
(
config
):
def
removeCurrentInstance
(
config
):
...
@@ -775,7 +775,7 @@ def md5sum(file):
...
@@ -775,7 +775,7 @@ def md5sum(file):
return False
return False
try:
try:
fh = open(file, 'rb')
fh = open(file, 'rb')
m =
md5
.md5()
m =
hashlib
.md5()
while True:
while True:
data = fh.read(8192)
data = fh.read(8192)
if not data:
if not data:
...
@@ -828,7 +828,7 @@ def readParameters(path):
...
@@ -828,7 +828,7 @@ def readParameters(path):
sub_obj[str(subnode.getAttribute('
id
'))] = subnode.childNodes[0].data # .decode('
utf
-
8
').decode('
utf
-
8
')
sub_obj[str(subnode.getAttribute('
id
'))] = subnode.childNodes[0].data # .decode('
utf
-
8
').decode('
utf
-
8
')
obj[str(elt.tagName)] = sub_obj
obj[str(elt.tagName)] = sub_obj
return obj
return obj
except Exception
,
e:
except Exception
as
e:
return str(e)
return str(e)
else:
else:
return "No such file or directory: %s" % path
return "No such file or directory: %s" % path
...
@@ -932,7 +932,7 @@ def setupDefaultSR(config):
...
@@ -932,7 +932,7 @@ def setupDefaultSR(config):
if not os.path.exists(project) and config['
default_sr
'] != '':
if not os.path.exists(project) and config['
default_sr
'] != '':
configNewSR(config, config['
default_sr
'])
configNewSR(config, config['
default_sr
'])
if config['
auto_deploy
']:
if config['
auto_deploy
']:
thread.start_new_thread(buildAndRun, (config,))
_
thread.start_new_thread(buildAndRun, (config,))
def setMiniShellHistory(config, command):
def setMiniShellHistory(config, command):
...
...
slapos/securedelete.py
View file @
5ceae36b
...
@@ -24,6 +24,8 @@
...
@@ -24,6 +24,8 @@
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
#
#
##############################################################################
##############################################################################
from
__future__
import
print_function
import
os
import
os
import
argparse
import
argparse
import
subprocess
import
subprocess
...
@@ -108,4 +110,4 @@ def shred(options):
...
@@ -108,4 +110,4 @@ def shred(options):
def
main
():
def
main
():
arg_parser
=
getAgumentParser
()
arg_parser
=
getAgumentParser
()
output
=
shred
(
arg_parser
.
parse_args
())
output
=
shred
(
arg_parser
.
parse_args
())
print
output
print
(
output
)
slapos/systool.py
View file @
5ceae36b
from
__future__
import
print_function
import
argparse
import
argparse
import
sys
import
sys
import
os
import
os
...
@@ -12,7 +14,7 @@ def killpidfromfile():
...
@@ -12,7 +14,7 @@ def killpidfromfile():
if
sig
is
None
:
if
sig
is
None
:
raise
ValueError
(
'Unknown signal name %s'
%
sys
.
argv
[
2
])
raise
ValueError
(
'Unknown signal name %s'
%
sys
.
argv
[
2
])
pid
=
int
(
open
(
file
).
read
())
pid
=
int
(
open
(
file
).
read
())
print
'Killing pid %s with signal %s'
%
(
pid
,
sys
.
argv
[
2
]
)
print
(
'Killing pid %s with signal %s'
%
(
pid
,
sys
.
argv
[
2
])
)
os
.
kill
(
pid
,
sig
)
os
.
kill
(
pid
,
sig
)
def
sublist
(
a
,
b
):
def
sublist
(
a
,
b
):
...
@@ -63,7 +65,7 @@ def kill():
...
@@ -63,7 +65,7 @@ def kill():
cmdline
=
p
.
cmdline
()
cmdline
=
p
.
cmdline
()
if
cmdline
==
args
.
arg
if
args
.
full
else
sublist
(
cmdline
,
args
.
arg
):
if
cmdline
==
args
.
arg
if
args
.
full
else
sublist
(
cmdline
,
args
.
arg
):
p
.
send_signal
(
s
)
p
.
send_signal
(
s
)
print
'killed pid %s with signal %s'
%
(
p
.
pid
,
args
.
signal
)
print
(
'killed pid %s with signal %s'
%
(
p
.
pid
,
args
.
signal
)
)
r
=
0
r
=
0
except
psutil
.
Error
:
except
psutil
.
Error
:
pass
pass
...
...
slapos/test/monitor/test_config_document.py
View file @
5ceae36b
...
@@ -78,7 +78,7 @@ echo "htpasswd $@" > %s/monitor-htpasswd
...
@@ -78,7 +78,7 @@ echo "htpasswd $@" > %s/monitor-htpasswd
self
.
writeContent
(
self
.
monitor_https_cors
,
'{% set allow_domain = "|".join(domain.replace(".", "
\
.
"
).split()) -%}
\
n
'
self
.
writeContent
(
self
.
monitor_https_cors
,
'{% set allow_domain = "|".join(domain.replace(".", "
\
.
"
).split()) -%}
\
n
'
'SetEnvIf Origin "^http(s)?://(.+
\
.)?({{
a
llow_domain }})$" ORIGIN_DOMAIN=$0
\
n
'
'SetEnvIf Origin "^http(s)?://(.+
\
.)?({{
a
llow_domain }})$" ORIGIN_DOMAIN=$0
\
n
'
'Header always set Access-Control-Allow-Origin "%{ORIGIN_DOMAIN}e" env=ORIGIN_DOMAIN'
)
'Header always set Access-Control-Allow-Origin "%{ORIGIN_DOMAIN}e" env=ORIGIN_DOMAIN'
)
os
.
chmod
(
self
.
httpd_passwd_bin
,
0755
)
os
.
chmod
(
self
.
httpd_passwd_bin
,
0
o
755
)
def
tearDown
(
self
):
def
tearDown
(
self
):
if
os
.
path
.
exists
(
self
.
base_dir
):
if
os
.
path
.
exists
(
self
.
base_dir
):
...
@@ -106,7 +106,7 @@ echo "htpasswd $@" > %s/monitor-htpasswd
...
@@ -106,7 +106,7 @@ echo "htpasswd $@" > %s/monitor-htpasswd
for
config
in
config_json
:
for
config
in
config_json
:
if
config
[
"key"
]:
if
config
[
"key"
]:
self
.
assertTrue
(
config
_parameter_json
.
has_key
(
config
[
"key"
])
)
self
.
assertTrue
(
config
[
"key"
]
in
config_parameter_json
)
parameter
=
config_parameter_json
[
config
[
"key"
]]
parameter
=
config_parameter_json
[
config
[
"key"
]]
else
:
else
:
continue
continue
...
...
slapos/test/monitor/testbootstrap.py
View file @
5ceae36b
...
@@ -102,11 +102,11 @@ partition-folder = %(base_dir)s
...
@@ -102,11 +102,11 @@ partition-folder = %(base_dir)s
for
index
in
range
(
1
,
amount
+
1
):
for
index
in
range
(
1
,
amount
+
1
):
promise_file
=
os
.
path
.
join
(
promise_dir
,
'monitor_promise-%s'
%
index
)
promise_file
=
os
.
path
.
join
(
promise_dir
,
'monitor_promise-%s'
%
index
)
self
.
writeContent
(
promise_file
,
promse_content
)
self
.
writeContent
(
promise_file
,
promse_content
)
os
.
chmod
(
promise_file
,
0755
)
os
.
chmod
(
promise_file
,
0
o
755
)
for
index
in
range
(
1
,
amount
+
1
):
for
index
in
range
(
1
,
amount
+
1
):
promise_file
=
os
.
path
.
join
(
plugin_dir
,
'monitor_promise-%s.py'
%
index
)
promise_file
=
os
.
path
.
join
(
plugin_dir
,
'monitor_promise-%s.py'
%
index
)
self
.
writeContent
(
promise_file
,
promse_content
)
self
.
writeContent
(
promise_file
,
promse_content
)
os
.
chmod
(
promise_file
,
0644
)
os
.
chmod
(
promise_file
,
0
o
644
)
def
checkOPML
(
self
,
url_list
):
def
checkOPML
(
self
,
url_list
):
opml_title
=
"<title>%(root_title)s</title>"
%
self
.
monitor_config_dict
opml_title
=
"<title>%(root_title)s</title>"
%
self
.
monitor_config_dict
...
...
slapos/test/monitor/testglobalstate.py
View file @
5ceae36b
...
@@ -44,7 +44,7 @@ class MonitorGlobalTest(unittest.TestCase):
...
@@ -44,7 +44,7 @@ class MonitorGlobalTest(unittest.TestCase):
pkg_resources
.
resource_string
(
pkg_resources
.
resource_string
(
'slapos.monitor'
,
'slapos.monitor'
,
'doc/monitor_instance.schema.json'
)
'doc/monitor_instance.schema.json'
)
self
.
monitor_instance_schema
=
json
.
loads
(
monitor_schema_string
)
self
.
monitor_instance_schema
=
json
.
loads
(
monitor_schema_string
.
decode
(
'utf-8'
)
)
self
.
monitor_config_dict
=
dict
(
self
.
monitor_config_dict
=
dict
(
...
@@ -132,7 +132,7 @@ exit %(code)s
...
@@ -132,7 +132,7 @@ exit %(code)s
"""
%
result_dict
"""
%
result_dict
promise_path
=
os
.
path
.
join
(
self
.
etc_dir
,
'promise'
,
name
)
promise_path
=
os
.
path
.
join
(
self
.
etc_dir
,
'promise'
,
name
)
self
.
writeContent
(
promise_path
,
content
)
self
.
writeContent
(
promise_path
,
content
)
os
.
chmod
(
promise_path
,
0755
)
os
.
chmod
(
promise_path
,
0
o
755
)
return
promise_path
return
promise_path
def
getPromiseParser
(
self
):
def
getPromiseParser
(
self
):
...
...
slapos/test/monitor/testrunpromise.py
View file @
5ceae36b
...
@@ -69,7 +69,7 @@ exit 0
...
@@ -69,7 +69,7 @@ exit 0
"""
"""
promise_path
=
os
.
path
.
join
(
self
.
old_promise_dir
,
name
)
promise_path
=
os
.
path
.
join
(
self
.
old_promise_dir
,
name
)
self
.
writeContent
(
promise_path
,
content
)
self
.
writeContent
(
promise_path
,
content
)
os
.
chmod
(
promise_path
,
0755
)
os
.
chmod
(
promise_path
,
0
o
755
)
return
promise_path
return
promise_path
def
writePromiseNOK
(
self
,
name
):
def
writePromiseNOK
(
self
,
name
):
...
@@ -80,7 +80,7 @@ exit 2
...
@@ -80,7 +80,7 @@ exit 2
"""
"""
promise_path
=
os
.
path
.
join
(
self
.
old_promise_dir
,
name
)
promise_path
=
os
.
path
.
join
(
self
.
old_promise_dir
,
name
)
self
.
writeContent
(
promise_path
,
content
)
self
.
writeContent
(
promise_path
,
content
)
os
.
chmod
(
promise_path
,
0755
)
os
.
chmod
(
promise_path
,
0
o
755
)
return
promise_path
return
promise_path
def
generatePromiseScript
(
self
,
name
,
success
=
True
,
failure_count
=
1
,
content
=
""
,
def
generatePromiseScript
(
self
,
name
,
success
=
True
,
failure_count
=
1
,
content
=
""
,
...
@@ -151,7 +151,7 @@ class RunPromise(GenericPromise):
...
@@ -151,7 +151,7 @@ class RunPromise(GenericPromise):
result_file
=
os
.
path
.
join
(
self
.
output_dir
,
'my_promise.status.json'
)
result_file
=
os
.
path
.
join
(
self
.
output_dir
,
'my_promise.status.json'
)
os
.
system
(
'cat %s'
%
result_file
)
os
.
system
(
'cat %s'
%
result_file
)
self
.
assertTrue
(
os
.
path
.
exists
(
result_file
))
self
.
assertTrue
(
os
.
path
.
exists
(
result_file
))
my_result
=
json
.
load
s
(
open
(
result_file
).
read
().
decode
(
"utf-8"
))
my_result
=
json
.
load
(
open
(
result_file
))
my_result
[
'result'
].
pop
(
'date'
)
my_result
[
'result'
].
pop
(
'date'
)
expected_result
=
{
expected_result
=
{
u'title'
:
u'my_promise'
,
u'name'
:
u'my_promise.py'
,
u'title'
:
u'my_promise'
,
u'name'
:
u'my_promise.py'
,
...
@@ -165,7 +165,7 @@ class RunPromise(GenericPromise):
...
@@ -165,7 +165,7 @@ class RunPromise(GenericPromise):
result_file
=
os
.
path
.
join
(
self
.
output_dir
,
'my_second_promise.status.json'
)
result_file
=
os
.
path
.
join
(
self
.
output_dir
,
'my_second_promise.status.json'
)
self
.
assertTrue
(
os
.
path
.
exists
(
result_file
))
self
.
assertTrue
(
os
.
path
.
exists
(
result_file
))
second_result
=
json
.
load
s
(
open
(
result_file
).
read
().
decode
(
"utf-8"
))
second_result
=
json
.
load
(
open
(
result_file
))
second_result
[
'result'
].
pop
(
'date'
)
second_result
[
'result'
].
pop
(
'date'
)
expected_result
=
{
expected_result
=
{
...
@@ -186,7 +186,7 @@ class RunPromise(GenericPromise):
...
@@ -186,7 +186,7 @@ class RunPromise(GenericPromise):
result_file
=
os
.
path
.
join
(
self
.
output_dir
,
'my_promise.status.json'
)
result_file
=
os
.
path
.
join
(
self
.
output_dir
,
'my_promise.status.json'
)
self
.
assertTrue
(
os
.
path
.
exists
(
result_file
))
self
.
assertTrue
(
os
.
path
.
exists
(
result_file
))
my_result
=
json
.
load
s
(
open
(
result_file
).
read
().
decode
(
"utf-8"
))
my_result
=
json
.
load
(
open
(
result_file
))
my_result
[
'result'
].
pop
(
'date'
)
my_result
[
'result'
].
pop
(
'date'
)
expected_result
=
{
expected_result
=
{
...
@@ -207,7 +207,7 @@ class RunPromise(GenericPromise):
...
@@ -207,7 +207,7 @@ class RunPromise(GenericPromise):
result_file
=
os
.
path
.
join
(
self
.
output_dir
,
'my_promise.status.json'
)
result_file
=
os
.
path
.
join
(
self
.
output_dir
,
'my_promise.status.json'
)
self
.
assertTrue
(
os
.
path
.
exists
(
result_file
))
self
.
assertTrue
(
os
.
path
.
exists
(
result_file
))
my_result
=
json
.
load
s
(
open
(
result_file
).
read
().
decode
(
"utf-8"
))
my_result
=
json
.
load
(
open
(
result_file
))
my_result
[
'result'
].
pop
(
'date'
)
my_result
[
'result'
].
pop
(
'date'
)
expected_result
=
{
expected_result
=
{
...
@@ -226,7 +226,7 @@ class RunPromise(GenericPromise):
...
@@ -226,7 +226,7 @@ class RunPromise(GenericPromise):
promise_runner2
=
MonitorPromiseLauncher
(
parser
)
promise_runner2
=
MonitorPromiseLauncher
(
parser
)
promise_runner2
.
start
()
promise_runner2
.
start
()
my_result
=
json
.
load
s
(
open
(
result_file
).
read
().
decode
(
"utf-8"
))
my_result
=
json
.
load
(
open
(
result_file
))
my_result
[
'result'
].
pop
(
'date'
)
my_result
[
'result'
].
pop
(
'date'
)
expected_result
=
{
expected_result
=
{
...
@@ -287,7 +287,7 @@ class RunPromise(GenericPromise):
...
@@ -287,7 +287,7 @@ class RunPromise(GenericPromise):
result_file
=
os
.
path
.
join
(
self
.
output_dir
,
'promise_1.status.json'
)
result_file
=
os
.
path
.
join
(
self
.
output_dir
,
'promise_1.status.json'
)
self
.
assertTrue
(
os
.
path
.
exists
(
result_file
))
self
.
assertTrue
(
os
.
path
.
exists
(
result_file
))
result1
=
json
.
load
s
(
open
(
result_file
).
read
().
decode
(
"utf-8"
))
result1
=
json
.
load
(
open
(
result_file
))
start_date
=
datetime
.
strptime
(
result1
[
'result'
].
pop
(
'date'
),
'%Y-%m-%dT%H:%M:%S'
)
start_date
=
datetime
.
strptime
(
result1
[
'result'
].
pop
(
'date'
),
'%Y-%m-%dT%H:%M:%S'
)
expected_result
=
{
expected_result
=
{
...
@@ -303,7 +303,7 @@ class RunPromise(GenericPromise):
...
@@ -303,7 +303,7 @@ class RunPromise(GenericPromise):
parser
=
self
.
getPromiseParser
(
force
=
True
)
parser
=
self
.
getPromiseParser
(
force
=
True
)
promise_runner
=
MonitorPromiseLauncher
(
parser
)
promise_runner
=
MonitorPromiseLauncher
(
parser
)
promise_runner
.
start
()
promise_runner
.
start
()
result2
=
json
.
load
s
(
open
(
result_file
).
read
().
decode
(
"utf-8"
))
result2
=
json
.
load
(
open
(
result_file
))
start_date2
=
datetime
.
strptime
(
result2
[
'result'
].
pop
(
'date'
),
'%Y-%m-%dT%H:%M:%S'
)
start_date2
=
datetime
.
strptime
(
result2
[
'result'
].
pop
(
'date'
),
'%Y-%m-%dT%H:%M:%S'
)
self
.
assertEquals
(
expected_result
,
result2
)
self
.
assertEquals
(
expected_result
,
result2
)
...
@@ -319,7 +319,7 @@ class RunPromise(GenericPromise):
...
@@ -319,7 +319,7 @@ class RunPromise(GenericPromise):
result2_file
=
os
.
path
.
join
(
self
.
output_dir
,
'promise_2.status.json'
)
result2_file
=
os
.
path
.
join
(
self
.
output_dir
,
'promise_2.status.json'
)
self
.
assertTrue
(
os
.
path
.
exists
(
result_file
))
self
.
assertTrue
(
os
.
path
.
exists
(
result_file
))
self
.
assertTrue
(
os
.
path
.
exists
(
result2_file
))
self
.
assertTrue
(
os
.
path
.
exists
(
result2_file
))
result1
=
json
.
load
s
(
open
(
result_file
).
read
().
decode
(
"utf-8"
))
result1
=
json
.
load
(
open
(
result_file
))
start_date
=
datetime
.
strptime
(
result1
[
'result'
].
pop
(
'date'
),
'%Y-%m-%dT%H:%M:%S'
)
start_date
=
datetime
.
strptime
(
result1
[
'result'
].
pop
(
'date'
),
'%Y-%m-%dT%H:%M:%S'
)
expected_result
=
{
expected_result
=
{
...
@@ -332,7 +332,7 @@ class RunPromise(GenericPromise):
...
@@ -332,7 +332,7 @@ class RunPromise(GenericPromise):
}
}
self
.
assertEquals
(
expected_result
,
result1
)
self
.
assertEquals
(
expected_result
,
result1
)
result2
=
json
.
load
s
(
open
(
result2_file
).
read
(
))
result2
=
json
.
load
(
open
(
result_file
))
start_date2
=
datetime
.
strptime
(
result2
[
'result'
].
pop
(
'date'
),
'%Y-%m-%dT%H:%M:%S'
)
start_date2
=
datetime
.
strptime
(
result2
[
'result'
].
pop
(
'date'
),
'%Y-%m-%dT%H:%M:%S'
)
expected_result
=
{
expected_result
=
{
...
@@ -353,7 +353,7 @@ class RunPromise(GenericPromise):
...
@@ -353,7 +353,7 @@ class RunPromise(GenericPromise):
result_file
=
os
.
path
.
join
(
self
.
output_dir
,
'promise_1.status.json'
)
result_file
=
os
.
path
.
join
(
self
.
output_dir
,
'promise_1.status.json'
)
self
.
assertTrue
(
os
.
path
.
exists
(
result_file
))
self
.
assertTrue
(
os
.
path
.
exists
(
result_file
))
result1
=
json
.
load
s
(
open
(
result_file
).
read
().
decode
(
"utf-8"
))
result1
=
json
.
load
(
open
(
result_file
))
result1
[
'result'
].
pop
(
'date'
)
result1
[
'result'
].
pop
(
'date'
)
expected_result
=
{
expected_result
=
{
u'title'
:
u'promise_1'
,
u'name'
:
u'promise_1'
,
u'title'
:
u'promise_1'
,
u'name'
:
u'promise_1'
,
...
@@ -368,7 +368,7 @@ class RunPromise(GenericPromise):
...
@@ -368,7 +368,7 @@ class RunPromise(GenericPromise):
# second run
# second run
promise_runner
=
MonitorPromiseLauncher
(
parser
)
promise_runner
=
MonitorPromiseLauncher
(
parser
)
promise_runner
.
start
()
promise_runner
.
start
()
result2
=
json
.
load
s
(
open
(
result_file
).
read
().
decode
(
"utf-8"
))
result2
=
json
.
load
(
open
(
result_file
))
result2
[
'result'
].
pop
(
'date'
)
result2
[
'result'
].
pop
(
'date'
)
self
.
assertEquals
(
expected_result
,
result2
)
self
.
assertEquals
(
expected_result
,
result2
)
...
@@ -380,7 +380,7 @@ class RunPromise(GenericPromise):
...
@@ -380,7 +380,7 @@ class RunPromise(GenericPromise):
result_file
=
os
.
path
.
join
(
self
.
output_dir
,
'promise_1.status.json'
)
result_file
=
os
.
path
.
join
(
self
.
output_dir
,
'promise_1.status.json'
)
self
.
assertTrue
(
os
.
path
.
exists
(
result_file
))
self
.
assertTrue
(
os
.
path
.
exists
(
result_file
))
result1
=
json
.
load
s
(
open
(
result_file
).
read
().
decode
(
"utf-8"
))
result1
=
json
.
load
(
open
(
result_file
))
result1
[
'result'
].
pop
(
'date'
)
result1
[
'result'
].
pop
(
'date'
)
expected_result
=
{
expected_result
=
{
u'title'
:
u'promise_1'
,
u'name'
:
u'promise_1'
,
u'title'
:
u'promise_1'
,
u'name'
:
u'promise_1'
,
...
@@ -401,7 +401,7 @@ class RunPromise(GenericPromise):
...
@@ -401,7 +401,7 @@ class RunPromise(GenericPromise):
promise_runner
=
MonitorPromiseLauncher
(
parser
)
promise_runner
=
MonitorPromiseLauncher
(
parser
)
promise_runner
.
start
()
promise_runner
.
start
()
result2
=
json
.
load
s
(
open
(
result_file
).
read
().
decode
(
"utf-8"
))
result2
=
json
.
load
(
open
(
result_file
))
result2
[
'result'
].
pop
(
'date'
)
result2
[
'result'
].
pop
(
'date'
)
self
.
assertEquals
(
expected_result
,
result2
)
self
.
assertEquals
(
expected_result
,
result2
)
slapos/test/test_qemuqmpclient.py
View file @
5ceae36b
...
@@ -140,7 +140,7 @@ class TestQemuQMPWrapper(unittest.TestCase):
...
@@ -140,7 +140,7 @@ class TestQemuQMPWrapper(unittest.TestCase):
elif
message
[
'execute'
]
==
'query-memory-devices'
:
elif
message
[
'execute'
]
==
'query-memory-devices'
:
memory_list
=
[]
memory_list
=
[]
added_mem
=
self
.
readChange
(
'dimm'
)
+
self
.
hotplugged_memory_amount
added_mem
=
self
.
readChange
(
'dimm'
)
+
self
.
hotplugged_memory_amount
slot_amount
=
added_mem
/
self
.
memory_slot_size
slot_amount
=
added_mem
/
/
self
.
memory_slot_size
for
i
in
range
(
slot_amount
,
0
,
-
1
):
for
i
in
range
(
slot_amount
,
0
,
-
1
):
memory_list
.
append
({
memory_list
.
append
({
u'data'
:
{
u'data'
:
{
...
@@ -159,7 +159,7 @@ class TestQemuQMPWrapper(unittest.TestCase):
...
@@ -159,7 +159,7 @@ class TestQemuQMPWrapper(unittest.TestCase):
elif
message
[
'execute'
]
==
'query-memdev'
:
elif
message
[
'execute'
]
==
'query-memdev'
:
memory_list
=
[]
memory_list
=
[]
added_mem
=
self
.
readChange
(
'dimm'
)
+
self
.
hotplugged_memory_amount
added_mem
=
self
.
readChange
(
'dimm'
)
+
self
.
hotplugged_memory_amount
slot_amount
=
added_mem
/
self
.
memory_slot_size
slot_amount
=
added_mem
/
/
self
.
memory_slot_size
for
i
in
range
(
slot_amount
,
0
,
-
1
):
for
i
in
range
(
slot_amount
,
0
,
-
1
):
memory_list
.
append
({
memory_list
.
append
({
u'dump'
:
True
,
u'dump'
:
True
,
...
...
slapos/test/test_runner.py
View file @
5ceae36b
...
@@ -3,7 +3,7 @@ import os
...
@@ -3,7 +3,7 @@ import os
import
string
import
string
import
random
import
random
import
supervisor
import
supervisor
import
thread
from
six.moves
import
_
thread
import
unittest
import
unittest
...
@@ -35,7 +35,7 @@ class TestRunnerBackEnd(unittest.TestCase):
...
@@ -35,7 +35,7 @@ class TestRunnerBackEnd(unittest.TestCase):
open
(
supervisord_config_file
,
'w'
).
write
(
"""
open
(
supervisord_config_file
,
'w'
).
write
(
"""
"""
)
"""
)
supervisord
=
supervisor
.
supervisord
.
Supervisord
(
'-c'
,
supervisord_config_file
)
supervisord
=
supervisor
.
supervisord
.
Supervisord
(
'-c'
,
supervisord_config_file
)
thread
.
start_new_thread
()
_
thread
.
start_new_thread
()
def
test_UserCanLoginAndUpdateCredentials
(
self
):
def
test_UserCanLoginAndUpdateCredentials
(
self
):
"""
"""
...
...
slapos/test/test_securedelete.py
View file @
5ceae36b
...
@@ -58,32 +58,32 @@ class TestSecureDelete(unittest.TestCase):
...
@@ -58,32 +58,32 @@ class TestSecureDelete(unittest.TestCase):
passes
=
2
+
1
# Option -z is used, plus one more pass
passes
=
2
+
1
# Option -z is used, plus one more pass
result
=
shred
(
options
)
result
=
shred
(
options
)
self
.
assertFalse
(
os
.
path
.
exists
(
self
.
remove_file
))
self
.
assertFalse
(
os
.
path
.
exists
(
self
.
remove_file
))
self
.
assertTrue
(
"pass %s/%s
"
%
(
passes
,
passes
)
in
result
)
self
.
assertTrue
(
b"pass %d/%d
"
%
(
passes
,
passes
)
in
result
)
self
.
assertTrue
(
"%s: removed"
%
os
.
path
.
basename
(
self
.
remove_file
)
in
result
)
self
.
assertTrue
(
b"%s: removed"
%
os
.
path
.
basename
(
self
.
remove_file
).
encode
(
'utf-8'
)
in
result
)
def
test_secure_remove_file_keep_file
(
self
):
def
test_secure_remove_file_keep_file
(
self
):
options
=
getAgumentParser
().
parse_args
([
'-n'
,
'2'
,
'-z'
,
'--file'
,
self
.
remove_file
])
options
=
getAgumentParser
().
parse_args
([
'-n'
,
'2'
,
'-z'
,
'--file'
,
self
.
remove_file
])
passes
=
2
+
1
# Option -z is used, plus one more pass
passes
=
2
+
1
# Option -z is used, plus one more pass
result
=
shred
(
options
)
result
=
shred
(
options
)
self
.
assertTrue
(
os
.
path
.
exists
(
self
.
remove_file
))
self
.
assertTrue
(
os
.
path
.
exists
(
self
.
remove_file
))
self
.
assertTrue
(
"pass %s/%s
"
%
(
passes
,
passes
)
in
result
)
self
.
assertTrue
(
b"pass %d/%d
"
%
(
passes
,
passes
)
in
result
)
self
.
assertFalse
(
"%s: removed"
%
os
.
path
.
basename
(
self
.
remove_file
)
in
result
)
self
.
assertFalse
(
b"%s: removed"
%
os
.
path
.
basename
(
self
.
remove_file
).
encode
(
'utf-8'
)
in
result
)
def
test_secure_remove_file_non_zero
(
self
):
def
test_secure_remove_file_non_zero
(
self
):
options
=
getAgumentParser
().
parse_args
([
'-n'
,
'2'
,
'-u'
,
'--file'
,
self
.
remove_file
])
options
=
getAgumentParser
().
parse_args
([
'-n'
,
'2'
,
'-u'
,
'--file'
,
self
.
remove_file
])
passes
=
2
passes
=
2
result
=
shred
(
options
)
result
=
shred
(
options
)
self
.
assertFalse
(
os
.
path
.
exists
(
self
.
remove_file
))
self
.
assertFalse
(
os
.
path
.
exists
(
self
.
remove_file
))
self
.
assertTrue
(
"pass %s/%s
"
%
(
passes
,
passes
)
in
result
)
self
.
assertTrue
(
b"pass %d/%d
"
%
(
passes
,
passes
)
in
result
)
self
.
assertTrue
(
"%s: removed"
%
os
.
path
.
basename
(
self
.
remove_file
)
in
result
)
self
.
assertTrue
(
b"%s: removed"
%
os
.
path
.
basename
(
self
.
remove_file
).
encode
(
'utf-8'
)
in
result
)
def
test_secure_remove_file_check_exist
(
self
):
def
test_secure_remove_file_check_exist
(
self
):
options
=
getAgumentParser
().
parse_args
([
'-n'
,
'2'
,
'-u'
,
'-s'
,
'--file'
,
'random.txt'
,
self
.
remove_file
])
options
=
getAgumentParser
().
parse_args
([
'-n'
,
'2'
,
'-u'
,
'-s'
,
'--file'
,
'random.txt'
,
self
.
remove_file
])
passes
=
2
passes
=
2
result
=
shred
(
options
)
result
=
shred
(
options
)
self
.
assertFalse
(
os
.
path
.
exists
(
self
.
remove_file
))
self
.
assertFalse
(
os
.
path
.
exists
(
self
.
remove_file
))
self
.
assertTrue
(
"pass %s/%s
"
%
(
passes
,
passes
)
in
result
)
self
.
assertTrue
(
b"pass %d/%d
"
%
(
passes
,
passes
)
in
result
)
self
.
assertTrue
(
"%s: removed"
%
os
.
path
.
basename
(
self
.
remove_file
)
in
result
)
self
.
assertTrue
(
b"%s: removed"
%
os
.
path
.
basename
(
self
.
remove_file
).
encode
(
'utf-8'
)
in
result
)
def
test_secure_remove_file_check_exist_false
(
self
):
def
test_secure_remove_file_check_exist_false
(
self
):
options
=
getAgumentParser
().
parse_args
([
'-n'
,
'2'
,
'-u'
,
'--file'
,
'random.txt'
])
options
=
getAgumentParser
().
parse_args
([
'-n'
,
'2'
,
'-u'
,
'--file'
,
'random.txt'
])
...
@@ -99,19 +99,19 @@ class TestSecureDelete(unittest.TestCase):
...
@@ -99,19 +99,19 @@ class TestSecureDelete(unittest.TestCase):
# shred removed link and target file
# shred removed link and target file
self
.
assertFalse
(
os
.
path
.
exists
(
self
.
remove_file
))
self
.
assertFalse
(
os
.
path
.
exists
(
self
.
remove_file
))
self
.
assertFalse
(
os
.
path
.
exists
(
self
.
link_name
))
self
.
assertFalse
(
os
.
path
.
exists
(
self
.
link_name
))
self
.
assertTrue
(
"pass %s/%s
"
%
(
passes
,
passes
)
in
result
)
self
.
assertTrue
(
b"pass %d/%d
"
%
(
passes
,
passes
)
in
result
)
self
.
assertTrue
(
"%s: removed"
%
os
.
path
.
basename
(
self
.
remove_file
)
in
result
)
self
.
assertTrue
(
b"%s: removed"
%
os
.
path
.
basename
(
self
.
remove_file
).
encode
(
'utf-8'
)
in
result
)
def
test_secure_remove_file_multiple_files
(
self
):
def
test_secure_remove_file_multiple_files
(
self
):
options
=
getAgumentParser
().
parse_args
([
'-n'
,
'2'
,
'-u'
,
'-z'
,
'--file'
,
self
.
remove_file
,
self
.
remove_file2
])
options
=
getAgumentParser
().
parse_args
([
'-n'
,
'2'
,
'-u'
,
'-z'
,
'--file'
,
self
.
remove_file
,
self
.
remove_file2
])
passes
=
2
+
1
# Option -z is used, plus one more pass
passes
=
2
+
1
# Option -z is used, plus one more pass
result
=
shred
(
options
)
result
=
shred
(
options
)
self
.
assertFalse
(
os
.
path
.
exists
(
self
.
remove_file
))
self
.
assertFalse
(
os
.
path
.
exists
(
self
.
remove_file
))
self
.
assertTrue
(
"pass %s/%s
"
%
(
passes
,
passes
)
in
result
)
self
.
assertTrue
(
b"pass %d/%d
"
%
(
passes
,
passes
)
in
result
)
self
.
assertTrue
(
"%s: removed"
%
os
.
path
.
basename
(
self
.
remove_file
)
in
result
)
self
.
assertTrue
(
b"%s: removed"
%
os
.
path
.
basename
(
self
.
remove_file
).
encode
(
'utf-8'
)
in
result
)
self
.
assertFalse
(
os
.
path
.
exists
(
self
.
remove_file2
))
self
.
assertFalse
(
os
.
path
.
exists
(
self
.
remove_file2
))
self
.
assertTrue
(
"%s: removed"
%
os
.
path
.
basename
(
self
.
remove_file2
)
in
result
)
self
.
assertTrue
(
b"%s: removed"
%
os
.
path
.
basename
(
self
.
remove_file2
).
encode
(
'utf-8'
)
in
result
)
if
__name__
==
'__main__'
:
if
__name__
==
'__main__'
:
unittest
.
main
()
unittest
.
main
()
Write
Preview
Markdown
is supported
0%
Try again
or
attach a new file
Attach a file
Cancel
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Cancel
Please
register
or
sign in
to comment