def setUp(self, *args, **kw): self.db = DbFactory() self.outfile = '/tmp/test.png' if os.path.isfile(self.outfile): try: os.remove(self.outfile) except Exception, e: pass
def main(*args, **kw): opts = parse_cli(args, kw) if opts.debug: log.setLevel(logging.DEBUG) db = DbFactory(verbose=opts.verbose) assert db, "No db_factory in build_db" Base.metadata.bind = db.engine if opts.verbose: db.meta.bind.echo = True if opts.delete_db == True: log.debug('Dropping database') db.drop_all_tables_and_sequences(no_confirm=True) if opts.populate: s = db.Session() assert s, "No Session in build_db.py populate" # Need to call this explicitely to make the __extra_table_args__ hack work configure_mappers() # Create all tables upfront Base.metadata.create_all(checkfirst=True) if opts.populate: load_from_file(s, opts.populate) env = os.environ.copy() env['AQDCONF'] = config.baseconfig rc = subprocess.call([os.path.join(BINDIR, 'add_admin.py')], env=env, stdout=1, stderr=2) if rc != 0: log.warn("Failed to add current user as administrator.") # CONSTRAINTS if db.engine.dialect.name == 'oracle': #TODO: rename should be able to dump DDL to a file log.debug('renaming constraints...') cnst.rename_non_null_check_constraints(db) log.info('database built and populated')
def main(): from aquilon.config import Config config = Config() if config.has_option("database", "module"): ms.modulecmd.load(config.get("database", "module")) db = DbFactory() Base.metadata.bind = db.engine session = db.Session() add_interfaces(session) add_addresses(session) session.rollback() raise Exception("Replace the rollback() in the code with commit() when " "ready to go, and disable this exception")
def main(*args, **kw): opts = parse_cli(args, kw) if opts.debug: log.setLevel(logging.DEBUG) (principal, realm) = parse_klist() db = DbFactory(verbose=opts.verbose) Base.metadata.bind = db.engine if opts.verbose: db.meta.bind.echo = True session = db.Session() aqd_admin = Role.get_unique(session, "aqd_admin", compel=True) dbrealm = Realm.get_unique(session, realm) if not dbrealm: dbrealm = Realm(name=realm) session.add(dbrealm) dbuser = UserPrincipal.get_unique(session, name=principal, realm=dbrealm) if dbuser: if dbuser.role == aqd_admin: log.info("%s@%s is already an aqd_admin, nothing to do", principal, realm) else: log.info("Updating %s %s to aqd_admin", dbuser.name, dbuser.role.name) dbuser.role = aqd_admin else: log.info("Creating %s@%s as aqd_admin", principal, realm) dbuser = UserPrincipal(name=principal, realm=dbrealm, role=aqd_admin, comments='User with write access to database') session.add(dbuser) if opts.commit: session.commit() elif session.new or session.dirty: log.debug("dry-run mode enabled, not running commit()")
# 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 sys.path.insert(0, '../../lib/python2.6') from aquilon.aqdb.dsdb import DsdbConnection from aquilon.aqdb.db_factory import DbFactory from aquilon.aqdb.utils.constraints import rename_non_null_check_constraints dsdb = DsdbConnection() dbf = DbFactory() add_column = "ALTER TABLE building ADD address VARCHAR(255)" dbf.engine.execute(add_column) dsdb_select = "SELECT bldg_name, bldg_addr FROM bldg WHERE state >=0" upd = """UPDATE building SET address=q'#{0}#' WHERE id=( SELECT id FROM location WHERE name='{1}' AND location_type='building') """ buildings = dsdb.run_query(dsdb_select) for row in buildings.fetchall(): try: dbf.engine.execute(upd.format(row[1], row[0])) except Exception, e: print e
sys.path.append(os.path.join(BINDIR, "..", "..", "lib", "python2.6")) import aquilon.aqdb.depends import aquilon.worker.depends from aquilon.config import Config from aquilon.exceptions_ import AquilonError, IncompleteError from aquilon.aqdb.model import Base, Resource, ResourceGroup, Cluster, Host from aquilon.aqdb.db_factory import DbFactory from aquilon.worker.templates.base import PlenaryCollection from aquilon.worker.templates.resource import PlenaryResource from aquilon.worker.templates.cluster import PlenaryCluster from aquilon.worker.templates.host import PlenaryHost from aquilon.worker.locks import CompileKey db = DbFactory() Base.metadata.bind = db.engine session = db.Session() config = Config() def main(): logging.basicConfig(level=logging.DEBUG) query = session.query(Resource) old_paths = [] with CompileKey(): for res in query.all():
raise SystemExit(err) except Exception: print("%s caught exception, bailing out." % lexer.error_leader(lexer.filename)) session.rollback() raise session.commit() if __name__ == '__main__': logging.basicConfig(levl=logging.ERROR) parser = argparse.ArgumentParser(description="Loads initial data to aqdb") parser.add_argument("-v", "--verbose", action="store_true", help="Enable verbose mode; show objects as they are added") parser.add_argument("-d", "--debug", action="store_true", help="Enable debug mode; show SQL queries") parser.add_argument("-f", "--file", action="store", required=True, help="Name of the input file") opts = parser.parse_args() if opts.debug: log = logging.getLogger('sqlalchemy.engine') log.setLevel(logging.INFO) db = DbFactory(verbose=opts.verbose) aquilon.aqdb.model.Base.metadata.bind = db.engine session = db.Session() load_from_file(session, opts.file, verbose=opts.verbose)
def __init__(self): """ Provides some convenient variables for commands. Also sets requires_* parameters for some sets of commands. All of the command objects are singletons (or Borg). """ self.dbf = DbFactory() self.config = Config() self.az = AuthorizationBroker() self.formatter = ResponseFormatter() self.catalog = StatusCatalog() # Force the instance to have local copies of the class defaults... # This allows resources.py to modify instances without worrying # about inheritance issues (classes sharing required or optional # parameters). self.required_parameters = self.required_parameters[:] self.optional_parameters = self.optional_parameters[:] # Parameter checks are filled in automatically based on input.xml. This # lets us do some rudimentary checks before the actual command is # invoked. self.parameter_checks = {} # The parameter types are filled in automatically based on input.xml. self.parameter_types = {} # This is the pivot of the above, filled in at the same time. It is a # dictionary of type names to lists of parameters. self.parameters_by_type = {} self.action = self.__module__ package_prefix = "aquilon.worker.commands." if self.action.startswith(package_prefix): self.action = self.action[len(package_prefix):] # self.command is set correctly in resources.py after parsing input.xml self.command = self.action # The readonly and format flags are done here for convenience # and simplicity. They could be overridden by the __init__ # method of any show/search/cat commands that do not want these # defaults. Some 'one-off' commands (like ping and status) # just set the variables themselves. if self.action.startswith("show") or self.action.startswith("search"): self.requires_readonly = True self.requires_format = True if self.action.startswith("cat"): self.requires_format = True self.requires_readonly = True self._is_lock_free = True if not self.requires_readonly \ and self.config.get('broker', 'mode') == 'readonly': self.badmode = 'readonly' else: self.badmode = False self._update_render(self.render) if not self.defer_to_thread: if self.requires_azcheck or self.requires_transaction: self.defer_to_thread = True log.msg("Forcing defer_to_thread to True because of " "required authorization or transaction for %s" % self.command) # Not sure how to handle formatting with deferred... self.requires_format = False
def test_init(): db = DbFactory() assert db, 'No db factory created'
#from aquilon.aqdb.shell import ipshell #FIXME: import server.depends from utils.load_server_classpath() import ms.version ms.version.addpkg('ipaddr', '2.1.9') from ipaddr import IPv4Address as IPAddr from nose.tools import eq_ NUM_MACHINES = 2 DNAME = 'ms.com' DNSENV = 'internal' SHORT_NAME_PREFIX = 'aqdb-test-host-' MACHINE_NAME_PREFIX = 'test_machine_' sess = DbFactory().Session() assert sess, 'No session in %s' % func_name() #TODO: factor out assert_type(obj, cls, func_name) the isinstance calls STATUS = Status.get_unique(sess, 'ready') assert isinstance(STATUS, Status), 'No ready status @ %s' % func_name() DOMAIN = Domain.get_unique(sess, 'ny-prod') assert isinstance(DOMAIN, Domain), 'no ny-prod domain @ %s' % func_name() ARCH = Archetype.get_unique(sess, 'aquilon') assert isinstance(ARCH, Archetype), 'No archetype @ %s' % func_name() OS = OperatingSystem.get_unique(sess, name='linux', version='5.0.1-x86_64',