index
int64
repo_name
string
branch_name
string
path
string
content
string
import_graph
string
32,370
ElvinOuyang/todoist-history-analytics
refs/heads/master
/print_recent_activities.py
import todoist_functions as todofun import sys if __name__ == '__main__': try: script, activity_count = sys.argv except ValueError: sys.stderr.write( "Please input desired rows of records after the script...\n") sys.exit(1) if int(activity_count) > 100: print(">>> This program prints up to 100 records. Printing:") activity_count = 100 else: print(">>> Printing:") activity_count = int(activity_count) # set up api engine to my developer app api = todofun.create_api() # get one-time activity log from api act = api.activity.get(limit=activity_count) act_df = todofun.transform_act(act) act_df = todofun.df_standardization(act_df) print(act_df)
{"/test-data-load.py": ["/todoist_functions.py", "/mysql_functions.py"], "/test-api-download.py": ["/todoist_functions.py"], "/mysql_update_history.py": ["/todoist_functions.py", "/mysql_functions.py"], "/print_recent_activities.py": ["/todoist_functions.py"], "/mysql_save_full_history.py": ["/todoist_functions.py", "/mysql_functions.py"], "/mysql_functions.py": ["/todoist_functions.py"]}
32,371
ElvinOuyang/todoist-history-analytics
refs/heads/master
/mysql_save_full_history.py
import todoist_functions as todofun import mysql_functions as sqlfun import datetime if __name__ == '__main__': full_fetch_until = datetime.datetime.now() full_df = todofun.act_fetch_all(until=full_fetch_until) print('>>> full_df is created with shape {}'.format(full_df.shape)) print('>>> the history ranges from {} to {}'.format( full_df.event_date.min().strftime('%Y-%m-%d'), full_df.event_date.max().strftime('%Y-%m-%d') )) sqlfun.overwrite_table_mysql(full_df, 'activity_history')
{"/test-data-load.py": ["/todoist_functions.py", "/mysql_functions.py"], "/test-api-download.py": ["/todoist_functions.py"], "/mysql_update_history.py": ["/todoist_functions.py", "/mysql_functions.py"], "/print_recent_activities.py": ["/todoist_functions.py"], "/mysql_save_full_history.py": ["/todoist_functions.py", "/mysql_functions.py"], "/mysql_functions.py": ["/todoist_functions.py"]}
32,372
ElvinOuyang/todoist-history-analytics
refs/heads/master
/mysql_functions.py
import os import sys import pandas as pd import todoist_functions as todofun from sqlalchemy import create_engine, select, func, Table, MetaData def connect_mysql(): """ Setup MySQL connection for data connection -----Environment Variables----- Five enviroment variables should be set up before calling this function: MYSQL_HOST, MYSQL_PORT, MYSQL_USER, MYSQL_PASSWORD, MYSQL_DB The default encoding is set to utf-8 for better compatibility -----OUTPUT----- A SQLAlchemy engine with connections to MySQL database """ try: host = os.environ['MYSQL_HOST'] port = int(os.environ['MYSQL_PORT']) user = os.environ['MYSQL_USER'] password = os.environ['MYSQL_PASSWORD'] db = os.environ['MYSQL_DB'] except KeyError: sys.stderr.write("MYSQL_* environment variable not set\n") sys.exit(1) conn = create_engine( 'mysql+pymysql://{}:{}@{}:{}/{}?charset=utf8'.format( user, password, host, port, db), encoding='utf-8') metadata = MetaData(conn) activity_history = Table('activity_history', metadata, autoload=True, autoload_with=conn) return conn, activity_history def overwrite_table_mysql(df, table_name): """ Function that overwrites a table in MysQL database -----INPUT----- df: the pandas dataframe to write in the MySQL table table_name: the destination table name in the MySQL database -----OUTPUT----- none. the action was taken to upload data to MySQL database """ conn = connect_mysql()[0] df.to_sql(name=table_name, con=conn, if_exists='replace', index=False) def append_table_mysql(df, table_name): """ Function that appends a table in MysQL database -----INPUT----- df: the pandas dataframe to write in the MySQL table table_name: the destination table name in the MySQL database -----OUTPUT----- none. the action was taken to upload data to MySQL database """ conn = connect_mysql()[0] df.to_sql(name=table_name, con=conn, if_exists='append', index=False) def create_full_activity(table_name='activity_history'): """ Function that creates a standardized activity pandas dataframe from MySQL table -----INPUT----- table_name: the table name of the full activity history table in MySQL database -----OUTPUT----- df: the standardized pandas dataframe of activity history """ conn = connect_mysql()[0] df = pd.read_sql(table_name, conn) df = todofun.df_standardization(df) return df def get_latest_eventdate(): conn, activity_history = connect_mysql() stmt = select([func.max(activity_history.columns.event_date)]) since_date = conn.connect().execute(stmt).fetchone()[0] return since_date
{"/test-data-load.py": ["/todoist_functions.py", "/mysql_functions.py"], "/test-api-download.py": ["/todoist_functions.py"], "/mysql_update_history.py": ["/todoist_functions.py", "/mysql_functions.py"], "/print_recent_activities.py": ["/todoist_functions.py"], "/mysql_save_full_history.py": ["/todoist_functions.py", "/mysql_functions.py"], "/mysql_functions.py": ["/todoist_functions.py"]}
32,375
marchon/yaybu
refs/heads/master
/yaybu/resources/file.py
# Copyright 2011 Isotoma Limited # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ Resources for handling the creation and removal of files. These deal with both the metadata associated with the file (for example owner and permission) and the contents of the files themselves. """ import os, hashlib from yaybu.core.resource import Resource from yaybu.core.policy import (Policy, Absent, Present, XOR, NAND) from yaybu.core.argument import ( FullPath, String, Integer, Octal, File, Dict, ) class File(Resource): """ A provider for this resource will create or amend an existing file to the provided specification. For example, the following will create the /etc/hosts file based on a static local file:: File: name: /etc/hosts owner: root group: root mode: 644 static: my_hosts_file The following will create a file using a jinja2 template, and will back up the old version of the file if necessary:: File: name: /etc/email_addresses owner: root group: root mode: 644 template: email_addresses.j2 template_args: foo: foo@example.com bar: bar@example.com backup: /etc/email_addresses.{year}-{month}-{day} """ name = FullPath() """The full path to the file this resource represents.""" owner = String(default="root") """A unix username or UID who will own created objects. An owner that begins with a digit will be interpreted as a UID, otherwise it will be looked up using the python 'pwd' module.""" group = String(default="root") """A unix group or GID who will own created objects. A group that begins with a digit will be interpreted as a GID, otherwise it will be looked up using the python 'grp' module.""" mode = Octal(default=0644) """A mode representation as an octal. This can begin with leading zeros if you like, but this is not required. DO NOT use yaml Octal representation (0o666), this will NOT work.""" static = File() """A static file to copy into this resource. The file is located on the yaybu path, so can be colocated with your recipes.""" encrypted = File() """A static encrypted file to copy to this resource. The file is located on the yaybu path, so can be colocated with your recipe.""" template = File() """A jinja2 template, used to generate the contents of this resource. The template is located on the yaybu path, so can be colocated with your recipes""" template_args = Dict(default={}) """The arguments passed to the template.""" def hash(self): if not os.path.exists(self.name): return "" return hashlib.sha1(open(self.name).read()).hexdigest() class FileApplyPolicy(Policy): """ Create a file and populate it's contents if required. You must provide a name. You may provide one of template, static, or encrypted to act as a file source. """ resource = File name = "apply" default = True signature = (Present("name"), NAND(Present("template"), Present("static"), Present("encrypted")), ) class FileRemovePolicy(Policy): """ Delete a file if it exists. You should only provide the name in this case. """ resource = File name = "remove" default = False signature = (Present("name"), Absent("owner"), Absent("group"), Absent("mode"), Absent("static"), Absent("encrypted"), Absent("template"), Absent("template_args"), ) class FileWatchedPolicy(Policy): """ Watches a file to see if it changes when a resource a file. This policy is used internally and shouldn't be used directly. """ resource = File name = "watched" default = False signature = FileRemovePolicy.signature
{"/yaybu/resources/prompt.py": ["/yaybu/core/resource.py", "/yaybu/core/policy.py", "/yaybu/core/argument.py"], "/yaybu/core/protocol/changelog.py": ["/yaybu/core/protocol/server.py"], "/yaybu/core/tests/test_whitehat.py": ["/yaybu/core/whitehat.py"], "/yaybu/providers/git.py": ["/yaybu/core/error.py"], "/yaybu/providers/tests/test_subversion.py": ["/yaybu/core/error.py"], "/yaybu/providers/tests/test_filesystem.py": ["/yaybu/providers/filesystem/__init__.py"], "/yaybu/providers/tests/test_rsync.py": ["/yaybu/core/error.py"], "/yaybu/providers/filesystem/directory.py": ["/yaybu/providers/filesystem/files.py"], "/yaybu/core/protocol/file.py": ["/yaybu/core/protocol/server.py"]}
32,376
marchon/yaybu
refs/heads/master
/yaybu/providers/tests/test_group.py
import os, shutil, grp from yaybu.harness import FakeChrootTestCase from yaybu.util import sibpath class TestGroup(FakeChrootTestCase): def test_simple_group(self): self.fixture.check_apply(""" resources: - Group: name: test """) self.failUnless(self.fixture.get_group("test")) def test_group_with_gid(self): self.fixture.check_apply(""" resources: - Group: name: test gid: 1111 """) self.failUnless(self.fixture.get_group("test")) def test_existing_group(self): """ Test creating a group whose name already exists. """ self.failUnless(self.fixture.get_group("users")) rv = self.fixture.apply(""" resources: - Group: name: users """) self.failUnlessEqual(rv, 255) self.failUnless(self.fixture.get_group("users")) def test_existing_gid(self): """ Test creating a group whose specified gid already exists. """ rv = self.fixture.apply(""" resources: - Group: name: test gid: 100 """) self.failUnlessEqual(rv, 4) self.failUnlessRaises(KeyError, self.fixture.get_group, "test") def test_add_group_and_use_it(self): self.fixture.check_apply(""" resources: - Group: name: test - File: name: /etc/test group: test - Execute: name: test-group command: python -c "import os, grp; open('/etc/test2', 'w').write(grp.getgrgid(os.getgid()).gr_name)" creates: /etc/test2 group: test """) self.failUnlessEqual(self.fixture.open("/etc/test2").read(), "test") class TestGroupRemove(FakeChrootTestCase): def test_remove_existing(self): self.failUnless(self.fixture.get_group("users")) self.fixture.check_apply(""" resources: - Group: name: users policy: remove """) self.failUnlessRaises(KeyError, self.fixture.get_group, "users") def test_remove_non_existing(self): self.failUnlessRaises(KeyError, self.fixture.get_group, "zzidontexistzz") rv = self.fixture.apply(""" resources: - Group: name: zzidontexistzz policy: remove """) self.failUnlessEqual(rv, 255) self.failUnlessRaises(KeyError, self.fixture.get_group, "zzidontexistzz")
{"/yaybu/resources/prompt.py": ["/yaybu/core/resource.py", "/yaybu/core/policy.py", "/yaybu/core/argument.py"], "/yaybu/core/protocol/changelog.py": ["/yaybu/core/protocol/server.py"], "/yaybu/core/tests/test_whitehat.py": ["/yaybu/core/whitehat.py"], "/yaybu/providers/git.py": ["/yaybu/core/error.py"], "/yaybu/providers/tests/test_subversion.py": ["/yaybu/core/error.py"], "/yaybu/providers/tests/test_filesystem.py": ["/yaybu/providers/filesystem/__init__.py"], "/yaybu/providers/tests/test_rsync.py": ["/yaybu/core/error.py"], "/yaybu/providers/filesystem/directory.py": ["/yaybu/providers/filesystem/files.py"], "/yaybu/core/protocol/file.py": ["/yaybu/core/protocol/server.py"]}
32,377
marchon/yaybu
refs/heads/master
/yaybu/core/runcontext.py
# Copyright 2011 Isotoma Limited # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import logging import pickle import subprocess import StringIO import yay from yay.openers import Openers from yay.errors import NotFound from yaybu.core.error import ParseError, MissingAsset, Incompatible from yaybu.core.protocol.client import HTTPConnection from yaybu.core.shell import Shell from yaybu.core import change logger = logging.getLogger("runcontext") class RunContext(object): simulate = False ypath = () verbose = 0 def __init__(self, configfile, opts=None): self.path = [] self.ypath = [] self.options = {} self._config = None self.resume = opts.resume self.no_resume = opts.no_resume self.user = opts.user self.host = opts.host self.connect_user = None self.port = None if self.host: if "@" in self.host: self.connect_user, self.host = self.host.split("@", 1) if ":" in self.host: self.host, self.port = self.host.split(":", 1) if os.path.exists("/etc/yaybu"): self.options = yay.load_uri("/etc/yaybu") if opts is not None: logger.debug("Invoked with ypath: %r" % opts.ypath) logger.debug("Environment YAYBUPATH: %r" % os.environ.get("YAYBUPATH", "")) self.simulate = opts.simulate self.ypath = opts.ypath self.verbose = opts.verbose if "PATH" in os.environ: for term in os.environ["PATH"].split(":"): self.path.append(term) if "YAYBUPATH" in os.environ: for term in os.environ["YAYBUPATH"].split(":"): self.ypath.append(term) if not len(self.ypath): self.ypath.append(os.getcwd()) self.configfile = configfile self.setup_shell(opts.env_passthrough) self.setup_changelog() def setup_shell(self, environment): self.shell = Shell(context=self, verbose=self.verbose, simulate=self.simulate, environment=environment) def setup_changelog(self): self.changelog = change.ChangeLog(self) def locate(self, paths, filename): if filename.startswith("/"): return filename for prefix in paths: candidate = os.path.realpath(os.path.join(prefix, filename)) logger.debug("Testing for existence of %r" % (candidate,)) if os.path.exists(candidate): return candidate logger.debug("%r does not exist" % candidate) raise MissingAsset("Cannot locate file %r" % filename) def locate_file(self, filename): """ Locates a file by referring to the defined yaybu path. If the filename starts with a / then it is absolutely rooted in the filesystem and will be returned unmolested. """ return self.locate(self.ypath, filename) def locate_bin(self, filename): """ Locates a binary by referring to the defined yaybu path and PATH. If the filename starts with a / then it is absolutely rooted in the filesystem and will be returned unmolested. """ return self.locate(self.ypath + self.path, filename) def set_config(self, config): """ Rather than have yaybu load a config you can provide one """ self._config = config def get_config(self): if self._config: return self._config.get() try: c = yay.config.Config(searchpath=self.ypath) if self.host: extra = { "yaybu": { "host": self.host, } } # This is fugly. Oh dear. c.load(StringIO.StringIO(yay.dump(extra))) c.load_uri(self.configfile) self._config = c return c.get() except yay.errors.Error, e: raise ParseError(e.get_string()) def get_decrypted_file(self, filename): p = subprocess.Popen(["gpg", "-d", self.locate_file(filename)], stdout=subprocess.PIPE) return p.stdout def get_file(self, filename): try: return Openers(searchpath=self.ypath).open(filename) except NotFound, e: raise MissingAsset(str(e)) class RemoteRunContext(RunContext): def __init__(self, configfile, opts=None): self.connection = HTTPConnection() self.check_versions() super(RemoteRunContext, self).__init__(configfile, opts) def check_versions(self): self.connection.request("GET", "/about") rsp = self.connection.getresponse() if rsp.status != 200: self.features = [] self.versions = {"Yaybu": "0", "yay": "0"} else: self.features = rsp.getheader("features", "").split(",") self.versions = { "Yaybu": rsp.getheader("Yaybu", "0"), "yay": rsp.getheader("yay", "0"), } import pkg_resources if pkg_resources.parse_version(self.versions["Yaybu"]) <= pkg_resources.parse_version("0"): raise Incompatible("You require a newer version of 'Yaybu' to deploy to this server") if pkg_resources.parse_version(self.versions["yay"]) <= pkg_resources.parse_version("0"): raise Incompatible("You require a newer version of 'yay' to deploy to this server") def setup_changelog(self): self.changelog = change.RemoteChangeLog(self) def get_config(self): self.connection.request("GET", "/config") rsp = self.connection.getresponse() return pickle.loads(rsp.read()) def get_decrypted_file(self, filename): self.connection.request("GET", "/encrypted/" + filename) rsp = self.connection.getresponse() return rsp def get_file(self, filename): if filename.startswith("/"): return super(RemoteRunContext, self).get_file(filename) self.connection.request("GET", "/files/?path=" + filename) rsp = self.connection.getresponse() if rsp.status == 404: raise MissingAsset("Cannot fetch %r" % filename) return rsp
{"/yaybu/resources/prompt.py": ["/yaybu/core/resource.py", "/yaybu/core/policy.py", "/yaybu/core/argument.py"], "/yaybu/core/protocol/changelog.py": ["/yaybu/core/protocol/server.py"], "/yaybu/core/tests/test_whitehat.py": ["/yaybu/core/whitehat.py"], "/yaybu/providers/git.py": ["/yaybu/core/error.py"], "/yaybu/providers/tests/test_subversion.py": ["/yaybu/core/error.py"], "/yaybu/providers/tests/test_filesystem.py": ["/yaybu/providers/filesystem/__init__.py"], "/yaybu/providers/tests/test_rsync.py": ["/yaybu/core/error.py"], "/yaybu/providers/filesystem/directory.py": ["/yaybu/providers/filesystem/files.py"], "/yaybu/core/protocol/file.py": ["/yaybu/core/protocol/server.py"]}
32,378
marchon/yaybu
refs/heads/master
/yaybu/core/error.py
""" Classes that represent errors within yaybu. What is listed here are the exceptions raised within Python, with an explanation of their meaning. If you wish to detect a specific error on invocation, you can do so via the return code of the yaybu process. All yaybu errors have a returncode, which is returned from the yaybu program if these errors occur. This is primarily for the test harness, but feel free to rely on these, they should be stable. A returncode of less than 128 is an error from within the range specified in the errno library, which contains the standard C error codes. These may have been actually returned from a shell command, or they may be based on our interpretation of the failure mode they represent. Resources will define the errors they may return. """ import errno class Error(Exception): """ Base class for all yaybu specific exceptions. """ returncode = 255 def __init__(self, msg=""): self.msg = msg def __str__(self): return "%s: %s" % (self.__class__.__name__, self.msg) class ParseError(Error): """ Root of exceptions that are caused by an error in input. """ returncode = 128 """ returns error code 128 to the invoking environment. """ class BindingError(Error): """ An error during policy binding. """ returncode = 129 """ returns error code 129 to the invoking environment. """ class ExecutionError(Error): """ Root of exceptions that are caused by execution failing in an unexpected way. """ returncode = 130 """ returns error code 130 to the invoking environment. """ class DpkgError(ExecutionError): """ dpkg returned something other than 0 or 1 """ returncode = 131 """ returns error code 131 to the invoking environment. """ class AptError(ExecutionError): """ An apt command failed unrecoverably. """ returncode = 132 """ returns error code 132 to the invoking environment. """ class CommandError(ExecutionError): """ A command from the Execute provider did not return the expected return code. """ returncode = 133 """ returns error code 133 to the invoking environment. """ class NoValidPolicy(ParseError): """ There is no valid policy for the resource. """ returncode = 135 """ returns error code 135 to the invoking environment. """ class NonConformingPolicy(ParseError): """ A policy has been specified, or has been chosen by default, but the parameters provided for the resource do not match those required for the policy. Check the documentation to ensure you have provided all required parameters. """ returncode = 136 """ returns error code 136 to the invoking environment. """ class NoSuitableProviders(ParseError): """ There are no suitable providers available for the policy and resource chosen. This may be because a provider has not been written for this Operating System or service, or it may be that you have not specified the parameters correctly. """ returncode = 137 """ returns error code 137 to the invoking environment. """ class TooManyProviders(ParseError): """ More than one provider matches the specified resource, and Yaybu is unable to choose between them. """ returncode = 138 """ returns error code 138 to the invoking environment. """ class InvalidProvider(ExecutionError): """ A provider is not valid. This is detected before any changes have been applied. """ returncode = 139 """ returns error code 139 to the invoking environment. """ class InvalidGroup(ExecutionError): """ The specified user group does not exist. """ returncode = 140 """ returns error code 140 to the invoking environment. """ class InvalidUser(ExecutionError): """ The specified user does not exist. """ returncode = 141 """ returns error code 141 to the invoking environment. """ class OperationFailed(ExecutionError): """ A general failure of an operation. For example, we tried to create a symlink, everything appeared to work but then a link does not exist. This should probably never happen. """ returncode = 142 """ returns error code 142 to the invoking environment. """ class BinaryMissing(ExecutionError): """ A specific error for an expected binary (ln, rm, etc.) not being present where expected. """ returncode = 143 """ returns error code 143 to the invoking environment. """ class DanglingSymlink(ExecutionError): """ The destination of a symbolic link does not exist. """ returncode = 144 """ returns error code 144 to the invoking environment. """ class UserAddError(ExecutionError): """ An error from the useradd command. It has a bunch of error codes of it's own. """ returncode = 145 """ returns error code 145 to the invoking environment. """ class PathComponentMissing(ExecutionError): """ A component of the path is not present """ returncode = 146 """ returns error code 146 to the invoking environment. """ class PathComponentNotDirectory(ExecutionError): """ A component of the path is in fact not a directory """ returncode = 147 """ returns error code 147 to the invoking environment. """ class SavedEventsAndNoInstruction(Error): """ There is a saved events file and the user has not decided what to do about it. Invoke with --resume or --no-resume. """ returncode = 148 """ returns error code 148 to the invoking environment. """ class MissingAsset(ExecutionError): """ An asset referenced by a resource could not be found on the Yaybu search path. """ returncode = 149 """ returns error code 149 to the invoking environment. """ class CheckoutError(Error): """ An insurmountable problem was encountered during checkout """ returncode = 150 """ returns error code 150 to the invoking environment. """ class Incompatible(Error): """ An incompatibility was detected and execution can't continue """ returncode = 151 class MissingDependency(ExecutionError): """ A dependency required for a feature or provider is missing """ returncode = 152 class NothingChanged(ExecutionError): """ Not really an error, but we need to know if this happens for our tests. This exception is never really raised, but it's useful to keep the error code here!""" returncode = 255 """ returns error code 255 to the invoking environment. """ class SystemError(ExecutionError): """ An error represented by something in the errno list. """ def __init__(self, returncode): # if the returncode is not in errno, this will blow up. self.msg = errno.errorcode[returncode] self.returncode = returncode
{"/yaybu/resources/prompt.py": ["/yaybu/core/resource.py", "/yaybu/core/policy.py", "/yaybu/core/argument.py"], "/yaybu/core/protocol/changelog.py": ["/yaybu/core/protocol/server.py"], "/yaybu/core/tests/test_whitehat.py": ["/yaybu/core/whitehat.py"], "/yaybu/providers/git.py": ["/yaybu/core/error.py"], "/yaybu/providers/tests/test_subversion.py": ["/yaybu/core/error.py"], "/yaybu/providers/tests/test_filesystem.py": ["/yaybu/providers/filesystem/__init__.py"], "/yaybu/providers/tests/test_rsync.py": ["/yaybu/core/error.py"], "/yaybu/providers/filesystem/directory.py": ["/yaybu/providers/filesystem/files.py"], "/yaybu/core/protocol/file.py": ["/yaybu/core/protocol/server.py"]}
32,379
marchon/yaybu
refs/heads/master
/yaybu/core/resource.py
# Copyright 2011 Isotoma Limited # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import sys, os, hashlib from argument import Argument, List, PolicyArgument, String import policy import error import collections import ordereddict import event class ResourceType(type): """ Keeps a registry of resources as they are created, and provides some simple access to their arguments. """ resources = {} def __new__(meta, class_name, bases, new_attrs): cls = type.__new__(meta, class_name, bases, new_attrs) cls.__args__ = [] for b in bases: if hasattr(b, "__args__"): cls.__args__.extend(b.__args__) cls.policies = AvailableResourcePolicies() if class_name != 'Resource': rname = new_attrs.get("__resource_name__", class_name) if rname in meta.resources: raise error.ParseError("Redefinition of resource %s" % rname) else: meta.resources[rname] = cls for key, value in new_attrs.items(): if isinstance(value, Argument): cls.__args__.append(key) return cls @classmethod def clear(self): self.resources = {} class AvailableResourcePolicies(dict): """ A collection of the policies available for a resource, with some logic to work out which of them is the one and only default policy. """ def default(self): default = [p for p in self.values() if p.default] if default: return default[0] else: return policy.NullPolicy class Resource(object): """ A resource represents a resource that can be configured on the system. This might be as simple as a symlink or as complex as a database schema migration. Resources have policies that represent how the resource is to be treated. Providers are the implementation of the resource policy. Resource definitions specify the complete set of attributes that can be configured for a resource. Policies define which attributes must be configured for the policy to be used. """ __metaclass__ = ResourceType # The arguments for this resource, set in the metaclass __args__ = [] policies = AvailableResourcePolicies() """ A dictionary of policy names mapped to policy classes (not objects). These are the policies for this resource class. Here be metaprogramming magic. Dynamically allocated as Yaybu starts up this is effectively static once we're up and running. The combination of this attribute and the policy argument below is sufficient to determine which provider might be appropriate for this resource. """ policy = PolicyArgument() """ The list of policies provided by configuration. This is an argument like any other, but has a complex representation that holds the conditions and options for the policies as specified in the input file. """ name = String() watch = List() """ A list of files to monitor while this resource is applied The file will be hashed before and after a resource is applied. If the hash changes, then it will be like a policy has been applied on that file. For example:: resources.append: - Execute: name: buildout-foobar command: buildout2.6 watch: - /var/local/sites/foobar/apache/apache.cfg - Service: name: apache2 policy: restart: when: watched on: File[/var/local/sites/foobar/apache/apache.cfg] """ def __init__(self, **kwargs): """ Pass a dictionary of arguments and they will be updated from the supplied data. """ setattr(self, "name", kwargs["name"]) for key, value in kwargs.items(): if not key in self.__args__: raise AttributeError("Cannot assign argument '%s' to resource %s" % (key, self)) setattr(self, key, value) self.observers = collections.defaultdict(list) def register_observer(self, when, resource, policy, immediately): self.observers[when].append((immediately, resource, policy)) def validate(self, yay=None): """ Given the provided yay configuration dictionary, validate that this resource is correctly specified. Will raise an exception if it is invalid. Returns the provider if it is valid. We only validate if: - the chosen policies all exist, or - there is at least one default policy, and - the arguments provided conform with all selected policies, and - the selected policies all share a single provider If the above is all true then we can identify a provider that should be able to implement the required policies. """ if yay is None: yay = {} this_policy = self.get_default_policy() if not this_policy.conforms(self): raise error.NonConformingPolicy(this_policy.name) # throws an exception if there is not oneandonlyone provider provider = this_policy.get_provider(self, yay) return True def apply(self, context, yay=None, policy=None): """ Apply the provider for the selected policy, and then fire any events that are being observed. """ if yay is None: yay = {} if policy is None: pol = self.get_default_policy() else: pol_class = self.policies[policy] pol = pol_class(self) prov_class = pol.get_provider(yay) prov = prov_class(self) changed = prov.apply(context) event.state.clear_override(self) if changed: self.fire_event(pol.name) return changed def fire_event(self, name): """ Apply the appropriate policies on the resources that are observing this resource for the firing of a policy. """ for immediately, resource, policy in self.observers[name]: if immediately is False: raise NotImplementedError event.state.override(resource, policy) def bind(self, resources): """ Bind this resource to all the resources on which it triggers. Returns a list of the resources to which we are bound. """ bound = [] if self.policy is not None: for trigger in self.policy.triggers: bound.append(trigger.bind(resources, self)) return bound def get_default_policy(self): """ Return an instantiated policy for this resource. """ return event.state.policy(self) def dict_args(self): """ Return all argument names and values in a dictionary. If an argument has no default and has not been set, it's value in the dictionary will be None. """ d = {} for a in self.__args__: d[a] = getattr(self, a, None) return d @property def id(self): classname = getattr(self, '__resource_name__', self.__class__.__name__) return "%s[%s]" % (classname, self.name.encode("utf-8")) def __repr__(self): return self.id def __unicode__(self): classname = getattr(self, '__resource_name__', self.__class__.__name__) return u"%s[%s]" % (classname, self.name) class ResourceBundle(ordereddict.OrderedDict): """ An ordered, indexed collection of resources. Pass in a specification that consists of scalars, lists and dictionaries and this class will instantiate the appropriate resources into the structure. """ def __init__(self, specification=()): super(ResourceBundle, self).__init__() for resource in specification: if len(resource.keys()) > 1: raise error.ParseError("Too many keys in list item") typename, instances = resource.items()[0] if not isinstance(instances, list): instances = [instances] for instance in instances: self.create(typename, instance) def key_remap(self, kw): """ Maps - to _ to make resource attribute name more pleasant. """ for k, v in kw.items(): k = k.replace("-", "_") yield str(k),v def create(self, typename, instance): if not isinstance(instance, dict): raise error.ParseError("Expected mapping for %s, got %s" % (typename, instance)) kls = ResourceType.resources[typename](**dict(self.key_remap(instance))) self[kls.id] = kls # Create implicit File[] nodes for any watched files for watched in instance.get("watch", []): w = self.create("File", { "name": watched, "policy": "watched", }) w._original_hash = w.hash() return kls def bind(self): """ Bind all the resources so they can observe each others for policy triggers. """ for i, resource in enumerate(self.values()): for bound in resource.bind(self): if bound == resource: raise error.BindingError("Attempt to bind %r to itself!" % resource) j = self.values().index(bound) if j > i: raise error.BindingError("Attempt to bind forwards on %r" % resource) def apply(self, ctx, config): """ Apply the resources to the system, using the provided context and overall configuration. """ something_changed = False for resource in self.values(): with ctx.changelog.resource(resource): if resource.apply(ctx, config): something_changed = True return something_changed
{"/yaybu/resources/prompt.py": ["/yaybu/core/resource.py", "/yaybu/core/policy.py", "/yaybu/core/argument.py"], "/yaybu/core/protocol/changelog.py": ["/yaybu/core/protocol/server.py"], "/yaybu/core/tests/test_whitehat.py": ["/yaybu/core/whitehat.py"], "/yaybu/providers/git.py": ["/yaybu/core/error.py"], "/yaybu/providers/tests/test_subversion.py": ["/yaybu/core/error.py"], "/yaybu/providers/tests/test_filesystem.py": ["/yaybu/providers/filesystem/__init__.py"], "/yaybu/providers/tests/test_rsync.py": ["/yaybu/core/error.py"], "/yaybu/providers/filesystem/directory.py": ["/yaybu/providers/filesystem/files.py"], "/yaybu/core/protocol/file.py": ["/yaybu/core/protocol/server.py"]}
32,380
marchon/yaybu
refs/heads/master
/yaybu/core/whitehat.py
# Copyright 2011 Isotoma Limited # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ This module provides support functions for people wanting to use Yaybu without Yay. This functionality is EXPERIMENTAL. """ import sys, inspect from yaybu.core import resource __bundle = None def get_bundle(): global __bundle if not __bundle: __bundle = resource.ResourceBundle() return __bundle def reset_bundle(): global __bundle __bundle = None def create_wrapper(resource_type): """ This creates a function for a Resource that performs string substitution and registers the resource with a bundle. """ def create_resource(**kwargs): caller = inspect.currentframe().f_back # Mutate kwargs based on local variables for k, v in kwargs.items(): if isinstance(v, basestring): kwargs[k] = v.format(**caller.f_locals) # Create a Resource and add it to the bundle get_bundle().create(resource_type, kwargs) return create_resource def register_resources(): """ This iterates over all known Resource Types and creates a proxy for them. The proxy will automatically format any strings it is passed with all variables in the local context. The proxy automatically registers the Resource with a resource bundle. It is called automatically when this module is imported. """ module = sys.modules[__name__] for resource_type in resource.ResourceType.resources.keys(): setattr(module, resource_type, create_wrapper(resource_type)) register_resources()
{"/yaybu/resources/prompt.py": ["/yaybu/core/resource.py", "/yaybu/core/policy.py", "/yaybu/core/argument.py"], "/yaybu/core/protocol/changelog.py": ["/yaybu/core/protocol/server.py"], "/yaybu/core/tests/test_whitehat.py": ["/yaybu/core/whitehat.py"], "/yaybu/providers/git.py": ["/yaybu/core/error.py"], "/yaybu/providers/tests/test_subversion.py": ["/yaybu/core/error.py"], "/yaybu/providers/tests/test_filesystem.py": ["/yaybu/providers/filesystem/__init__.py"], "/yaybu/providers/tests/test_rsync.py": ["/yaybu/core/error.py"], "/yaybu/providers/filesystem/directory.py": ["/yaybu/providers/filesystem/files.py"], "/yaybu/core/protocol/file.py": ["/yaybu/core/protocol/server.py"]}
32,381
marchon/yaybu
refs/heads/master
/yaybu/core/main.py
# Copyright 2011 Isotoma Limited # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import optparse import yay from yaybu.core import runner, remote, runcontext import logging, atexit def version(): import pkg_resources yaybu_version = pkg_resources.get_distribution('Yaybu').version yay_version = pkg_resources.get_distribution('Yay').version return 'Yaybu %s\n' \ 'yay %s' % (yaybu_version, yay_version) def main(): parser = optparse.OptionParser(version=version()) parser.add_option("-s", "--simulate", default=False, action="store_true") parser.add_option("-p", "--ypath", default=[], action="append") parser.add_option("", "--log-facility", default="2", help="the syslog local facility number to which to write the audit trail") parser.add_option("", "--log-level", default="info", help="the minimum log level to write to the audit trail") parser.add_option("-d", "--debug", default=False, action="store_true", help="switch all logging to maximum, and write out to the console") parser.add_option("-l", "--logfile", default=None, help="The filename to write the audit log to, instead of syslog. Note: the standard console log will still be written to the console.") parser.add_option("-v", "--verbose", default=2, action="count", help="Write additional informational messages to the console log. repeat for even more verbosity.") parser.add_option("--host", default=None, action="store", help="A host to remotely run yaybu on") parser.add_option("-u", "--user", default="root", action="store", help="User to attempt to run as") parser.add_option("--remote", default=False, action="store_true", help="Run yaybu.protocol client on stdio") parser.add_option("--ssh-auth-sock", default=None, action="store", help="Path to SSH Agent socket") parser.add_option("--expand-only", default=False, action="store_true", help="Set to parse config, expand it and exit") parser.add_option("--resume", default=False, action="store_true", help="Resume from saved events if terminated abnormally") parser.add_option("--no-resume", default=False, action="store_true", help="Clobber saved event files if present and do not resume") parser.add_option("--env-passthrough", default=[], action="append", help="Preserve an environment variable in any processes Yaybu spawns") opts, args = parser.parse_args() if len(args) != 1: parser.print_help() return 1 if opts.debug: opts.logfile = "-" opts.verbose = 2 if opts.expand_only: ctx = runcontext.RunContext(args[0], opts) cfg = ctx.get_config() if opts.verbose <= 2: cfg = dict(resources=cfg.get("resources", [])) print yay.dump(cfg) return 0 if opts.ssh_auth_sock: os.environ["SSH_AUTH_SOCK"] = opts.ssh_auth_sock atexit.register(logging.shutdown) # Probably not the best place to put this stuff... if os.path.exists("/etc/yaybu"): config = yay.load_uri("/etc/yaybu") opts.env_passthrough = config.get("env-passthrough", opts.env_passthrough) if opts.host: r = remote.RemoteRunner() r.load_system_host_keys() r.set_missing_host_key_policy("ask") else: r = runner.Runner() if not opts.remote: ctx = runcontext.RunContext(args[0], opts) else: ctx = runcontext.RemoteRunContext(args[0], opts) rv = r.run(ctx) return rv
{"/yaybu/resources/prompt.py": ["/yaybu/core/resource.py", "/yaybu/core/policy.py", "/yaybu/core/argument.py"], "/yaybu/core/protocol/changelog.py": ["/yaybu/core/protocol/server.py"], "/yaybu/core/tests/test_whitehat.py": ["/yaybu/core/whitehat.py"], "/yaybu/providers/git.py": ["/yaybu/core/error.py"], "/yaybu/providers/tests/test_subversion.py": ["/yaybu/core/error.py"], "/yaybu/providers/tests/test_filesystem.py": ["/yaybu/providers/filesystem/__init__.py"], "/yaybu/providers/tests/test_rsync.py": ["/yaybu/core/error.py"], "/yaybu/providers/filesystem/directory.py": ["/yaybu/providers/filesystem/files.py"], "/yaybu/core/protocol/file.py": ["/yaybu/core/protocol/server.py"]}
32,382
marchon/yaybu
refs/heads/master
/yaybu/core/shell.py
# Copyright 2011 Isotoma Limited # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import logging import subprocess import StringIO import change import error import os, getpass, pwd, grp, select import shlex from yay import String class Command(String): """ Horrible horrible cludge """ pass class Handle(object): def __init__(self, handle, callback=None): self.handle = handle self.callback = callback self._output = [] def fileno(self): return self.handle.fileno() def read(self): data = os.read(self.fileno(), 1024) if data == "": self.handle.close() return False self._output.append(data) if self.callback: for l in data.splitlines(): self.callback(l + "\r") return True def isready(self): return bool(self.handle) @property def output(self): out = ''.join(self._output) return out class ShellCommand(change.Change): """ Execute and log a change """ def __init__(self, command, shell, stdin, cwd=None, env=None, env_passthru=None, verbose=0, passthru=False, user=None, group=None, simulate=False, logas=None): self.command = command self.shell = shell self.stdin = stdin self.cwd = cwd self.env = env self.env_passthru = env_passthru self.verbose = verbose self.passthru = passthru self.simulate = simulate self.logas = logas self._generated_env = {} self.user = None self.uid = None self.group = None self.gid = None self.homedir = None if self.simulate and not self.passthru: # For now, we skip this setup in simulate mode - not sure it will ever be possible return self.user = user if user: u = pwd.getpwnam(user) self.uid = u.pw_uid self.homedir = u.pw_dir else: self.uid = None self.homedir = pwd.getpwuid(os.getuid()).pw_dir self.user = pwd.getpwuid(os.getuid()).pw_name self.group = group if group: self.gid = grp.getgrnam(self.group).gr_gid def preexec(self): if self.uid is not None: if self.uid != os.getuid(): os.setuid(self.uid) if self.uid != os.geteuid(): os.seteuid(self.uid) if self.gid is not None: if self.gid != os.getgid(): os.setgid(self.gid) if self.gid != os.getegid(): os.setegid(self.gid) os.environ.clear() os.environ.update(self._generated_env) def communicate(self, p, stdout_fn=None, stderr_fn=None): if p.stdin: p.stdin.flush() p.stdin.close() stdout = Handle(p.stdout, stdout_fn) stderr = Handle(p.stderr, stderr_fn) # Initial readlist is any handle that is valid readlist = [h for h in (stdout, stderr) if h.isready()] while readlist: try: rlist, wlist, xlist = select.select(readlist, [], []) except select.error, e: if e.args[0] == errno.EINTR: continue raise # Read from all handles that select told us can be read from # If they return false then we are at the end of the stream # and stop reading from them for r in rlist: if not r.read(): readlist.remove(r) returncode = p.wait() return returncode, stdout.output, stderr.output def _tounicode(self, l): """ Ensure all elements of the list are unicode """ def uni(x): if type(x) is type(u""): return x return unicode(x, "utf-8") return map(uni, l) def apply(self, renderer): if isinstance(self.command, Command): logas = self.command.as_list(secret=True) command = self.command.as_list(secret=False) elif isinstance(self.command, String): logas = shlex.split(self.command.protected.encode("UTF-8")) command = shlex.split(self.command.unprotected.encode("UTF-8")) elif isinstance(self.command, list): logas = command = self.command[:] elif isinstance(self.command, basestring): logas = command = shlex.split(self.command.encode("UTF-8")) command = self._tounicode(command) logas = self._tounicode(logas) renderer.passthru = self.passthru renderer.command(self.logas or logas) env = { "HOME": self.homedir, "LOGNAME": self.user, "PATH": "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin", "SHELL": "/bin/sh", } if self.env_passthru: for var in self.env_passthru: if var in os.environ: env[var] = os.environ[var] if self.env: env.update(self.env) self._generated_env = env if self.simulate and not self.passthru: self.returncode = 0 self.stdout = "" self.stderr = "" return try: p = subprocess.Popen(command, shell=self.shell, stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=self.cwd, env=None, preexec_fn=self.preexec, ) self.returncode, self.stdout, self.stderr = self.communicate(p, renderer.stdout, renderer.stderr) renderer.output(p.returncode) except Exception, e: renderer.exception(e) raise class ShellTextRenderer(change.TextRenderer): """ Render a ShellCommand on a textual changelog. """ renderer_for = ShellCommand passthru = False def command(self, command): if not self.passthru: self.logger.notice(u"# " + u" ".join(command)) def output(self, returncode): if self.verbose >= 1 and returncode != 0 and not self.passthru: self.logger.notice("returned %s", returncode) def stdout(self, data): if self.verbose >= 2 and not self.passthru: self.logger.info(data) def stderr(self, data): if self.verbose >= 1: self.logger.info(data) def exception(self, exception): self.logger.notice("Exception: %r" % exception) class Shell(object): """ This object wraps a shell in yet another shell. When the shell is switched into "simulate" mode it can just print what would be done. """ def __init__(self, context, verbose=0, simulate=False, environment=None): self.simulate = context.simulate self.verbose = context.verbose self.context = context self.environment = ["SSH_AUTH_SOCK"] if environment: self.environment.extend(environment) def locate_bin(self, filename): return self.context.locate_bin(filename) def execute(self, command, stdin=None, shell=False, passthru=False, cwd=None, env=None, exceptions=True, user=None, group=None, logas=None): cmd = ShellCommand(command, shell, stdin, cwd, env, self.environment, self.verbose, passthru, user, group, self.simulate, logas) self.context.changelog.apply(cmd) if exceptions and cmd.returncode != 0: self.context.changelog.info(cmd.stdout) self.context.changelog.notice(cmd.stderr) raise error.SystemError(cmd.returncode) return (cmd.returncode, cmd.stdout, cmd.stderr)
{"/yaybu/resources/prompt.py": ["/yaybu/core/resource.py", "/yaybu/core/policy.py", "/yaybu/core/argument.py"], "/yaybu/core/protocol/changelog.py": ["/yaybu/core/protocol/server.py"], "/yaybu/core/tests/test_whitehat.py": ["/yaybu/core/whitehat.py"], "/yaybu/providers/git.py": ["/yaybu/core/error.py"], "/yaybu/providers/tests/test_subversion.py": ["/yaybu/core/error.py"], "/yaybu/providers/tests/test_filesystem.py": ["/yaybu/providers/filesystem/__init__.py"], "/yaybu/providers/tests/test_rsync.py": ["/yaybu/core/error.py"], "/yaybu/providers/filesystem/directory.py": ["/yaybu/providers/filesystem/files.py"], "/yaybu/core/protocol/file.py": ["/yaybu/core/protocol/server.py"]}
32,383
marchon/yaybu
refs/heads/master
/yaybu/resources/prompt.py
# Copyright 2011 Isotoma Limited # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from yaybu.core.resource import Resource from yaybu.core.policy import ( Policy, Absent, Present, ) from yaybu.core.argument import ( String, Integer, ) class Prompt(Resource): """ Ask a question of the operator. This is useful if manual steps are required as part of implementing a configuration. For example, changes to off-system web interfaces or databases may be required as part of applying a change. """ name = String() """ A unique descriptive name for the resource. """ question = String() """ The question to ask the operator. """ class PromptPolicy(Policy): """ Prompt the operator. The value of the question attribute will be displayed to the operator and deployment will not continue until they acknowledge the prompt.""" resource = Prompt name = "prompt" default = True signature = ( Present("name"), Present("question"), )
{"/yaybu/resources/prompt.py": ["/yaybu/core/resource.py", "/yaybu/core/policy.py", "/yaybu/core/argument.py"], "/yaybu/core/protocol/changelog.py": ["/yaybu/core/protocol/server.py"], "/yaybu/core/tests/test_whitehat.py": ["/yaybu/core/whitehat.py"], "/yaybu/providers/git.py": ["/yaybu/core/error.py"], "/yaybu/providers/tests/test_subversion.py": ["/yaybu/core/error.py"], "/yaybu/providers/tests/test_filesystem.py": ["/yaybu/providers/filesystem/__init__.py"], "/yaybu/providers/tests/test_rsync.py": ["/yaybu/core/error.py"], "/yaybu/providers/filesystem/directory.py": ["/yaybu/providers/filesystem/files.py"], "/yaybu/core/protocol/file.py": ["/yaybu/core/protocol/server.py"]}
32,384
marchon/yaybu
refs/heads/master
/yaybu/providers/execute.py
# Copyright 2011 Isotoma Limited # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import shlex from yaybu.core import provider from yaybu.core import error from yaybu import resources class Execute(provider.Provider): policies = (resources.execute.ExecutePolicy,) @classmethod def isvalid(self, *args, **kwargs): return super(Execute, self).isvalid(*args, **kwargs) def execute(self, shell, command, expected_returncode=None, passthru=False): # Filter out empty strings... cwd = self.resource.cwd or None env = self.resource.environment or None returncode, stdout, stderr = shell.execute(command, cwd=cwd, env=env, user=self.resource.user, group=self.resource.group, passthru=passthru, exceptions=False) if not shell.simulate and expected_returncode != None and expected_returncode != returncode: raise error.CommandError("%s failed with return code %d" % (self.resource, returncode)) return returncode def apply(self, context): if self.resource.creates is not None \ and os.path.exists(self.resource.creates): #logging.info("%r: %s exists, not executing" % (self.resource, self.resource.creates)) return False if self.resource.touch is not None \ and os.path.exists(self.resource.touch): return False if self.resource.unless: if self.execute(context.shell, self.resource.unless, passthru=True) == 0: return False commands = [self.resource.command] if self.resource.command else self.resource.commands for command in commands: self.execute(context.shell, command, self.resource.returncode) if self.resource.touch is not None: context.shell.execute(["touch", self.resource.touch]) return True
{"/yaybu/resources/prompt.py": ["/yaybu/core/resource.py", "/yaybu/core/policy.py", "/yaybu/core/argument.py"], "/yaybu/core/protocol/changelog.py": ["/yaybu/core/protocol/server.py"], "/yaybu/core/tests/test_whitehat.py": ["/yaybu/core/whitehat.py"], "/yaybu/providers/git.py": ["/yaybu/core/error.py"], "/yaybu/providers/tests/test_subversion.py": ["/yaybu/core/error.py"], "/yaybu/providers/tests/test_filesystem.py": ["/yaybu/providers/filesystem/__init__.py"], "/yaybu/providers/tests/test_rsync.py": ["/yaybu/core/error.py"], "/yaybu/providers/filesystem/directory.py": ["/yaybu/providers/filesystem/files.py"], "/yaybu/core/protocol/file.py": ["/yaybu/core/protocol/server.py"]}
32,385
marchon/yaybu
refs/heads/master
/yaybu/core/tests/test_arguments.py
# coding=utf-8 import unittest import datetime from yaybu.core import argument from yaybu.core import resource class TestArguments(unittest.TestCase): def test_octal(self): class R_test_octal(resource.Resource): a = argument.Octal() r = R_test_octal(name="test") r.a = "666" self.assertEqual(r.a, 438) r.a = 666 self.assertEqual(r.a, 438) def test_string(self): class R_test_string(resource.Resource): a = argument.String() r = R_test_string(name="test") r.a = "foo" self.assertEqual(r.a, "foo") r.a = u"foo" self.assertEqual(r.a, "foo") r.a = u"£40" self.assertEqual(r.a, u"£40") r.a = u"£40".encode("utf-8") self.assertEqual(r.a, u"£40") def test_integer(self): class R_test_integer(resource.Resource): a = argument.Integer() r = R_test_integer(name="test") r.a = 10 self.assertEqual(r.a, 10) r.a = "10" self.assertEqual(r.a, 10) r.a = 10.5 self.assertEqual(r.a, 10) def test_datetime(self): class R_test_datetime(resource.Resource): a = argument.DateTime() r = R_test_datetime(name="test") r.a = "2011-02-20" self.assertEqual(r.a, datetime.datetime(2011, 02, 20))
{"/yaybu/resources/prompt.py": ["/yaybu/core/resource.py", "/yaybu/core/policy.py", "/yaybu/core/argument.py"], "/yaybu/core/protocol/changelog.py": ["/yaybu/core/protocol/server.py"], "/yaybu/core/tests/test_whitehat.py": ["/yaybu/core/whitehat.py"], "/yaybu/providers/git.py": ["/yaybu/core/error.py"], "/yaybu/providers/tests/test_subversion.py": ["/yaybu/core/error.py"], "/yaybu/providers/tests/test_filesystem.py": ["/yaybu/providers/filesystem/__init__.py"], "/yaybu/providers/tests/test_rsync.py": ["/yaybu/core/error.py"], "/yaybu/providers/filesystem/directory.py": ["/yaybu/providers/filesystem/files.py"], "/yaybu/core/protocol/file.py": ["/yaybu/core/protocol/server.py"]}
32,386
marchon/yaybu
refs/heads/master
/yaybu/core/change.py
""" Classes that handle logging of changes. """ import abc import sys import logging import types import json from yaybu.core import error logger = logging.getLogger("audit") class ResourceFormatter(logging.Formatter): """ Automatically add a header and footer to log messages about particular resources """ def __init__(self, *args): logging.Formatter.__init__(self, *args) self.resource = None def format(self, record): next_resource = getattr(record, "resource", None) rv = u"" # Is the logging now about a different resource? if self.resource != next_resource: # If there was already a resource, let us add a footer if self.resource: rv += self.render_resource_footer() self.resource = next_resource # Are we now logging for a new resource? if self.resource: rv += self.render_resource_header() formatted = logging.Formatter.format(self, record) if self.resource: rv += "\r\n".join("| %s" % line for line in formatted.splitlines()) + "\r" else: rv += formatted return rv def render_resource_header(self): header = unicode(self.resource) rl = len(header) if rl < 80: total_minuses = 77 - rl minuses = total_minuses/2 leftover = total_minuses % 2 else: minuses = 4 leftover = 0 return u"/%s %s %s\n" % ("-"*minuses, header, "-"*(minuses + leftover)) def render_resource_footer(self): return u"\%s\n\n" % ("-" *79,) class Change(object): """ Base class for changes """ __metaclass__ = abc.ABCMeta @abc.abstractmethod def apply(self, renderer): """ Apply the specified change. The supplied renderer will be instantiated as below. """ class AttributeChange(Change): """ A change to one attribute of a file's metadata """ class ChangeRendererType(type): """ Keeps a registry of available renderers by type. The only types supported are text """ renderers = {} def __new__(meta, class_name, bases, new_attrs): cls = type.__new__(meta, class_name, bases, new_attrs) if cls.renderer_for is not None: ChangeRendererType.renderers[(cls.renderer_type, cls.renderer_for)] = cls return cls class ChangeRenderer: """ A class that knows how to render a change. """ __metaclass__ = ChangeRendererType renderer_for = None renderer_type = None def __init__(self, logger, verbose): self.logger = logger self.verbose = verbose def render(self, logger): pass class TextRenderer(ChangeRenderer): renderer_type = "text" class ResourceChange(object): """ A context manager that handles logging per resource. This allows us to elide unchanged resources, which is the default logging output option. """ def __init__(self, changelog, resource): self.changelog = changelog self.resource = resource # We wrap the logger so it always has context information logger = logging.getLogger("yaybu.changelog") self.logger = logging.LoggerAdapter(logger, dict(resource=unicode(resource))) def info(self, message, *args): self.logger.info(message, *args) def notice(self, message, *args): self.logger.info(message, *args) def __enter__(self): self.changelog.current_resource = self return self def __exit__(self, exc_type, exc_val, exc_tb): self.exc_type = exc_type self.exc_val = exc_val self.exc_tb = exc_tb if self.exc_val is not None: self.notice("Exception: %s" % (self.exc_val,)) self.changelog.current_resource = None class ChangeLog: """ Orchestrate writing output to a changelog. """ def __init__(self, context): self.current_resource = None self.ctx = context self.verbose = self.ctx.verbose self.logger = logging.getLogger("yaybu.changelog") self.configure_session_logging() self.configure_audit_logging() def configure_session_logging(self): root = logging.getLogger("yaybu.changelog") root.setLevel(logging.INFO) if len(root.handlers): # Session logging has already been configured elsewhere? return handler = logging.StreamHandler(sys.stdout) #handler.setFormatter(logging.Formatter("%(message)s")) handler.setFormatter(ResourceFormatter("%(message)s")) root.addHandler(handler) def configure_audit_logging(self): """ configure the audit trail to log to file or to syslog """ if self.ctx.simulate: return options = self.ctx.options.get("auditlog", {}) mode = options.get("mode", "off") if mode == "off": return levels = { 'debug': logging.DEBUG, 'info': logging.INFO, 'warning': logging.WARNING, 'error': logging.ERROR, 'critical': logging.CRITICAL, } level = levels.get(options.get("level", "info"), None) if level is None: raise KeyError("Log level %s not recognised, terminating" % option["level"]) root = logging.getLogger() if mode == "file": handler = logging.FileHandler(options.get("logfile", "/var/log/yaybu.log")) #handler.setFormatter(logging.Formatter("%(message)s")) handler.setFormatter(ResourceFormatter("%(asctime)s %(message)s")) root.addHandler(handler) elif mode == "syslog": facility = getattr(logging.handlers.SysLogHandler, "LOG_LOCAL%s" % options.get("facility", "7")) handler = logging.handlers.SysLogHandler("/dev/log", facility=facility) formatter = logging.Formatter("%(asctime)s %(levelname)s %(message)s") handler.setFormatter(formatter) logging.getLogger().addHandler(handler) def write(self, line=""): #FIXME: Very much needs removing self.logger.info(line) def resource(self, resource): return ResourceChange(self, resource) def apply(self, change): """ Execute the change, passing it the appropriate renderer to use. """ renderers = [] text_class = ChangeRendererType.renderers.get(("text", change.__class__), None) return change.apply(text_class(self, self.verbose)) def info(self, message, *args, **kwargs): """ Write a textual information message. This is used for both the audit trail and the text console log. """ if self.current_resource: self.current_resource.info(message, *args) else: self.logger.info(message, *args) def notice(self, message, *args, **kwargs): """ Write a textual notification message. This is used for both the audit trail and the text console log. """ if self.current_resource: self.current_resource.notice(message, *args) else: self.logger.info(message, *args) def debug(self, message, *args, **kwargs): pass def error(self, message, *args): self.logger.error(message, *args) def handle(self, record): self.logger.handle(record) class RemoteHandler(logging.Handler): def __init__(self, connection): logging.Handler.__init__(self) self.connection = connection def emit(self, record): data = json.dumps(record.__dict__) self.connection.request("POST", "/changelog/", data, {"Content-Length": len(data)}) rsp = self.connection.getresponse() lngth = rsp.getheader("Content-Length", 0) rsp.read(lngth) class RemoteChangeLog(ChangeLog): def configure_session_logging(self): root = logging.getLogger() root.setLevel(logging.INFO) handler = RemoteHandler(self.ctx.connection) handler.setFormatter(logging.Formatter("%(message)s")) root.addHandler(handler) def configure_audit_logging(self): # We don't want to try and log changes in syslog on the box we are pressing go on, # only the box we are deploying to. So no audit logging here. pass
{"/yaybu/resources/prompt.py": ["/yaybu/core/resource.py", "/yaybu/core/policy.py", "/yaybu/core/argument.py"], "/yaybu/core/protocol/changelog.py": ["/yaybu/core/protocol/server.py"], "/yaybu/core/tests/test_whitehat.py": ["/yaybu/core/whitehat.py"], "/yaybu/providers/git.py": ["/yaybu/core/error.py"], "/yaybu/providers/tests/test_subversion.py": ["/yaybu/core/error.py"], "/yaybu/providers/tests/test_filesystem.py": ["/yaybu/providers/filesystem/__init__.py"], "/yaybu/providers/tests/test_rsync.py": ["/yaybu/core/error.py"], "/yaybu/providers/filesystem/directory.py": ["/yaybu/providers/filesystem/files.py"], "/yaybu/core/protocol/file.py": ["/yaybu/core/protocol/server.py"]}
32,387
marchon/yaybu
refs/heads/master
/yaybu/providers/filesystem/files.py
# Copyright 2011 Isotoma Limited # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import sys import stat import pwd import grp import difflib import logging import string try: import magic except ImportError: magic = None from jinja2 import Environment from yaybu import resources from yaybu.core import provider from yaybu.core import change from yaybu.core import error from yay import String def binary_buffers(*buffers): """ Check all of the passed buffers to see if any of them are binary. If any of them are binary this will return True. """ if not magic: check = lambda buff: len(buff) == sum(1 for c in buff if c in string.printable) else: ms = magic.open(magic.MAGIC_MIME) ms.load() check = lambda buff: ms.buffer(buff).startswith("text/") for buff in buffers: if buff and not check(buff): return True return False class AttributeChanger(change.Change): """ Make the changes required to a file's attributes """ def __init__(self, context, filename, user=None, group=None, mode=None): self.context = context self.filename = filename self.user = user self.group = group self.mode = mode self.changed = False def apply(self, renderer): """ Apply the changes """ exists = False uid = None gid = None mode = None if os.path.exists(self.filename): exists = True st = os.stat(self.filename) uid = st.st_uid gid = st.st_gid mode = stat.S_IMODE(st.st_mode) if self.user is not None: try: owner = pwd.getpwnam(self.user) except KeyError: if not self.context.simulate: raise error.InvalidUser("User '%s' not found" % self.user) self.context.changelog.info("User '%s' not found; assuming this recipe will create it" % self.user) owner = None if not owner or owner.pw_uid != uid: self.context.shell.execute(["/bin/chown", self.user, self.filename]) self.changed = True if self.group is not None: try: group = grp.getgrnam(self.group) except KeyError: if not self.context.simulate: raise error.InvalidGroup("No such group '%s'" % self.group) self.context.changelog.info("Group '%s' not found; assuming this recipe will create it" % self.group) #FIXME group = None if not group or group.gr_gid != gid: self.context.shell.execute(["/bin/chgrp", self.group, self.filename]) self.changed = True if self.mode is not None and mode is not None: if mode != self.mode: self.context.shell.execute(["/bin/chmod", "%o" % self.mode, self.filename]) # Clear the user and group bits # We don't need to set them as chmod will *set* this bits with an octal # but won't clear them without a symbolic mode if mode & stat.S_ISGID and not self.mode & stat.S_ISGID: self.context.shell.execute(["/bin/chmod", "g-s", self.filename]) if mode & stat.S_ISUID and not self.mode & stat.S_ISUID: self.context.shell.execute(["/bin/chmod", "u-s", self.filename]) self.changed = True class AttributeChangeRenderer(change.TextRenderer): renderer_for = AttributeChanger class FileContentChanger(change.Change): """ Apply a content change to a file in a managed way. Simulation mode is catered for. Additionally the minimum changes required to the contents are applied, and logs of the changes made are recorded. """ def __init__(self, context, filename, contents, sensitive): self.context = context self.filename = filename self.current = "" self.contents = contents self.changed = False self.renderer = None self.sensitive = sensitive def empty_file(self): """ Write an empty file """ exists = os.path.exists(self.filename) if not exists: self.context.shell.execute(["touch", self.filename]) self.changed = True else: st = os.stat(self.filename) if st.st_size != 0: self.renderer.empty_file(self.filename) if not self.context.simulate: open(self.filename, "w").close() self.changed = True def overwrite_existing_file(self): """ Change the content of an existing file """ self.current = open(self.filename).read() if self.current != self.contents: self.renderer.changed_file(self.filename, self.current, self.contents, self.sensitive) if not self.context.simulate: open(self.filename, "w").write(self.contents) self.changed = True def write_new_file(self): """ Write contents to a new file. """ self.renderer.new_file(self.filename, self.contents, self.sensitive) if not self.context.simulate: open(self.filename, "w").write(self.contents) self.changed = True def write_file(self): """ Write to either an existing or new file """ exists = os.path.exists(self.filename) if exists: self.overwrite_existing_file() else: self.write_new_file() def apply(self, renderer): """ Apply the changes necessary to the file contents. """ self.renderer = renderer if self.contents is None: self.empty_file() else: self.write_file() class FileChangeTextRenderer(change.TextRenderer): renderer_for = FileContentChanger def empty_file(self, filename): self.logger.notice("Emptied file %s", filename) def new_file(self, filename, contents, sensitive): self.logger.notice("Writting new file '%s'" % filename) if not sensitive: self.diff("", contents) def changed_file(self, filename, previous, replacement, sensitive): self.logger.notice("Changed file %s", filename) if not sensitive: self.diff(previous, replacement) def diff(self, previous, replacement): if not binary_buffers(previous, replacement): diff = "".join(difflib.unified_diff(previous.splitlines(1), replacement.splitlines(1))) for l in diff.splitlines(): self.logger.info(" %s", l) else: self.logger.notice("Binary contents; not showing delta") class File(provider.Provider): """ Provides file creation using templates or static files. """ policies = (resources.file.FileApplyPolicy,) @classmethod def isvalid(self, *args, **kwargs): return super(File, self).isvalid(*args, **kwargs) def check_path(self, directory, simulate): frags = directory.split("/") path = "/" for i in frags: path = os.path.join(path, i) if not os.path.exists(path): #FIXME if not simulate: raise error.PathComponentMissing(path) elif not os.path.isdir(path): raise error.PathComponentNotDirectory(path) def has_protected_strings(self): def iter(val): if isinstance(val, dict): for v in val.values(): if iter(v): return True return False elif isinstance(val, list): for v in val: if iter(v): return True return False else: return isinstance(val, String) return iter(self.resource.template_args) def get_template_args(self): """ I return a copy of the template_args that contains only basic types (i.e. no protected strings) """ def _(val): if isinstance(val, dict): return dict((k,_(v)) for (k,v) in val.items()) elif isinstance(val, list): return list(_(v) for v in val) elif isinstance(val, String): return val.unprotected else: return val return _(self.resource.template_args) def apply(self, context): name = self.resource.name self.check_path(os.path.dirname(name), context.simulate) if self.resource.template: # set a special line ending # this strips the \n from the template line meaning no blank line, # if a template variable is undefined. See ./yaybu/recipe/interfaces.j2 for an example env = Environment(line_statement_prefix='%') template = env.from_string(context.get_file(self.resource.template).read()) contents = template.render(self.get_template_args()) + "\n" # yuk sensitive = self.has_protected_strings() elif self.resource.static: contents = context.get_file(self.resource.static).read() sensitive = False elif self.resource.encrypted: contents = context.get_decrypted_file(self.resource.encrypted).read() sensitive = True else: contents = None sensitive = False fc = FileContentChanger(context, self.resource.name, contents, sensitive) context.changelog.apply(fc) ac = AttributeChanger(context, self.resource.name, self.resource.owner, self.resource.group, self.resource.mode) context.changelog.apply(ac) if fc.changed or ac.changed: return True class RemoveFile(provider.Provider): policies = (resources.file.FileRemovePolicy,) @classmethod def isvalid(self, *args, **kwargs): return super(RemoveFile, self).isvalid(*args, **kwargs) def apply(self, context): if os.path.exists(self.resource.name): if not os.path.isfile(self.resource.name): raise error.InvalidProvider("%r: %s exists and is not a file" % (self, self.resource.name)) context.shell.execute(["/bin/rm", self.resource.name]) changed = True else: context.changelog.debug("File %s missing already so not removed" % self.resource.name) changed = False return changed class WatchFile(provider.Provider): policies = (resources.file.FileWatchedPolicy, ) @classmethod def isvalid(self, *args, **kwargs): return super(WatchFile, self).isvalid(*args, **kwargs) def apply(self, context): """ Watched files don't have any policy applied to them """ return self.resource.hash() != self.resource._original_hash
{"/yaybu/resources/prompt.py": ["/yaybu/core/resource.py", "/yaybu/core/policy.py", "/yaybu/core/argument.py"], "/yaybu/core/protocol/changelog.py": ["/yaybu/core/protocol/server.py"], "/yaybu/core/tests/test_whitehat.py": ["/yaybu/core/whitehat.py"], "/yaybu/providers/git.py": ["/yaybu/core/error.py"], "/yaybu/providers/tests/test_subversion.py": ["/yaybu/core/error.py"], "/yaybu/providers/tests/test_filesystem.py": ["/yaybu/providers/filesystem/__init__.py"], "/yaybu/providers/tests/test_rsync.py": ["/yaybu/core/error.py"], "/yaybu/providers/filesystem/directory.py": ["/yaybu/providers/filesystem/files.py"], "/yaybu/core/protocol/file.py": ["/yaybu/core/protocol/server.py"]}
32,388
marchon/yaybu
refs/heads/master
/yaybu/providers/tests/test_service_upstart.py
# coding=utf-8 import unittest from yaybu.providers.service.upstart import _UpstartServiceMixin class TestUpstartParser(unittest.TestCase): """ Tests our ability to handle output from /sbin/status """ def parse(self, block): u = _UpstartServiceMixin() return list(u._parse_status_output(block)) def test_multiple(self): lines = [ "network-interface-security (network-manager) start/running", "network-interface-security (network-interface/eth0) start/running", "network-interface-security (network-interface/lo) start/running", "network-interface-security (networking) start/running", ] output = self.parse("\n".join(lines)) self.assertEqual(len(output), 4) self.assertEqual(output[1].name, "network-interface/eth0") self.assertEqual(output[2].goal, "start") self.assertEqual(output[3].status, "running") def test_with_instance_name(self): output = self.parse("network-interface-security (network-manager) start/running\n") self.assertEqual(len(output), 1) self.assertEqual(output[0].name, "network-manager") self.assertEqual(output[0].goal, "start") self.assertEqual(output[0].status, "running") def test_start_running_with_pid(self): output = self.parse("ssh start/running, process 1234\n") self.assertEqual(len(output), 1) self.assertEqual(output[0].name, "ssh") self.assertEqual(output[0].goal, "start") self.assertEqual(output[0].status, "running") def test_stop_waiting_no_pid(self): output = self.parse("hwclock stop/waiting\n") self.assertEqual(len(output), 1) self.assertEqual(output[0].name, "hwclock") self.assertEqual(output[0].goal, "stop") self.assertEqual(output[0].status, "waiting")
{"/yaybu/resources/prompt.py": ["/yaybu/core/resource.py", "/yaybu/core/policy.py", "/yaybu/core/argument.py"], "/yaybu/core/protocol/changelog.py": ["/yaybu/core/protocol/server.py"], "/yaybu/core/tests/test_whitehat.py": ["/yaybu/core/whitehat.py"], "/yaybu/providers/git.py": ["/yaybu/core/error.py"], "/yaybu/providers/tests/test_subversion.py": ["/yaybu/core/error.py"], "/yaybu/providers/tests/test_filesystem.py": ["/yaybu/providers/filesystem/__init__.py"], "/yaybu/providers/tests/test_rsync.py": ["/yaybu/core/error.py"], "/yaybu/providers/filesystem/directory.py": ["/yaybu/providers/filesystem/files.py"], "/yaybu/core/protocol/file.py": ["/yaybu/core/protocol/server.py"]}
32,389
marchon/yaybu
refs/heads/master
/yaybu/core/protocol/changelog.py
# Copyright 2011 Isotoma Limited # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os, logging, json from yaybu.core.protocol.server import HttpResource class ChangeLogResource(HttpResource): leaf = True def render_POST(self, context, request, restpath): body = json.loads(request.rfile.read(int(request.headers["content-length"]))) # Python logging seems to screw up if this isnt a tuple body['args'] = tuple(body.get('args', [])) logrecord = logging.makeLogRecord(body) context.changelog.handle(logrecord) request.send_response(200, "OK") request.send_header("Content-Type", "application/octect-stream") request.send_header("Content-Length", "0") request.send_header("Content", "keep-alive") request.end_headers()
{"/yaybu/resources/prompt.py": ["/yaybu/core/resource.py", "/yaybu/core/policy.py", "/yaybu/core/argument.py"], "/yaybu/core/protocol/changelog.py": ["/yaybu/core/protocol/server.py"], "/yaybu/core/tests/test_whitehat.py": ["/yaybu/core/whitehat.py"], "/yaybu/providers/git.py": ["/yaybu/core/error.py"], "/yaybu/providers/tests/test_subversion.py": ["/yaybu/core/error.py"], "/yaybu/providers/tests/test_filesystem.py": ["/yaybu/providers/filesystem/__init__.py"], "/yaybu/providers/tests/test_rsync.py": ["/yaybu/core/error.py"], "/yaybu/providers/filesystem/directory.py": ["/yaybu/providers/filesystem/files.py"], "/yaybu/core/protocol/file.py": ["/yaybu/core/protocol/server.py"]}
32,390
marchon/yaybu
refs/heads/master
/yaybu/core/tests/test_secret.py
import os import sys from yaybu.harness import FakeChrootTestCase from yaybu.core import error class TestWatched(FakeChrootTestCase): def test_execute(self): self.fixture.check_apply(""" hello.secret: world resources: - Execute: name: test_watched command: /bin/touch ${hello} creates: /world """) self.failUnlessExists("/world")
{"/yaybu/resources/prompt.py": ["/yaybu/core/resource.py", "/yaybu/core/policy.py", "/yaybu/core/argument.py"], "/yaybu/core/protocol/changelog.py": ["/yaybu/core/protocol/server.py"], "/yaybu/core/tests/test_whitehat.py": ["/yaybu/core/whitehat.py"], "/yaybu/providers/git.py": ["/yaybu/core/error.py"], "/yaybu/providers/tests/test_subversion.py": ["/yaybu/core/error.py"], "/yaybu/providers/tests/test_filesystem.py": ["/yaybu/providers/filesystem/__init__.py"], "/yaybu/providers/tests/test_rsync.py": ["/yaybu/core/error.py"], "/yaybu/providers/filesystem/directory.py": ["/yaybu/providers/filesystem/files.py"], "/yaybu/core/protocol/file.py": ["/yaybu/core/protocol/server.py"]}
32,391
marchon/yaybu
refs/heads/master
/yaybu/core/protocol/client.py
# Copyright 2011 Isotoma Limited # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import sys from httplib import HTTPResponse as BaseHTTPResponse from httplib import HTTPConnection as BaseHTTPConnection class FileSocket(object): """ I adapt a pair of file objects to look like a socket """ def __init__(self, rfile, wfile): self.rfile = rfile self.wfile = wfile def sendall(self, data): self.wfile.write(data) self.wfile.flush() def makefile(self, mode, flags): if mode.startswith("r"): return self.rfile raise NotImplementedError def close(self): pass class HTTPResponse(BaseHTTPResponse): def close(self): pass class HTTPConnection(BaseHTTPConnection): response_class = HTTPResponse def __init__(self, rfile=sys.stdin, wfile=sys.stdout): self.rfile = rfile self.wfile = wfile BaseHTTPConnection.__init__(self, "stdio") def connect(self): self.sock = FileSocket(self.rfile, self.wfile)
{"/yaybu/resources/prompt.py": ["/yaybu/core/resource.py", "/yaybu/core/policy.py", "/yaybu/core/argument.py"], "/yaybu/core/protocol/changelog.py": ["/yaybu/core/protocol/server.py"], "/yaybu/core/tests/test_whitehat.py": ["/yaybu/core/whitehat.py"], "/yaybu/providers/git.py": ["/yaybu/core/error.py"], "/yaybu/providers/tests/test_subversion.py": ["/yaybu/core/error.py"], "/yaybu/providers/tests/test_filesystem.py": ["/yaybu/providers/filesystem/__init__.py"], "/yaybu/providers/tests/test_rsync.py": ["/yaybu/core/error.py"], "/yaybu/providers/filesystem/directory.py": ["/yaybu/providers/filesystem/files.py"], "/yaybu/core/protocol/file.py": ["/yaybu/core/protocol/server.py"]}
32,392
marchon/yaybu
refs/heads/master
/yaybu/providers/tests/test_link.py
import os from yaybu.harness import FakeChrootTestCase from yaybu.core import error def sibpath(filename): return os.path.join(os.path.dirname(__file__), filename) class TestLink(FakeChrootTestCase): def test_create_link(self): self.fixture.check_apply(""" resources: - Link: name: /etc/somelink to: /etc owner: root group: root """) self.failUnlessExists("/etc/somelink") def test_remove_link(self): self.fixture.symlink("/", "/etc/toremovelink") rv = self.fixture.check_apply(""" resources: - Link: name: /etc/toremovelink policy: remove """) self.failIfExists("/etc/toremovelink") def test_already_exists(self): self.fixture.symlink("/", "/etc/existing") rv = self.fixture.apply(""" resources: - Link: name: /etc/existing to: / """) self.assertEqual(rv, 255) self.failUnlessEqual(self.fixture.readlink("/etc/existing"), "/") def test_already_exists_notalink(self): """ Test for the path already existing but is not a link. """ with self.fixture.open("/bar_notalink", "w") as fp: fp.write("") with self.fixture.open("/foo", "w") as fp: fp.write("") self.fixture.check_apply(""" resources: - Link: name: /bar_notalink to: /foo """) self.failUnlessEqual(self.fixture.readlink("/bar_notalink"), "/foo") def test_already_exists_pointing_elsewhere(self): """ Test for the path already existing but being a link to somewhere else. """ self.fixture.touch("/baz") self.fixture.touch("/foo") self.fixture.symlink("/baz", "/bar_elsewhere") self.fixture.check_apply(""" resources: - Link: name: /bar_elsewhere to: /foo """) self.failUnlessEqual(self.fixture.readlink("/bar_elsewhere"), "/foo") def test_dangling(self): rv = self.fixture.apply(""" resources: - Link: name: /etc/test_dangling to: /etc/not_there """) self.assertEqual(rv, error.DanglingSymlink.returncode) def test_unicode(self): self.fixture.check_apply(open(sibpath("link_unicode1.yay")).read())
{"/yaybu/resources/prompt.py": ["/yaybu/core/resource.py", "/yaybu/core/policy.py", "/yaybu/core/argument.py"], "/yaybu/core/protocol/changelog.py": ["/yaybu/core/protocol/server.py"], "/yaybu/core/tests/test_whitehat.py": ["/yaybu/core/whitehat.py"], "/yaybu/providers/git.py": ["/yaybu/core/error.py"], "/yaybu/providers/tests/test_subversion.py": ["/yaybu/core/error.py"], "/yaybu/providers/tests/test_filesystem.py": ["/yaybu/providers/filesystem/__init__.py"], "/yaybu/providers/tests/test_rsync.py": ["/yaybu/core/error.py"], "/yaybu/providers/filesystem/directory.py": ["/yaybu/providers/filesystem/files.py"], "/yaybu/core/protocol/file.py": ["/yaybu/core/protocol/server.py"]}
32,393
marchon/yaybu
refs/heads/master
/yaybu/core/tests/test_random.py
from yaybu.harness import FakeChrootTestCase from yaybu.core import resource from yaybu.core import argument from yaybu.core import error import mock class Test_Random(FakeChrootTestCase): # needs more work, particularly the File argument def resource_args(self, resource): for k, v in resource.__dict__.items(): if isinstance(v, argument.Argument): yield k, v.__class__ def resource_test_valid(self, resource): d = {} for name, klass in self.resource_args(resource): d[name] = klass._generate_valid() r = resource(**d) shell = mock.Mock() ctx = mock.Mock() ctx.simulate = True ctx.shell = shell ctx.shell.execute = mock.Mock(return_value=(0, '', '')) config = mock.Mock() try: r.apply(ctx, config) except error.Error: pass def NOtest_random(self): for r in resource.ResourceType.resources.values(): self.resource_test_valid(r)
{"/yaybu/resources/prompt.py": ["/yaybu/core/resource.py", "/yaybu/core/policy.py", "/yaybu/core/argument.py"], "/yaybu/core/protocol/changelog.py": ["/yaybu/core/protocol/server.py"], "/yaybu/core/tests/test_whitehat.py": ["/yaybu/core/whitehat.py"], "/yaybu/providers/git.py": ["/yaybu/core/error.py"], "/yaybu/providers/tests/test_subversion.py": ["/yaybu/core/error.py"], "/yaybu/providers/tests/test_filesystem.py": ["/yaybu/providers/filesystem/__init__.py"], "/yaybu/providers/tests/test_rsync.py": ["/yaybu/core/error.py"], "/yaybu/providers/filesystem/directory.py": ["/yaybu/providers/filesystem/files.py"], "/yaybu/core/protocol/file.py": ["/yaybu/core/protocol/server.py"]}
32,394
marchon/yaybu
refs/heads/master
/yaybu/core/debug.py
# Copyright 2011 Isotoma Limited # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import pdb, socket, sys class Rdb(pdb.Pdb): def __init__(self, port=4444): self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.socket.bind(("127.0.0.1", port)) self.socket.listen(1) client, address = self.socket.accept() handle = client.makefile('rw') pdb.Pdb.__init__(self, completekey='tab', stdin=handle, stdout=handle) def do_continue(self, arg): self.socket.shutdown(socket.SHUT_RDWR) self.socket.close() self.socket = None self.set_continue() return 1 def __enter__(self): return self def __exit__(self, *args): if self.socket: self.socket.shutdown(socket.SHUT_RDWR) self.socket.close() return False def set_trace(): Rdb().set_trace(sys._getframe().f_back) def post_mortem(exc_traceback=None): if exc_traceback is None: exc_type, exc_value, exc_traceback = sys.exc_info() with Rdb() as p: p.reset() p.interaction(None, exc_traceback) def pm(): post_mortem(sys.last_traceback)
{"/yaybu/resources/prompt.py": ["/yaybu/core/resource.py", "/yaybu/core/policy.py", "/yaybu/core/argument.py"], "/yaybu/core/protocol/changelog.py": ["/yaybu/core/protocol/server.py"], "/yaybu/core/tests/test_whitehat.py": ["/yaybu/core/whitehat.py"], "/yaybu/providers/git.py": ["/yaybu/core/error.py"], "/yaybu/providers/tests/test_subversion.py": ["/yaybu/core/error.py"], "/yaybu/providers/tests/test_filesystem.py": ["/yaybu/providers/filesystem/__init__.py"], "/yaybu/providers/tests/test_rsync.py": ["/yaybu/core/error.py"], "/yaybu/providers/filesystem/directory.py": ["/yaybu/providers/filesystem/files.py"], "/yaybu/core/protocol/file.py": ["/yaybu/core/protocol/server.py"]}
32,395
marchon/yaybu
refs/heads/master
/yaybu/core/argument.py
# Copyright 2011 Isotoma Limited # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import error import datetime import dateutil.parser import types import urlparse import sys import os from abc import ABCMeta, abstractmethod, abstractproperty import unicodedata import random import yay unicode_glyphs = ''.join( unichr(char) for char in xrange(sys.maxunicode+1) if unicodedata.category(unichr(char))[0] in ('LMNPSZ') ) # we abuse urlparse for our parsing needs urlparse.uses_netloc.append("package") class Argument(object): """ Stores the argument value on the instance object. It's a bit fugly, neater ways of doing this that do not involve passing extra arguments to Argument are welcome. """ metaclass = ABCMeta argument_id = 0 def __init__(self, **kwargs): self.default = kwargs.pop("default", None) self.__doc__ = kwargs.pop("help", None) self.arg_id = "argument_%d" % Argument.argument_id Argument.argument_id += 1 def __get__(self, instance, owner): if instance is None: # sphinx complains? #raise AttributeError return None if hasattr(instance, self.arg_id): return getattr(instance, self.arg_id) else: return self.default @abstractmethod def __set__(self, instance, value): """ Set the property. The value will be a UTF-8 encoded string read from the yaml source file. """ class Boolean(Argument): """ Represents a boolean. "1", "yes", "on" and "true" are all considered to be True boolean values. Anything else is False. """ def __set__(self, instance, value): if type(value) in types.StringTypes: if value.lower() in ("1", "yes", "on", "true"): value = True else: value = False else: value = bool(value) setattr(instance, self.arg_id, value) class String(Argument): """ Represents a string. """ def __set__(self, instance, value): if value is None: pass elif not isinstance(value, (unicode, yay.String)): value = unicode(value, 'utf-8') setattr(instance, self.arg_id, value) @classmethod def _generate_valid(self): l = [] for i in range(random.randint(0, 1024)): l.append(random.choice(unicode_glyphs)) return "".join(l) class FullPath(Argument): """ Represents a full path on the filesystem. This should start with a '/'. """ def __set__(self, instance, value): if value is None: pass elif not isinstance(value, unicode): value = unicode(value, 'utf-8') if not value.startswith("/"): raise error.ParseError("%s is not a full path" % value) setattr(instance, self.arg_id, value) @classmethod def _generate_valid(self): # TODO: needs work l = [] for i in range(random.randint(0, 1024)): l.append(random.choice(unicode_glyphs)) return "/" + "".join(l) class Integer(Argument): """ Represents an integer argument taken from the source file. This can throw an :py:exc:error.ParseError if the passed in value cannot represent a base-10 integer. """ def __set__(self, instance, value): if not isinstance(value, int): try: value = int(value) except ValueError: raise error.ParseError("%s is not an integer" % value) setattr(instance, self.arg_id, value) @classmethod def _generate_valid(self): return random.randint(0,sys.maxint) class DateTime(Argument): """ Represents a date and time. This is parsed in ISO8601 format. """ def __set__(self, instance, value): if isinstance(value, basestring): value = dateutil.parser.parse(value) setattr(instance, self.arg_id, value) @classmethod def _generate_valid(self): return datetime.datetime.fromtimestamp(random.randint(0, sys.maxint)) class Octal(Integer): """ An octal integer. This is specifically used for file permission modes. """ def __set__(self, instance, value): if isinstance(value, int): # we assume this is due to lame magic in yaml and rebase it value = int(str(value), 8) else: value = int(value, 8) setattr(instance, self.arg_id, value) class Dict(Argument): def __set__(self, instance, value): setattr(instance, self.arg_id, value) @classmethod def _generate_valid(self): return {} class List(Argument): def __set__(self, instance, value): setattr(instance, self.arg_id, value) @classmethod def _generate_valid(self): return [] class File(Argument): """ Provided with a URL, this can get files by various means. Often used with the package:// scheme """ def __set__(self, instance, value): setattr(instance, self.arg_id, value) class StandardPolicy: def __init__(self, policy_name): self.policy_name = policy_name class PolicyTrigger: def __init__(self, policy, when, on, immediately=True): self.policy = policy self.when = when self.on = on self.immediately = immediately def bind(self, resources, target): if self.on in resources: resources[self.on].register_observer(self.when, target, self.policy, self.immediately) else: raise error.BindingError("Cannot bind %r to missing resource named '%s'" % (target, self.on)) return resources[self.on] class PolicyCollection: """ A collection of policy structures. """ literal = None """ The policy that is set as the "standard" policy, not one that depends on a trigger. """ triggers = () """ A list of PolicyTrigger objects that represent optional triggered policies. """ def __init__(self, literal=None, triggers=()): self.literal = literal self.triggers = triggers def literal_policy(self, resource): if self.literal is not None: return resource.policies[self.literal.policy_name] else: import policy return policy.NullPolicy class PolicyArgument(Argument): """ Parses the policy: argument for resources, including triggers etc. """ def __set__(self, instance, value): """ Set either a default policy or a set of triggers on the policy collection """ if type(value) in types.StringTypes: coll = PolicyCollection(StandardPolicy(value)) else: triggers = [] for policy, conditions in value.items(): if not isinstance(conditions, list): conditions = [conditions] for condition in conditions: triggers.append( PolicyTrigger( policy=policy, when=condition['when'], on=condition['on'], immediately=condition.get('immediately', 'true') == 'true') ) coll = PolicyCollection(triggers=triggers) setattr(instance, self.arg_id, coll)
{"/yaybu/resources/prompt.py": ["/yaybu/core/resource.py", "/yaybu/core/policy.py", "/yaybu/core/argument.py"], "/yaybu/core/protocol/changelog.py": ["/yaybu/core/protocol/server.py"], "/yaybu/core/tests/test_whitehat.py": ["/yaybu/core/whitehat.py"], "/yaybu/providers/git.py": ["/yaybu/core/error.py"], "/yaybu/providers/tests/test_subversion.py": ["/yaybu/core/error.py"], "/yaybu/providers/tests/test_filesystem.py": ["/yaybu/providers/filesystem/__init__.py"], "/yaybu/providers/tests/test_rsync.py": ["/yaybu/core/error.py"], "/yaybu/providers/filesystem/directory.py": ["/yaybu/providers/filesystem/files.py"], "/yaybu/core/protocol/file.py": ["/yaybu/core/protocol/server.py"]}
32,396
marchon/yaybu
refs/heads/master
/yaybu/core/protocol/server.py
# Copyright 2011 Isotoma Limited # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import sys import shutil from abc import ABCMeta, abstractmethod from BaseHTTPServer import BaseHTTPRequestHandler import StringIO class RequestHandler(BaseHTTPRequestHandler): def __init__(self, rfile, wfile): self.rfile = rfile self.wfile = wfile def address_string(self): return 'stdio' def log_message(self, format, *args): # Uncomment to get HTTP request logs # super(RequestHandler, self).log_message(format, *args) return def handle_one_request(self): self.raw_requestline = self.rfile.readline() if not self.raw_requestline: self.close_connection = 1 return False if not self.parse_request(): return False path = self.path if "?" in path: path, self.getargs = path.split("?", 1) if "#" in path: path, self.bookmark = path.split("#", 1) self.path = filter(None, path.split("/")) return True def write_fileobj(self, fileobj): shutil.copyfileobj(fileobj, self.wfile) def send_error(self, code, message=None): """Send and log an error reply. We override the standard python code *soley* to keep the connection alive """ try: short, long = self.responses[code] except KeyError: short, long = '???', '???' if message is None: message = short self.send_response(code, message) self.send_header("Content-Type", self.error_content_type) self.send_header('Connection', 'keepalive') self.end_headers() class Server(object): def __init__(self, context, root, rfile=sys.stdin, wfile=sys.stdout): self.context = context self.root = root self.rfile = rfile self.wfile = wfile self.handlers = [] def handle_request(self): # This will use BaseHTTPRequestHandler to parse HTTP headers off stdin, # stdin is then ready to read any payload? r = RequestHandler(self.rfile, self.wfile) if not r.handle_one_request(): return False node = self.root try: if r.path: segment, rest = r.path[0], r.path[1:] while segment: node = node.get_child(segment) if node.leaf: break if not rest: break segment, rest = rest[0], rest[1:] node.render(self.context, r, "/".join(rest)) except Error, e: e.render(r, None) return True def serve_forever(self): while self.handle_request(): pass class Error(Exception): def render(self, request, post): request.send_error(self.error_code, self.error_string) class NotFound(Error): error_code = 404 error_string = "Resource not found" class MethodNotSupported(Error): error_code = 501 error_string = "Method not supported" class HttpResource(object): leaf = False def __init__(self): self.children = {} def put_child(self, key, child): self.children[key] = child def get_child(self, key): if key in self.children: return self.children[key] raise NotFound(key) def render(self, yaybu, request, postpath): if not hasattr(self, "render_" + request.command): raise MethodNotSupported(request.command) getattr(self, "render_" + request.command)(yaybu, request, postpath) class StaticResource(HttpResource): leaf = True def __init__(self, content): super(StaticResource, self).__init__() self.content = content def render_GET(self, yaybu, request, postpath): request.send_response(200, "OK") request.send_header("Content-Type", "application/json") request.send_header("Content-Length", str(len(self.content))) request.send_header("Content", "keep-alive") request.end_headers() request.write_fileobj(StringIO.StringIO(self.content)) class AboutResource(HttpResource): leaf = True def get_version(self, thing): """ Returns the version of a python egg. Returns 0 if it can't be determined """ import pkg_resources try: return pkg_resources.get_distribution(thing).version except pkg_resources.DistributionNotFound: return "0" def render_GET(self, yaybu, request, postpath): request.send_response(200, "OK") request.send_header("Content-Type", "text/plain") request.send_header("Content-Length", "0") request.send_header("Content", "keep-alive") request.send_header("Yaybu", self.get_version("Yaybu")) request.send_header("yay", self.get_version("yay")) request.end_headers() request.write_fileobj(StringIO.StringIO(""))
{"/yaybu/resources/prompt.py": ["/yaybu/core/resource.py", "/yaybu/core/policy.py", "/yaybu/core/argument.py"], "/yaybu/core/protocol/changelog.py": ["/yaybu/core/protocol/server.py"], "/yaybu/core/tests/test_whitehat.py": ["/yaybu/core/whitehat.py"], "/yaybu/providers/git.py": ["/yaybu/core/error.py"], "/yaybu/providers/tests/test_subversion.py": ["/yaybu/core/error.py"], "/yaybu/providers/tests/test_filesystem.py": ["/yaybu/providers/filesystem/__init__.py"], "/yaybu/providers/tests/test_rsync.py": ["/yaybu/core/error.py"], "/yaybu/providers/filesystem/directory.py": ["/yaybu/providers/filesystem/files.py"], "/yaybu/core/protocol/file.py": ["/yaybu/core/protocol/server.py"]}
32,397
marchon/yaybu
refs/heads/master
/yaybu/providers/filesystem/link.py
# Copyright 2011 Isotoma Limited # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import sys import os import stat import pwd import grp import logging from yaybu import resources from yaybu.core import provider, error class Link(provider.Provider): policies = (resources.link.LinkAppliedPolicy,) @classmethod def isvalid(self, *args, **kwargs): # TODO: validation could provide warnings based on things # that are not the correct state at the point of invocation # but that will be modified by the yaybu script return super(Link, self).isvalid(*args, **kwargs) def _get_owner(self): """ Return the uid for the resource owner, or None if no owner is specified. """ if self.resource.owner is not None: try: return pwd.getpwnam(self.resource.owner).pw_uid except KeyError: raise error.InvalidUser() def _get_group(self): """ Return the gid for the resource group, or None if no group is specified. """ if self.resource.group is not None: try: return grp.getgrnam(self.resource.group).gr_gid except KeyError: raise error.InvalidGroup() def _stat(self): """ Extract stat information for the resource. """ st = os.lstat(self.resource.name) uid = st.st_uid gid = st.st_gid mode = stat.S_IMODE(st.st_mode) return uid, gid, mode def apply(self, context): changed = False name = self.resource.name to = self.resource.to exists = False uid = None gid = None mode = None isalink = False if not os.path.exists(to): if not context.simulate: raise error.DanglingSymlink("Destination of symlink %r does not exist" % to) context.changelog.info("Destination of sylink %r does not exist" % to) owner = self._get_owner() group = self._get_group() try: linkto = os.readlink(name) isalink = True except OSError: isalink = False if not isalink or linkto != to: if os.path.exists(name): context.shell.execute(["/bin/rm", "-rf", name]) context.shell.execute(["/bin/ln", "-s", self.resource.to, name]) changed = True try: linkto = os.readlink(name) isalink = True except OSError: isalink = False if not isalink and not context.simulate: raise error.OperationFailed("Did not create expected symbolic link") if isalink: uid, gid, mode = self._stat() if owner is not None and owner != uid: context.shell.execute(["/bin/chown", "-h", self.resource.owner, name]) changed = True if group is not None and group != gid: context.shell.execute(["/bin/chgrp", "-h", self.resource.group, name]) changed = True return changed class RemoveLink(provider.Provider): policies = (resources.link.LinkRemovedPolicy,) @classmethod def isvalid(self, *args, **kwargs): return super(RemoveLink, self).isvalid(*args, **kwargs) def apply(self, context): if os.path.exists(self.resource.name): if not os.path.islink(self.resource.name): raise error.InvalidProvider("%r: %s exists and is not a link" % (self, self.resource.name)) context.shell.execute(["/bin/rm", self.resource.name]) changed = True else: context.changelog.info("File %s missing already so not removed" % self.resource.name) changed = False return changed
{"/yaybu/resources/prompt.py": ["/yaybu/core/resource.py", "/yaybu/core/policy.py", "/yaybu/core/argument.py"], "/yaybu/core/protocol/changelog.py": ["/yaybu/core/protocol/server.py"], "/yaybu/core/tests/test_whitehat.py": ["/yaybu/core/whitehat.py"], "/yaybu/providers/git.py": ["/yaybu/core/error.py"], "/yaybu/providers/tests/test_subversion.py": ["/yaybu/core/error.py"], "/yaybu/providers/tests/test_filesystem.py": ["/yaybu/providers/filesystem/__init__.py"], "/yaybu/providers/tests/test_rsync.py": ["/yaybu/core/error.py"], "/yaybu/providers/filesystem/directory.py": ["/yaybu/providers/filesystem/files.py"], "/yaybu/core/protocol/file.py": ["/yaybu/core/protocol/server.py"]}
32,398
marchon/yaybu
refs/heads/master
/yaybu/harness/testcase.py
# Copyright 2011 Isotoma Limited # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import unittest import testtools class TestCase(testtools.TestCase): def useFixture(self, fixture): """ Use a fixture in a test case. The fixture will be setUp, and self.addCleanup(fixture.cleanUp) called. The fixture will be available as self.fixture. :param fixture: The fixture to use :return: The fixture, after setting it up and scheduling a cleanup for it """ self.fixture = fixture return super(TestCase, self).useFixture(fixture) def failUnlessExists(self, path): if not self.fixture.exists(path): self.fail("Path '%s' does not exist" % path) def failIfExists(self, path): if self.fixture.exists(path): self.fail("Path '%s' exists" % path)
{"/yaybu/resources/prompt.py": ["/yaybu/core/resource.py", "/yaybu/core/policy.py", "/yaybu/core/argument.py"], "/yaybu/core/protocol/changelog.py": ["/yaybu/core/protocol/server.py"], "/yaybu/core/tests/test_whitehat.py": ["/yaybu/core/whitehat.py"], "/yaybu/providers/git.py": ["/yaybu/core/error.py"], "/yaybu/providers/tests/test_subversion.py": ["/yaybu/core/error.py"], "/yaybu/providers/tests/test_filesystem.py": ["/yaybu/providers/filesystem/__init__.py"], "/yaybu/providers/tests/test_rsync.py": ["/yaybu/core/error.py"], "/yaybu/providers/filesystem/directory.py": ["/yaybu/providers/filesystem/files.py"], "/yaybu/core/protocol/file.py": ["/yaybu/core/protocol/server.py"]}
32,399
marchon/yaybu
refs/heads/master
/yaybu/providers/group.py
# Copyright 2011 Isotoma Limited # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import grp from yaybu.core import provider from yaybu.core import error from yaybu import resources import logging logger = logging.getLogger("provider") class Group(provider.Provider): policies = (resources.group.GroupApplyPolicy,) @classmethod def isvalid(self, *args, **kwargs): return super(Group, self).isvalid(*args, **kwargs) def get_group_info(self): fields = ("name", "passwd", "gid", "members",) try: info_tuple = grp.getgrnam(self.resource.name.encode("utf-8")) except KeyError: info = dict((f, None) for f in fields) info["exists"] = False return info info = {"exists": True} for i, field in enumerate(fields): info[field] = info_tuple[i] return info def apply(self, context): changed = False info = self.get_group_info() if info["exists"]: command = ["groupmod"] else: command = ["groupadd"] changed = True if self.resource.gid and info["gid"] != self.resource.gid: command.extend(["--gid", str(self.resource.gid)]) command.extend([self.resource.name]) if not changed: return False returncode, stdout, stderr = context.shell.execute(command) if returncode != 0: raise error.GroupError("%s failed with return code %d" % (self.resource, returncode)) return True class GroupRemove(provider.Provider): policies = (resources.group.GroupRemovePolicy,) @classmethod def isvalid(self, *args, **kwargs): return super(GroupRemove, self).isvalid(*args, **kwargs) def apply(self, context): try: existing = grp.getgrnam(self.resource.name.encode("utf-8")) except KeyError: # If we get a key errror then there is no such group. This is good. return False command = ["groupdel", self.resource.name] returncode, stdout, stderr = context.shell.execute(command) if returncode != 0: raise error.GroupError("Removing group %s failed with return code %d" % (self.resource, returncode)) return True
{"/yaybu/resources/prompt.py": ["/yaybu/core/resource.py", "/yaybu/core/policy.py", "/yaybu/core/argument.py"], "/yaybu/core/protocol/changelog.py": ["/yaybu/core/protocol/server.py"], "/yaybu/core/tests/test_whitehat.py": ["/yaybu/core/whitehat.py"], "/yaybu/providers/git.py": ["/yaybu/core/error.py"], "/yaybu/providers/tests/test_subversion.py": ["/yaybu/core/error.py"], "/yaybu/providers/tests/test_filesystem.py": ["/yaybu/providers/filesystem/__init__.py"], "/yaybu/providers/tests/test_rsync.py": ["/yaybu/core/error.py"], "/yaybu/providers/filesystem/directory.py": ["/yaybu/providers/filesystem/files.py"], "/yaybu/core/protocol/file.py": ["/yaybu/core/protocol/server.py"]}
32,400
marchon/yaybu
refs/heads/master
/docs/minidoc.py
from sphinx.ext.autodoc import Documenter import sys def format_name(self): if self.objpath: return self.objpath[-1] def add_directive_header(self, sig): """Add the directive header and options to the generated content.""" domain = getattr(self, 'domain', 'py') directive = getattr(self, 'directivetype', self.objtype) name = self.format_name() self.add_line(u'.. %s:%s:: %s%s' % (domain, directive, name, sig), '<autodoc>') if self.options.noindex: self.add_line(u' :noindex:', '<autodoc>') Documenter.format_name = format_name Documenter.add_directive_header = add_directive_header
{"/yaybu/resources/prompt.py": ["/yaybu/core/resource.py", "/yaybu/core/policy.py", "/yaybu/core/argument.py"], "/yaybu/core/protocol/changelog.py": ["/yaybu/core/protocol/server.py"], "/yaybu/core/tests/test_whitehat.py": ["/yaybu/core/whitehat.py"], "/yaybu/providers/git.py": ["/yaybu/core/error.py"], "/yaybu/providers/tests/test_subversion.py": ["/yaybu/core/error.py"], "/yaybu/providers/tests/test_filesystem.py": ["/yaybu/providers/filesystem/__init__.py"], "/yaybu/providers/tests/test_rsync.py": ["/yaybu/core/error.py"], "/yaybu/providers/filesystem/directory.py": ["/yaybu/providers/filesystem/files.py"], "/yaybu/core/protocol/file.py": ["/yaybu/core/protocol/server.py"]}
32,401
marchon/yaybu
refs/heads/master
/yaybu/core/tests/test_resource.py
# Copyright 2011 Isotoma Limited # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import unittest import datetime from yaybu.core import (resource, argument, policy, error, provider, change, ) from mock import Mock class F(resource.Resource): foo = argument.String(default="42") bar = argument.String() class G(resource.Resource): foo = argument.String() bar = argument.String() class H(resource.Resource): foo = argument.Integer() bar = argument.DateTime() baz = argument.File() class TestResource(unittest.TestCase): def test_init(self): h = H(**{ 'name': 'test', 'foo': u'42', 'bar': u'20100501', }) self.assertEqual(h.foo, 42) self.assertEqual(h.bar, datetime.datetime(2010, 05, 01)) class TestArgument(unittest.TestCase): def test_storage(self): f1 = F(name="test") f2 = F(name="test") g1 = G(name="test") g2 = G(name="test") f1.foo = "a" f1.bar = "b" f2.foo = "c" f2.bar = "d" g1.foo = "e" g1.bar = "f" g2.foo = "g" g2.bar = "h" self.assertEqual(f1.foo, "a") self.assertEqual(f1.bar, "b") self.assertEqual(f2.foo, "c") self.assertEqual(f2.bar, "d") self.assertEqual(g1.foo, "e") self.assertEqual(g1.bar, "f") self.assertEqual(g2.foo, "g") self.assertEqual(g2.bar, "h") def test_default(self): f = F(name="test") self.assertEqual(f.foo, "42") def test_integer(self): h = H(name="test") h.foo = u"42" self.assertEqual(h.foo, 42) def test_datetime(self): h = H(name="test") h.bar = "20100105" self.assertEqual(h.bar, datetime.datetime(2010, 1, 5)) class TestArgumentAssertion(unittest.TestCase): def test_present(self): class P(policy.Policy): signature = [policy.Present("foo")] class Q(policy.Policy): signature = [policy.Present("bar")] class R(policy.Policy): signature = [policy.Present("baz")] f = F(name="test") self.assertEqual(P.conforms(f), True) self.assertEqual(Q.conforms(f), False) self.assertRaises(AttributeError, R.conforms, f) def test_absent(self): class P(policy.Policy): signature = [policy.Absent("foo")] class Q(policy.Policy): signature = [policy.Absent("bar")] class R(policy.Policy): signature = [policy.Absent("baz")] f = F(name="test") self.assertEqual(P.conforms(f), False) self.assertEqual(Q.conforms(f), True) self.assertRaises(AttributeError, R.conforms, f) def test_and(self): class P(policy.Policy): signature = [policy.Present("foo"), policy.Absent("bar"), ] f = F(name="test") self.assertEqual(P.conforms(f), True) def test_xor(self): class P(policy.Policy): signature = [policy.XOR( policy.Present("foo"), policy.Present("bar"), )] g = G(name="test") self.assertEqual(P.conforms(g), False) g.foo = "yes" self.assertEqual(P.conforms(g), True) g.bar = "yes" self.assertEqual(P.conforms(g), False) g.foo = None self.assertEqual(P.conforms(g), True) class Ev1(resource.Resource): pass class Ev1FooPolicy(policy.Policy): name = "foo" resource = Ev1 class Ev1BarPolicy(policy.Policy): name = "bar" resource = Ev1 class Ev1BazPolicy(policy.Policy): name = "baz" resource = Ev1 class Ev1Provider(provider.Provider): policies = (Ev1FooPolicy, Ev1BarPolicy, Ev1BazPolicy) applied = 0 def apply(self, shell): Ev1Provider.applied += 1 return True class TestResourceBundle(unittest.TestCase): def setUp(self): from yaybu.core import event event.reset() def test_creation(self): resources = resource.ResourceBundle([ {"File": [{ "name": "/etc/foo", "mode": "666", }] }]) self.assertEqual(resources["File[/etc/foo]"].mode, 438) def test_firing(self): Ev1Provider.applied = 0 resources = resource.ResourceBundle([ {"Ev1": [ { "name": "e1", "policy": "foo", }, { "name": "e2", "policy": {"baz": [{ "when": "foo", "on": "Ev1[e1]", }], }, }, ]}]) e1 = resources['Ev1[e1]'] e2 = resources['Ev1[e2]'] resources.bind() self.assertEqual(dict(e2.observers), {}) self.assertEqual(dict(e1.observers), {'foo': [ (True, e2, 'baz')] }) shell = Mock() p1 = e1.get_default_policy().get_provider({}) p2 = e2.get_default_policy().get_provider({}) self.assertEqual(p1, Ev1Provider) self.assertEqual(p2, provider.NullProvider) e1.apply(shell) self.assertEqual(Ev1Provider.applied, 1) e2.apply(shell) self.assertEqual(Ev1Provider.applied, 2) def test_not_firing(self): Ev1Provider.applied = 0 resources = resource.ResourceBundle([ {"Ev1": [ { "name": "e1", "policy": "foo", }, { "name": "e2", "policy": {"baz": [{ "when": "baz", "on": "Ev1[e1]", }], }, }, ]}]) e1 = resources['Ev1[e1]'] e2 = resources['Ev1[e2]'] resources.bind() self.assertEqual(dict(e2.observers), {}) self.assertEqual(dict(e1.observers), {'baz': [ (True, e2, 'baz')] }) shell = Mock() p1 = e1.get_default_policy().get_provider({}) p2 = e2.get_default_policy().get_provider({}) self.assertEqual(p1, Ev1Provider) self.assertEqual(p2, provider.NullProvider) e1.apply(shell) self.assertEqual(Ev1Provider.applied, 1) e2.apply(shell) self.assertEqual(Ev1Provider.applied, 1) def test_forwardreference(self): Ev1Provider.applied = 0 resources = resource.ResourceBundle([ {"Ev1": [ { "name": "e1", "policy": {"baz": [{ "when": "baz", "on": "Ev1[e2]", }], }, }, { "name": "e2", "policy": "foo", } ]}]) e1 = resources['Ev1[e1]'] e2 = resources['Ev1[e2]'] self.assertRaises(error.BindingError, resources.bind) def test_structure(self): e1 = Ev1(name="e1", policy = { 'pol1': { 'when': 'bar', 'on': 'e2'}, }) e2 = Ev1(name="e2") resources = {'e1': e1, 'e2': e2} e1.bind(resources) e2.bind(resources) self.assertEqual(len(e1.observers), 0) self.assertEqual(dict(e2.observers), { 'bar': [(True, e1, 'pol1')] }) def test_multiple(self): e1 = Ev1(name="e1", policy = { 'pol1': [{ 'when': 'bar', 'on': 'e2'}], 'pol2': [{ 'when': 'foo', 'on': 'e3'}], 'pol3': [{ 'when': 'baz', 'on': 'e2', }] }) e2 = Ev1(name="e2") e3 = Ev1(name="e3") resources = {'e1': e1, 'e2': e2, 'e3': e3} e1.bind(resources) e2.bind(resources) self.assertEqual(dict(e1.observers), {}) self.assertEqual(dict(e2.observers), { 'bar': [(True, e1, 'pol1')], 'baz': [(True, e1, 'pol3')], }) self.assertEqual(dict(e3.observers), { 'foo': [(True, e1, 'pol2')], }) def test_missing(self): e1 = Ev1(name="e1", policy = { 'pol1': [{ 'when': 'bar', 'on': 'missing'}], }) e2 = Ev1(name="e2") resources = {'e1': e1, 'e2': e2} self.assertRaises(error.BindingError, e1.bind, resources)
{"/yaybu/resources/prompt.py": ["/yaybu/core/resource.py", "/yaybu/core/policy.py", "/yaybu/core/argument.py"], "/yaybu/core/protocol/changelog.py": ["/yaybu/core/protocol/server.py"], "/yaybu/core/tests/test_whitehat.py": ["/yaybu/core/whitehat.py"], "/yaybu/providers/git.py": ["/yaybu/core/error.py"], "/yaybu/providers/tests/test_subversion.py": ["/yaybu/core/error.py"], "/yaybu/providers/tests/test_filesystem.py": ["/yaybu/providers/filesystem/__init__.py"], "/yaybu/providers/tests/test_rsync.py": ["/yaybu/core/error.py"], "/yaybu/providers/filesystem/directory.py": ["/yaybu/providers/filesystem/files.py"], "/yaybu/core/protocol/file.py": ["/yaybu/core/protocol/server.py"]}
32,402
marchon/yaybu
refs/heads/master
/yaybu/core/policy.py
# Copyright 2011 Isotoma Limited # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import error class PolicyType(type): """ Registers the policy on the resource """ def __new__(meta, class_name, bases, new_attrs): cls = type.__new__(meta, class_name, bases, new_attrs) cls.providers = [] if cls.resource is not None: cls.resource.policies[cls.name] = cls return cls class Policy(object): """ A policy is a representation of a resource. A policy requires a certain argument signature to be present before it can be used. There may be multiple policies selected for a resource, in which case all argument signatures must be conformant. Providers must provide all selected policies to be a valid provider for the resource. """ __metaclass__ = PolicyType # specify true if you wish this policy to be enabled by default default = False # the name of the policy, used to find it in the ensures config name = None # specify the resource to which this policy applies resource = None # the list of providers that provide this policy providers = [] # Override this with a list of assertions signature = () def __init__(self, resource): self.resource = resource @classmethod def conforms(self, resource): """ Test if the provided resource conforms to the signature for this policy. """ for a in self.signature: if not a.test(resource): return False return True def get_provider(self, yay): """ Get the one and only one provider that is valid for this resource, policy and overall context """ valid = [p.isvalid(self, self.resource, yay) for p in self.providers] if valid.count(True) > 1: raise error.TooManyProviders() if valid.count(True) == 0: raise error.NoSuitableProviders() return self.providers[valid.index(True)] class NullPolicy(Policy): pass class ArgumentAssertion(object): """ An assertion of the state of an argument """ def __init__(self, name): self.name = name class Present(ArgumentAssertion): """ The argument has been specified, or has a default value. """ def test(self, resource): """ Test that the argument this asserts for is present in the resource. """ if getattr(resource, self.name) is not None: return True return False class Absent(ArgumentAssertion): """ The argument has not been specified by the user and has no default value. An argument with a default value is always defined. """ def test(self, resource): if getattr(resource, self.name) is None: return True return False class AND(ArgumentAssertion): def __init__(self, *args): self.args = args def test(self, resource): for a in self.args: if not a.test(resource): return False return True class NAND(ArgumentAssertion): def __init__(self, *args): self.args = args def test(self, resource): results = [1 for a in self.args if a.test(resource)] if len(results) > 1: return False return True class XOR(ArgumentAssertion): def __init__(self, *args): self.args = args def test(self, resource): l = [1 for a in self.args if a.test(resource)] if len(l) == 0: return False elif len(l) == 1: return True else: return False
{"/yaybu/resources/prompt.py": ["/yaybu/core/resource.py", "/yaybu/core/policy.py", "/yaybu/core/argument.py"], "/yaybu/core/protocol/changelog.py": ["/yaybu/core/protocol/server.py"], "/yaybu/core/tests/test_whitehat.py": ["/yaybu/core/whitehat.py"], "/yaybu/providers/git.py": ["/yaybu/core/error.py"], "/yaybu/providers/tests/test_subversion.py": ["/yaybu/core/error.py"], "/yaybu/providers/tests/test_filesystem.py": ["/yaybu/providers/filesystem/__init__.py"], "/yaybu/providers/tests/test_rsync.py": ["/yaybu/core/error.py"], "/yaybu/providers/filesystem/directory.py": ["/yaybu/providers/filesystem/files.py"], "/yaybu/core/protocol/file.py": ["/yaybu/core/protocol/server.py"]}
32,403
marchon/yaybu
refs/heads/master
/yaybu/core/tests/test_watched.py
import os import sys from yaybu.harness import FakeChrootTestCase from yaybu.core import error class TestWatched(FakeChrootTestCase): def test_watched(self): self.fixture.check_apply(""" resources: - Execute: name: test_watched command: touch /watched-file creates: /watched-file watch: - /watched-file - Execute: name: test_output command: touch /event-triggered creates: /event-triggered policy: execute: when: watched on: File[/watched-file] """) self.failUnlessExists("/event-triggered")
{"/yaybu/resources/prompt.py": ["/yaybu/core/resource.py", "/yaybu/core/policy.py", "/yaybu/core/argument.py"], "/yaybu/core/protocol/changelog.py": ["/yaybu/core/protocol/server.py"], "/yaybu/core/tests/test_whitehat.py": ["/yaybu/core/whitehat.py"], "/yaybu/providers/git.py": ["/yaybu/core/error.py"], "/yaybu/providers/tests/test_subversion.py": ["/yaybu/core/error.py"], "/yaybu/providers/tests/test_filesystem.py": ["/yaybu/providers/filesystem/__init__.py"], "/yaybu/providers/tests/test_rsync.py": ["/yaybu/core/error.py"], "/yaybu/providers/filesystem/directory.py": ["/yaybu/providers/filesystem/files.py"], "/yaybu/core/protocol/file.py": ["/yaybu/core/protocol/server.py"]}
32,404
marchon/yaybu
refs/heads/master
/yaybu/providers/tests/test_package_apt.py
from yaybu.harness import FakeChrootTestCase from time import sleep class TestPackageInstallation(FakeChrootTestCase): def test_already_installed(self): rv = self.fixture.apply(""" resources: - Package: name: python """) self.assertEqual(rv, 255) def test_installation(self): self.fixture.check_apply(""" resources: - Package: name: hello """) def test_nonexistent_package(self): """ Try to install a package that does not exist. """ rv = self.fixture.apply(""" resources: - Package: name: zzzz """) self.assertEqual(rv, 132) def test_package_reinstallation(self): """ Try reinstalling a previously-removed package """ hello_install = """ resources: - Package: name: hello """ hello_remove = """ resources: - Package: name: hello policy: uninstall """ self.fixture.check_apply(hello_install) self.fixture.check_apply(hello_remove) self.fixture.check_apply(hello_install) class TestPackageRemoval(FakeChrootTestCase): def test_installed(self): """ Try removing a package that is installed. """ self.fixture.check_apply(""" resources: - Package: name: ubuntu-keyring policy: uninstall """)
{"/yaybu/resources/prompt.py": ["/yaybu/core/resource.py", "/yaybu/core/policy.py", "/yaybu/core/argument.py"], "/yaybu/core/protocol/changelog.py": ["/yaybu/core/protocol/server.py"], "/yaybu/core/tests/test_whitehat.py": ["/yaybu/core/whitehat.py"], "/yaybu/providers/git.py": ["/yaybu/core/error.py"], "/yaybu/providers/tests/test_subversion.py": ["/yaybu/core/error.py"], "/yaybu/providers/tests/test_filesystem.py": ["/yaybu/providers/filesystem/__init__.py"], "/yaybu/providers/tests/test_rsync.py": ["/yaybu/core/error.py"], "/yaybu/providers/filesystem/directory.py": ["/yaybu/providers/filesystem/files.py"], "/yaybu/core/protocol/file.py": ["/yaybu/core/protocol/server.py"]}
32,405
marchon/yaybu
refs/heads/master
/yaybu/core/tests/test_whitehat.py
# Copyright 2011 Isotoma Limited # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # (This is to test that resources we define outsite of yaybu.resources can # be picked up by whitehat) from yaybu.core import resource class WhiteHat(resource.Resource): pass import unittest from yaybu.core.whitehat import * def dummy_function(sitename): Directory( name = '{sitename}', ) class TestWhitehat(unittest.TestCase): def setUp(self): reset_bundle() def at(self, idx): return get_bundle().values()[idx] def test_custom_resources(self): WhiteHat(name='hello') self.failUnlessEqual(self.at(0).name, 'hello') def test_simple_locals(self): local1 = 'hello' local2 = '0755' File( name = '/etc/{local1}', mode = '{local2}', ) def test_for_each(self): for i in range(3): Service( name = 'zope{i}', ) self.failUnlessEqual(self.at(0).name, 'zope0') self.failUnlessEqual(self.at(1).name, 'zope1') self.failUnlessEqual(self.at(2).name, 'zope2') def test_function(self): dummy_function('/www.foo.com') self.failUnlessEqual(self.at(0).name, '/www.foo.com') def test_inner_function(self): def dummy_function(somevar): Directory( name = '/www.foo.com-{somevar}', ) dummy_function('test') self.failUnlessEqual(self.at(0).name, '/www.foo.com-test')
{"/yaybu/resources/prompt.py": ["/yaybu/core/resource.py", "/yaybu/core/policy.py", "/yaybu/core/argument.py"], "/yaybu/core/protocol/changelog.py": ["/yaybu/core/protocol/server.py"], "/yaybu/core/tests/test_whitehat.py": ["/yaybu/core/whitehat.py"], "/yaybu/providers/git.py": ["/yaybu/core/error.py"], "/yaybu/providers/tests/test_subversion.py": ["/yaybu/core/error.py"], "/yaybu/providers/tests/test_filesystem.py": ["/yaybu/providers/filesystem/__init__.py"], "/yaybu/providers/tests/test_rsync.py": ["/yaybu/core/error.py"], "/yaybu/providers/filesystem/directory.py": ["/yaybu/providers/filesystem/files.py"], "/yaybu/core/protocol/file.py": ["/yaybu/core/protocol/server.py"]}
32,406
marchon/yaybu
refs/heads/master
/yaybu/harness/fixture.py
# Copyright 2011 Isotoma Limited # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. try: from fixtures import Fixture as BaseFixture except ImportError: class BaseFixture(object): """ I am a Fixture compatible with the fixtures API by Robert Collins If the fixtures package is installed I won't be used. """ def getDetails(self): return {} class Fixture(BaseFixture): """ A base class for Fixtures that providing virtual environments to deploy configuration in. This base class is abstract and provides no concrete implementations. For a simple implementation of this interface see :py:class:`~yaybu.harness.fakechroot.FakeChrootFixture`. """ def exists(self, path): """ Checks whether or not a path exists in the target """ raise NotImplementedError(self.exists) def isdir(self, path): """ Checks whether or not a path is a directory in the target """ raise NotImplementedError(self.isdir) def mkdir(self, path): """ Creates a directory in the target """ raise NotImplementedError(self.mkdir) def open(self, path, mode='r'): """ Opens a file in the target """ raise NotImplementedError(self.open) def touch(self, path): """ Ensures that a file exists in the target """ raise NotImplementedError(self.touch) def chmod(self, path, mode): """ Change the permissions of a path in the target """ raise NotImplementedError(self.chmod) def readlink(self, path): """ Return a string containing the path that a symbolic link points to """ raise NotImplementedError(self.readlink) def symlink(self, source, dest): """ Create a symbolic link pointing to source at dest """ raise NotImplementedError(self.symlink) def stat(self, path): """ Perform the equivalent of the a stat() system call on the given path """ raise NotImplementedError(self.stat)
{"/yaybu/resources/prompt.py": ["/yaybu/core/resource.py", "/yaybu/core/policy.py", "/yaybu/core/argument.py"], "/yaybu/core/protocol/changelog.py": ["/yaybu/core/protocol/server.py"], "/yaybu/core/tests/test_whitehat.py": ["/yaybu/core/whitehat.py"], "/yaybu/providers/git.py": ["/yaybu/core/error.py"], "/yaybu/providers/tests/test_subversion.py": ["/yaybu/core/error.py"], "/yaybu/providers/tests/test_filesystem.py": ["/yaybu/providers/filesystem/__init__.py"], "/yaybu/providers/tests/test_rsync.py": ["/yaybu/core/error.py"], "/yaybu/providers/filesystem/directory.py": ["/yaybu/providers/filesystem/files.py"], "/yaybu/core/protocol/file.py": ["/yaybu/core/protocol/server.py"]}
32,407
marchon/yaybu
refs/heads/master
/yaybu/providers/tests/test_service_simple.py
import os, shutil, grp, signal from yaybu.harness import FakeChrootTestCase from yaybu.util import sibpath simpleservice = """ #! /usr/bin/env python import os, select, sys if __name__ == "__main__": if os.fork() != 0: os._exit(0) os.setsid() if os.fork() != 0: os._exit(0) open("simple_daemon.pid", "w").write(str(os.getpid())) #os.chdir("/") os.umask(0) for fd in range(0, 1024): try: os.close(fd) except OSError: pass os.open("/dev/null", os.O_RDWR) os.dup2(0, 1) os.dup2(0, 2) while True: select.select([sys.stdin], [], []) """ class TestSimpleService(FakeChrootTestCase): def setUp(self): super(TestSimpleService, self).setUp() with self.fixture.open("/bin/simple_daemon", "w") as fp: fp.write(simpleservice) def test_start(self): self.fixture.check_apply(""" resources: - Service: name: test policy: start start: python /bin/simple_daemon pidfile: /simple_daemon.pid """) with self.fixture.open("/simple_daemon.pid") as fp: pid = int(fp.read()) os.kill(pid, signal.SIGTERM) def test_stop(self): self.fixture.call(["python", "/bin/simple_daemon"]) self.fixture.check_apply(""" resources: - Service: name: test policy: stop stop: sh -c 'kill $(cat /simple_daemon.pid)' pidfile: /simple_daemon.pid """) def test_restart(self): rv = self.fixture.apply(""" resources: - Service: name: test policy: restart restart: touch /foo """) # We restart every time config is applied - so check_apply would fail the # automatic idempotentcy check self.failUnlessEqual(rv, 0) self.failUnlessExists("/foo")
{"/yaybu/resources/prompt.py": ["/yaybu/core/resource.py", "/yaybu/core/policy.py", "/yaybu/core/argument.py"], "/yaybu/core/protocol/changelog.py": ["/yaybu/core/protocol/server.py"], "/yaybu/core/tests/test_whitehat.py": ["/yaybu/core/whitehat.py"], "/yaybu/providers/git.py": ["/yaybu/core/error.py"], "/yaybu/providers/tests/test_subversion.py": ["/yaybu/core/error.py"], "/yaybu/providers/tests/test_filesystem.py": ["/yaybu/providers/filesystem/__init__.py"], "/yaybu/providers/tests/test_rsync.py": ["/yaybu/core/error.py"], "/yaybu/providers/filesystem/directory.py": ["/yaybu/providers/filesystem/files.py"], "/yaybu/core/protocol/file.py": ["/yaybu/core/protocol/server.py"]}
32,408
marchon/yaybu
refs/heads/master
/yaybu/providers/filesystem/__init__.py
import files import link import directory
{"/yaybu/resources/prompt.py": ["/yaybu/core/resource.py", "/yaybu/core/policy.py", "/yaybu/core/argument.py"], "/yaybu/core/protocol/changelog.py": ["/yaybu/core/protocol/server.py"], "/yaybu/core/tests/test_whitehat.py": ["/yaybu/core/whitehat.py"], "/yaybu/providers/git.py": ["/yaybu/core/error.py"], "/yaybu/providers/tests/test_subversion.py": ["/yaybu/core/error.py"], "/yaybu/providers/tests/test_filesystem.py": ["/yaybu/providers/filesystem/__init__.py"], "/yaybu/providers/tests/test_rsync.py": ["/yaybu/core/error.py"], "/yaybu/providers/filesystem/directory.py": ["/yaybu/providers/filesystem/files.py"], "/yaybu/core/protocol/file.py": ["/yaybu/core/protocol/server.py"]}
32,409
marchon/yaybu
refs/heads/master
/yaybu/providers/git.py
# Copyright 2011 Isotoma Limited # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os, logging import re from yaybu.core.provider import Provider from yaybu.core.error import CheckoutError from yaybu import resources log = logging.getLogger("git") class Git(Provider): policies = (resources.checkout.CheckoutSyncPolicy,) REMOTE_NAME = "origin" @classmethod def isvalid(self, policy, resource, yay): return resource.scm and resource.scm.lower() == "git" def git(self, context, action, *args, **kwargs): command = [ "git", #"--git-dir=%s" % os.path.join(self.resource.name, ".git"), #"--work-tree=%s" % self.resource.name, "--no-pager", action, ] command.extend(list(args)) if os.path.exists(self.resource.name): cwd = self.resource.name else: cwd = os.path.dirname(self.resource.name) return context.shell.execute(command, user=self.resource.user, exceptions=False, cwd=cwd, **kwargs) def action_clone(self, context): """Adds resource.repository as a remote, but unlike a typical clone, does not check it out """ if not os.path.exists(self.resource.name): rv, out, err = context.shell.execute( ["/bin/mkdir", self.resource.name], user=self.resource.user, exceptions=False, ) if not rv == 0: raise CheckoutError("Cannot create the repository directory") rv, out, err = self.git(context, "init", self.resource.name) if not rv == 0: raise CheckoutError("Cannot initialise local repository.") self.action_set_remote(context) return True else: return False def action_set_remote(self, context): git_parameters = [ "remote", "add", self.REMOTE_NAME, self.resource.repository, ] rv, out, err = self.git(context, *git_parameters) if not rv == 0: raise CheckoutError("Could not set the remote repository.") def action_update_remote(self, context): # Determine if the remote repository has changed remote_re = re.compile(self.REMOTE_NAME + r"\t(.*) \(.*\)\n") rv, stdout, stderr = self.git(context, "remote", "-v", passthru=True) remote = remote_re.search(stdout) if remote: if not self.resource.repository == remote.group(1): log.info("The remote repository has changed.") self.git(context, "remote", "rm", self.REMOTE_NAME) self.action_set_remote(context) return True else: raise CheckoutError("Cannot determine repository remote.") return False def action_checkout(self, context): # Determine which SHA is currently checked out. if os.path.exists(os.path.join(self.resource.name, ".git")): rv, stdout, stderr = self.git(context, "rev-parse", "--verify", "HEAD", passthru=True) if not rv == 0: head_sha = '0' * 40 else: head_sha = stdout[:40] log.info("Current HEAD sha: %s" % head_sha) else: head_sha = '0' * 40 changed = True # Revision takes precedent over branch if self.resource.revision: newref = self.resource.revision if newref == head_sha: changed = False elif self.resource.branch: rv, stdout, stderr = self.git(context, "ls-remote", self.resource.repository, passthru=True) if not rv == 0: raise CheckoutError("Could not query the remote repository") r = re.compile('([0-9a-f]{40})\t(.*)\n') refs_to_shas = dict([(b,a) for (a,b) in r.findall(stdout)]) as_tag = "refs/tags/%s" % self.resource.branch as_branch = "refs/heads/%s" % self.resource.branch if as_tag in refs_to_shas.keys(): annotated_tag = as_tag + "^{}" if annotated_tag in refs_to_shas.keys(): as_tag = annotated_tag newref = self.resource.branch changed = head_sha != refs_to_shas.get(as_tag) elif as_branch in refs_to_shas.keys(): newref = "remotes/%s/%s" % ( self.REMOTE_NAME, self.resource.branch ) changed = head_sha != refs_to_shas.get(as_branch) else: raise CheckoutError("You must specify either a revision or a branch") if changed: rv, stdout, stderr = self.git(context, "checkout", newref) if not rv == 0: raise CheckoutError("Could not check out '%s'" % newref) return changed def apply(self, context): log.info("Syncing %s" % self.resource) # If necessary, clone the repository if not os.path.exists(os.path.join(self.resource.name, ".git")): self.action_clone(context) else: self.action_update_remote(context) # Always update the REMOTE_NAME remote self.git(context, "fetch", self.REMOTE_NAME) return self.action_checkout(context)
{"/yaybu/resources/prompt.py": ["/yaybu/core/resource.py", "/yaybu/core/policy.py", "/yaybu/core/argument.py"], "/yaybu/core/protocol/changelog.py": ["/yaybu/core/protocol/server.py"], "/yaybu/core/tests/test_whitehat.py": ["/yaybu/core/whitehat.py"], "/yaybu/providers/git.py": ["/yaybu/core/error.py"], "/yaybu/providers/tests/test_subversion.py": ["/yaybu/core/error.py"], "/yaybu/providers/tests/test_filesystem.py": ["/yaybu/providers/filesystem/__init__.py"], "/yaybu/providers/tests/test_rsync.py": ["/yaybu/core/error.py"], "/yaybu/providers/filesystem/directory.py": ["/yaybu/providers/filesystem/files.py"], "/yaybu/core/protocol/file.py": ["/yaybu/core/protocol/server.py"]}
32,410
marchon/yaybu
refs/heads/master
/yaybu/providers/tests/test_subversion.py
from yaybu.harness import FakeChrootTestCase from yaybu.core.error import MissingDependency class SubversionMissingTest(FakeChrootTestCase): def test_missing_svn(self): rv = self.fixture.apply(""" resources: - Checkout: scm: subversion name: /dest repository: /source """) self.assertEqual(MissingDependency.returncode, rv)
{"/yaybu/resources/prompt.py": ["/yaybu/core/resource.py", "/yaybu/core/policy.py", "/yaybu/core/argument.py"], "/yaybu/core/protocol/changelog.py": ["/yaybu/core/protocol/server.py"], "/yaybu/core/tests/test_whitehat.py": ["/yaybu/core/whitehat.py"], "/yaybu/providers/git.py": ["/yaybu/core/error.py"], "/yaybu/providers/tests/test_subversion.py": ["/yaybu/core/error.py"], "/yaybu/providers/tests/test_filesystem.py": ["/yaybu/providers/filesystem/__init__.py"], "/yaybu/providers/tests/test_rsync.py": ["/yaybu/core/error.py"], "/yaybu/providers/filesystem/directory.py": ["/yaybu/providers/filesystem/files.py"], "/yaybu/core/protocol/file.py": ["/yaybu/core/protocol/server.py"]}
32,411
marchon/yaybu
refs/heads/master
/yaybu/providers/tests/test_directory.py
# coding=utf-8 import os import pwd import grp import stat from yaybu.harness import FakeChrootTestCase def sibpath(filename): return os.path.join(os.path.dirname(__file__), filename) class TestDirectory(FakeChrootTestCase): def test_create_directory(self): self.fixture.check_apply(""" resources: - Directory: name: /etc/somedir owner: root group: root """) self.failUnless(self.fixture.isdir("/etc/somedir")) def test_create_directory_and_parents(self): self.fixture.check_apply(""" resources: - Directory: name: /etc/foo/bar/baz parents: True """) self.failUnless(self.fixture.isdir("/etc/foo/bar/baz")) def test_remove_directory(self): self.fixture.mkdir("/etc/somedir") self.fixture.check_apply(""" resources: - Directory: name: /etc/somedir policy: remove """) def test_remove_directory_recursive(self): self.fixture.mkdir("/etc/somedir") self.fixture.touch("/etc/somedir/child") self.fixture.check_apply(""" resources: - Directory: name: /etc/somedir policy: remove-recursive """) self.failIfExists("/etc/somedir") def test_unicode(self): utf8 = "/etc/£££££" # this is utf-8 encoded self.fixture.check_apply(open(sibpath("directory_unicode1.yay")).read()) self.failUnlessExists(utf8) def test_attributes(self): self.fixture.check_apply(""" resources: - Directory: name: /etc/somedir2 owner: nobody group: nogroup mode: 0777 """) self.failUnlessExists("/etc/somedir2") st = self.fixture.stat("/etc/somedir2") self.failUnless(pwd.getpwuid(st.st_uid)[0] != 'nobody') self.failUnless(grp.getgrgid(st.st_gid)[0] != 'nogroup') mode = stat.S_IMODE(st.st_mode) self.assertEqual(mode, 0777)
{"/yaybu/resources/prompt.py": ["/yaybu/core/resource.py", "/yaybu/core/policy.py", "/yaybu/core/argument.py"], "/yaybu/core/protocol/changelog.py": ["/yaybu/core/protocol/server.py"], "/yaybu/core/tests/test_whitehat.py": ["/yaybu/core/whitehat.py"], "/yaybu/providers/git.py": ["/yaybu/core/error.py"], "/yaybu/providers/tests/test_subversion.py": ["/yaybu/core/error.py"], "/yaybu/providers/tests/test_filesystem.py": ["/yaybu/providers/filesystem/__init__.py"], "/yaybu/providers/tests/test_rsync.py": ["/yaybu/core/error.py"], "/yaybu/providers/filesystem/directory.py": ["/yaybu/providers/filesystem/files.py"], "/yaybu/core/protocol/file.py": ["/yaybu/core/protocol/server.py"]}
32,412
marchon/yaybu
refs/heads/master
/yaybu/core/tests/test_provider.py
# Copyright 2011 Isotoma Limited # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import unittest from yaybu.core import (resource, policy, argument, provider, error) class R(resource.Resource): foo = argument.String() bar = argument.String() class P1(policy.Policy): default = True name = 'p1' resource = R signature = [policy.Present("foo")] class P2(policy.Policy): name = 'p2' resource = R signature = [policy.Present("bar")] class P3(policy.Policy): name = 'p3' resource = R signature = [policy.Present("foo"), policy.Present("bar")] class Prov1(provider.Provider): policies = [P1,P2] class Prov2(provider.Provider): policies = [P3] class TestOrchestration(unittest.TestCase): def test_validate(self): r = R(name="1", foo="a", bar="b") pol = r.get_default_policy() self.assertEqual(r.get_default_policy().get_provider({}), Prov1) r = R(name="2") self.assertRaises(error.NonConformingPolicy, r.validate) r = R(name="3", policy="p1") self.assertRaises(error.NonConformingPolicy, r.validate)
{"/yaybu/resources/prompt.py": ["/yaybu/core/resource.py", "/yaybu/core/policy.py", "/yaybu/core/argument.py"], "/yaybu/core/protocol/changelog.py": ["/yaybu/core/protocol/server.py"], "/yaybu/core/tests/test_whitehat.py": ["/yaybu/core/whitehat.py"], "/yaybu/providers/git.py": ["/yaybu/core/error.py"], "/yaybu/providers/tests/test_subversion.py": ["/yaybu/core/error.py"], "/yaybu/providers/tests/test_filesystem.py": ["/yaybu/providers/filesystem/__init__.py"], "/yaybu/providers/tests/test_rsync.py": ["/yaybu/core/error.py"], "/yaybu/providers/filesystem/directory.py": ["/yaybu/providers/filesystem/files.py"], "/yaybu/core/protocol/file.py": ["/yaybu/core/protocol/server.py"]}
32,413
marchon/yaybu
refs/heads/master
/yaybu/core/tests/test_auditlog.py
import os import sys from yaybu.harness import FakeChrootTestCase from yaybu.core import error class TestAuditLog(FakeChrootTestCase): def test_auditlog_apply(self): self.fixture.check_apply(""" resources: - File: name: /test_auditlog_apply """) self.failUnlessExists("/var/log/yaybu.log") def test_auditlog_simulate(self): self.fixture.check_apply_simulate(""" resources: - File: name: /test_auditlog_simulate """) self.failIfExists("/var/log/yaybu.log")
{"/yaybu/resources/prompt.py": ["/yaybu/core/resource.py", "/yaybu/core/policy.py", "/yaybu/core/argument.py"], "/yaybu/core/protocol/changelog.py": ["/yaybu/core/protocol/server.py"], "/yaybu/core/tests/test_whitehat.py": ["/yaybu/core/whitehat.py"], "/yaybu/providers/git.py": ["/yaybu/core/error.py"], "/yaybu/providers/tests/test_subversion.py": ["/yaybu/core/error.py"], "/yaybu/providers/tests/test_filesystem.py": ["/yaybu/providers/filesystem/__init__.py"], "/yaybu/providers/tests/test_rsync.py": ["/yaybu/core/error.py"], "/yaybu/providers/filesystem/directory.py": ["/yaybu/providers/filesystem/files.py"], "/yaybu/core/protocol/file.py": ["/yaybu/core/protocol/server.py"]}
32,414
marchon/yaybu
refs/heads/master
/yaybu/harness/fakechroot.py
# Copyright 2011 Isotoma Limited # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os, signal, shlex, subprocess, tempfile, time, shutil, StringIO import testtools from yaybu.core import error from yaybu.util import sibpath from yaybu.harness.fixture import Fixture # Setup environment passthrough for chroot environment # And turn on auditlog yaybu_cfg = """ env-passthrough: - COWDANCER_ILISTFILE - FAKECHROOT - FAKECHROOT_VERSION - FAKECHROOT_BASE - FAKED_MODE - FAKEROOTKEY - LD_PRELOAD - LD_LIBRARY_PATH auditlog: mode: file """ # A little SSH wrapper for faking SSH into a fakechroot # (Obviously won't let us fake paramiko...) sshwrapper = """ #! /usr/bin/env python import os, sys args = sys.argv[1:] while args and not args[0] == "yaybu": del args[0] if args: os.execvp(args[0], args) """.strip() class FakeChrootFixture(Fixture): """ I provide a very simple COW userspace environment in which to test configuration I am used for some of Yaybu's internal tests. """ firstrun = True fakerootkey = None testbase = os.getenv("YAYBU_TESTS_BASE", "base-image") test_network = os.environ.get("TEST_NETWORK", "0") == "1" def setUp(self): if self.firstrun: if not os.path.exists(self.testbase): self.build_environment() self.refresh_environment() # We only refresh the base environment once, so # set this on the class to make sure any other fixtures pick it up FakeChrootFixture.firstrun = False self.clone() def clone(self): self.chroot_path = os.path.realpath("tmp") subprocess.check_call(["cp", "-al", self.testbase, self.chroot_path]) with self.open("/usr/bin/ssh", "w") as fp: fp.write(sshwrapper) self.chmod("/usr/bin/ssh", 0755) with self.open("/etc/yaybu", "w") as fp: fp.write(yaybu_cfg) self.chmod("/etc/yaybu", 0644) def cleanUp(self): self.cleanup_session() subprocess.check_call(["rm", "-rf", self.chroot_path]) def reset(self): self.cleanUp() self.clone() def default_distro(self): options = { "Ubuntu 9.10": "karmic", "Ubuntu 10.04": "lucid", "Ubuntu 10.10": "maverick", "Ubuntu 11.04": "natty", } sundayname = open("/etc/issue.net","r").read().strip() return options[sundayname[:12]] def run_commands(self, commands, distro=None): for command in commands: command = command % dict(base_image=self.testbase, distro=distro) p = subprocess.Popen(shlex.split(command)) if p.wait(): raise SystemExit("Command failed") def build_environment(self): distro = self.default_distro() commands = [ "fakeroot fakechroot -s debootstrap --variant=fakechroot --include=git-core,python-setuptools,python-dateutil,python-magic,ubuntu-keyring,gpgv %(distro)s %(base_image)s", "fakeroot fakechroot -s /usr/sbin/chroot %(base_image)s apt-get update", ] if not os.path.exists(self.testbase): self.run_commands(commands, distro) def refresh_environment(self): commands = [ "rm -rf /usr/local/lib/python2.6/dist-packages/Yaybu*", "python setup.py sdist --dist-dir %(base_image)s", "fakeroot fakechroot -s /usr/sbin/chroot %(base_image)s sh -c 'easy_install /Yaybu-*.tar.gz'", ] self.run_commands(commands) def cleanup_session(self): if self.faked: os.kill(int(self.faked.strip()), signal.SIGTERM) self.faked = None def get_session(self): if self.fakerootkey: return self.fakerootkey p = subprocess.Popen(['faked-sysv'], stdout=subprocess.PIPE) stdout, stderr = p.communicate() self.fakerootkey, self.faked = stdout.split(":") return self.fakerootkey def write_temporary_file(self, contents): f = tempfile.NamedTemporaryFile(dir=os.path.join(self.chroot_path, 'tmp'), delete=False) f.write(contents) f.close() return f.name def call(self, command): env = os.environ.copy() env['FAKEROOTKEY'] = self.get_session() env['LD_PRELOAD'] = "/usr/lib/libfakeroot/libfakeroot-sysv.so" env['HOME'] = '/root/' # Meh, we inherit the invoking users environment - LAME. env['HOME'] = '/root' env['PWD'] = '/' env['LOGNAME'] = 'root' env['USERNAME'] = 'root' env['USER'] = 'root' chroot = ["fakechroot", "-s", "cow-shell", "/usr/sbin/chroot", self.chroot_path] retval = subprocess.call(chroot + command, cwd=self.chroot_path, env=env) self.wait_for_cowdancer() return retval def yaybu(self, *args): filespath = os.path.join(self.chroot_path, "tmp", "files") args = list(args) if self.test_network: args.insert(0, "localhost") args.insert(0, "--host") return self.call(["yaybu", "-d", "--ypath", filespath] + list(args)) def simulate(self, *args): """ Run yaybu in simulate mode """ args = ["--simulate"] + list(args) return self.yaybu(*args) def apply(self, contents, *args): path = self.write_temporary_file(contents) return self.yaybu(path, *args) def apply_simulate(self, contents): path = self.write_temporary_file(contents) return self.simulate(path) def check_apply(self, contents, *args, **kwargs): expect = kwargs.get('expect', 0) # Apply the change in simulate mode sim_args = list(args) + ["-s"] rv = self.apply(contents, *sim_args) if rv != expect: raise subprocess.CalledProcessError(rv, "Simulation failed: got rv %s" % rv) # Apply the change for real rv = self.apply(contents, *args) if rv != expect: raise subprocess.CalledProcessError(rv, "Apply failed: got rv %s" % rv) # If 'expect' isnt 0 then theres no point doing a no-changes check if expect != 0: return # If we apply the change again nothing should be changed rv = self.apply(contents, *args) if rv != error.NothingChanged.returncode: raise subprocess.CalledProcessError(rv, "Change still outstanding") def check_apply_simulate(self, contents): rv = self.apply_simulate(contents) if rv != 0: raise subprocess.CalledProcessError(rv, "Simulate failed rv %s" % rv) def wait_for_cowdancer(self): # give cowdancer a few seconds to exit (avoids a race where it delets another sessions .ilist) for i in range(20): if not os.path.exists(os.path.join(self.chroot_path, ".ilist")): break time.sleep(0.1) def exists(self, path): return os.path.exists(self._enpathinate(path)) def isdir(self, path): return os.path.isdir(self._enpathinate(path)) def mkdir(self, path): os.mkdir(self._enpathinate(path)) def open(self, path, mode='r'): return open(self._enpathinate(path), mode) def touch(self, path): if not self.exists(path): with self.open(path, "w") as fp: fp.write("") def chmod(self, path, mode): self.call(["chmod", "%04o" % mode, self._enpathinate(path)]) def readlink(self, path): relpath = os.path.relpath(os.readlink(self._enpathinate(path)), self.chroot_path) for x in (".", "/"): if relpath.startswith(x): relpath = relpath[1:] return "/" + relpath def symlink(self, source, dest): os.symlink(self._enpathinate(source), self._enpathinate(dest)) def stat(self, path): return os.stat(self._enpathinate(path)) def _enpathinate(self, path): return os.path.join(self.chroot_path, *path.split(os.path.sep)) def get_user(self, user): users_list = open(self._enpathinate("/etc/passwd")).read().splitlines() users = dict(u.split(":", 1) for u in users_list) return users[user].split(":") def get_group(self, group): # Returns a tuple of group info if the group exists, or raises KeyError if it does not groups_list = open(self._enpathinate("/etc/group")).read().splitlines() groups = dict(g.split(":", 1) for g in groups_list) return groups[group].split(":")
{"/yaybu/resources/prompt.py": ["/yaybu/core/resource.py", "/yaybu/core/policy.py", "/yaybu/core/argument.py"], "/yaybu/core/protocol/changelog.py": ["/yaybu/core/protocol/server.py"], "/yaybu/core/tests/test_whitehat.py": ["/yaybu/core/whitehat.py"], "/yaybu/providers/git.py": ["/yaybu/core/error.py"], "/yaybu/providers/tests/test_subversion.py": ["/yaybu/core/error.py"], "/yaybu/providers/tests/test_filesystem.py": ["/yaybu/providers/filesystem/__init__.py"], "/yaybu/providers/tests/test_rsync.py": ["/yaybu/core/error.py"], "/yaybu/providers/filesystem/directory.py": ["/yaybu/providers/filesystem/files.py"], "/yaybu/core/protocol/file.py": ["/yaybu/core/protocol/server.py"]}
32,415
marchon/yaybu
refs/heads/master
/yaybu/providers/tests/test_user.py
import os, shutil from yaybu.harness import FakeChrootTestCase from yaybu.util import sibpath from yaybu.core import error class TestUser(FakeChrootTestCase): def test_simple_user(self): self.fixture.check_apply(""" resources: - User: name: test """) def test_disabled_login(self): self.fixture.check_apply(""" resources: - User: - name: test disabled-login: True """) rv = self.fixture.apply(""" resources: - User: - name: test disabled-login: True """) self.assertEqual(rv, 255) def test_user_with_home(self): self.fixture.check_apply(""" resources: - User: name: test home: /home/foo """) def test_user_with_impossible_home(self): rv = self.fixture.apply(""" resources: - User: name: test home: /does/not/exist """) self.assertEqual(rv, error.UserAddError.returncode) def test_user_with_uid(self): self.fixture.check_apply(""" resources: - User: name: test uid: 1111 """) def test_user_with_gid(self): self.fixture.check_apply(""" resources: - Group: name: testgroup gid: 1111 - User: name: test gid: 1111 """) def test_user_with_fullname(self): self.fixture.check_apply(""" resources: - User: name: test fullname: testy mctest """) def test_user_with_password(self): self.fixture.check_apply(""" resources: - User: name: test password: password """) def test_user_with_group(self): self.fixture.check_apply(""" resources: - User: name: test group: nogroup """) def test_user_with_groups(self): self.fixture.check_apply(""" resources: - User: name: test groups: - nogroup """) def test_user_with_groups_replace(self): self.fixture.check_apply(""" resources: - User: name: test groups: - nogroup append: False """) class TestUserRemove(FakeChrootTestCase): def test_remove_existing(self): self.failUnless(self.fixture.get_user("nobody")) self.fixture.check_apply(""" resources: - User: name: nobody policy: remove """) self.failUnlessRaises(KeyError, self.fixture.get_user, "nobody") def test_remove_non_existing(self): self.failUnlessRaises(KeyError, self.fixture.get_user, "zzidontexistzz") rv = self.fixture.apply(""" resources: - User: name: zzidontexistzz policy: remove """) self.failUnlessEqual(rv, 255) self.failUnlessRaises(KeyError, self.fixture.get_user, "zzidontexistzz")
{"/yaybu/resources/prompt.py": ["/yaybu/core/resource.py", "/yaybu/core/policy.py", "/yaybu/core/argument.py"], "/yaybu/core/protocol/changelog.py": ["/yaybu/core/protocol/server.py"], "/yaybu/core/tests/test_whitehat.py": ["/yaybu/core/whitehat.py"], "/yaybu/providers/git.py": ["/yaybu/core/error.py"], "/yaybu/providers/tests/test_subversion.py": ["/yaybu/core/error.py"], "/yaybu/providers/tests/test_filesystem.py": ["/yaybu/providers/filesystem/__init__.py"], "/yaybu/providers/tests/test_rsync.py": ["/yaybu/core/error.py"], "/yaybu/providers/filesystem/directory.py": ["/yaybu/providers/filesystem/files.py"], "/yaybu/core/protocol/file.py": ["/yaybu/core/protocol/server.py"]}
32,416
marchon/yaybu
refs/heads/master
/yaybu/providers/tests/test_execute.py
import os, shutil from yaybu.harness import FakeChrootTestCase from yaybu.util import sibpath from yaybu.core import error test_execute_on_path = """ #!/bin/sh touch /etc/test_execute_on_path """.strip() test_touches = """ #!/bin/sh touch /etc/test_execute_touches """.strip() class TestExecute(FakeChrootTestCase): def test_execute_on_path(self): with self.fixture.open("/usr/bin/test_execute_on_path.sh", "w") as fp: fp.write(test_execute_on_path) self.fixture.chmod("/usr/bin/test_execute_on_path.sh", 0755) self.fixture.check_apply(""" resources: - Execute: name: test command: test_execute_on_path.sh creates: /etc/test_execute_on_path """) def test_execute_touches(self): """ test that command works as expected """ with self.fixture.open("/usr/bin/test_touches.sh", "w") as fp: fp.write(test_touches) self.fixture.chmod("/usr/bin/test_touches.sh", 0755) self.fixture.check_apply(""" resources: - Execute: name: test command: test_touches.sh creates: /etc/test_execute_touches """) def test_command(self): """ test that commands works as expected """ self.fixture.check_apply(""" resources: - Execute: name: test command: touch /etc/foo creates: /etc/foo """) self.failUnlessExists("/etc/foo") def test_commands(self): self.fixture.check_apply(""" resources: - Execute: name: test commands: - touch /etc/foo - touch /etc/bar creates: /etc/bar """) self.failUnlessExists("/etc/foo") self.failUnlessExists("/etc/bar") def test_cwd(self): """ test that cwd works as expected. """ self.fixture.check_apply(""" resources: - Execute: name: test command: touch foo cwd: /etc creates: /etc/foo """) self.failUnlessExists("/etc/foo") def test_environment(self): """ test that the environment is passed as expected. """ self.fixture.check_apply(""" resources: - Execute: name: test command: sh -c "touch $FOO" environment: FOO: /etc/foo creates: /etc/foo """) self.failUnlessExists("/etc/foo") def test_returncode(self): """ test that the returncode is interpreted as expected. """ self.fixture.check_apply(""" resources: - Execute: name: test-execute-returncode-true command: /bin/true touch: /test_returncode_marker_true - Execute: name: test-execute-returncode-false command: /bin/false touch: /test_returncode_marker_false returncode: 1 """) def test_user(self): """ test that the user has been correctly set. """ self.fixture.check_apply(""" resources: - Execute: name: test_user_change command: python -c "import os; open('/foo','w').write(str(os.getuid())+'\\n'+str(os.geteuid()))" user: nobody creates: /foo """) with self.fixture.open("/foo") as fp: check_file = fp.read().split() self.failUnlessEqual(["65534"] * 2, check_file) def test_group(self): """ test that the group has been correctly set. """ self.fixture.check_apply(""" resources: - Execute: name: test_group_change command: python -c "import os; open('/foo','w').write(str(os.getgid())+'\\n'+str(os.getegid()))" group: nogroup creates: /foo """) with self.fixture.open("/foo") as fp: check_file = fp.read().split() self.failUnlessEqual(["65534"] * 2, check_file) def test_user_and_group(self): """ test that both user and group can be set together. """ self.fixture.check_apply(""" resources: - Execute: name: test_group_change command: python -c "import os; open('/foo','w').write('\\n'.join(str(x) for x in (os.getuid(),os.geteuid(),os.getgid(),os.getegid())))" user: nobody group: nogroup creates: /foo """) with self.fixture.open("/foo") as fp: check_file = fp.read().split() self.failUnlessEqual(["65534"] * 4, check_file) def test_creates(self): """ test that the execute will not happen if the creates parameter specifies an existing file. """ self.fixture.touch("/existing-file") self.fixture.check_apply(""" resources: - Execute: name: test_creates command: touch /existing-file creates: /existing-file """, expect=error.NothingChanged.returncode) def test_touch(self): """ test that touch does touch a file. """ self.fixture.check_apply(""" resources: - Execute: name: test_touch command: whoami touch: /touched-file """) self.failUnlessExists("/touched-file") def test_touch_present(self): """ test that we do not execute if the touched file exists. """ self.fixture.touch("/touched-file") self.fixture.check_apply(""" resources: - Execute: name: test_touch_present command: touch /checkpoint touch: /touched-file """, expect=255) self.failIfExists("/checkpoint") def test_touch_not_present(self): """ test that we do execute if the touched file does not exist. """ self.fixture.check_apply(""" resources: - Execute: name: test_touch_not_present command: touch /checkpoint touch: /touched-file """) self.failUnlessExists("/checkpoint") self.failUnlessExists("/touched-file") def test_unless_true(self): """ test that an Execute wont execute if the unless expression is true """ rv = self.fixture.apply(""" resources: - Execute: name: test command: touch /test_unless_true unless: /bin/true """) self.failUnlessEqual(rv, 255) def test_unless_false(self): """ test that an Execute will execute when the unless expression is false """ self.fixture.check_apply(""" resources: - Execute: name: test command: touch /test_unless_false unless: /bin/false creates: /test_unless_false """) self.failUnlessExists("/test_unless_false")
{"/yaybu/resources/prompt.py": ["/yaybu/core/resource.py", "/yaybu/core/policy.py", "/yaybu/core/argument.py"], "/yaybu/core/protocol/changelog.py": ["/yaybu/core/protocol/server.py"], "/yaybu/core/tests/test_whitehat.py": ["/yaybu/core/whitehat.py"], "/yaybu/providers/git.py": ["/yaybu/core/error.py"], "/yaybu/providers/tests/test_subversion.py": ["/yaybu/core/error.py"], "/yaybu/providers/tests/test_filesystem.py": ["/yaybu/providers/filesystem/__init__.py"], "/yaybu/providers/tests/test_rsync.py": ["/yaybu/core/error.py"], "/yaybu/providers/filesystem/directory.py": ["/yaybu/providers/filesystem/files.py"], "/yaybu/core/protocol/file.py": ["/yaybu/core/protocol/server.py"]}
32,417
marchon/yaybu
refs/heads/master
/yaybu/core/tests/test_events.py
import os import sys from yaybu.harness import FakeChrootTestCase from yaybu.core import error class TestEvents(FakeChrootTestCase): def test_nochange(self): self.fixture.check_apply(""" resources: - Directory: name: /etc/wibble """) rv = self.fixture.apply(""" resources: - Directory: name: /etc/wibble - File: name: /frob/somedir/foo policy: apply: when: apply on: Directory[/etc/wibble] """) self.assertEqual(rv, error.NothingChanged.returncode) def test_recover(self): rv = self.fixture.apply(""" resources: - Directory: name: /etc/somedir - Directory: name: /frob/somedir - File: name: /frob/somedir/foo policy: apply: when: apply on: Directory[/etc/somedir] """) self.assertEqual(rv, error.PathComponentMissing.returncode) self.fixture.check_apply(""" resources: - Directory: name: /etc/somedir - Directory: name: /frob - Directory: name: /frob/somedir - File: name: /frob/somedir/foo policy: apply: when: apply on: Directory[/etc/somedir] """, "--resume") self.failUnlessExists("/frob/somedir/foo")
{"/yaybu/resources/prompt.py": ["/yaybu/core/resource.py", "/yaybu/core/policy.py", "/yaybu/core/argument.py"], "/yaybu/core/protocol/changelog.py": ["/yaybu/core/protocol/server.py"], "/yaybu/core/tests/test_whitehat.py": ["/yaybu/core/whitehat.py"], "/yaybu/providers/git.py": ["/yaybu/core/error.py"], "/yaybu/providers/tests/test_subversion.py": ["/yaybu/core/error.py"], "/yaybu/providers/tests/test_filesystem.py": ["/yaybu/providers/filesystem/__init__.py"], "/yaybu/providers/tests/test_rsync.py": ["/yaybu/core/error.py"], "/yaybu/providers/filesystem/directory.py": ["/yaybu/providers/filesystem/files.py"], "/yaybu/core/protocol/file.py": ["/yaybu/core/protocol/server.py"]}
32,418
marchon/yaybu
refs/heads/master
/yaybu/providers/rsync.py
# Copyright 2011 Isotoma Limited # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os, logging import re from yaybu.core.provider import Provider from yaybu.core.error import CheckoutError, MissingDependency from yaybu import resources from yaybu.providers.filesystem.files import AttributeChanger class Rsync(Provider): policies = (resources.checkout.CheckoutSyncPolicy,) REMOTE_NAME = "origin" @classmethod def isvalid(self, policy, resource, yay): return resource.scm and resource.scm.lower() == "rsync" def _get_svn_ignore(self, context, path): command = ["svn", "status", "--non-interactive", "--no-ignore", path] returncode, stdout, stderr = context.shell.execute(command, passthru=True) if not returncode == 0: raise CheckoutError("Could not generate updated .rsync-exclude for Subversion checkout") ignore = [] for line in stdout.split("\n"): if not line.startswith("I"): continue ignore.append(os.path.relpath(line.lstrip("I").strip(), start=path)) return ignore def _get_git_ignore(self, context, path): command = ["git", "clean", "-nXd"] returncode, stdout, stderr = context.shell.execute(command, cwd=path, passthru=True) if not returncode == 0: raise CheckoutError("Could not generate updated .rsync-exclude for Git checkout") ignore = [] for line in stdout.split("\n"): ignore.append(line.replace("Would remove ", "").strip()) return ignore def _build_exclude_list(self, context): path = os.path.join(self.resource.name, ".rsync-exclude") ignore = [".rsync-exclude"] if os.path.isdir(self.resource.repository): svndir = os.path.join(self.resource.repository, ".svn") if os.path.isdir(svndir): ignore.append(".svn") ignore.extend(self._get_svn_ignore(context, self.resource.repository)) gitdir = os.path.join(self.resource.repository, ".git") if os.path.isdir(gitdir): ignore.append(".git") ignore.extend(self._get_git_ignore(context, self.resource.repository)) ignorefile = os.path.join(self.resource.repository, ".rsync-exclude") if os.path.exists(ignorefile): ignore.extend(x for x in open(ignorefile).read().split("\n") if x.strip()) open(path, "w").write("\n".join(ignore)) return path def _sync(self, context, dryrun=False): # FIXME: This will touch disk even in simulate mode... But *only* the exclude file. command = ["/usr/bin/rsync", "-rltv", "--stats", "--delete", "--exclude-from", self._build_exclude_list(context)] if dryrun: command.extend(["-n"]) command.extend([".", self.resource.name+"/"]) rv, out, err = context.shell.execute(command, cwd=self.resource.repository, user=self.resource.user, exceptions=False, passthru=dryrun) if context.simulate and not dryrun: # We won't get any output from _sync if we aren't doing a dry-run whilst in simulate mode # But this is only called with dryrun = False when there is stuff to sync return True if out.split("\n")[1].strip(): return True return False def apply(self, context): changed = False if not os.path.exists("/usr/bin/rsync"): context.changelog.info("'/usr/bin/rsync' command is not available.") if not context.simulate: raise MissingDependency("Cannot continue with unmet dependency") if not os.path.exists(self.resource.name): command = ["/bin/mkdir", self.resource.name] rv, out, err = context.shell.execute(command, exceptions=False) changed = True if context.simulate and changed: context.changelog.info("Root directory not found; assuming rsync will occur") return True ac = AttributeChanger(context, self.resource.name, self.resource.user, mode=0755) ac.apply(context) changed = changed or ac.changed if self._sync(context, True): self._sync(context) changed = True return changed
{"/yaybu/resources/prompt.py": ["/yaybu/core/resource.py", "/yaybu/core/policy.py", "/yaybu/core/argument.py"], "/yaybu/core/protocol/changelog.py": ["/yaybu/core/protocol/server.py"], "/yaybu/core/tests/test_whitehat.py": ["/yaybu/core/whitehat.py"], "/yaybu/providers/git.py": ["/yaybu/core/error.py"], "/yaybu/providers/tests/test_subversion.py": ["/yaybu/core/error.py"], "/yaybu/providers/tests/test_filesystem.py": ["/yaybu/providers/filesystem/__init__.py"], "/yaybu/providers/tests/test_rsync.py": ["/yaybu/core/error.py"], "/yaybu/providers/filesystem/directory.py": ["/yaybu/providers/filesystem/files.py"], "/yaybu/core/protocol/file.py": ["/yaybu/core/protocol/server.py"]}
32,419
marchon/yaybu
refs/heads/master
/yaybu/providers/tests/test_filesystem.py
# Copyright 2011 Isotoma Limited # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import unittest from yay import String from yaybu.providers.filesystem import files class TestSecretTemplateArgs(unittest.TestCase): def setUp(self): self.ps = String() self.ps.add_secret('hello') class DummyResource: template_args = {} self.args = DummyResource.template_args self.provider = files.File(DummyResource) def test_no_secret(self): self.args['level1'] = dict(foo=1, bar=[1,2,3], baz=dict()) self.failUnless(not self.provider.has_protected_strings()) def test_secret_in_dict(self): self.args['level1'] = dict(foo=self.ps, bar=1) self.failUnless(self.provider.has_protected_strings()) def test_secret_in_list(self): self.args['level1'] = [self.ps, 1, 2] self.failUnless(self.provider.has_protected_strings()) def test_secret_in_dict_in_list(self): self.args['level1'] = [dict(foo=self.ps, bar=1)] self.failUnless(self.provider.has_protected_strings())
{"/yaybu/resources/prompt.py": ["/yaybu/core/resource.py", "/yaybu/core/policy.py", "/yaybu/core/argument.py"], "/yaybu/core/protocol/changelog.py": ["/yaybu/core/protocol/server.py"], "/yaybu/core/tests/test_whitehat.py": ["/yaybu/core/whitehat.py"], "/yaybu/providers/git.py": ["/yaybu/core/error.py"], "/yaybu/providers/tests/test_subversion.py": ["/yaybu/core/error.py"], "/yaybu/providers/tests/test_filesystem.py": ["/yaybu/providers/filesystem/__init__.py"], "/yaybu/providers/tests/test_rsync.py": ["/yaybu/core/error.py"], "/yaybu/providers/filesystem/directory.py": ["/yaybu/providers/filesystem/files.py"], "/yaybu/core/protocol/file.py": ["/yaybu/core/protocol/server.py"]}
32,420
marchon/yaybu
refs/heads/master
/yaybu/providers/tests/test_rsync.py
from yaybu.harness import FakeChrootTestCase from yaybu.core.error import MissingDependency class RsyncTest(FakeChrootTestCase): """ Test the rsync checkout provider. To run these tests, rsync must be installed in the test environment. """ def setUp(self): super(RsyncTest, self).setUp() self.sync() def sync(self, expect=0): return self.fixture.check_apply(""" resources: - Package: name: rsync - Directory: - name: /source mode: 0755 - Checkout: scm: rsync name: /dest repository: /source """, expect=expect) def test_add(self): self.fixture.touch("/source/a") self.sync() self.failUnless(self.fixture.exists("/dest/a")) def test_del(self): self.fixture.touch("/dest/b") self.sync() self.failUnless(not self.fixture.exists("/dest/b")) def test_nochange(self): self.sync(expect=255) class RsyncMissingTest(FakeChrootTestCase): def test_missing_rsync(self): rv = self.fixture.apply(""" resources: - Checkout: scm: rsync name: /dest repository: /source """) self.assertEqual(MissingDependency.returncode, rv)
{"/yaybu/resources/prompt.py": ["/yaybu/core/resource.py", "/yaybu/core/policy.py", "/yaybu/core/argument.py"], "/yaybu/core/protocol/changelog.py": ["/yaybu/core/protocol/server.py"], "/yaybu/core/tests/test_whitehat.py": ["/yaybu/core/whitehat.py"], "/yaybu/providers/git.py": ["/yaybu/core/error.py"], "/yaybu/providers/tests/test_subversion.py": ["/yaybu/core/error.py"], "/yaybu/providers/tests/test_filesystem.py": ["/yaybu/providers/filesystem/__init__.py"], "/yaybu/providers/tests/test_rsync.py": ["/yaybu/core/error.py"], "/yaybu/providers/filesystem/directory.py": ["/yaybu/providers/filesystem/files.py"], "/yaybu/core/protocol/file.py": ["/yaybu/core/protocol/server.py"]}
32,421
marchon/yaybu
refs/heads/master
/yaybu/providers/filesystem/directory.py
# Copyright 2011 Isotoma Limited # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import stat import pwd import grp import logging from yaybu import resources from yaybu.core import provider, error from yaybu.providers.filesystem.files import AttributeChanger class Directory(provider.Provider): policies = (resources.directory.DirectoryAppliedPolicy,) @classmethod def isvalid(self, *args, **kwargs): return super(Directory, self).isvalid(*args, **kwargs) def check_path(self, directory, simulate): frags = directory.split("/") path = "/" for i in frags: path = os.path.join(path, i) if not os.path.exists(path): if self.resource.parents: return if simulate: return raise error.PathComponentMissing(path) if not os.path.isdir(path): raise error.PathComponentNotDirectory(path) def apply(self, context): changed = False self.check_path(os.path.dirname(self.resource.name), context.simulate) ac = AttributeChanger(context, self.resource.name, self.resource.owner, self.resource.group, self.resource.mode) if not os.path.exists(self.resource.name): command = ["/bin/mkdir"] if self.resource.parents: command.append("-p") command.append(self.resource.name.encode("utf-8")) context.shell.execute(command) changed = True ac.apply(context) if changed or ac.changed: return True else: return False class RemoveDirectory(provider.Provider): policies = (resources.directory.DirectoryRemovedPolicy,) @classmethod def isvalid(self, *args, **kwargs): return super(RemoveDirectory, self).isvalid(*args, **kwargs) def apply(self, context): if os.path.exists(self.resource.name) and not os.path.isdir(self.resource.name): raise error.InvalidProviderError("%r: %s exists and is not a directory" % (self, self.resource.name)) if os.path.exists(self.resource.name): context.shell.execute(["/bin/rmdir", self.resource.name]) changed = True else: changed = False return changed class RemoveDirectoryRecursive(provider.Provider): policies = (resources.directory.DirectoryRemovedRecursivePolicy,) @classmethod def isvalid(self, *args, **kwargs): return super(RemoveDirectoryRecursive, self).isvalid(*args, **kwargs) def apply(self, context): if os.path.exists(self.resource.name) and not os.path.isdir(self.resource.name): raise error.InvalidProviderError("%r: %s exists and is not a directory" % (self, self.resource.name)) if os.path.exists(self.resource.name): context.shell.execute(["/bin/rm", "-rf", self.resource.name]) changed = True else: changed = False return changed
{"/yaybu/resources/prompt.py": ["/yaybu/core/resource.py", "/yaybu/core/policy.py", "/yaybu/core/argument.py"], "/yaybu/core/protocol/changelog.py": ["/yaybu/core/protocol/server.py"], "/yaybu/core/tests/test_whitehat.py": ["/yaybu/core/whitehat.py"], "/yaybu/providers/git.py": ["/yaybu/core/error.py"], "/yaybu/providers/tests/test_subversion.py": ["/yaybu/core/error.py"], "/yaybu/providers/tests/test_filesystem.py": ["/yaybu/providers/filesystem/__init__.py"], "/yaybu/providers/tests/test_rsync.py": ["/yaybu/core/error.py"], "/yaybu/providers/filesystem/directory.py": ["/yaybu/providers/filesystem/files.py"], "/yaybu/core/protocol/file.py": ["/yaybu/core/protocol/server.py"]}
32,422
marchon/yaybu
refs/heads/master
/yaybu/core/protocol/file.py
# Copyright 2011 Isotoma Limited # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os from urlparse import urlparse, parse_qs from yaybu.core.protocol.server import HttpResource from yaybu.core import error class FileResource(HttpResource): leaf = True def render_GET(self, yaybu, request, restpath): params = parse_qs(request.getargs) try: # Always read in binary mode. Opening files in text mode may cause # newline translations, making the actual size of the content # transmitted *less* than the content-length! f = yaybu.get_file(params["path"][0]) except error.MissingAsset: request.send_error(404, "File not found") return None request.send_response(200, "OK") request.send_header("Content-Type", "application/octect-stream") request.send_header("Content-Length", str(f.len)) #request.send_header("Last-Modified", self.date_time_string(fs.st_mtime)) request.send_header("Content", "keep-alive") request.end_headers() request.write_fileobj(f) class EncryptedResource(HttpResource): leaf = True def render_GET(self, yaybu, request, restpath): contents = yaybu.get_decrypted_file(restpath).read() request.send_response(200, "OK") request.send_header("Content-Type", "application/octect-stream") request.send_header("Content-Length", str(len(contents))) request.send_header("Content", "keep-alive") request.end_headers() request.wfile.write(contents)
{"/yaybu/resources/prompt.py": ["/yaybu/core/resource.py", "/yaybu/core/policy.py", "/yaybu/core/argument.py"], "/yaybu/core/protocol/changelog.py": ["/yaybu/core/protocol/server.py"], "/yaybu/core/tests/test_whitehat.py": ["/yaybu/core/whitehat.py"], "/yaybu/providers/git.py": ["/yaybu/core/error.py"], "/yaybu/providers/tests/test_subversion.py": ["/yaybu/core/error.py"], "/yaybu/providers/tests/test_filesystem.py": ["/yaybu/providers/filesystem/__init__.py"], "/yaybu/providers/tests/test_rsync.py": ["/yaybu/core/error.py"], "/yaybu/providers/filesystem/directory.py": ["/yaybu/providers/filesystem/files.py"], "/yaybu/core/protocol/file.py": ["/yaybu/core/protocol/server.py"]}
32,423
marchon/yaybu
refs/heads/master
/setup.py
from setuptools import setup, find_packages import os version = '0.1.14dev' setup(name='Yaybu', version=version, url="http://yaybu.com/", description="Server deployment and configuration management in Python", long_description=open("README.rst").read(), author="Isotoma Limited", author_email="support@isotoma.com", license="Apache Software License", classifiers = [ "Intended Audience :: System Administrators", "Operating System :: POSIX", "License :: OSI Approved :: Apache Software License", ], packages=find_packages(exclude=['ez_setup']), namespace_packages = ['yaybu'], include_package_data=True, zip_safe=False, install_requires=[ 'setuptools', 'jinja2', 'yay >= 0.0.39', 'python-dateutil < 2.0', ], extras_require = { 'test': ['testtools', 'discover', 'mock'], }, entry_points = """ [console_scripts] yaybu = yaybu.core.main:main [yaybu.resources] resources = yaybu.resources [yaybu.providers] providers = yaybu.providers """ )
{"/yaybu/resources/prompt.py": ["/yaybu/core/resource.py", "/yaybu/core/policy.py", "/yaybu/core/argument.py"], "/yaybu/core/protocol/changelog.py": ["/yaybu/core/protocol/server.py"], "/yaybu/core/tests/test_whitehat.py": ["/yaybu/core/whitehat.py"], "/yaybu/providers/git.py": ["/yaybu/core/error.py"], "/yaybu/providers/tests/test_subversion.py": ["/yaybu/core/error.py"], "/yaybu/providers/tests/test_filesystem.py": ["/yaybu/providers/filesystem/__init__.py"], "/yaybu/providers/tests/test_rsync.py": ["/yaybu/core/error.py"], "/yaybu/providers/filesystem/directory.py": ["/yaybu/providers/filesystem/files.py"], "/yaybu/core/protocol/file.py": ["/yaybu/core/protocol/server.py"]}
32,424
marchon/yaybu
refs/heads/master
/yaybu/providers/tests/test_file.py
from yaybu.harness import FakeChrootTestCase from yaybu.core import error import pwd import grp import os import stat import errno def sibpath(filename): return os.path.join(os.path.dirname(__file__), filename) class TestFileApply(FakeChrootTestCase): def test_create_missing_component(self): rv = self.fixture.apply(""" resources: - File: name: /etc/missing/filename """) self.assertEqual(rv, error.PathComponentMissing.returncode) def test_create_missing_component_simulate(self): """ Right now we treat missing directories as a warning in simulate mode, as other outside processes might have created them. Later on we might not generate warnings for resources we can see will be created """ rv = self.fixture.apply_simulate(""" resources: - File: name: /etc/missing/filename """) self.assertEqual(rv, 0) def test_create_file(self): self.fixture.check_apply(""" resources: - File: name: /etc/somefile owner: root group: root """) self.failUnlessExists("/etc/somefile") def test_attributes(self): self.fixture.check_apply(""" resources: - File: name: /etc/somefile2 owner: nobody group: nogroup mode: 0666 """) self.failUnlessExists("/etc/somefile2") st = self.fixture.stat("/etc/somefile2") self.failUnless(pwd.getpwuid(st.st_uid)[0] != 'nobody') self.failUnless(grp.getgrgid(st.st_gid)[0] != 'nogroup') mode = stat.S_IMODE(st.st_mode) self.assertEqual(mode, 0666) def test_create_file_template(self): self.fixture.check_apply(""" resources: - File: name: /etc/templated template: package://yaybu.providers.tests/template1.j2 template_args: foo: this is foo bar: 42 owner: root group: root """) self.failUnlessExists("/etc/templated") def test_modify_file(self): with self.fixture.open("/etc/test_modify_file", "w") as fp: fp.write("foo\nbar\nbaz") self.fixture.check_apply(""" resources: - File: name: /etc/test_modify_file template: package://yaybu.providers.tests/template1.j2 template_args: foo: this is a modified file bar: 37 """) def test_remove_file(self): self.fixture.check_apply(""" resources: - File: name: /etc/toremove """) self.fixture.check_apply(""" resources: - File: name: /etc/toremove policy: remove """) self.failIfExists("/etc/toremove") def test_empty(self): with self.fixture.open("/etc/foo", "w") as fp: fp.write("foo") self.fixture.check_apply(""" resources: - File: name: /etc/foo """) def test_empty_nochange(self): with self.fixture.open("/etc/foo", "w") as fp: fp.write("") rv = self.fixture.apply(""" resources: - File: name: /etc/foo """) self.assertEqual(rv, 255) def test_carriage_returns(self): """ a template that does not end in \n will still result in a file ending in \n """ with self.fixture.open("/etc/test_carriage_returns", "w") as fp: fp.write("foo\n") rv = self.fixture.apply(""" resources: - File: name: /etc/test_carriage_returns template: package://yaybu.providers.tests/test_carriage_returns.j2 """) self.assertEqual(rv, 255) # nothing changed def test_carriage_returns2(self): """ a template that does end in \n will not gain an extra \n in the resulting file""" with self.fixture.open("/etc/test_carriage_returns2", "w") as fp: fp.write("foo\n") rv = self.fixture.apply(""" resources: - File: name: /etc/test_carriage_returns2 template: package://yaybu.providers.tests/test_carriage_returns2.j2 """) self.assertEqual(rv, 255) # nothing changed def test_unicode(self): self.fixture.check_apply(open(sibpath("unicode1.yay")).read()) def test_static(self): """ Test setting the contents to that of a static file. """ self.fixture.check_apply(""" resources: - File: name: /etc/foo static: package://yaybu.providers.tests/test_carriage_returns2.j2 """) def test_missing(self): """ Test trying to use a file that isn't in the yaybu path """ rv = self.fixture.apply(""" resources: - File: name: /etc/foo static: this-doesnt-exist """) self.failUnlessEqual(rv, error.MissingAsset.returncode) class TestFileRemove(FakeChrootTestCase): def test_remove(self): """ Test removing a file that exists. """ with self.fixture.open("/etc/bar","w") as fp: fp.write("") self.fixture.check_apply(""" resources: - File: name: /etc/bar policy: remove """) def test_remove_missing(self): """ Test removing a file that does not exist. """ self.failIfExists("/etc/baz") rv = self.fixture.apply(""" resources: - File: name: /etc/baz policy: remove """) self.failUnlessEqual(rv, 255) def test_remove_notafile(self): """ Test removing something that is not a file. """ self.fixture.mkdir("/etc/qux") rv = self.fixture.apply(""" resources: - File: name: /etc/qux policy: remove """) self.failUnlessEqual(rv, 139)
{"/yaybu/resources/prompt.py": ["/yaybu/core/resource.py", "/yaybu/core/policy.py", "/yaybu/core/argument.py"], "/yaybu/core/protocol/changelog.py": ["/yaybu/core/protocol/server.py"], "/yaybu/core/tests/test_whitehat.py": ["/yaybu/core/whitehat.py"], "/yaybu/providers/git.py": ["/yaybu/core/error.py"], "/yaybu/providers/tests/test_subversion.py": ["/yaybu/core/error.py"], "/yaybu/providers/tests/test_filesystem.py": ["/yaybu/providers/filesystem/__init__.py"], "/yaybu/providers/tests/test_rsync.py": ["/yaybu/core/error.py"], "/yaybu/providers/filesystem/directory.py": ["/yaybu/providers/filesystem/files.py"], "/yaybu/core/protocol/file.py": ["/yaybu/core/protocol/server.py"]}
32,425
marchon/yaybu
refs/heads/master
/yaybu/core/runner.py
# Copyright 2011 Isotoma Limited # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import sys import logging import logging.handlers import subprocess import getpass from yaybu.core import resource from yaybu.core import error from yaybu.core import runcontext from yaybu.core import event logger = logging.getLogger("runner") class LoaderError(Exception): pass class Runner(object): resources = None def trampoline(self, username): command = ["sudo", "-u", username] + sys.argv[0:1] if "SSH_AUTH_SOCK" in os.environ: command.extend(["--ssh-auth-sock", os.environ["SSH_AUTH_SOCK"]]) command.extend(sys.argv[1:]) os.execvp(command[0], command) def run(self, ctx, bundle=None): """ Run locally. """ if ctx.user and getpass.getuser() != ctx.user: self.trampoline(ctx.user) return 0 event.EventState.save_file = "/var/run/yaybu/events.saved" # This makes me a little sad inside, but the whole # context thing needs a little thought before jumping in event.state.simulate = ctx.simulate if not ctx.simulate: save_parent = os.path.realpath(os.path.join(event.EventState.save_file, os.path.pardir)) if not os.path.exists(save_parent): os.mkdir(save_parent) try: if os.path.exists(event.EventState.save_file): if ctx.resume: event.state.loaded = False elif ctx.no_resume: if not ctx.simulate: os.unlink(event.EventState.save_file) event.state.loaded = True else: raise error.SavedEventsAndNoInstruction("There is a saved events file - you need to specify --resume or --no-resume") if bundle: self.resources = bundle else: config = ctx.get_config() self.resources = resource.ResourceBundle(config.get("resources", [])) self.resources.bind() changed = self.resources.apply(ctx, config) if not ctx.simulate and os.path.exists(event.EventState.save_file): os.unlink(event.EventState.save_file) if not changed: # nothing changed ctx.changelog.info("No changes were required") return 255 ctx.changelog.info("All changes were applied successfully") return 0 except error.ExecutionError, e: # this will have been reported by the context manager, so we wish to terminate # but not to raise it further. Other exceptions should be fully reported with # tracebacks etc automatically ctx.changelog.error("Terminated due to execution error in processing") return e.returncode except error.Error, e: # If its not an Execution error then it won't have been logged by the # Resource.apply() machinery - make sure we log it here. ctx.changelog.write(str(e)) ctx.changelog.error("Terminated due to error in processing") return e.returncode except SystemExit: # A normal sys.exit() is fine.. raise #except: # from yaybu.core.debug import post_mortem # post_mortem() # raise
{"/yaybu/resources/prompt.py": ["/yaybu/core/resource.py", "/yaybu/core/policy.py", "/yaybu/core/argument.py"], "/yaybu/core/protocol/changelog.py": ["/yaybu/core/protocol/server.py"], "/yaybu/core/tests/test_whitehat.py": ["/yaybu/core/whitehat.py"], "/yaybu/providers/git.py": ["/yaybu/core/error.py"], "/yaybu/providers/tests/test_subversion.py": ["/yaybu/core/error.py"], "/yaybu/providers/tests/test_filesystem.py": ["/yaybu/providers/filesystem/__init__.py"], "/yaybu/providers/tests/test_rsync.py": ["/yaybu/core/error.py"], "/yaybu/providers/filesystem/directory.py": ["/yaybu/providers/filesystem/files.py"], "/yaybu/core/protocol/file.py": ["/yaybu/core/protocol/server.py"]}
32,426
marchon/yaybu
refs/heads/master
/yaybu/core/remote.py
# Copyright 2011 Isotoma Limited # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import subprocess import pickle import sys import os import yay from yaybu.core.protocol.server import Server, HttpResource, StaticResource, AboutResource from yaybu.core.protocol.file import FileResource, EncryptedResource from yaybu.core.protocol.changelog import ChangeLogResource from yaybu.core.runner import Runner from yaybu.core.runcontext import RunContext from yaybu.core import error class RemoteRunner(Runner): user_known_hosts_file = "/dev/null" identity_file = None strict_host_key_checking = "ask" interactive = True def load_host_keys(self, filename): self.user_known_hosts_file = filename def load_system_host_keys(self): self.user_known_hosts_file = os.path.expanduser("~/.ssh/known_hosts") def set_identity_file(self, identity_file): self.identity_file = identity_file def set_missing_host_key_policy(self, policy): self.strict_host_key_checking = policy def set_interactive(self, interactive): self.interactive = interactive def run(self, ctx): command = ["ssh", "-A"] command.extend(["-o", "UserKnownHostsFile %s" % self.user_known_hosts_file]) command.extend(["-o", "StrictHostKeyChecking %s" % self.strict_host_key_checking]) if self.identity_file: command.extend(["-o", "IdentityFile %s" % self.identity_file]) if not self.interactive: command.extend(["-o", "BatchMode yes"]) if ctx.connect_user: command.extend(["-l", ctx.connect_user]) if ctx.port: command.extend(["-p", ctx.port]) command.append(ctx.host) command.extend(["yaybu", "--remote"]) if ctx.user: command.extend(["--user", ctx.user]) if ctx.simulate: command.append("-s") if ctx.verbose: command.extend(list("-v" for x in range(ctx.verbose))) if ctx.resume: command.append("--resume") if ctx.no_resume: command.append("--no-resume") command.append("-") try: p = subprocess.Popen(command, stdin=subprocess.PIPE, stdout=subprocess.PIPE) root = HttpResource() root.put_child("config", StaticResource(pickle.dumps(ctx.get_config()))) root.put_child("files", FileResource()) root.put_child("encrypted", EncryptedResource()) root.put_child("changelog", ChangeLogResource()) root.put_child("about", AboutResource()) Server(ctx, root, p.stdout, p.stdin).serve_forever() p.wait() return p.returncode except error.Error, e: print >>sys.stderr, "Error: %s" % str(e) p.kill() return e.returncode return p.returncode
{"/yaybu/resources/prompt.py": ["/yaybu/core/resource.py", "/yaybu/core/policy.py", "/yaybu/core/argument.py"], "/yaybu/core/protocol/changelog.py": ["/yaybu/core/protocol/server.py"], "/yaybu/core/tests/test_whitehat.py": ["/yaybu/core/whitehat.py"], "/yaybu/providers/git.py": ["/yaybu/core/error.py"], "/yaybu/providers/tests/test_subversion.py": ["/yaybu/core/error.py"], "/yaybu/providers/tests/test_filesystem.py": ["/yaybu/providers/filesystem/__init__.py"], "/yaybu/providers/tests/test_rsync.py": ["/yaybu/core/error.py"], "/yaybu/providers/filesystem/directory.py": ["/yaybu/providers/filesystem/files.py"], "/yaybu/core/protocol/file.py": ["/yaybu/core/protocol/server.py"]}
32,440
Younghoon-Lee/robo-advisor-api
refs/heads/master
/handler.py
try: import unzip_requirements except ImportError: pass from src.sharpeRatioData.sharpeRatioReports import SharpeRatioReports from src.sharpeRatioData.sharpeRecommendedHoldings import SharpeRecommendedPortfolio def skip_execution_if_warmup_call(func): def wrapper(event, context): if event.get("source") == "serverless-plugin-warmup": print("WarmUp - Lambda is warm!") return {} return func(event, context) return wrapper @skip_execution_if_warmup_call def main(event, context): arguments = event["arguments"] if event["field"] == "sharpeRatioReports": sharpeRatioData = SharpeRatioReports(arguments["portfolio"]) return sharpeRatioData.result elif event["field"] == "sharpeRecommendedPortfolio": sharpeRatioData = SharpeRecommendedPortfolio(arguments["portfolio"]) return sharpeRatioData.result else: raise Exception("PYTHON MAIN HANDLER ERROR")
{"/handler.py": ["/src/sharpeRatioData/sharpeRatioReports.py", "/src/sharpeRatioData/sharpeRecommendedHoldings.py"], "/src/sharpeRatioData/sharpeRatioReports.py": ["/src/sharpeRatioData/main.py"], "/src/sharpeRatioData/sharpeRecommendedHoldings.py": ["/src/sharpeRatioData/main.py"]}
32,441
Younghoon-Lee/robo-advisor-api
refs/heads/master
/src/sharpeRatioData/sharpeRatioReports.py
import numpy as np import pandas as pd from src.sharpeRatioData.main import SharpeRatioData from libs.errorHandler import set_log logger = set_log(__name__) # Constant CASH = 100000 RISK_FREE_RATE =0.02 class SharpeRatioReports(SharpeRatioData): def __init__(self, arguments): super().__init__(arguments) self.result = self.sharpeRatioReports() def sharpeRatioReports(self): try: S = self.covariance df = self.df userWeights = self.userWeights optimalWeights = self.optimalWeights userWeights = np.array(userWeights) optAssignedCash = optimalWeights * CASH optUnitHoldings = np.divide(optAssignedCash, df.iloc[0]) userAssignedCash = userWeights * CASH userUnitHoldings = np.divide(userAssignedCash, df.iloc[0]) date, userPort, optPort = [], [], [] for i in range(len(df)): date.append(df.iloc[i].name) userPort.append(np.dot(userUnitHoldings, df.iloc[i])/CASH) optPort.append(np.dot(optUnitHoldings, df.iloc[i])/CASH) comparedResult = pd.DataFrame( {"Date": date, "User": userPort, "Opt": optPort}) comparedResult = comparedResult.set_index(['Date']) self.comparedResult = comparedResult expectedReturnsMean = np.array(self.expectedReturnsMean) userPortfolioReturns = np.sum(expectedReturnsMean * userWeights) optimizedPortfolioReturns = np.sum( expectedReturnsMean * optimalWeights) userPortfolioVolatility = np.sqrt( np.dot(userWeights.T, np.dot(S, userWeights))) optimalPortfolioVolatility = np.sqrt( np.dot(optimalWeights.T, np.dot(S, optimalWeights))) userPortfolioSharpe = (userPortfolioReturns-RISK_FREE_RATE)/userPortfolioVolatility optimalPortfolioSharpe = (optimizedPortfolioReturns-RISK_FREE_RATE)/optimalPortfolioVolatility result = {"inputPortfolio": {"expectedReturnRates": [], "volatility": 0.0, "sharpeRatio": 0.0}, "optimalPortfolio": {"expectedReturnRates": [], "volatility": 0.0, "sharpeRatio": 0.0}} for i in range(len(df)): result["inputPortfolio"]["expectedReturnRates"].append({"date": list(comparedResult.index)[ i], "expectedReturnRate": list(comparedResult["User"])[i]}) result["optimalPortfolio"]["expectedReturnRates"].append({"date": list(comparedResult.index)[ i], "expectedReturnRate": list(comparedResult["Opt"])[i]}) result['inputPortfolio']['volatility'] = userPortfolioVolatility result['optimalPortfolio']['volatility'] = optimalPortfolioVolatility result['inputPortfolio']['sharpeRatio'] = round( userPortfolioSharpe * 10, 2) result['optimalPortfolio']['sharpeRatio'] = round( optimalPortfolioSharpe * 10, 2) return result except Exception as error: logger.error("PYTHON INTERNAL FUNCTION ERROR") raise error
{"/handler.py": ["/src/sharpeRatioData/sharpeRatioReports.py", "/src/sharpeRatioData/sharpeRecommendedHoldings.py"], "/src/sharpeRatioData/sharpeRatioReports.py": ["/src/sharpeRatioData/main.py"], "/src/sharpeRatioData/sharpeRecommendedHoldings.py": ["/src/sharpeRatioData/main.py"]}
32,442
Younghoon-Lee/robo-advisor-api
refs/heads/master
/src/sharpeRatioData/sharpeRecommendedHoldings.py
from src.sharpeRatioData.main import SharpeRatioData from libs.errorHandler import set_log logger = set_log(__name__) class SharpeRecommendedPortfolio(SharpeRatioData): def __init__(self, arguments): super().__init__(arguments) self.result = self.sharpeRecommendedHoldings() def sharpeRecommendedHoldings(self): try: cash = self.totalCashAmount optimalWeights = self.optimalWeights allocatedCash = [cash*x for x in optimalWeights] holdings, recommendedCash = [], [] for i in range(len(self.unitAmount)): holdings.append(allocatedCash[i]//self.unitAmount[i]) calculated_amount = holdings[i]*self.unitAmount[i] if calculated_amount < self.defaultAmount[i]: print("stock {} minimum bound Warning: {} is lower than {} ".format( self.assets_[i], calculated_amount, self.defaultAmount[i])) calculated_amount = 0 recommendedCash.append(calculated_amount) print("holdings(0.01): ", holdings) recommendedCash.append(cash - sum(recommendedCash)) print("User input Cash Amount: {}".format(recommendedCash)) sharpePortfolio = {"items": []} for i in range(len(self.assets_)): sharpePortfolio["items"].append( {"amount": recommendedCash[i], "stockId": self.assets_[i]}) sharpePortfolio["cashAmount"] = recommendedCash[-1] return sharpePortfolio except Exception as error: logger.error("PYTHON INTERNAL FUNCTION ERROR") raise error
{"/handler.py": ["/src/sharpeRatioData/sharpeRatioReports.py", "/src/sharpeRatioData/sharpeRecommendedHoldings.py"], "/src/sharpeRatioData/sharpeRatioReports.py": ["/src/sharpeRatioData/main.py"], "/src/sharpeRatioData/sharpeRecommendedHoldings.py": ["/src/sharpeRatioData/main.py"]}
32,443
Younghoon-Lee/robo-advisor-api
refs/heads/master
/src/debug/quicktest.py
# Debugging script [ purpose for mathematical error ] # 해당 스크립트는 디버깅을 원할하게 도와줌. # 에러 센트리에서 오류가 발생할 경우 해당 스크립트를 통해 debugging 후 hotfix 하는 것을 추천 # 클라우드 워치에서 로그를 확인한 후 argument에 오류를 발생시킨 값을 넣어서 test import pandas as pd import numpy as np from pypfopt import risk_models, expected_returns from pypfopt.exceptions import OptimizationError from pypfopt.efficient_frontier import EfficientFrontier from datetime import datetime, timedelta import pypfopt.objective_functions as objective_functions import boto3 from boto3.dynamodb.conditions import Key import math import os RISK_FREE_RATE=0.02 class SharpeRatioData: def __init__(self, arguments): self.userCash_ = [] self.assets_ = [] for i in range(len(arguments)): self.userCash_.append(arguments[i]["amount"]) self.assets_.append(arguments[i]["stockId"]) self.totalCashAmount = sum(self.userCash_) def _fetch_data(self): try: dynamodb = boto3.resource('dynamodb') table = dynamodb.Table(os.environ['chartTable']) stockEndDate = "chart-lastPrice-" + datetime.today().strftime("%Y-%m%d") + \ "T15:00:00Z" stockStartDate = 'chart-lastPrice-' + \ (datetime.today()-timedelta(weeks=52) ).strftime("%Y-%m-%d")+"T15:00:00Z" assets = self.assets_ df = pd.DataFrame() count = 0 for asset in assets: if count == 0: response = table.query( KeyConditionExpression=Key('PK').eq(asset) & Key( 'SK').between(stockStartDate, stockEndDate) ) datas = response['Items'] AdjPrice = [] dates = [] for data in datas: AdjPrice.append(float(data['price'])) dates.append(data['tradeDate']) df[asset] = AdjPrice df['Dates'] = dates df = df.sort_values(by=['Dates']) df = df.set_index('Dates', drop=True) count += 1 else: temp = pd.DataFrame() response = table.query( KeyConditionExpression=Key('PK').eq(asset) & Key( 'SK').between(stockStartDate, stockEndDate) ) datas = response['Items'] AdjPrice = [] dates = [] for data in datas: AdjPrice.append(float(data['price'])) dates.append(data['tradeDate']) temp[asset] = AdjPrice temp['Dates'] = dates temp = temp.sort_values(by=['Dates']) temp = temp.set_index('Dates', drop=True) df = pd.merge(df, temp, how='outer', left_index=True, right_index=True) except Exception as e: print("DynamoDB connection Error :", e) try: df = df.dropna() self.df = df self.userWeights = [x/sum(self.userCash_) for x in self.userCash_] mu = expected_returns.capm_return(df) self.expectedReturnsMean = mu # provide methods for computing shrinkage estimates of the covariance matrix S = risk_models.CovarianceShrinkage(df).ledoit_wolf() self.covariance = S ef = EfficientFrontier(mu, S) # increase the number of nonzero weights # ef.add_objective(objective_functions.L2_reg, gamma=1) # weights = ef.efficient_return(0.2) # weights = ef.clean_weights() # count = list(weights.values()).count(0) weights = ef.max_sharpe() # if count > 1: # print("max_sharpe not applied") # ef.add_objective(objective_functions.L2_reg, gamma=1) # weights = ef.efficient_return(0.2) # weights = ef.clean_weights() optimalWeights = [] for i in range(len(assets)): optimalWeights.append(weights[assets[i]]) optimalWeights = np.array(optimalWeights) self.optimalWeights = optimalWeights except OptimizationError: ef = EfficientFrontier(mu, S) weights = ef.min_volatility() optimalWeights = [] for i in range(len(assets)): optimalWeights.append(weights[assets[i]]) optimalWeights = np.array(optimalWeights) self.optimalWeights = optimalWeights except Exception as e: print("processing Data error : ", e) def sharpeRatioReports(self): try: S = self.covariance df = self.df cash = 100000 userWeights = self.userWeights optimalWeights = self.optimalWeights userWeights = np.array(userWeights) optAssignedCash = optimalWeights * cash optUnitHoldings = np.divide(optAssignedCash, df.iloc[0]) userAssignedCash = userWeights * cash userUnitHoldings = np.divide(userAssignedCash, df.iloc[0]) date = [] userPort = [] optPort = [] for i in range(len(df)): date.append(df.iloc[i].name) userPort.append(np.dot(userUnitHoldings, df.iloc[i])/cash) optPort.append(np.dot(optUnitHoldings, df.iloc[i])/cash) comparedResult = pd.DataFrame( {"Date": date, "User": userPort, "Opt": optPort}) comparedResult = comparedResult.set_index(['Date']) self.comparedResult = comparedResult expectedReturnsMean = np.array(self.expectedReturnsMean) userPortfolioReturns = np.sum(expectedReturnsMean * userWeights) optimizedPortfolioReturns = np.sum( expectedReturnsMean * optimalWeights) userVolatility = np.sqrt( np.dot(userWeights.T, np.dot(S, userWeights))) optimalVolatility = np.sqrt( np.dot(optimalWeights.T, np.dot(S, optimalWeights))) print("유저 변동성: {}, 최적 변동성: {}".format(userVolatility, optimalVolatility)) userPortfolioSharpe = (userPortfolioReturns-RISK_FREE_RATE)/userVolatility optimalPortfolioSharpe = (optimizedPortfolioReturns-RISK_FREE_RATE)/optimalVolatility print("유저 샤프지수: {}, 최적의 샤프지수: {}".format(userPortfolioSharpe,optimalPortfolioSharpe)) result = {"inputPortfolio": {"expectedReturnRates": [], "volatility": 0.0, "sharpeRatio": 0.0}, "optimalPortfolio": {"expectedReturnRates": [], "volatility": 0.0, "sharpeRatio": 0.0}} for i in range(len(df)): result["inputPortfolio"]["expectedReturnRates"].append({"date": list(comparedResult.index)[ i], "expectedReturnRate": list(comparedResult["User"])[i]}) result["optimalPortfolio"]["expectedReturnRates"].append({"date": list(comparedResult.index)[ i], "expectedReturnRate": list(comparedResult["Opt"])[i]}) result['inputPortfolio']['volatility'] = userVolatility result['optimalPortfolio']['volatility'] = optimalVolatility result['inputPortfolio']['sharpeRatio'] = userPortfolioSharpe result['optimalPortfolio']['sharpeRatio'] = optimalPortfolioSharpe return result except Exception as e: print("Python Lambda Function Error : ", e) return {'Python Lambda Function complete': False} def sharpeRecommendedHoldings(self): try: df = self.df cash = self.totalCashAmount optimalWeights = self.optimalWeights print("target weights: {}".format(optimalWeights)) dynamodb = boto3.resource('dynamodb') table = dynamodb.Table(os.environ['tickleTable']) response = table.query( KeyConditionExpression=Key('PK').eq( 'exchangeRate') & Key('SK').eq('currency-USD') ) datas = response['Items'] exchangeRate = float(datas[0]['rate']) allocatedCash = [((cash*x)/exchangeRate) for x in optimalWeights] latest = df.tail(1).to_numpy() trade_cost = latest * 0.0025 holdings = [] for i in range(len(latest[0])): if trade_cost[0][i] > 0.01: holdings.append( allocatedCash[i]/(latest[0][i]*1.0025*1.11*1.1)) else: holdings.append( allocatedCash[i]/((latest[0][i]+0.01)*1.11*1.1)) print("holdings before round: ", holdings) holdings = [(math.floor(x*100)/100) for x in holdings] print("holdings after round: {}".format(holdings)) recommendedCash = [] for i in range(len(latest[0])): if trade_cost[0][i] > 0.01: recommendedCash.append( math.ceil(holdings[i]*latest[0][i]*1.0025*1.11*1.1*exchangeRate/100)*100) else: recommendedCash.append( math.ceil(holdings[i]*(latest[0][i]+0.01)*1.1*1.11*exchangeRate/100)*100) print(recommendedCash) recommendedCash.append(cash - sum(recommendedCash)) sharpePortfolio = {"items": []} for i in range(len(self.assets_)): sharpePortfolio["items"].append( {"amount": recommendedCash[i], "stockId": self.assets_[i]}) sharpePortfolio["items"].append( {"amount": recommendedCash[-1], "stockId": "cash-KRW"}) return sharpePortfolio except Exception as e: print("Python Lambda Function Error : ", e) return {'python lambda function complete': False} def showChart(self): # local test for graph analysis comparedResult = self.comparedResult plt.figure(figsize=[12.2, 4.5]) for compare in comparedResult: plt.plot(comparedResult[compare], label=compare) plt.title('Back test') plt.xlabel('Date', fontsize=18) plt.ylabel('portfolio Return Rate', fontsize=18) plt.legend(comparedResult.columns.values, loc='upper left') plt.show() if __name__ == "__main__": import matplotlib.pyplot as plt os.environ['chartTable'] = "prod-charts" os.environ['tickleTable'] = 'prod-tickle' args = [ { "amount": 5700, "stockId": "CH0334081137" }, { "amount": 6000, "stockId": "US91332U1016" }, { "amount": 5700, "stockId": "US0090661010" } ] test = SharpeRatioData(args) test._fetch_data() test.sharpeRatioReports() test.showChart() # holdings = test.sharpeRecommendedHoldings() # print(holdings) # print(holdings)
{"/handler.py": ["/src/sharpeRatioData/sharpeRatioReports.py", "/src/sharpeRatioData/sharpeRecommendedHoldings.py"], "/src/sharpeRatioData/sharpeRatioReports.py": ["/src/sharpeRatioData/main.py"], "/src/sharpeRatioData/sharpeRecommendedHoldings.py": ["/src/sharpeRatioData/main.py"]}
32,444
Younghoon-Lee/robo-advisor-api
refs/heads/master
/src/sharpeRatioData/main.py
import pandas as pd import numpy as np from pypfopt import risk_models, expected_returns from pypfopt.efficient_frontier import EfficientFrontier from pypfopt.exceptions import OptimizationError from datetime import datetime, timedelta import pypfopt.objective_functions as objective_functions import boto3 import os from boto3.dynamodb.conditions import Key from libs.errorHandler import set_log logger = set_log(__name__) class SharpeRatioData: def __init__(self, portfolio): self.holdings = portfolio["items"] self.userCash_, self.assets_, self.defaultAmount, self.unitAmount = [], [], [], [] for i in range(len(self.holdings)): self.userCash_.append(self.holdings[i]["amount"]) self.assets_.append(self.holdings[i]["stockId"]) self.defaultAmount.append(self.holdings[i]["defaultAmount"]) self.unitAmount.append(self.holdings[i]["unitAmount"]) self.totalCashAmount = sum(self.userCash_) + portfolio["cashAmount"] self._fetch_data() def _fetch_data(self): try: dynamodb = boto3.resource('dynamodb') table = dynamodb.Table(os.environ['chartTable']) stockEndDate = "chart-lastPrice-" + datetime.utcnow().strftime("%Y-%m%d") + \ "T15:00:00Z" stockStartDate = 'chart-lastPrice-' + \ (datetime.utcnow()-timedelta(weeks=52) ).strftime("%Y-%m-%d")+"T15:00:00Z" assets = self.assets_ df = pd.DataFrame() for index, asset in enumerate(assets): if index == 0: response = table.query( KeyConditionExpression=Key('PK').eq(asset) & Key( 'SK').between(stockStartDate, stockEndDate) ) datas = response['Items'] AdjPrice, dates = [], [] for data in datas: AdjPrice.append(float(data['price'])) dates.append(data['tradeDate']) df[asset] = AdjPrice df['Dates'] = dates df = df.sort_values(by=['Dates']) df = df.set_index('Dates', drop=True) else: temp = pd.DataFrame() response = table.query( KeyConditionExpression=Key('PK').eq(asset) & Key( 'SK').between(stockStartDate, stockEndDate) ) datas = response['Items'] AdjPrice, dates = [], [] for data in datas: AdjPrice.append(float(data['price'])) dates.append(data['tradeDate']) temp[asset] = AdjPrice temp['Dates'] = dates temp = temp.sort_values(by=['Dates']) temp = temp.set_index('Dates', drop=True) df = pd.merge(df, temp, how='outer', left_index=True, right_index=True) except Exception as error: logger.fatal("DYNAMODB CONNECTION ERROR") raise error try: df = df.dropna() self.df = df self.userWeights = [x/sum(self.userCash_) for x in self.userCash_] print("user weights : {}".format(self.userWeights)) mu = expected_returns.capm_return(df) self.expectedReturnsMean = mu S = risk_models.CovarianceShrinkage(df).ledoit_wolf() self.covariance = S ef = EfficientFrontier(mu, S) # ef.add_objective(objective_functions.L2_reg, gamma=1) weights = ef.max_sharpe() # count = list(weights.values()).count(0) # if count > 1: # ef.add_objective(objective_functions.L2_reg, gamma=1) # weights = ef.efficient_return(0.2) # weights = ef.clean_weights() optimalWeights = [] for i in range(len(assets)): optimalWeights.append(weights[assets[i]]) optimalWeights = np.array(optimalWeights) print("optimal weights : {}".format(optimalWeights)) self.optimalWeights = optimalWeights except OptimizationError: logger.info("solver has been changed to minimize volatility due to infeasibility") ef = EfficientFrontier(mu, S) weights = ef.min_volatility() optimalWeights = [] for i in range(len(assets)): optimalWeights.append(weights[assets[i]]) optimalWeights = np.array(optimalWeights) print("optimal weights : {}".format(optimalWeights)) self.optimalWeights = optimalWeights except Exception as error: logger.error("PROCESSING DATA ERROR") raise error
{"/handler.py": ["/src/sharpeRatioData/sharpeRatioReports.py", "/src/sharpeRatioData/sharpeRecommendedHoldings.py"], "/src/sharpeRatioData/sharpeRatioReports.py": ["/src/sharpeRatioData/main.py"], "/src/sharpeRatioData/sharpeRecommendedHoldings.py": ["/src/sharpeRatioData/main.py"]}
32,446
NicoKc/mocManager
refs/heads/master
/song.py
class Song(object): def __init__(self, rowId, title, artist): self.rowId = rowId self.title = title self.artist = artist def __str__(self): return "({0}, {1} - {2})".format(self.rowId, self.artist, self.title)
{"/mocManager.py": ["/musicLibrary.py"], "/musicLibrary.py": ["/model/musicLibraryRepository.py", "/model/mp3.py", "/song.py"], "/mocManagerController.py": ["/mocManager.py", "/musicLibrary.py", "/mocAction.py"]}
32,447
NicoKc/mocManager
refs/heads/master
/mocAction.py
class MocAction(object): PLAY_NOW = 0 TOGGLE_PAUSE_PLAY = 1 ENQUEUE = 2 NEXT = 3 PREVIOUS = 4 GO_TO_SECONDS = 5 INFO = 6
{"/mocManager.py": ["/musicLibrary.py"], "/musicLibrary.py": ["/model/musicLibraryRepository.py", "/model/mp3.py", "/song.py"], "/mocManagerController.py": ["/mocManager.py", "/musicLibrary.py", "/mocAction.py"]}
32,448
NicoKc/mocManager
refs/heads/master
/model/context.py
from sqlalchemy import * from sqlalchemy.orm import sessionmaker from sqlalchemy.ext.declarative import declarative_base engine = create_engine('sqlite:///musicLibrary.db', echo=True) Base = declarative_base(engine) Session = sessionmaker() Session.configure(bind=engine)
{"/mocManager.py": ["/musicLibrary.py"], "/musicLibrary.py": ["/model/musicLibraryRepository.py", "/model/mp3.py", "/song.py"], "/mocManagerController.py": ["/mocManager.py", "/musicLibrary.py", "/mocAction.py"]}
32,449
NicoKc/mocManager
refs/heads/master
/mocManager.py
import os import subprocess import logging import musicLibrary _mocp = "mocp" _playNow = "-l" _startServer = "-F" _stopServer = "-X" _togglePause = "-G" _enqueue = "-q" _next = "-f" _previous = "-r" _goToSeconds = "-k" _getInfo = "-i" def starServer(mp3Id): subprocess.call([_mocp, _starServer]) def stopServer(mp3Id): subprocess.call([_mocp, _stopServer]) def playMp3(mp3Id): musicLibrary.startNewCurrentPlaylist(mp3Id) mp3 = musicLibrary.getMp3ById(mp3Id) fullPath = os.path.join(mp3.path, mp3.fileName) print(mp3Path) #subprocess.call([_mocp, _playNow, mp3Path]) def togglePause(mp3Id): subprocess.call([_mocp, _togglePause]) def enqueue(mp3Id): musicLibrary.enqueueInCurrentPlaylist(mp3Id) mp3Path = musicLibrary.getMp3ById(mp3Id) subprocess.call([_mocp, _enqueue, mp3Path]) def playNext(mp3Id): subprocess.call([_mocp, _next]) def playPrevious(mp3Id): subprocess.call([_mocp, _previous]) def goToSeconds(seconds): subprocess.call([_mocp, _goToSeconds, str(seconds)]) def getInfo(mp3Id): subprocess.call([_mocp, _getInfo])
{"/mocManager.py": ["/musicLibrary.py"], "/musicLibrary.py": ["/model/musicLibraryRepository.py", "/model/mp3.py", "/song.py"], "/mocManagerController.py": ["/mocManager.py", "/musicLibrary.py", "/mocAction.py"]}
32,450
NicoKc/mocManager
refs/heads/master
/musicLibrary.py
import os import sqlite3 import eyed3 import model.musicLibraryRepository as repository from model.mp3 import * from song import * #_dbName = 'mp3Library.db' #_musicPath = "/{0}".format(os.path.join("","home","kechunet","Music")) _musicPath = "/{0}".format(os.path.join("","home","kechusoft","Music")) #_musicPath = os.path.join("C:/", "Users","nkinaschuk","Music") def getMp3InMusic(): os.listdir(_musicPath) mp3Files = [(eyed3.load(os.path.join(_musicPath, mp3)), mp3) for mp3 in os.listdir(_musicPath) if mp3.endswith(".mp3")] return mp3Files def saveMp3s(): mp3Files = getMp3InMusic() mp3s = [Mp3(title=mp3File[0].tag.title, artist=mp3File[0].tag.artist, fileName=mp3File[1], path=_musicPath) for mp3File in mp3Files] repository.insertMp3s(mp3s) def getMp3s(): mp3s = repository.getAllMp3s() return [Song(mp3.mp3Id,mp3.title, mp3.artist) for mp3 in mp3s] def getMp3ById(mp3Id): mp3 = repository.getMp3ById(mp3Id) return mp3 def startNewCurrentPlaylist(mp3Id): repository.startNewCurrentPlaylist(mp3Id) def enqueueInCurrentPlaylist(mp3Id): repository.enqueueInCurrentPlaylist(mp3Id)
{"/mocManager.py": ["/musicLibrary.py"], "/musicLibrary.py": ["/model/musicLibraryRepository.py", "/model/mp3.py", "/song.py"], "/mocManagerController.py": ["/mocManager.py", "/musicLibrary.py", "/mocAction.py"]}
32,451
NicoKc/mocManager
refs/heads/master
/mocManagerController.py
import logging import falcon import mocManager as mm import musicLibrary as ml import json from mocAction import MocAction as ma class MocManagerController(object): def __init__(self): self.logger = logging.getLogger('mocManagerApi.' + __name__) self.actions = { ma.PLAY_NOW: mm.playMp3, ma.TOGGLE_PAUSE_PLAY: mm.togglePause, ma.ENQUEUE: mm.enqueue, ma.NEXT: mm.playNext, ma.PREVIOUS: mm.playPrevious, ma.GO_TO_SECONDS: mm.goToSeconds, ma.INFO: mm.getInfo, } def on_get(self, req, resp, user_id): print("Entro Por Get") songs = ml.getMp3s() resp.body = json.dumps([song.__dict__ for song in songs]) #resp.body = json.dumps(songs[0].__dict__) resp.set_header('Powered-By', 'Falcon') resp.status = falcon.HTTP_200 def on_post(self, req, resp, user_id): try: print("Entro Por post") request = req.context['doc'] print("Request es {0}".format(request)) action = int(request['Action']) print("Action es {0}".format(action)) #if not action in range(0,5): # req.context['result'] = "Invalid ateration" #else: # mp3Path = int(request['Mp3']) # print("mp3Path es {0}".format(mp3Path)) # self.actions[action](mp3Path) except Exception as ex: #self.logger.error(ex) raise ex resp.set_header('Powered-By', 'Falcon') resp.status = falcon.HTTP_200
{"/mocManager.py": ["/musicLibrary.py"], "/musicLibrary.py": ["/model/musicLibraryRepository.py", "/model/mp3.py", "/song.py"], "/mocManagerController.py": ["/mocManager.py", "/musicLibrary.py", "/mocAction.py"]}
32,452
NicoKc/mocManager
refs/heads/master
/model/mp3.py
from sqlalchemy import * from sqlalchemy.orm import relationship from sqlalchemy.ext.declarative import declarative_base from playlistMp3 import * from context import Base class Mp3(Base): __tablename__ = 'mp3s' mp3Id = Column(Integer, primary_key=True) title = Column(String(50)) artist = Column(String(50)) fileName = Column(String(50)) path = Column(String(250)) playlists = relationship('Playlist', secondary='playlistsMp3s', back_populates='mp3s') def __init__(self, title, artist, fileName, path, mp3Id=None): self.title = title self.artist = artist self.fileName = fileName self.path = path self.mp3Id = mp3Id def __repr__(self): return "<Mp3(mp3Id='%s', \ title='%s', \ artist='%s', \ fileName='%s', \ path='%s')>" % (self.mp3Id, self.title, self.artist, self.fileName, self.path)
{"/mocManager.py": ["/musicLibrary.py"], "/musicLibrary.py": ["/model/musicLibraryRepository.py", "/model/mp3.py", "/song.py"], "/mocManagerController.py": ["/mocManager.py", "/musicLibrary.py", "/mocAction.py"]}
32,453
NicoKc/mocManager
refs/heads/master
/model/musicLibraryRepository.py
from sqlalchemy import * from context import engine, Session from mp3 import * from sqlalchemy.sql import func from playlist import * from playlistMp3 import * _currentPlaylistId = 0 def getAllMp3s(): return Session().query(Mp3) def getMp3ById(mp3Id): return Session().query(Mp3).filter_by(mp3Id=mp3Id).first() def getPlaylistLastPosition(playlistId): session = Session() lastPosition = int(session.query(func.max(PlaylistMp3.position)).filter_by(playlistId=playlistId).first()[0]) session.close() return lastPosition def insertMp3s(mp3s): session = Session() session.add_all(mp3s) session.commit() def insertPlaylists(playlists): session = Session() session.add_all(playlists) session.commit() def instertMp3sInPlaylists(mp3Id, playlistId, position=None): session = Session() if(position is None): position = getPlaylistLastPosition(playlistId) + 1 playlist = Playlist(mp3Id, playlistId, position) session.add_all(playlist) session.commit() def startNewCurrentPlaylist(mp3Id): session = Session() session.query(PlaylistMp3s).filter_by(playlistId=_currentPlaylistId).delete() playlistMp3 = PlaylistMp3(mp3Id, _currentPlaylistId, 1) session.add(playlistMp3) session.commit() def enqueueInCurrentPlaylist(mp3Id): session = Session() lastPosition = getPlaylistLastPosition(_currentPlaylistId) playlistMp3 = PlaylistMp3(mp3Id, _currentPlaylistId, lastPosition + 1) session.add(playlistMp3) session.commit() def createPlaylist(name, description): session = Session() playlist = Playlist(name, description) session.add(playlist) session.commit()
{"/mocManager.py": ["/musicLibrary.py"], "/musicLibrary.py": ["/model/musicLibraryRepository.py", "/model/mp3.py", "/song.py"], "/mocManagerController.py": ["/mocManager.py", "/musicLibrary.py", "/mocAction.py"]}
32,454
NicoKc/mocManager
refs/heads/master
/model/playlist.py
from sqlalchemy import * from sqlalchemy.orm import relationship from sqlalchemy.ext.declarative import declarative_base from playlistMp3 import * from context import Base class Playlist(Base): __tablename__ = 'playlists' playlistId = Column(Integer, primary_key=True) name = Column(String(50)) description = Column(String(50)) mp3s = relationship('Mp3', secondary='playlistsMp3s', back_populates='playlists') def __init__(self, name, description, playlistId = None): self.name = name self.description = description self.playlistId = playlistId def __repr__(self): return "<Playlist(playlistId='%s', \ name='%s', \ description='%s')>" % (self.playlistId, self.name, self.description)
{"/mocManager.py": ["/musicLibrary.py"], "/musicLibrary.py": ["/model/musicLibraryRepository.py", "/model/mp3.py", "/song.py"], "/mocManagerController.py": ["/mocManager.py", "/musicLibrary.py", "/mocAction.py"]}
32,455
NicoKc/mocManager
refs/heads/master
/model/playlistMp3.py
from sqlalchemy import * from sqlalchemy import ForeignKey from sqlalchemy.orm import relationship from sqlalchemy.ext.declarative import declarative_base from context import Base class PlaylistMp3(Base): __tablename__ = 'playlistsMp3s' playlistId = Column(Integer, ForeignKey('playlists.playlistId'), primary_key=True) mp3Id = Column(Integer, ForeignKey('mp3s.mp3Id'), primary_key=True) position = Column(Integer) def __init__(self, playlistId, mp3Id, position): self.playlistId = playlistId self.mp3Id = mp3Id self.position = position def __repr__(self): return "<PlaylistMp3(playlistId='%s', \ mp3Id='%s', \ position='%s')>" % (self.playlistId, self.mp3Id, self.position)
{"/mocManager.py": ["/musicLibrary.py"], "/musicLibrary.py": ["/model/musicLibraryRepository.py", "/model/mp3.py", "/song.py"], "/mocManagerController.py": ["/mocManager.py", "/musicLibrary.py", "/mocAction.py"]}
32,456
brenoSCosta/projetoNovel
refs/heads/master
/projetoNovels/models.py
from django.db import models # Create your models here. class User(models.Model): nickname = models.CharField(max_length=16) login = models.CharField(max_length=16, unique=True) password = models.CharField(max_length=16) email = models.EmailField(unique=True) class Meta: verbose_name_plural = "Users" def __str__(self): return self.nickname
{"/projetoNovels/forms.py": ["/projetoNovels/models.py"]}
32,457
brenoSCosta/projetoNovel
refs/heads/master
/projetoNovels/forms.py
from django import forms from .models import * class UserForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput) class Meta: model = User fields = ('nickname', 'login', 'password', 'email')
{"/projetoNovels/forms.py": ["/projetoNovels/models.py"]}
32,458
brenoSCosta/projetoNovel
refs/heads/master
/projetoNovels/migrations/0003_auto_20200814_0027.py
# Generated by Django 3.1 on 2020-08-14 03:27 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('projetoNovels', '0002_auto_20200814_0021'), ] operations = [ migrations.RenameModel( old_name='Usuario', new_name='User', ), migrations.AlterModelOptions( name='user', options={'verbose_name_plural': 'Users'}, ), ]
{"/projetoNovels/forms.py": ["/projetoNovels/models.py"]}
32,459
brenoSCosta/projetoNovel
refs/heads/master
/projetoNovels/apps.py
from django.apps import AppConfig class ProjetonovelsConfig(AppConfig): name = 'projetoNovels'
{"/projetoNovels/forms.py": ["/projetoNovels/models.py"]}
32,460
dylan-plummer/speed-counting
refs/heads/master
/models.py
from keras.models import Sequential, Model from keras.layers import Dense, Activation, Conv2D, MaxPooling2D, Conv3D, MaxPooling3D, AveragePooling3D, Dropout from keras.layers import BatchNormalization, Input, GlobalMaxPooling3D, Embedding, Flatten, LSTM, TimeDistributed from keras.layers import concatenate, GlobalAveragePooling3D from keras.initializers import glorot_uniform, Constant kernel_init = glorot_uniform() bias_init = Constant(value=0.2) def stacked_model(use_flow_field, grayscale, window_size, frame_size): if use_flow_field: encoder = Input(shape=(window_size - 1, frame_size, frame_size, 2), name='video') elif grayscale: encoder = Input(shape=(window_size, frame_size, frame_size, 1), name='video') else: encoder = Input(shape=(window_size, frame_size, frame_size, 3), name='video') output = Conv3D(4, (2, 16, 16))(encoder) output = BatchNormalization()(output) output = Activation('relu')(output) output = MaxPooling3D((2, 2, 2))(output) output = Conv3D(8, (2, 8, 8))(output) output = BatchNormalization()(output) output = Activation('relu')(output) output = MaxPooling3D((2, 2, 2))(output) output = Conv3D(16, (1, 4, 4))(output) output = BatchNormalization()(output) output = Activation('relu')(output) #output = MaxPooling3D((1, 2, 2))(output) #output = Conv3D(32, (1, 3, 3))(output) #output = BatchNormalization()(output) #output = Activation('relu')(output) #output = MaxPooling3D((1, 2, 2))(output) #output = Conv3D(64, (1, 3, 3))(output) #output = BatchNormalization()(output) #output = Activation('relu')(output) #output = TimeDistributed(MaxPooling2D(pool_size=(4, 4)))(output) #output = Conv3D(num_filters, (kernel_frames, kernel_size, kernel_size), activation='relu')(encoder) #output = MaxPooling3D(pool_size=(2, 2, 2), strides=(4, 2, 2))(output) #output = Conv3D(64, (3, 3, 3), activation='relu')(output) #output = MaxPooling3D(pool_size=(2, 2, 2), strides=(3, 2, 2))(output) #output = LSTM(100, input_shape=(batch_size, 1, window_size - 1, 32, 32, 2))(output) #output = Conv3D(128, (2, 2, 2), activation='relu')(output) #output = MaxPooling3D(pool_size=(1, 2, 2), strides=(1, 2, 2))(output) #output = TimeDistributed(Dense(256, activation='relu'))(output) #output = TimeDistributed(Dense(512, activation='relu'))(output) #output = TimeDistributed(Dense(128, activation='relu'))(output) output = Flatten()(output) #output = Dense(256, activation='relu')(output) #output = LSTM(50)(output) #output = TimeDistributed(Flatten())(output) #repetitions = Dense(1, activation='sigmoid', name='count')(output) if use_flow_field: output = Dense(window_size - 1, activation='sigmoid', name='frames')(output) else: output = Dense(window_size, activation='sigmoid', name='frames')(output) model = Model(inputs=encoder, outputs=output) return model def inception_module(x, filters_1x1, filters_3x3_reduce, filters_3x3, filters_5x5_reduce, filters_5x5, filters_pool_proj, name=None): conv_1x1 = Conv3D(filters_1x1, (2, 1, 1), padding='same', activation='relu', kernel_initializer=kernel_init, bias_initializer=bias_init)(x) conv_3x3 = Conv3D(filters_3x3_reduce, (2, 1, 1), padding='same', activation='relu', kernel_initializer=kernel_init, bias_initializer=bias_init)(x) conv_3x3 = Conv3D(filters_3x3, (2, 3, 3), padding='same', activation='relu', kernel_initializer=kernel_init, bias_initializer=bias_init)(conv_3x3) conv_5x5 = Conv3D(filters_5x5_reduce, (1, 1, 1), padding='same', activation='relu', kernel_initializer=kernel_init, bias_initializer=bias_init)(x) conv_5x5 = Conv3D(filters_5x5, (2, 5, 5), padding='same', activation='relu', kernel_initializer=kernel_init, bias_initializer=bias_init)(conv_5x5) pool_proj = MaxPooling3D((1, 3, 3), strides=(1, 1, 1), padding='same')(x) pool_proj = Conv3D(filters_pool_proj, (2, 1, 1), padding='same', activation='relu', kernel_initializer=kernel_init, bias_initializer=bias_init)(pool_proj) output = concatenate([conv_1x1, conv_3x3, conv_5x5, pool_proj], axis=4, name=name) return output def build_inception_model(use_flow_field, window_size, frame_size): if use_flow_field: input_layer = Input(shape=(window_size - 1, frame_size, frame_size, 2), name='video') else: input_layer = Input(shape=(window_size, frame_size, frame_size, 3), name='video') x = Conv3D(16, (2, 7, 7), padding='same', strides=(2, 2, 2), activation='relu', name='conv_1_7x7/2', kernel_initializer=kernel_init, bias_initializer=bias_init)(input_layer) x = MaxPooling3D((1, 3, 3), padding='same', strides=(2, 2, 2), name='max_pool_1_3x3/2')(x) x = Conv3D(16, (2, 1, 1), padding='same', strides=(1, 1, 1), activation='relu', name='conv_2a_3x3/1')(x) x = Conv3D(64, (1, 3, 3), padding='same', strides=(1, 1, 1), activation='relu', name='conv_2b_3x3/1')(x) x = MaxPooling3D((1, 3, 3), padding='same', strides=(2, 2, 2), name='max_pool_2_3x3/2')(x) x = inception_module(x, filters_1x1=16, filters_3x3_reduce=32, filters_3x3=64, filters_5x5_reduce=16, filters_5x5=32, filters_pool_proj=32, name='inception_3a') x = inception_module(x, filters_1x1=32, filters_3x3_reduce=64, filters_3x3=64, filters_5x5_reduce=32, filters_5x5=64, filters_pool_proj=64, name='inception_3b') x = MaxPooling3D((1, 3, 3), padding='same', strides=(2, 2, 2), name='max_pool_3_3x3/2')(x) x = inception_module(x, filters_1x1=64, filters_3x3_reduce=128, filters_3x3=128, filters_5x5_reduce=16, filters_5x5=32, filters_pool_proj=64, name='inception_4a') x1 = AveragePooling3D((1, 5, 5), strides=3)(x) x1 = Conv3D(128, (1, 1, 1), padding='same', activation='relu')(x1) x1 = Flatten()(x1) x1 = Dense(1024, activation='relu')(x1) x1 = Dropout(0.7)(x1) x1 = Dense(1, activation='sigmoid', name='auxilliary_output_1')(x1) x = inception_module(x, filters_1x1=128, filters_3x3_reduce=128, filters_3x3=128, filters_5x5_reduce=32, filters_5x5=64, filters_pool_proj=64, name='inception_4b') x = inception_module(x, filters_1x1=64, filters_3x3_reduce=64, filters_3x3=128, filters_5x5_reduce=32, filters_5x5=64, filters_pool_proj=64, name='inception_4c') x = inception_module(x, filters_1x1=32, filters_3x3_reduce=64, filters_3x3=64, filters_5x5_reduce=16, filters_5x5=32, filters_pool_proj=32, name='inception_4d') x2 = AveragePooling3D((1, 5, 5), strides=3)(x) x2 = Conv3D(128, (1, 1, 1), padding='same', activation='relu')(x2) x2 = Flatten()(x2) x2 = Dense(1024, activation='relu')(x2) x2 = Dropout(0.7)(x2) x2 = Dense(1, activation='sigmoid', name='auxilliary_output_2')(x2) x = inception_module(x, filters_1x1=32, filters_3x3_reduce=32, filters_3x3=64, filters_5x5_reduce=16, filters_5x5=32, filters_pool_proj=32, name='inception_4e') x = MaxPooling3D((1, 3, 3), padding='same', strides=(2, 2, 2), name='max_pool_4_3x3/2')(x) x = inception_module(x, filters_1x1=16, filters_3x3_reduce=64, filters_3x3=32, filters_5x5_reduce=64, filters_5x5=128, filters_pool_proj=128, name='inception_5a') x = inception_module(x, filters_1x1=256, filters_3x3_reduce=128, filters_3x3=256, filters_5x5_reduce=64, filters_5x5=128, filters_pool_proj=128, name='inception_5b') x = GlobalAveragePooling3D(name='avg_pool_5_3x3/1')(x) x = Dropout(0.4)(x) x = Dense(1, activation='sigmoid', name='output')(x) model = Model(input_layer, [x, x1, x2], name='inception_v1') print(model.summary()) return model
{"/train_video.py": ["/data_helpers.py", "/models.py"], "/vis_video.py": ["/data_helpers.py", "/train_video.py"]}
32,461
dylan-plummer/speed-counting
refs/heads/master
/label_videos.py
import cv2 import os import numpy as np data_dir = os.getcwd() + '/unlabeled_videos/' annotation_dir = os.getcwd() + '/data/speed_annotations/' def open_video(file, label): print('\nOpening', file) cap = cv2.VideoCapture(file) frame_i = 0 count = [] while cap.isOpened(): try: ret, frame = cap.read() cv2.imshow('frame', frame) key = cv2.waitKey(100) if key & 0xFF == ord('s'): print(frame_i) count.append(frame_i) elif key & 0xFF == ord('q'): print('quitting') break frame_i += 1 except Exception as e: print('Done reading video') break cap.release() cv2.destroyAllWindows() np.save(annotation_dir + label, count) return count def label_videos(): for filename in os.listdir(data_dir): label = filename[:-4] print(open_video(data_dir + filename, label)) label_videos()
{"/train_video.py": ["/data_helpers.py", "/models.py"], "/vis_video.py": ["/data_helpers.py", "/train_video.py"]}
32,462
dylan-plummer/speed-counting
refs/heads/master
/train_video.py
import numpy as np import cv2 import os import matplotlib.pyplot as plt from keras.models import Sequential, Model from keras.layers import Dense, Activation, Conv2D, MaxPooling2D, Conv3D, MaxPooling3D, AveragePooling3D, BatchNormalization, Input, GlobalMaxPooling3D, Embedding, Flatten, LSTM, TimeDistributed from keras.layers import SpatialDropout1D from keras.optimizers import SGD, Adam from data_helpers import smooth, fit_sin from models import stacked_model, build_inception_model data_dir = os.getcwd() + '/data/' video_dir = 'speed_videos/' annotation_dir = 'speed_annotations/' learning_rate = 5e-4 batch_size = 16 num_epochs = 10 num_filters = 32 kernel_size = 32 kernel_frames = 4 frame_size = 64 window_size = 8 use_flow_field = False grayscale = True def video_to_flow_field(video): flow = np.array([]) for i in range(len(video) - 1): field = get_flow_field(video, i, i + 1) flow = np.append(flow, field) return np.reshape(flow, (video.shape[0] - 1, video.shape[1], video.shape[2], 2)) def open_video(file, window_size, flow_field=False): cap = cv2.VideoCapture(file) frameCount = int(cap.get(cv2.CAP_PROP_FRAME_COUNT)) frameWidth = frame_size frameHeight = frame_size if grayscale: buf = np.zeros((frameCount, frameHeight, frameWidth), dtype=np.uint8) else: buf = np.zeros((frameCount, frameHeight, frameWidth, 3)) fc = 0 ret = 1 while True: try: ret, img = cap.read() if grayscale: img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) else: img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) img = cv2.resize(img, (frame_size, frame_size), interpolation=cv2.INTER_AREA) buf[fc] = img.copy() fc += 1 except Exception as e: break cap.release() if grayscale: buf = np.reshape(buf, (frameCount, frameHeight, frameWidth, 1)) return buf def get_flow_field(video, i, j): prev = cv2.cvtColor(video[i], cv2.COLOR_BGR2GRAY) next = cv2.cvtColor(video[j], cv2.COLOR_BGR2GRAY) flow = cv2.calcOpticalFlowFarneback(prev, next, None, 0.5, 3, 15, 3, 5, 1.2, 0) mag, ang = cv2.cartToPolar(flow[..., 0], flow[..., 1]) hsv = np.zeros_like(video[i]) hsv[..., 1] = 255 hsv[..., 0] = ang * 180 / np.pi / 2 hsv[..., 2] = cv2.normalize(mag, None, 0, 255, cv2.NORM_MINMAX) bgr = cv2.cvtColor(hsv, cv2.COLOR_HSV2BGR) return flow def get_total_frames(): global data_dir total = 0 for filename in os.listdir(data_dir + video_dir): label_path = data_dir + annotation_dir + filename.replace('.mp4', '.npy') label = np.load(label_path) print(label[-1]) total += label[-1] return total def generate_batch(batch_size): global data_dir x_batch = np.array([]) y_batch = np.array([]) total_batch = np.array([]) while True: for filename in os.listdir(data_dir + video_dir): video_path = data_dir + video_dir + filename label_path = data_dir + annotation_dir + filename.replace('.mp4', '.npy') label = np.load(label_path) video = open_video(video_path, window_size=window_size) num_clips = 0 random_offset = np.random.randint(0, window_size) for start_frame in range(random_offset, len(video), window_size): if start_frame + window_size < len(video): clip = video[start_frame:start_frame + window_size] if use_flow_field: flow_field = video_to_flow_field(np.uint8(clip)) label_clip = label[np.where(label < start_frame + window_size - 1)] label_clip = label_clip[np.where(label_clip > start_frame)] y = np.zeros(window_size - 1) else: label_clip = label[np.where(label < start_frame + window_size)] label_clip = label_clip[np.where(label_clip > start_frame)] y = np.zeros(window_size) for frame in label_clip: y[frame - start_frame] = 1 if y.any() == 1: binary_y = 1 else: binary_y = 0 if use_flow_field: x_batch = np.append(x_batch, flow_field) else: x_batch = np.append(x_batch, clip / 255.) y_batch = np.append(y_batch, y) total_batch = np.append(total_batch, np.sum(y)) num_clips += 1 if num_clips == batch_size: num_clips = 0 if use_flow_field: x_batch = np.reshape(x_batch, (-1, window_size - 1, frame_size, frame_size, 2)) elif grayscale: x_batch = np.reshape(x_batch, (-1, window_size, frame_size, frame_size, 1)) else: x_batch = np.reshape(x_batch, (-1, window_size, frame_size, frame_size, 3)) if use_flow_field: y_batch = np.reshape(y_batch, (-1, window_size - 1)) else: y_batch = np.reshape(y_batch, (-1, window_size)) yield {'video': x_batch}, {'frames': y_batch} x_batch = np.array([]) y_batch = np.array([]) total_batch = np.array([]) print('Trained on all videos.') if __name__ == '__main__': total_frames = get_total_frames() + 1 print('Total Frames:', total_frames) print('Total Samples:', total_frames // window_size) model = stacked_model(use_flow_field, grayscale, window_size, frame_size) #model = build_inception_model(use_flow_field, window_size, frame_size) adam = Adam(lr=learning_rate) sgd = SGD(lr=learning_rate, nesterov=True, decay=1e-6, momentum=0.9) losses = { 'frames': 'mse', 'count': 'mse', } loss_weights = { 'frames': 0.75, 'count': 0.25, } model.compile(loss='binary_crossentropy', #loss_weights=loss_weights, optimizer=sgd, metrics=['accuracy']) # model.compile(loss='mse', optimizer='rmsprop') print(model.summary()) history = model.fit_generator(generate_batch(batch_size), epochs=num_epochs, steps_per_epoch=100, verbose=2) # Save the weights model.save_weights('models/model_weights.h5') # Save the model architecture with open('models/model_architecture.json', 'w') as f: f.write(model.to_json()) print(history.history.keys()) # summarize history for accuracy for loss_plot in history.history.keys(): if 'loss' in loss_plot: plt.plot(history.history[loss_plot], label=loss_plot) plt.title('model loss') plt.ylabel('loss') plt.xlabel('epoch') plt.legend(loc='best') plt.show() for acc_plot in history.history.keys(): if 'acc' in acc_plot: plt.plot(history.history[acc_plot], label=acc_plot) plt.title('model accuracy') plt.ylabel('accuracy') plt.xlabel('epoch') plt.legend(loc='best') plt.show()
{"/train_video.py": ["/data_helpers.py", "/models.py"], "/vis_video.py": ["/data_helpers.py", "/train_video.py"]}
32,463
dylan-plummer/speed-counting
refs/heads/master
/train_flow.py
import numpy as np import cv2 import os import matplotlib.pyplot as plt from keras.models import Sequential, Model from keras.layers import Dense, Activation, Conv3D, MaxPooling3D, BatchNormalization, Input, GlobalMaxPooling3D, Embedding, Flatten, LSTM from keras.layers import SpatialDropout1D from keras.optimizers import SGD, Adam data_dir = os.getcwd() + '/data/' video_dir = 'speed_videos/' annotation_dir = 'speed_annotations/' learning_rate = 0.1 batch_size = 4 num_filters = 32 kernel_size = 16 kernel_frames = 16 frame_size = 64 window_size = 32 def video_to_flow_field(video): flow = np.array([]) for i in range(len(video) - 1): field = get_flow_field(video, i, i + 1) flow = np.append(flow, field) return np.reshape(flow, (video.shape[0] - 1, video.shape[1], video.shape[2], 2)) def open_video(file, window_size): #print('\nOpening', file) cap = cv2.VideoCapture(file) frameCount = int(cap.get(cv2.CAP_PROP_FRAME_COUNT)) frameWidth = frame_size frameHeight = frame_size buf = np.empty((frameCount, frameHeight, frameWidth, 3), np.dtype('uint8')) fc = 0 ret = 1 while cap.isOpened(): try: ret, buf[fc] = cv2.resize(cap.read(), (frame_size, frame_size)) fc += 1 except: # print('Done reading video') break #print('Done reading video') cap.release() return buf def get_flow_field(video, i, j): prev = cv2.cvtColor(video[i], cv2.COLOR_BGR2GRAY) next = cv2.cvtColor(video[j], cv2.COLOR_BGR2GRAY) flow = cv2.calcOpticalFlowFarneback(prev, next, None, 0.5, 3, 15, 3, 5, 1.2, 0) mag, ang = cv2.cartToPolar(flow[..., 0], flow[..., 1]) hsv = np.zeros_like(video[i]) hsv[..., 1] = 255 hsv[..., 0] = ang * 180 / np.pi / 2 hsv[..., 2] = cv2.normalize(mag, None, 0, 255, cv2.NORM_MINMAX) bgr = cv2.cvtColor(hsv, cv2.COLOR_HSV2BGR) return flow def get_max_length(): global data_dir max_frames = 0 for filename in os.listdir(data_dir + video_dir): label_path = data_dir + annotation_dir + filename.replace('.mp4', '.npy') label = np.load(label_path) print(label[-1]) if label[-1] > max_frames: max_frames = label[-1] return max_frames def generate_batch(max_frames): global data_dir x_batch = np.array([]) y_batch = np.array([]) total_batch = np.array([]) while True: for filename in os.listdir(data_dir + video_dir): video_path = data_dir + video_dir + filename label_path = data_dir + annotation_dir + filename.replace('.mp4', '.npy') label = np.load(label_path) video = open_video(video_path, window_size=window_size) num_clips = 0 random_offset = np.random.randint(0, window_size) for start_frame in range(random_offset, len(video), window_size): if start_frame + window_size < len(video): clip = video[start_frame:start_frame + window_size] flow_field = video_to_flow_field(clip) label_clip = label[np.where(label < start_frame + window_size)] label_clip = label_clip[np.where(label_clip > start_frame)] #print(label_clip) #start_frame += window_size y = np.zeros(window_size) for frame in label_clip: y[frame - start_frame] = 1 x_batch = np.append(x_batch, flow_field) y_batch = np.append(y_batch, y) total_batch = np.append(total_batch, np.sum(y)) num_clips += 1 if num_clips == batch_size: num_clips = 0 x_batch = np.reshape(x_batch, (-1, window_size - 1, frame_size, frame_size, 2)) y_batch = np.reshape(y_batch, (-1, window_size)) yield {'video': x_batch}, {'frames': y_batch} x_batch = np.array([]) y_batch = np.array([]) total_batch = np.array([]) max_frames = get_max_length() + 1 print('Max Frames:', max_frames) encoder = Input(shape=(window_size - 1, frame_size, frame_size, 2), name='video') output = Conv3D(num_filters, (kernel_frames, kernel_size, kernel_size), activation='relu')(encoder) output = MaxPooling3D(pool_size=(5, 2, 2), strides=(5, 2, 2))(output) output = Conv3D(64, (3, 3, 3), activation='relu')(output) output = MaxPooling3D(pool_size=(1, 2, 2), strides=(5, 2, 2))(output) #output = Conv3D(128, (2, 2, 2), activation='relu')(output) #output = MaxPooling3D(pool_size=(1, 2, 2), strides=(1, 2, 2))(output) output = GlobalMaxPooling3D()(output) output = Dense(512, activation='relu')(output) repetitions = Dense(1, activation='sigmoid', name='count')(output) output = Dense(window_size, activation='sigmoid', name='frames')(output) model = Model(inputs=encoder, outputs=output) adam = Adam(lr=learning_rate) sgd = SGD(lr=learning_rate, nesterov=True, decay=1e-6, momentum=0.9) losses = { 'frames': 'mse', 'count': 'mse', } loss_weights = { 'frames': 0.75, 'count': 0.25, } model.compile(loss='binary_crossentropy', #loss_weights=loss_weights, optimizer=sgd, metrics=['acc']) # model.compile(loss='mse', optimizer='rmsprop') print(model.summary()) history = model.fit_generator(generate_batch(max_frames), epochs=100, steps_per_epoch=4, verbose=1) # Save the weights model.save_weights('models/model_weights.h5') # Save the model architecture with open('models/model_architecture.json', 'w') as f: f.write(model.to_json()) print(history.history.keys()) # summarize history for accuracy plt.plot(history.history['loss']) plt.title('model loss') plt.ylabel('loss') plt.xlabel('epoch') plt.legend(['total_loss', 'frames_loss', 'count_loss'], loc='upper left') plt.show() plt.plot(history.history['acc']) plt.title('model accuracy') plt.ylabel('accuracy') plt.xlabel('epoch') plt.legend(['frame_acc'], loc='upper left') plt.show()
{"/train_video.py": ["/data_helpers.py", "/models.py"], "/vis_video.py": ["/data_helpers.py", "/train_video.py"]}
32,464
dylan-plummer/speed-counting
refs/heads/master
/data_helpers.py
import numpy as np import scipy.optimize def smooth(x, window_len=11, window='hanning'): """smooth the data using a window with requested size. This method is based on the convolution of a scaled window with the signal. The signal is prepared by introducing reflected copies of the signal (with the window size) in both ends so that transient parts are minimized in the begining and end part of the output signal. input: x: the input signal window_len: the dimension of the smoothing window; should be an odd integer window: the type of window from 'flat', 'hanning', 'hamming', 'bartlett', 'blackman' flat window will produce a moving average smoothing. output: the smoothed signal example: t=linspace(-2,2,0.1) x=sin(t)+randn(len(t))*0.1 y=smooth(x) see also: np.hanning, np.hamming, np.bartlett, np.blackman, np.convolve scipy.signal.lfilter TODO: the window parameter could be the window itself if an array instead of a string NOTE: length(output) != length(input), to correct this: return y[(window_len/2-1):-(window_len/2)] instead of just y. """ if x.ndim != 1: raise (ValueError, "smooth only accepts 1 dimension arrays.") if x.size < window_len: raise (ValueError, "Input vector needs to be bigger than window size.") if window_len < 3: return x if not window in ['flat', 'hanning', 'hamming', 'bartlett', 'blackman']: raise (ValueError, "Window is on of 'flat', 'hanning', 'hamming', 'bartlett', 'blackman'") s = np.r_[x[window_len - 1:0:-1], x, x[-2:-window_len - 1:-1]] # print(len(s)) if window == 'flat': # moving average w = np.ones(window_len, 'd') else: w = eval('np.' + window + '(window_len)') y = np.convolve(w / w.sum(), s, mode='valid') return y def fit_sin(tt, yy, window_size): '''Fit sin to the input time sequence, and return fitting parameters "amp", "omega", "phase", "offset", "freq", "period" and "fitfunc"''' tt = np.array(tt) yy = np.array(yy) ff = np.fft.fftfreq(len(tt), (tt[1]-tt[0])) # assume uniform spacing Fyy = abs(np.fft.fft(yy)) guess_freq = abs(ff[np.argmax(Fyy[1:])+1]) # excluding the zero frequency "peak", which is related to offset guess_amp = np.std(yy) * 2.**0.5 guess_offset = np.mean(yy) guess = np.array([guess_amp, 2.*np.pi*guess_freq, 0., guess_offset]) def sinfunc(t, A, w, p, c): return np.abs(A * np.sin(w*t + p) + c) popt, pcov = scipy.optimize.curve_fit(sinfunc, tt, yy, p0=guess, maxfev =5000) A, w, p, c = popt f = w/(2.*np.pi) fitfunc = lambda t: np.abs(A * np.sin(w*t + p) + c) smoothed_y = np.zeros(window_size) for i in range(window_size): smoothed_y[i] = fitfunc(i) return smoothed_y
{"/train_video.py": ["/data_helpers.py", "/models.py"], "/vis_video.py": ["/data_helpers.py", "/train_video.py"]}
32,465
dylan-plummer/speed-counting
refs/heads/master
/vis_video.py
from itertools import product import math import numpy as np import cv2 import os import matplotlib.pyplot as plt from matplotlib.colors import hsv_to_rgb from mpl_toolkits.mplot3d import Axes3D from keras.models import model_from_json, Model from keras import backend as K from keras.utils import np_utils from data_helpers import smooth, fit_sin from train_video import generate_batch, open_video data_dir = os.getcwd() + '/data/' video_dir = 'speed_videos/' annotation_dir = 'speed_annotations/' kernel_size = 32 kernel_frames = 4 frame_size = 64 window_size = 8 vis_frames = 8 vis_size = 64 vis_iter = 50 use_flow_field = False grayscale = True def video_to_flow_field(video): flow = np.array([]) for i in range(len(video) - 1): field = get_flow_field(video, i, i + 1) flow = np.append(flow, field) return np.reshape(flow, (video.shape[0] - 1, video.shape[1], video.shape[2], 2)) def flow_to_rgb(flow): mag, ang = cv2.cartToPolar(flow[..., 0], flow[..., 1]) hsv = np.zeros((flow.shape[0], flow.shape[1], 3)) hsv[..., 1] = 255 hsv[..., 0] = ang * 180 / np.pi / 2 hsv[..., 2] = cv2.normalize(mag, None, 0, 255, cv2.NORM_MINMAX) return cv2.cvtColor(np.uint8(hsv), cv2.COLOR_HSV2RGB) def get_flow_field(video, i, j): prev = cv2.cvtColor(video[i], cv2.COLOR_BGR2GRAY) next = cv2.cvtColor(video[j], cv2.COLOR_BGR2GRAY) flow = cv2.calcOpticalFlowFarneback(prev, next, None, 0.5, 3, 15, 3, 5, 1.2, 0) return flow def plot_weights(weights): print(weights.shape) for frame_i in range(kernel_frames): fig, axes = plt.subplots(8, 4) print('Saving frame', frame_i) for i in range(len(weights)): r = i // 4 c = i % 4 img = weights[i][frame_i] bgr = cv2.cvtColor(np.uint8(img), cv2.COLOR_HSV2RGB_FULL) axes[r][c].imshow(bgr) #axes[r][c].quiver(x, y, u, v, mag, edgecolor='k', width=0.05, pivot='tip') axes[r][c].set_xticks([]) axes[r][c].set_yticks([]) plt.tight_layout(0.5) plt.savefig('saved/' + str(frame_i) + '.png', dpi=250) plt.clf() def plot_clip(clip): rows = window_size // 2 cols = window_size // rows fig, axes = plt.subplots(rows, cols) for i in range(len(clip)): r = i // cols c = i % cols img = clip[i] # img = np.reshape(img, (vis_size, vis_size, 3)) if use_flow_field: img = flow_to_rgb(np.float32(img)) elif grayscale: img = img[..., 0] print(img.shape, img.max()) axes[r][c].imshow(img) axes[r][c].set_title(str(i)) axes[r][c].set_xticks([]) axes[r][c].set_yticks([]) plt.tight_layout() plt.show() # util function to convert a tensor into a valid image def deprocess_image(x): # normalize tensor: center on 0., ensure std is 0.1 x -= x.mean() x /= (x.std() + 1e-5) x *= 0.1 # clip to [0, 1] x += 0.5 x = np.clip(x, 0, 1) # convert to RGB array x *= 255 #x = x.transpose((1, 2, 0)) x = np.clip(x, 0, 255).astype('uint8') return x def plot_conv_layer(model, layer_name, layer_dict, input_video=None): visualizations = np.array([]) layer_output = layer_dict[layer_name].output input_img = model.input print(layer_output) rows = 4 cols = 4 num_filters = rows * cols active_layers = 0 # keeps track of number of activated layers currently in the visualization filter_index = 0 while active_layers < num_filters and 'video' not in layer_name: if input_video is None: if use_flow_field: noise_batch = np.random.random((1, vis_frames - 1, vis_size, vis_size, 2)) elif grayscale: noise_batch = np.random.normal(1, size=(1, vis_frames, vis_size, vis_size, 1)) else: noise_batch = np.random.normal(1, size=(1, vis_frames, vis_size, vis_size, 3)) else: noise_batch = input_video # build a loss function that maximizes the activation # of the nth filter of the layer considered try: loss = K.mean(layer_output[..., filter_index]) except Exception as e: layer_output = layer_dict[layer_name].output filter_index = 0 print(e) pass # compute the gradient of the input picture wrt this loss grads = K.gradients(loss, input_img)[0] # normalization trick: we normalize the gradient grads /= (K.sqrt(K.mean(K.square(grads))) + 1e-5) # this function returns the loss and grads given the input picture iterate = K.function([input_img], [loss, grads]) filter_index += 1 step = 1. # run gradient ascent for 20 steps for i in range(vis_iter): loss_value, grads_value = iterate([noise_batch]) if loss_value == 0: print('Neuron', filter_index, 'not activated') break noise_batch += grads_value * step if loss_value != 0: active_layers += 1 print(active_layers, '/', num_filters) visualizations = np.append(visualizations, noise_batch) if use_flow_field: print(visualizations.shape) visualizations = np.reshape(visualizations, (num_filters, 1, vis_frames - 1, vis_size, vis_size, 2)) elif grayscale: visualizations = np.reshape(visualizations, (num_filters, 1, vis_frames, vis_size, vis_size, 1)) else: visualizations = np.reshape(visualizations, (num_filters, 1, vis_frames, vis_size, vis_size, 3)) frame_offset = 0 if use_flow_field: frame_offset = -1 for frame_i in range(vis_frames + frame_offset): fig, axes = plt.subplots(rows, cols) print('Saving frame', frame_i) for i in range(num_filters): r = i // cols c = i % cols frame = visualizations[i][0][frame_i] if use_flow_field: img = flow_to_rgb(np.float32(frame)) axes[r][c].imshow(img) elif grayscale: img = deprocess_image(frame) img = np.reshape(img, (vis_size, vis_size)) axes[r][c].imshow(img, cmap='gray') else: img = deprocess_image(frame) img = np.reshape(img, (vis_size, vis_size, 3)) axes[r][c].imshow(img) axes[r][c].set_title(layer_name + ': ' + str(i)) axes[r][c].set_xticks([]) axes[r][c].set_yticks([]) try: os.mkdir('conv_vis/' + layer_name) except OSError: print('Directory', layer_name, 'already exists') plt.tight_layout() plt.savefig('conv_vis/' + layer_name + '/' + str(frame_i) + '.png', dpi=300) plt.clf() def predict_test(model): video_path = np.random.choice(os.listdir(data_dir + video_dir)) label_path = data_dir + annotation_dir + video_path.replace('.mp4', '.npy') label = np.load(label_path) video = open_video(data_dir + video_dir + video_path, window_size=window_size) print('Video shape', video.shape) print('Video max', video.max()) num_clips = 0 smoothed_y = np.zeros(window_size) while smoothed_y.all() == 0: start_frame = np.random.randint(0, len(video) - window_size) if start_frame + window_size < len(video): clip = video[start_frame:start_frame + window_size] if use_flow_field: flow_field = video_to_flow_field(np.uint8(clip)) label_clip = label[np.where(label < start_frame + window_size)] label_clip = label_clip[np.where(label_clip > start_frame)] y = np.zeros(window_size) for frame in label_clip: y[frame - start_frame] = 1 if y.any() != 0: print('fitting:') smoothed_y = fit_sin(np.arange(0, window_size), y, window_size) print('Smoothed', smoothed_y) if use_flow_field: pred = model.predict(np.array([flow_field])) else: pred = model.predict(np.array([clip / 255.])) print(pred[0]) print(y) if use_flow_field: plot_clip(flow_field) else: print(clip.max()) plot_clip(clip / 255.) plt.plot(pred[0]) plt.scatter(np.arange(0, window_size), y) plt.plot(smoothed_y) plt.show() print(np.sum(pred[0])) # load data dir = 'models/' with open(dir + 'model_architecture.json', 'r') as f: model = model_from_json(f.read()) # Load weights into the new model model.load_weights(dir + 'model_weights.h5') print(model.summary()) predict_test(model) # get the symbolic outputs of each "key" layer (we gave them unique names). layer_dict = dict([(layer.name, layer) for layer in model.layers]) print(layer_dict) for batch in generate_batch(1): for layer in layer_dict.keys(): if 'conv' in layer or 'activation' in layer or 'video' in layer: #if 'frames' in layer: try: #plot_conv_layer(model, layer, layer_dict, input_video=batch[0]['video']) plot_conv_layer(model, layer, layer_dict) except Exception as e: print(e) pass break
{"/train_video.py": ["/data_helpers.py", "/models.py"], "/vis_video.py": ["/data_helpers.py", "/train_video.py"]}
32,473
Kiyoshi-o/AI_Speaker
refs/heads/master
/VoiceRecognition.py
import speech_recognition as Srecog class ClVoiceRecognition: @staticmethod def voiceToText(): result = "" print("Say Something ...") with Srecog.Microphone() as source: Srecog.Recognizer().adjust_for_ambient_noise(source) audio = Srecog.Recognizer().listen(source) print("Now to recognize it ...") try: result = Srecog.Recognizer().recognize_google(audio, language='ja-Jp') print(result) return True, result # 以下は認識できなかったときに止まらないように。 except Srecog.UnknownValueError: print("could not understand audio") return False, result except Srecog.RequestError as e: print("Could not request results from Google Speech Recognition service; {0}".format(e)) return False, result
{"/main.py": ["/VoiceRecognition.py", "/SpeechSynthesis.py", "/GetReply.py", "/TextSpeaker.py"]}
32,474
Kiyoshi-o/AI_Speaker
refs/heads/master
/GetReply.py
import pya3rt class ClGetReply: Pya3rt_API = "DZZBA92i9EhCouadQ29CXrw1hMOKORxl" def __init__(self, message): self.message = message def getReply(self): client = pya3rt.TalkClient(self.Pya3rt_API) res = client.talk(self.message) rep = res['results'][0]['reply'] print("Takeru 「%s」" % rep) return rep
{"/main.py": ["/VoiceRecognition.py", "/SpeechSynthesis.py", "/GetReply.py", "/TextSpeaker.py"]}
32,475
Kiyoshi-o/AI_Speaker
refs/heads/master
/SpeechSynthesis.py
import os import requests class ClSpeechSynthesis(): VoiceTextWeb_API = "zjbjkyglhm1r2kv8" def __init__(self, fileName, text, speaker, emotion, emotion_level, pitch, speed, volume): self.file = fileName + ".wav" self.text = text self.speaker = speaker self.emotion = emotion self.emotion_level = emotion_level self.pitch = pitch self.speed = speed self.volume = volume def getVoice(self): adress = 'https://api.voicetext.jp/v1/tts' Parameters = { 'text': self.text, 'speaker': self.speaker, 'emotion': self.emotion, 'emotion_level': self.emotion_level, 'pitch': self.pitch, 'speed': self.speed, 'volume': self.volume } filePath = os.path.abspath(self.file) send = requests.post(adress, params=Parameters, auth=(self.VoiceTextWeb_API, '')) result = open(filePath, 'wb') result.write(send.content) result.close() return filePath
{"/main.py": ["/VoiceRecognition.py", "/SpeechSynthesis.py", "/GetReply.py", "/TextSpeaker.py"]}
32,476
Kiyoshi-o/AI_Speaker
refs/heads/master
/main.py
import sys import VoiceRecognition import SpeechSynthesis import GetReply import TextSpeaker import random as rd # TestCode from VoiceRecognition import ClVoiceRecognition def main(): speaker = "takeru" emotionList = ["happiness", "anger", "sadness"] pitch = 100 speed = 100 volume = 100 print("*** AI自動返信開始 ***") # print("([E]を押して終了)") while True: root_vR: ClVoiceRecognition = VoiceRecognition.ClVoiceRecognition() # インスタンス生成 result = root_vR.voiceToText() if bool(result[0]): root_gR = GetReply.ClGetReply(result[1]) # インスタンス生成 reply = root_gR.getReply() else: reply = "すみません。よく分かりません。" # TestCode 感情(ランダム) emotion = emotionList[rd.randint(0, 2)] emotion_level = rd.randint(1, 4) # TestCode_END root_sS = SpeechSynthesis.ClSpeechSynthesis( "voice", reply, speaker, emotion, emotion_level, pitch, speed, volume) # インスタンス生成 voiceFile = root_sS.getVoice() root_tS = TextSpeaker.ClTextSpeaker(voiceFile) # インスタンス生成 root_tS.outputWav() if not bool(result[0]): sys.exit() if __name__ == '__main__': main()
{"/main.py": ["/VoiceRecognition.py", "/SpeechSynthesis.py", "/GetReply.py", "/TextSpeaker.py"]}
32,477
Kiyoshi-o/AI_Speaker
refs/heads/master
/TextSpeaker.py
import winsound class ClTextSpeaker: def __init__(self, voiceFile): self.voiceFile = voiceFile def outputWav(self): with open(self.voiceFile, 'rb') as voice_f: data = voice_f.read() winsound.PlaySound(data, winsound.SND_MEMORY)
{"/main.py": ["/VoiceRecognition.py", "/SpeechSynthesis.py", "/GetReply.py", "/TextSpeaker.py"]}
32,478
xm2235/Project_Tools
refs/heads/master
/sightings/migrations/0005_auto_20200512_1327.py
# Generated by Django 3.0.6 on 2020-05-12 13:27 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('sightings', '0004_auto_20200512_1103'), ] operations = [ migrations.RenameField( model_name='sighting', old_name='other_activity', new_name='other_activities', ), migrations.RemoveField( model_name='sighting', name='color', ), migrations.RemoveField( model_name='sighting', name='location', ), migrations.AlterField( model_name='sighting', name='age', field=models.CharField(choices=[('Adult', 'Adult'), ('Juvenile', 'Juvenile'), ('None', 'None')], default=None, max_length=50, verbose_name='Age'), ), ]
{"/sightings/views.py": ["/sightings/models.py"]}
32,479
xm2235/Project_Tools
refs/heads/master
/sightings/admin.py
from django.contrib import admin from . import models admin.site.register(models.Sighting)
{"/sightings/views.py": ["/sightings/models.py"]}
32,480
xm2235/Project_Tools
refs/heads/master
/sightings/views.py
from django.shortcuts import render from django.http import HttpResponse from .models import Sighting def index(request): all_sightings = Sighting.objects.all() return render(request, 'sightings/index.html', {'all_sightings': all_sightings}) def unique(request, unique_squirrel_id): squirrel = Sighting.objects.get(unique_squirrel_id = unique_squirrel_id) return render(request, 'sightings/unique.html', {'squirrel' : squirrel}) def stats(request): stats1=Sighting.objects.all().count() stats2=Sighting.objects.filter(age='Adult').count() stats3=Sighting.objects.filter(age='Juvenile').count() stats4=Sighting.objects.filter(running=True).count() stats5=Sighting.objects.filter(eating=True).count() value = { 'Stats1':stats1, 'Stats2':stats2, 'Stats3':stats3, 'Stats4':stats4, 'Stats5':stats5, } return render(request, 'sightings/stats.html', value)
{"/sightings/views.py": ["/sightings/models.py"]}
32,481
xm2235/Project_Tools
refs/heads/master
/sightings/migrations/0003_auto_20200511_0813.py
# Generated by Django 3.0.6 on 2020-05-11 08:13 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('sightings', '0002_auto_20200511_0809'), ] operations = [ migrations.AddField( model_name='squirrel', name='approaches', field=models.BooleanField(default=False, verbose_name='Approaches'), ), migrations.AddField( model_name='squirrel', name='chasing', field=models.BooleanField(default=False, verbose_name='Chasing'), ), migrations.AddField( model_name='squirrel', name='climbing', field=models.BooleanField(default=False, verbose_name='Climbing'), ), migrations.AddField( model_name='squirrel', name='eating', field=models.BooleanField(default=False, verbose_name='Eating'), ), migrations.AddField( model_name='squirrel', name='foraging', field=models.BooleanField(default=False, verbose_name='Foraging'), ), migrations.AddField( model_name='squirrel', name='indifferent', field=models.BooleanField(default=False, verbose_name='Indifferent'), ), migrations.AddField( model_name='squirrel', name='kuks', field=models.BooleanField(default=False, verbose_name='Kuks'), ), migrations.AddField( model_name='squirrel', name='moans', field=models.BooleanField(default=False, verbose_name='Moans'), ), migrations.AddField( model_name='squirrel', name='other_activity', field=models.CharField(default=None, max_length=50, verbose_name='Other_activity'), ), migrations.AddField( model_name='squirrel', name='quaas', field=models.BooleanField(default=False, verbose_name='Quaas'), ), migrations.AddField( model_name='squirrel', name='running', field=models.BooleanField(default=False, verbose_name='Running'), ), migrations.AddField( model_name='squirrel', name='runs_from', field=models.BooleanField(default=False, verbose_name='Runs_from'), ), migrations.AddField( model_name='squirrel', name='tail_flags', field=models.BooleanField(default=False, verbose_name='Tail_flags'), ), migrations.AddField( model_name='squirrel', name='tail_twitches', field=models.BooleanField(default=False, verbose_name='Tail_twitches'), ), migrations.AlterField( model_name='squirrel', name='color', field=models.CharField(choices=[('Cinnamon', 'Cinnamon'), ('Black', 'Black'), ('Gray', 'Gray')], default=None, max_length=50, verbose_name='Color'), ), migrations.AlterField( model_name='squirrel', name='location', field=models.CharField(choices=[('Above Ground', 'Above Ground'), ('Ground Plane', 'Ground Plane'), ('None', 'None')], default=None, max_length=50, verbose_name='Location'), ), migrations.AlterField( model_name='squirrel', name='shift', field=models.CharField(choices=[('PM', 'PM'), ('AM', 'AM')], default=None, max_length=50, verbose_name='Shift'), ), ]
{"/sightings/views.py": ["/sightings/models.py"]}
32,482
xm2235/Project_Tools
refs/heads/master
/sightings/migrations/0004_auto_20200512_1103.py
# Generated by Django 3.0.6 on 2020-05-12 11:03 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('sightings', '0003_auto_20200511_0813'), ] operations = [ migrations.CreateModel( name='Sighting', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('latitude', models.DecimalField(decimal_places=10, default=None, max_digits=50, verbose_name='Latitude')), ('longitude', models.DecimalField(decimal_places=10, default=None, max_digits=50, verbose_name='Longitude')), ('unique_squirrel_id', models.CharField(default=None, max_length=50, verbose_name='ID')), ('shift', models.CharField(choices=[('PM', 'PM'), ('AM', 'AM')], default=None, max_length=50, verbose_name='Shift')), ('date', models.DateField(default=None, max_length=50, verbose_name='Date')), ('age', models.CharField(choices=[('Juvenile', 'Juvenile'), ('Adult', 'Adult'), ('None', 'None')], default=None, max_length=50, verbose_name='Age')), ('color', models.CharField(choices=[('Black', 'Black'), ('Gray', 'Gray'), ('Cinnamon', 'Cinnamon')], default=None, max_length=50, verbose_name='Color')), ('location', models.CharField(choices=[('Ground Plane', 'Ground Plane'), ('Above Ground', 'Above Ground'), ('None', 'None')], default=None, max_length=50, verbose_name='Location')), ('specific_location', models.CharField(default=None, max_length=50, verbose_name='Specific_location')), ('running', models.BooleanField(default=False, verbose_name='Running')), ('chasing', models.BooleanField(default=False, verbose_name='Chasing')), ('climbing', models.BooleanField(default=False, verbose_name='Climbing')), ('eating', models.BooleanField(default=False, verbose_name='Eating')), ('foraging', models.BooleanField(default=False, verbose_name='Foraging')), ('other_activity', models.CharField(default=None, max_length=50, verbose_name='Other_activity')), ('kuks', models.BooleanField(default=False, verbose_name='Kuks')), ('quaas', models.BooleanField(default=False, verbose_name='Quaas')), ('moans', models.BooleanField(default=False, verbose_name='Moans')), ('tail_flags', models.BooleanField(default=False, verbose_name='Tail_flags')), ('tail_twitches', models.BooleanField(default=False, verbose_name='Tail_twitches')), ('approaches', models.BooleanField(default=False, verbose_name='Approaches')), ('indifferent', models.BooleanField(default=False, verbose_name='Indifferent')), ('runs_from', models.BooleanField(default=False, verbose_name='Runs_from')), ], ), migrations.DeleteModel( name='squirrel', ), ]
{"/sightings/views.py": ["/sightings/models.py"]}
32,483
xm2235/Project_Tools
refs/heads/master
/sightings/models.py
from django.db import models class Sighting(models.Model): latitude = models.DecimalField('Latitude',default = None,max_digits =50,decimal_places = 10) longitude = models.DecimalField('Longitude',default = None,max_digits =50,decimal_places = 10) unique_squirrel_id = models.CharField('ID',max_length = 50,default = None) CHOICE1 = {('AM','AM'),('PM','PM'),} shift = models.CharField('Shift',max_length = 50,default = None,choices = CHOICE1) date = models.DateField('Date',max_length = 50,default = None,) CHOICE2 = {('Adult','Adult'),('Juvenile','Juvenile'),('None','None'),} age = models.CharField('Age',max_length = 50,default = None,choices = CHOICE2) # CHOICE3 = {('Black','Black'),('Cinnamon','Cinnamon'),('Gray','Gray'),} # primary_fur_color = models.CharField('Color',max_length = 50,default = None,choices = CHOICE3) specific_location = models.CharField('Specific_location',max_length = 50,default = None) running = models.BooleanField('Running',default = False) chasing = models.BooleanField('Chasing',default = False) climbing = models.BooleanField('Climbing',default = False) eating = models.BooleanField('Eating',default = False) foraging = models.BooleanField('Foraging',default = False) other_activities = models.CharField('Other_activity',max_length = 50,default = None) kuks = models.BooleanField('Kuks',default = False) quaas = models.BooleanField('Quaas',default = False) moans = models.BooleanField('Moans',default = False) tail_flags = models.BooleanField('Tail_flags',default = False) tail_twitches = models.BooleanField('Tail_twitches',default = False) approaches = models.BooleanField('Approaches',default = False) indifferent = models.BooleanField('Indifferent',default = False) runs_from = models.BooleanField('Runs_from',default = False)
{"/sightings/views.py": ["/sightings/models.py"]}
32,484
xm2235/Project_Tools
refs/heads/master
/sightings/migrations/0002_auto_20200511_0809.py
# Generated by Django 3.0.6 on 2020-05-11 08:09 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('sightings', '0001_initial'), ] operations = [ migrations.AddField( model_name='squirrel', name='age', field=models.CharField(choices=[('None', 'None'), ('Juvenile', 'Juvenile'), ('Adult', 'Adult')], default=None, max_length=50, verbose_name='Age'), ), migrations.AddField( model_name='squirrel', name='color', field=models.CharField(choices=[('Black', 'Black'), ('Cinnamon', 'Cinnamon'), ('Gray', 'Gray')], default=None, max_length=50, verbose_name='Color'), ), migrations.AddField( model_name='squirrel', name='date', field=models.DateField(default=None, max_length=50, verbose_name='Date'), ), migrations.AddField( model_name='squirrel', name='latitude', field=models.DecimalField(decimal_places=10, default=None, max_digits=50, verbose_name='Latitude'), ), migrations.AddField( model_name='squirrel', name='location', field=models.CharField(choices=[('None', 'None'), ('Above Ground', 'Above Ground'), ('Ground Plane', 'Ground Plane')], default=None, max_length=50, verbose_name='Location'), ), migrations.AddField( model_name='squirrel', name='longitude', field=models.DecimalField(decimal_places=10, default=None, max_digits=50, verbose_name='Longitude'), ), migrations.AddField( model_name='squirrel', name='shift', field=models.CharField(choices=[('AM', 'AM'), ('PM', 'PM')], default=None, max_length=50, verbose_name='Shift'), ), migrations.AddField( model_name='squirrel', name='specific_location', field=models.CharField(default=None, max_length=50, verbose_name='Specific_location'), ), migrations.AddField( model_name='squirrel', name='unique_id', field=models.CharField(default=None, max_length=50, verbose_name='ID'), ), ]
{"/sightings/views.py": ["/sightings/models.py"]}
32,491
BTruer/CaesarCipher
refs/heads/master
/logic.py
from random import randint from langdetect import detect, detect_langs def getCiphertext(keyE,plaintext): if int(keyE) == 0: keyE = getRandKey() ciphertext="" for char in plaintext: if char.isalpha(): if char.islower(): num = ord(char)+int(keyE) if num > 122: num=num-26 ciphertext = ciphertext + chr(num) else: ciphertext = ciphertext + chr(num) else: num = ord(char)+int(keyE) if num > 90: num=num-26 ciphertext = ciphertext + chr(num) else: ciphertext = ciphertext + chr(num) else: ciphertext = ciphertext + char return ciphertext def getPlaintext(keyD,ciphertext): if int(keyD) == 0: keyD = getRandKey() plaintext = "" for char in ciphertext: if char.isalpha(): if char.islower(): num = ord(char)-int(keyD) if num < 97: num=num+26 plaintext = plaintext + chr(num) else: plaintext = plaintext + chr(num) else: num = ord(char)-int(keyD) if num < 65: num = num+26 plaintext = plaintext + chr(num) else: plaintext = plaintext + chr(num) else: plaintext = plaintext + char return plaintext def getPlaintextAll(ciphertext): plaintextAll = "" for keyD in range(1,26): if len(str(keyD)) == 1: plaintextAll = plaintextAll + "Key Value = " + str(keyD) + " :" else: plaintextAll = plaintextAll + "Key Value = " + str(keyD) + ":" plaintext = getPlaintext(keyD,ciphertext) if str(detect(plaintext)) == "en": plaintextAll = plaintextAll + "***Eng detected*** " +plaintext + "\n" else: plaintextAll = plaintextAll + " " +plaintext + "\n" return plaintextAll def getRandKey(): return randint(1,25)
{"/app.py": ["/logic.py"]}
32,492
BTruer/CaesarCipher
refs/heads/master
/app.py
from flask import Flask, request, render_template from logic import * app = Flask(__name__) @app.route('/', methods=['GET', 'POST']) def index(): textE = "" textD = "" if request.method == 'GET': return render_template("index.html", textE=textE, textD=textD) if request.method == "POST": if(request.form.get('submitButton') == "encryptMe"): plaintext = request.form.get('plaintext') keyE = request.form.get('keyE') textE = getCiphertext(keyE,plaintext) return render_template("index.html", textE=textE, textD=textD) elif(request.form.get('submitButton') == "decryptMe"): ciphertext = request.form.get('ciphertext') keyD = request.form.get('keyD') textD = getPlaintext(keyD,ciphertext) return render_template("index.html", textE=textE, textD=textD) elif(request.form.get('submitButton') == "attackMe"): ciphertext = request.form.get('ciphertext') textD = getPlaintextAll(ciphertext) return render_template("index.html", textE=textE, textD=textD) if __name__ == '__main__': app.run(debug=True)
{"/app.py": ["/logic.py"]}
32,497
tonderys/File_Changer
refs/heads/master
/File_Changer_GUI.py
from Tkinter import * from threading import Thread from File_Finder import * from File_Changer import * from colour import Color class File_Changer_GUI: def __init__(self): self.top_window = Tk() self.path_label = Label(self.top_window, text = "path") self.path_label.grid(column = 1, row = 2) self.path_entry = Entry(self.top_window, width = 30) self.path_entry.insert(0,"./") self.path_entry.grid(column = 2, row = 2, columnspan = 2) self.extension_label = Label(self.top_window, text = "extension") self.extension_label.grid(column = 1, row = 3) self.extension_entry = Entry(self.top_window, width = 30) self.extension_entry.insert(0,"sm") self.extension_entry.grid(column = 2, row = 3, columnspan = 2) self.files_label = Label(self.top_window, text = "found files:") self.files_label.grid(column = 4, row = 1, columnspan = 2) self.files_list = Listbox(self.top_window, width = 60) self.files_list.grid(column = 4, row = 2, rowspan = 3, columnspan = 2) self.search_button = Button(self.top_window, text = "Search", command = self.search_for_files_and_put_to_list) self.search_button.grid (column = 1, columnspan = 3, row = 4) self.searched_phrase_label = Label(self.top_window, text = "searched phrase") self.searched_phrase_label.grid (column = 1, row = 6) self.searched_phrase_entry = Entry(self.top_window, width = 30) self.searched_phrase_entry.insert(0,"[0-4]") self.searched_phrase_entry.grid(column = 2, columnspan = 2, row = 6) self.old_phrase_label = Label(self.top_window, text = "old phrase") self.old_phrase_label.grid(column = 1, row = 7) self.old_phrase_entry = Entry(self.top_window, width = 30) self.old_phrase_entry.insert(0, "4") self.old_phrase_entry.grid(column = 2, columnspan = 2, row = 7) self.new_phrase_label = Label(self.top_window, text = "new phrase") self.new_phrase_label.grid(column = 1, row = 8) self.new_phrase_entry = Entry(self.top_window, width = 30) self.new_phrase_entry.insert(0, "2") self.new_phrase_entry.grid(column = 2, columnspan = 2, row = 8) self.line_length_label = Label(self.top_window, text = "line length") self.line_length_label.grid(column = 1, row = 9) self.line_length_entry = Entry(self.top_window, width = 3) self.line_length_entry.insert(0, "4") self.line_length_entry.grid(column = 2, row =9, sticky = "w") self.change_button = Button(self.top_window, text = "change", command = self.change_files) self.change_button.grid(column = 3, row = 9) self.changed_files_label = Label(self.top_window, text = "changed files:") self.changed_files_label.grid(column = 4, row = 5) self.changed_files_list = Listbox(self.top_window, width = 30, fg = Color("green")) self.changed_files_list.grid(column = 4, row = 6, rowspan = 4) self.unchanged_files_label = Label(self.top_window, text = "unchanged files:") self.unchanged_files_label.grid(column = 5, row = 5) self.unchanged_files_list = Listbox(self.top_window, width = 30, fg = Color("red")) self.unchanged_files_list.grid(column = 5, row = 6, rowspan = 4) def search_for_files_and_put_to_list(self): self.files_list.delete(0, END) self.finder = File_Finder(self.path_entry.get(), self.extension_entry.get()) for file_path in self.finder.file_paths: self.files_list.insert(1,file_path) def change_files(self): self.changed_files_list.delete(0, END) for file_path in self.files_list.get(0, END): changer = File_Changer(str(file_path), str(self.searched_phrase_entry.get()), int(self.line_length_entry.get()), str(self.old_phrase_entry.get()), str(self.new_phrase_entry.get())) self.put_on_proper_list(changer.output_code, file_path) def put_on_proper_list(self, code, file_path): if code != 1: self.unchanged_files_list.insert(1, file_path) else: self.changed_files_list.insert(1, file_path) if __name__ == "__main__": gui = File_Changer_GUI() gui.top_window.mainloop()
{"/File_Changer_GUI.py": ["/File_Finder.py", "/File_Changer.py"], "/tests.py": ["/File_Finder_test.py", "/File_Changer_test.py", "/File_Changer_GUI_test.py"], "/File_Changer_test.py": ["/File_Changer.py"], "/File_Changer_GUI_test.py": ["/File_Changer_GUI.py"], "/File_Finder_test.py": ["/File_Finder.py"]}
32,498
tonderys/File_Changer
refs/heads/master
/File_Finder.py
import os import sys class File_Finder: wanted_extension = "" output_code = 0 output_codes_dictionary = {1:"found files, and put on the list", 2:"haven't found any file with wanted extension", 3:"can't find/open file path"} def __init__(self, file_path, wanted_extension): self.file_paths = [] self.set_extension(wanted_extension) self.seek_for_files(file_path) def set_extension(self, wanted_extension): if wanted_extension[0] == '.': self.wanted_extension = wanted_extension else: self.wanted_extension = '.'+wanted_extension def seek_for_files(self, path): try: self.update_searched_file_list(path) for name in sorted(os.listdir(path)): full_path = os.path.join(path, name) if os.path.isdir(full_path): self.seek_for_files(full_path) if not self.found_any() and self.output_code != 1: self.output_code = 2 except OSError: self.output_code = 3 def update_searched_file_list(self, path): for name in sorted(os.listdir(path)): full_path = os.path.join(path, name) if self.is_searched_type(full_path) == True: self.file_paths.append(full_path) self.output_code = 1 def is_searched_type(self, file_path): if os.path.isfile(file_path): if os.path.splitext(file_path)[1] == self.wanted_extension: return True else: return False def print_file_paths(self): for path in self.file_paths: print path def found_any(self): if len(self.file_paths) == 0: return False else: return True if __name__ == "__main__": file_path = sys.argv[1] wanted_extension = sys.argv[2] finder = File_Finder(file_path, wanted_extension) finder.print_file_paths()
{"/File_Changer_GUI.py": ["/File_Finder.py", "/File_Changer.py"], "/tests.py": ["/File_Finder_test.py", "/File_Changer_test.py", "/File_Changer_GUI_test.py"], "/File_Changer_test.py": ["/File_Changer.py"], "/File_Changer_GUI_test.py": ["/File_Changer_GUI.py"], "/File_Finder_test.py": ["/File_Finder.py"]}
32,499
tonderys/File_Changer
refs/heads/master
/File_Changer.py
import shutil import sys import re class File_Changer: output_codes_dictionary={1:"zmiana pliku %s", 2:"w pliku %s nie znaleziono szukanej frazy", 3:"brak pliku/uprawnien do pliku: %s"} def __init__(self, filename, searched_phrase, line_length , old_phrase, new_phrase, quiet = 1): self.quiet = quiet self.output_code = 0 self.filename = str(filename) self.line_length = line_length self.searched_phrase = "%s{%s}" % (searched_phrase, line_length) self.old_phrase = str(old_phrase) self.new_phrase = str(new_phrase) self.change_file() def file_match(self): filename = self.filename searched_phrase = self.searched_phrase old_phrase = self.old_phrase try: source = open(filename) for line in source: if re.search(searched_phrase, line) and re.search(old_phrase, line) and len(line.strip())==self.line_length: self.output_code = 1 source.close() return True else: self.output_code = 2 source.close() return False except IOError: self.output_code = 3 def change_file(self): filename = self.filename searched_phrase = self.searched_phrase old_phrase = self.old_phrase new_phrase = self.new_phrase try: if (self.file_match() == True): shutil.move( filename, filename+"~") new_file = open (filename, "w") source = open (filename+"~", "r") for line in source: if re.search(searched_phrase, line) and re.search(old_phrase, line) and len(line.strip())==self.line_length: new_file.write(line.replace(old_phrase,new_phrase)) else: new_file.write(line) new_file.close() source.close() except (IOError): self.output_code = 3 if self.quiet == 0: print self.output_codes_dictionary[self.output_code] % self.filename if __name__ == "__main__": changer = File_Changer(sys.argv[1])
{"/File_Changer_GUI.py": ["/File_Finder.py", "/File_Changer.py"], "/tests.py": ["/File_Finder_test.py", "/File_Changer_test.py", "/File_Changer_GUI_test.py"], "/File_Changer_test.py": ["/File_Changer.py"], "/File_Changer_GUI_test.py": ["/File_Changer_GUI.py"], "/File_Finder_test.py": ["/File_Finder.py"]}
32,500
tonderys/File_Changer
refs/heads/master
/tests.py
#!/usr/bin/env python from File_Finder_test import * from File_Changer_test import * from File_Changer_GUI_test import * if __name__ == "__main__": unittest.main()
{"/File_Changer_GUI.py": ["/File_Finder.py", "/File_Changer.py"], "/tests.py": ["/File_Finder_test.py", "/File_Changer_test.py", "/File_Changer_GUI_test.py"], "/File_Changer_test.py": ["/File_Changer.py"], "/File_Changer_GUI_test.py": ["/File_Changer_GUI.py"], "/File_Finder_test.py": ["/File_Finder.py"]}
32,501
tonderys/File_Changer
refs/heads/master
/File_Changer_test.py
import unittest import os import os.path import shutil from File_Changer import * filename = "testTmpFile" class File_changer_test(unittest.TestCase): def setUp(self): if os.path.exists(filename): os.remove(filename) def tearDown(self): self.setUp() if os.path.exists(filename+"~"): os.remove(filename+"~") def test_no_input_file(self): self.assertEqual(File_Changer(filename, "[0-4]", 4, "4", "2").output_code, 3) self.assertFalse(os.path.exists(filename+"~")) def test_pattern_not_found(self): output = open(filename, "w") output.write("0000") output.close() self.assertEqual(File_Changer(filename, "[0-4]", 4, "4", "2").output_code, 2) self.assertFalse(os.path.exists(filename+"~")) def test_single_line_with_pattern(self): output = open(filename, "w") output.write("4444") output.close() self.assertEqual(File_Changer(filename, "[0-4]", 4, "4", "2").output_code, 1) self.assertTrue(os.path.exists(filename+"~")) def test_correctly_executed_program(self): output = open(filename, "w") output.write("0000\n01234\na324\n0004\n4444\n") output.close() self.assertEqual(File_Changer(filename, "[0-4]", 4, "4", "2").output_code, 1) output = open(filename, "r") self.assertEqual (output.read(), "0000\n01234\na324\n0002\n2222\n") output.close() if __name__ == "__main__": unittest.main()
{"/File_Changer_GUI.py": ["/File_Finder.py", "/File_Changer.py"], "/tests.py": ["/File_Finder_test.py", "/File_Changer_test.py", "/File_Changer_GUI_test.py"], "/File_Changer_test.py": ["/File_Changer.py"], "/File_Changer_GUI_test.py": ["/File_Changer_GUI.py"], "/File_Finder_test.py": ["/File_Finder.py"]}
32,502
tonderys/File_Changer
refs/heads/master
/File_Changer_GUI_test.py
import unittest import shutil import os import os.path from File_Changer_GUI import * testdir = "testingDirectory" class File_Changer_GUI_test(unittest.TestCase): def setUp(self): self.tearDown() os.mkdir(testdir) for i in range(0,9): tmp_path = testdir+"/"+str(i) os.mkdir(tmp_path) testFile = open("%s/%d.sm" % (tmp_path, i), "w") tmp = (i%2)*4 testFile.write("%d%d%d%d" % (tmp, tmp, tmp, tmp) ) testFile.close() def tearDown(self): if os.path.exists(testdir): shutil.rmtree(testdir) def test_GUI_normal_scenario(self): gui = File_Changer_GUI() gui.search_for_files_and_put_to_list() self.assertEqual(gui.files_list.size(), 9) gui.change_files() self.assertEqual(gui.changed_files_list.size(), 4) self.assertEqual(gui.unchanged_files_list.size(), 5) for i in range(0,9): if i%2 == 0: self.assertFalse(os.path.exists("%s/%d/%d.sm~" % (testdir,i,i))) else: self.assertTrue(os.path.exists("%s/%d/%d.sm~" % (testdir,i,i))) if __name__ == "__main__": unittest.main()
{"/File_Changer_GUI.py": ["/File_Finder.py", "/File_Changer.py"], "/tests.py": ["/File_Finder_test.py", "/File_Changer_test.py", "/File_Changer_GUI_test.py"], "/File_Changer_test.py": ["/File_Changer.py"], "/File_Changer_GUI_test.py": ["/File_Changer_GUI.py"], "/File_Finder_test.py": ["/File_Finder.py"]}