Example #1
0
/*
** Recreate the ticket table.
*/
void ticket_create_table(int separateConnection){
  const char *zSql;

  db_multi_exec("DROP TABLE IF EXISTS ticket;");
  zSql = ticket_table_schema();
  if( separateConnection ){
    db_init_database(g.zRepositoryName, zSql, 0);
  }else{
    db_multi_exec("%s", zSql);
  }
}
Example #2
0
/*
 * Fill in the remaining fields of the jcr as if it
 *  is going to run the job.
 */
bool complete_jcr_for_job(JCR *jcr, JOB *job, POOL *pool)
{
   POOL_DBR pr;

   memset(&pr, 0, sizeof(POOL_DBR));
   set_jcr_defaults(jcr, job);
   if (pool) {
      jcr->pool = pool;               /* override */
   }
   if (jcr->db) {
      Dmsg0(100, "complete_jcr close db\n");
      db_close_database(jcr, jcr->db);
      jcr->db = NULL;
   }

   Dmsg0(100, "complete_jcr open db\n");
   jcr->db = db_init_database(jcr, jcr->catalog->db_driver, jcr->catalog->db_name, 
                              jcr->catalog->db_user,
                              jcr->catalog->db_password, jcr->catalog->db_address,
                              jcr->catalog->db_port, jcr->catalog->db_socket,
                              jcr->catalog->mult_db_connections, 
                              jcr->catalog->disable_batch_insert);
   if (!jcr->db || !db_open_database(jcr, jcr->db)) {
      Jmsg(jcr, M_FATAL, 0, _("Could not open database \"%s\".\n"),
                 jcr->catalog->db_name);
      if (jcr->db) {
         Jmsg(jcr, M_FATAL, 0, "%s", db_strerror(jcr->db));
         db_close_database(jcr, jcr->db);
         jcr->db = NULL;
      }
      return false;
   }
   bstrncpy(pr.Name, jcr->pool->name(), sizeof(pr.Name));
   while (!db_get_pool_record(jcr, jcr->db, &pr)) { /* get by Name */
      /* Try to create the pool */
      if (create_pool(jcr, jcr->db, jcr->pool, POOL_OP_CREATE) < 0) {
         Jmsg(jcr, M_FATAL, 0, _("Pool %s not in database. %s"), pr.Name,
            db_strerror(jcr->db));
         if (jcr->db) {
            db_close_database(jcr, jcr->db);
            jcr->db = NULL;
         }
         return false;
      } else {
         Jmsg(jcr, M_INFO, 0, _("Pool %s created in database.\n"), pr.Name);
      }
   }
   jcr->jr.PoolId = pr.PoolId;
   return true;
}
Example #3
0
/*
 * Get a non-pooled connection used when either sql pooling is
 * runtime disabled or at compile time. Or when we run out of
 * pooled connections and need more database connections.
 */
B_DB *db_sql_get_non_pooled_connection(JCR *jcr,
                                       const char *db_drivername,
                                       const char *db_name,
                                       const char *db_user,
                                       const char *db_password,
                                       const char *db_address,
                                       int db_port,
                                       const char *db_socket,
                                       bool mult_db_connections,
                                       bool disable_batch_insert,
                                       bool need_private)
{
   B_DB *mdb;

#if defined(HAVE_DYNAMIC_CATS_BACKENDS)
   Dmsg2(100, "db_sql_get_non_pooled_connection allocating 1 new non pooled database connection to database %s, backend type %s\n",
         db_name, db_drivername);
#else
   Dmsg1(100, "db_sql_get_non_pooled_connection allocating 1 new non pooled database connection to database %s\n",
         db_name);
#endif
   mdb = db_init_database(jcr,
                          db_drivername,
                          db_name,
                          db_user,
                          db_password,
                          db_address,
                          db_port,
                          db_socket,
                          mult_db_connections,
                          disable_batch_insert,
                          need_private);
   if (mdb == NULL) {
      return NULL;
   }

   if (!db_open_database(jcr, mdb)) {
      Mmsg2(mdb->errmsg, _("Could not open database \"%s\": ERR=%s\n"), db_name, db_strerror(mdb));
      Jmsg(jcr, M_FATAL, 0, "%s", mdb->errmsg);
      db_close_database(jcr, mdb);
      return NULL;
   }

   return mdb;
}
Example #4
0
	/*****************************************************************************************************************************
		open

		Prepares the database for use. An existing database is opened or otherwise an empty database is created.

		If the database is openend a table _META with meta info is loaded into a dictionary _META. The dictionary key is the 
		code of the data element. A data element is either a tabel (dimension/event) or a field (characteristic/property). 
		The value of the dictionary is the MET_INFO structure. This structure contains meta data about the data element.

		If the database is created an empty table _META is created.

		The function calls virtual functions, db_,  which must be overriden by a derived class for a specific database implementation.  

	******************************************************************************************************************************/
	void ARAS::open(DBInfo dbInfo) {
		if (isopen)
			return;

		// store db information
		this->dbInfo = dbInfo;
		
		// open or create database
		// performs the database specific initialization code, the specific information to be used is stored in the struct DBInfo.
		db_init_database();
		// performs the database specific code to check whether a database alreay exists and open it. 
		if (db_open_database()) {
			// read _META table from database into dictionary _META
			TABLE values;
			db_select_table("_META", {"CODE","INFO"}, values);
			for (auto i : values)
				_META.insert(std::pair<std::string, META_INFO>(i[0], META_INFO(i[1])));
		}
		else {
			// performs the database specific code to create a new database based on DBInfo. 
			db_create_database();

			// create table _META: define the columns
			META_INFO imeta(data_type::DIM, 0, "_META", "", "", "_META", "CODE", 0, 0, 0, 0);
			META_INFO icode(data_type::STR, SIZE_META_CODE_MAX, "_META", "", "","_META", "", 0, 0, 1, 0);
			META_INFO idescs(data_type::STR, SIZE_DESCS_MAX, "_META", "", "", "_META", "", 0, 0, 0, 0);
			META_INFO idescl(data_type::STR, SIZE_DESCL_MAX, "_META", "", "", "_META", "", 0, 0, 0, 0);
			META_INFO iinfo(data_type::STR, 0, "_META", "", "", "_META", "",0, 0, 0, 0);

			// define the table
			META_TABLE meta = { { "_META", "Meta data", "Meta data", imeta }, { "CODE", "CODE", "CODE", icode }, { "DESCS", "Short Description", "Short Description", idescs }, { "DESCL", "Long Description", "Long Description", idescl }, { "INFO", "INFO", "INFO", iinfo } };

			// performs the database specific code to create a new table
			db_create_table(meta);

			// load the meta data into the dictionary and the database table _META
			for (auto i : meta)
				insert_meta(i);
		}
	}
Example #5
0
int main (int argc, char *argv[])
{
   int ch;
#if defined(HAVE_DYNAMIC_CATS_BACKENDS)
   alist *backend_directories = NULL;
#endif
   char *jobids = (char *)"1";
   char *path=NULL, *client=NULL;
   uint64_t limit=0;
   bool clean=false;
   setlocale(LC_ALL, "");
   bindtextdomain("bareos", LOCALEDIR);
   textdomain("bareos");
   init_stack_dump();

   Dmsg0(0, "Starting bvfs_test tool\n");

   my_name_is(argc, argv, "bvfs_test");
   init_msg(NULL, NULL);

   OSDependentInit();

   while ((ch = getopt(argc, argv, "h:c:l:d:D:n:P:Su:vf:w:?j:p:f:T")) != -1) {
      switch (ch) {
      case 'd':                    /* debug level */
         if (*optarg == 't') {
            dbg_timestamp = true;
         } else {
            debug_level = atoi(optarg);
            if (debug_level <= 0) {
               debug_level = 1;
            }
         }
         break;

      case 'D':
         db_driver = optarg;
         break;

      case 'l':
         limit = str_to_int64(optarg);
         break;

      case 'c':
         client = optarg;
         break;

      case 'h':
         db_host = optarg;
         break;

      case 'n':
         db_name = optarg;
         break;

      case 'w':
         working_directory = optarg;
         break;

      case 'u':
         db_user = optarg;
         break;

      case 'P':
         db_password = optarg;
         break;

      case 'v':
         verbose++;
         break;

      case 'p':
         path = optarg;
         break;

      case 'f':
         file = optarg;
         break;

      case 'j':
         jobids = optarg;
         break;

      case 'T':
         clean = true;
         break;

      case '?':
      default:
         usage();

      }
   }
   argc -= optind;
   argv += optind;

   if (argc != 0) {
      Pmsg0(0, _("Wrong number of arguments: \n"));
      usage();
   }
   JCR *bjcr = new_jcr(sizeof(JCR), NULL);
   bjcr->JobId = getpid();
   bjcr->setJobType(JT_CONSOLE);
   bjcr->setJobLevel(L_FULL);
   bjcr->JobStatus = JS_Running;
   bjcr->client_name = get_pool_memory(PM_FNAME);
   pm_strcpy(bjcr->client_name, "Dummy.Client.Name");
   bstrncpy(bjcr->Job, "bvfs_test", sizeof(bjcr->Job));

#if defined(HAVE_DYNAMIC_CATS_BACKENDS)
   backend_directories = New(alist(10, owned_by_alist));
   backend_directories->append((char *)backend_directory);

   db_set_backend_dirs(backend_directories);
#endif

   if ((db = db_init_database(NULL, NULL, db_name, db_user, db_password, db_host, 0, NULL)) == NULL) {
      Emsg0(M_ERROR_TERM, 0, _("Could not init Bareos database\n"));
   }
   Dmsg1(0, "db_type=%s\n", db_get_type(db));

   if (!db_open_database(NULL, db)) {
      Emsg0(M_ERROR_TERM, 0, db_strerror(db));
   }
   Dmsg0(200, "Database opened\n");
   if (verbose) {
      Pmsg2(000, _("Using Database: %s, User: %s\n"), db_name, db_user);
   }

   bjcr->db = db;

   if (clean) {
      Pmsg0(0, "Clean old table\n");
      db_sql_query(db, "DELETE FROM PathHierarchy", NULL, NULL);
      db_sql_query(db, "UPDATE Job SET HasCache=0", NULL, NULL);
      db_sql_query(db, "DELETE FROM PathVisibility", NULL, NULL);
      bvfs_update_cache(bjcr, db);
   }

   Bvfs fs(bjcr, db);
   fs.set_handler(result_handler, &fs);

   fs.set_jobids(jobids);
   fs.update_cache();
   if (limit)
      fs.set_limit(limit);

   if (path) {
      fs.ch_dir(path);
      fs.ls_special_dirs();
      fs.ls_dirs();
      while (fs.ls_files()) {
         fs.next_offset();
      }

      if (fnid && client) {
         Pmsg0(0, "---------------------------------------------\n");
         Pmsg1(0, "Getting file version for %s\n", file);
         fs.get_all_file_versions(fs.get_pwd(), fnid, client);
      }

      exit (0);
   }


   Pmsg0(0, "list /\n");
   fs.ch_dir("/");
   fs.ls_special_dirs();
   fs.ls_dirs();
   fs.ls_files();

   Pmsg0(0, "list /tmp/\n");
   fs.ch_dir("/tmp/");
   fs.ls_special_dirs();
   fs.ls_dirs();
   fs.ls_files();

   Pmsg0(0, "list /tmp/regress/\n");
   fs.ch_dir("/tmp/regress/");
   fs.ls_special_dirs();
   fs.ls_files();
   fs.ls_dirs();

   Pmsg0(0, "list /tmp/regress/build/\n");
   fs.ch_dir("/tmp/regress/build/");
   fs.ls_special_dirs();
   fs.ls_dirs();
   fs.ls_files();

   fs.get_all_file_versions(1, 347, "zog4-fd");

   char p[200];
   strcpy(p, "/tmp/toto/rep/");
   bvfs_parent_dir(p);
   if(!bstrcmp(p, "/tmp/toto/")) {
      Pmsg0(000, "Error in bvfs_parent_dir\n");
   }
   bvfs_parent_dir(p);
   if(!bstrcmp(p, "/tmp/")) {
      Pmsg0(000, "Error in bvfs_parent_dir\n");
   }
   bvfs_parent_dir(p);
   if(!bstrcmp(p, "/")) {
      Pmsg0(000, "Error in bvfs_parent_dir\n");
   }
   bvfs_parent_dir(p);
   if(!bstrcmp(p, "")) {
      Pmsg0(000, "Error in bvfs_parent_dir\n");
   }
   bvfs_parent_dir(p);
   if(!bstrcmp(p, "")) {
      Pmsg0(000, "Error in bvfs_parent_dir\n");
   }

   return 0;
}
Example #6
0
int main (int argc, char *argv[])
{
   int ch;
   char *jobids = (char *)"1";
   char *path=NULL, *client=NULL;
   uint64_t limit=0;
   bool clean=false;
   setlocale(LC_ALL, "");
   bindtextdomain("bareos", LOCALEDIR);
   textdomain("bareos");
   init_stack_dump();

   Dmsg0(0, "Starting ing_test tool\n");

   my_name_is(argc, argv, "ing_test");
   init_msg(NULL, NULL);

   OSDependentInit();

   while ((ch = getopt(argc, argv, "h:c:l:d:n:P:Su:vf:w:?j:p:f:T")) != -1) {
      switch (ch) {
      case 'd':                    /* debug level */
         if (*optarg == 't') {
            dbg_timestamp = true;
         } else {
            debug_level = atoi(optarg);
            if (debug_level <= 0) {
               debug_level = 1;
            }
         }
         break;
      case 'l':
         limit = str_to_int64(optarg);
         break;

      case 'c':
         client = optarg;
         break;

      case 'h':
         db_host = optarg;
         break;

      case 'n':
         db_name = optarg;
         break;

      case 'w':
         working_directory = optarg;
         break;

      case 'u':
         db_user = optarg;
         break;

      case 'P':
         db_password = optarg;
         break;

      case 'v':
         verbose++;
         break;

      case 'p':
         path = optarg;
         break;

      case 'f':
         file = optarg;
         break;

      case 'j':
         jobids = optarg;
         break;

      case 'T':
         clean = true;
         break;

      case '?':
      default:
         usage();

      }
   }
   argc -= optind;
   argv += optind;

   if (argc != 0) {
      Pmsg0(0, _("Wrong number of arguments: \n"));
      usage();
   }

   if ((db = db_init_database(NULL, "ingres", db_name, db_user, db_password, db_host, 0, NULL)) == NULL) {
      Emsg0(M_ERROR_TERM, 0, _("Could not init Bareos database\n"));
   }
   Dmsg1(0, "db_type=%s\n", db_get_type(db));

   if (!db_open_database(NULL, db)) {
      Emsg0(M_ERROR_TERM, 0, db_strerror(db));
   }
   Dmsg0(200, "Database opened\n");
   if (verbose) {
      Pmsg2(000, _("Using Database: %s, User: %s\n"), db_name, db_user);
   }

   /*
    * simple CRUD test including create/drop table
    */
   Pmsg0(0, "\nsimple CRUD test...\n\n");
   const char *stmt1[8] = {
      "CREATE TABLE t1 ( c1 integer, c2 varchar(29))",
      "INSERT INTO t1 VALUES (1, 'foo')",
      "SELECT c1,c2 FROM t1",
      "UPDATE t1 SET c2='bar' WHERE c1=1",
      "SELECT * FROM t1",
      "DELETE FROM t1 WHERE c2 LIKE '\%r'",
      "SELECT * FROM t1",
      "DROP TABLE t1"
   };
   int (*hndl1[8])(void*,int,char**) = {
      NULL,
      NULL,
      test_handler,
      NULL,
      test_handler,
      NULL,
      test_handler,
      NULL
   };

   for (int i=0; i<8; ++i) {
      Pmsg1(0, "DB-Statement: %s\n",stmt1[i]);
      if (!db_sql_query(db, stmt1[i], hndl1[i], NULL)) {
         Emsg0(M_ERROR_TERM, 0, _("Stmt went wrong\n"));
      }
   }


   /*
    * simple SELECT tests without tables
    */
   Pmsg0(0, "\nsimple SELECT tests without tables...\n\n");
   const char *stmt2[8] = {
      "SELECT 'Test of simple SELECT!'",
      "SELECT 'Test of simple SELECT!' as Text",
      "SELECT VARCHAR(LENGTH('Test of simple SELECT!'))",
      "SELECT DBMSINFO('_version')",
      "SELECT 'This is a ''quoting'' test with single quotes'",
      "SELECT 'This is a \"quoting\" test with double quotes'",
      "SELECT null",
      "SELECT ''"
   };
   int (*hndl2[8])(void*,int,char**) = {
      string_handler,
      string_handler,
      string_handler,
      string_handler,
      string_handler,
      string_handler,
      string_handler,
      string_handler
   };

   for (int i=0; i<8; ++i) {
      Pmsg1(0, "DB-Statement: %s\n",stmt2[i]);
      if (!db_sql_query(db, stmt2[i], hndl2[i], NULL)) {
         Emsg0(M_ERROR_TERM, 0, _("Stmt went wrong\n"));
      }
   }

   /*
    * testing aggregates like avg, max, sum
    */
   Pmsg0(0, "\ntesting aggregates...\n\n");
   const char *stmt[11] = {
      "CREATE TABLE t1 (c1 integer, c2 varchar(29))",
      "INSERT INTO t1 VALUES (1,'foo')",
      "INSERT INTO t1 VALUES (2,'bar')",
      "INSERT INTO t1 VALUES (3,'fun')",
      "INSERT INTO t1 VALUES (4,'egg')",
      "SELECT max(c1) from t1",
      "SELECT sum(c1) from t1",
      "INSERT INTO t1 VALUES (5,NULL)",
      "SELECT count(*) from t1",
      "SELECT count(c2) from t1",
      "DROP TABLE t1"
   };
   int (*hndl[11])(void*,int,char**) = {
      NULL,
      NULL,
      NULL,
      NULL,
      NULL,
      string_handler,
      string_handler,
      NULL,
      string_handler,
      string_handler,
      NULL
   };

   for (int i=0; i<11; ++i) {
      Pmsg1(0, "DB-Statement: %s\n",stmt[i]);
      if (!db_sql_query(db, stmt[i], hndl[i], NULL)) {
         Emsg0(M_ERROR_TERM, 0, _("Stmt went wrong\n"));
      }
   }


   /*
    * datatypes test
    */
   Pmsg0(0, "\ndatatypes test... (TODO)\n\n");


   Dmsg0(200, "DB-Statement: CREATE TABLE for datatypes\n");
   if (!db_sql_query(db, "CREATE TABLE t2 ("
     "c1        integer,"
     "c2        varchar(255),"
     "c3        char(255)"
     /* some more datatypes... "c4      ," */
     ")" , NULL, NULL)) {
      Emsg0(M_ERROR_TERM, 0, _("CREATE-Stmt went wrong\n"));
   }

   Dmsg0(200, "DB-Statement: DROP TABLE for datatypes\n");
   if (!db_sql_query(db, "DROP TABLE t2", NULL, NULL)) {
      Emsg0(M_ERROR_TERM, 0, _("DROP-Stmt went wrong\n"));
   }


   db_close_database(NULL, db);
   db_flush_backends();
   Dmsg0(200, "Database closed\n");

   return 0;
}
Example #7
0
bool setup_job(JCR *jcr) 
{
   int errstat;

   jcr->lock();
   Dsm_check(100);
   init_msg(jcr, jcr->messages);

   /* Initialize termination condition variable */
   if ((errstat = pthread_cond_init(&jcr->term_wait, NULL)) != 0) {
      berrno be;
      Jmsg1(jcr, M_FATAL, 0, _("Unable to init job cond variable: ERR=%s\n"), be.bstrerror(errstat));
      jcr->unlock();
      goto bail_out;
   }
   jcr->term_wait_inited = true;

   create_unique_job_name(jcr, jcr->job->name());
   jcr->setJobStatus(JS_Created);
   jcr->unlock();

   /*
    * Open database
    */
   Dmsg0(100, "Open database\n");
   jcr->db = db_init_database(jcr, jcr->catalog->db_driver, jcr->catalog->db_name, 
                              jcr->catalog->db_user, jcr->catalog->db_password,
                              jcr->catalog->db_address, jcr->catalog->db_port,
                              jcr->catalog->db_socket, jcr->catalog->mult_db_connections,
                              jcr->catalog->disable_batch_insert);
   if (!jcr->db || !db_open_database(jcr, jcr->db)) {
      Jmsg(jcr, M_FATAL, 0, _("Could not open database \"%s\".\n"),
                 jcr->catalog->db_name);
      if (jcr->db) {
         Jmsg(jcr, M_FATAL, 0, "%s", db_strerror(jcr->db));
         db_close_database(jcr, jcr->db);
      }
      goto bail_out;
   }
   Dmsg0(150, "DB opened\n");
   if (!jcr->fname) {
      jcr->fname = get_pool_memory(PM_FNAME);
   }
   if (!jcr->pool_source) {
      jcr->pool_source = get_pool_memory(PM_MESSAGE);
      pm_strcpy(jcr->pool_source, _("unknown source"));
   }

   if (jcr->JobReads()) {
      if (!jcr->rpool_source) {
         jcr->rpool_source = get_pool_memory(PM_MESSAGE);
         pm_strcpy(jcr->rpool_source, _("unknown source"));
      }
   }

   /*
    * Create Job record
    */
   init_jcr_job_record(jcr);
   if (!get_or_create_client_record(jcr)) {
      goto bail_out;
   }

   if (!db_create_job_record(jcr, jcr->db, &jcr->jr)) {
      Jmsg(jcr, M_FATAL, 0, "%s", db_strerror(jcr->db));
      goto bail_out;
   }
   jcr->JobId = jcr->jr.JobId;
   Dmsg4(100, "Created job record JobId=%d Name=%s Type=%c Level=%c\n",
       jcr->JobId, jcr->Job, jcr->jr.JobType, jcr->jr.JobLevel);

   generate_daemon_event(jcr, "JobStart");
   new_plugins(jcr);                  /* instantiate plugins for this jcr */
   generate_plugin_event(jcr, bDirEventJobStart);

   if (job_canceled(jcr)) {
      goto bail_out;
   }

   if (jcr->JobReads() && !jcr->rstorage) {
      if (jcr->job->storage) {
         copy_rwstorage(jcr, jcr->job->storage, _("Job resource"));
      } else {
         copy_rwstorage(jcr, jcr->job->pool->storage, _("Pool resource"));
      }
   }
   if (!jcr->JobReads()) {
      free_rstorage(jcr);
   }

   /*
    * Now, do pre-run stuff, like setting job level (Inc/diff, ...)
    *  this allows us to setup a proper job start record for restarting
    *  in case of later errors.
    */
   switch (jcr->getJobType()) {
   case JT_BACKUP:
      if (!do_backup_init(jcr)) {
         backup_cleanup(jcr, JS_ErrorTerminated);
         goto bail_out;
      }
      break;
   case JT_VERIFY:
      if (!do_verify_init(jcr)) {
         verify_cleanup(jcr, JS_ErrorTerminated);
         goto bail_out;
      }
      break;
   case JT_RESTORE:
      if (!do_restore_init(jcr)) {
         restore_cleanup(jcr, JS_ErrorTerminated);
         goto bail_out;
      }
      break;
   case JT_ADMIN:
      if (!do_admin_init(jcr)) {
         admin_cleanup(jcr, JS_ErrorTerminated);
         goto bail_out;
      }
      break;
   case JT_COPY:
   case JT_MIGRATE:
      if (!do_migration_init(jcr)) { 
         migration_cleanup(jcr, JS_ErrorTerminated);
         goto bail_out;
      }
      break;
   default:
      Pmsg1(0, _("Unimplemented job type: %d\n"), jcr->getJobType());
      jcr->setJobStatus(JS_ErrorTerminated);
      goto bail_out;
   }

   generate_job_event(jcr, "JobInit");
   generate_plugin_event(jcr, bDirEventJobInit);
   Dsm_check(100);
   return true;

bail_out:
   return false;
}
Example #8
0
/*
 * Initialize the sql connection pool.
 */
bool db_sql_pool_initialize(const char *db_drivername,
                            const char *db_name,
                            const char *db_user,
                            const char *db_password,
                            const char *db_address,
                            int db_port,
                            const char *db_socket,
                            bool disable_batch_insert,
                            int min_connections,
                            int max_connections,
                            int increment_connections,
                            int idle_timeout,
                            int validate_timeout)
{
   int cnt;
   B_DB *mdb;
   time_t now;
   SQL_POOL_DESCRIPTOR *spd = NULL;
   SQL_POOL_ENTRY *spe = NULL;
   bool retval = false;

   /*
    * See if pooling is runtime disabled.
    */
   if (max_connections == 0) {
      Dmsg0(100, "db_sql_pool_initialize pooling disabled as max_connections == 0\n");
      return true;
   }

   /*
    * First make sure the values make any sense.
    */
   if (min_connections <= 0 ||
       max_connections <= 0 ||
       increment_connections <= 0 ||
       min_connections > max_connections) {
      Jmsg(NULL, M_FATAL, 0,
           _("Illegal values for sql pool initialization, min_connections = %d, max_connections = %d, increment_connections = %d"),
           min_connections, max_connections, increment_connections);
      return false;
   }

   P(mutex);
   time(&now);

   if (db_pooling_descriptors == NULL) {
      db_pooling_descriptors = New(dlist(spd, &spd->link));
   }

   /*
    * Create a new pool descriptor.
    */
   spd = (SQL_POOL_DESCRIPTOR *)malloc(sizeof(SQL_POOL_DESCRIPTOR));
   memset(spd, 0, sizeof(SQL_POOL_DESCRIPTOR));
   spd->pool_entries = New(dlist(spe, &spe->link));
   spd->min_connections = min_connections;
   spd->max_connections = max_connections;
   spd->increment_connections = increment_connections;
   spd->idle_timeout = idle_timeout;
   spd->validate_timeout = validate_timeout;
   spd->last_update = now;
   spd->active = true;

   /*
    * Create a number of database connections.
    */
   for (cnt = 0; cnt < min_connections; cnt++) {
      mdb = db_init_database(NULL,
                             db_drivername,
                             db_name,
                             db_user,
                             db_password,
                             db_address,
                             db_port,
                             db_socket,
                             true,
                             disable_batch_insert);
      if (mdb == NULL) {
         Jmsg(NULL, M_FATAL, 0, "%s", _("Could not init database connection"));
         goto bail_out;
      }

      if (!db_open_database(NULL, mdb)) {
         Mmsg2(mdb->errmsg, _("Could not open database \"%s\": ERR=%s\n"),
               db_name, db_strerror(mdb));
         Jmsg(NULL, M_FATAL, 0, "%s", mdb->errmsg);
         db_close_database(NULL, mdb);
         goto bail_out;
      }

      /*
       * Push this new connection onto the connection pool.
       */
      spe = (SQL_POOL_ENTRY *)malloc(sizeof(SQL_POOL_ENTRY));
      memset(spe, 0, sizeof(SQL_POOL_ENTRY));
      spe->id = spd->nr_connections++;
      spe->last_update = now;
      spe->db_handle = mdb;
      spd->pool_entries->append(spe);
      spe = NULL;
   }

#if defined(HAVE_DYNAMIC_CATS_BACKENDS)
   Dmsg3(100, "db_sql_pool_initialize created %d connections to database %s, backend type %s\n",
         cnt, db_name, db_drivername);
#else
   Dmsg2(100, "db_sql_pool_initialize created %d connections to database %s\n",
         cnt, db_name);
#endif
   db_pooling_descriptors->append(spd);
   retval = true;
   goto ok_out;

bail_out:
   if (spe) {
      free(spe);
   }

   if (spd) {
      destroy_pool_descriptor(spd, false);
   }

ok_out:
   V(mutex);
   return retval;
}
Example #9
0
int main (int argc, char *argv[])
{
   int ch;
   bool disable_batch = false;
   char *restore_list=NULL;
   setlocale(LC_ALL, "");
   bindtextdomain("bareos", LOCALEDIR);
   textdomain("bareos");
   init_stack_dump();
   lmgr_init_thread();

   char **files = (char **) malloc (10 * sizeof(char *));
   int i;
   my_name_is(argc, argv, "bbatch");
   init_msg(NULL, NULL);

   OSDependentInit();

   while ((ch = getopt(argc, argv, "bBh:c:d:D:n:P:Su:vf:w:r:?")) != -1) {
      switch (ch) {
      case 'r':
         restore_list=bstrdup(optarg);
         break;

      case 'B':
         disable_batch = true;
         break;

      case 'b':
         disable_batch = false;
         break;

      case 'd':                    /* debug level */
         if (*optarg == 't') {
            dbg_timestamp = true;
         } else {
            debug_level = atoi(optarg);
            if (debug_level <= 0) {
               debug_level = 1;
            }
         }
         break;

      case 'D':
         db_driver = optarg;
         break;

      case 'h':
         db_host = optarg;
         break;

      case 'n':
         db_name = optarg;
         break;

      case 'w':
         working_directory = optarg;
         break;

      case 'u':
         db_user = optarg;
         break;

      case 'P':
         db_password = optarg;
         break;

      case 'v':
         verbose++;
         break;

      case 'f':
         if (nb < 10 ) {
            files[nb++] = optarg;
         }
         break;

      case '?':
      default:
         usage();

      }
   }
   argc -= optind;
   argv += optind;

   if (argc != 0) {
      Pmsg0(0, _("Wrong number of arguments: \n"));
      usage();
   }

   if (restore_list) {
      uint64_t nb_file=0;
      btime_t start, end;
      /* To use the -r option, the catalog should already contains records */

      if ((db = db_init_database(NULL, db_driver, db_name, db_user, db_password,
                                 db_host, 0, NULL, false, disable_batch)) == NULL) {
         Emsg0(M_ERROR_TERM, 0, _("Could not init Bareos database\n"));
      }
      if (!db_open_database(NULL, db)) {
         Emsg0(M_ERROR_TERM, 0, db_strerror(db));
      }

      start = get_current_btime();
      db_get_file_list(NULL, db, restore_list, false, false, list_handler, &nb_file);
      end = get_current_btime();

      Pmsg3(0, _("Computing file list for jobid=%s files=%lld secs=%d\n"),
            restore_list, nb_file, (uint32_t)btime_to_unix(end-start));

      free(restore_list);
      return 0;
   }

   if (disable_batch) {
      printf("Without new Batch mode\n");
   } else {
      printf("With new Batch mode\n");
   }

   i = nb;
   while (--i >= 0) {
      pthread_t thid;
      JCR *bjcr = new_jcr(sizeof(JCR), NULL);
      bjcr->bsr = NULL;
      bjcr->VolSessionId = 1;
      bjcr->VolSessionTime = (uint32_t)time(NULL);
      bjcr->NumReadVolumes = 0;
      bjcr->NumWriteVolumes = 0;
      bjcr->JobId = getpid();
      bjcr->setJobType(JT_CONSOLE);
      bjcr->setJobLevel(L_FULL);
      bjcr->JobStatus = JS_Running;
      bjcr->where = bstrdup(files[i]);
      bjcr->job_name = get_pool_memory(PM_FNAME);
      pm_strcpy(bjcr->job_name, "Dummy.Job.Name");
      bjcr->client_name = get_pool_memory(PM_FNAME);
      pm_strcpy(bjcr->client_name, "Dummy.Client.Name");
      bstrncpy(bjcr->Job, "bbatch", sizeof(bjcr->Job));
      bjcr->fileset_name = get_pool_memory(PM_FNAME);
      pm_strcpy(bjcr->fileset_name, "Dummy.fileset.name");
      bjcr->fileset_md5 = get_pool_memory(PM_FNAME);
      pm_strcpy(bjcr->fileset_md5, "Dummy.fileset.md5");

      if ((db = db_init_database(NULL, db_driver, db_name, db_user, db_password,
                                 db_host, 0, NULL, false, false)) == NULL) {
         Emsg0(M_ERROR_TERM, 0, _("Could not init Bareos database\n"));
      }
      if (!db_open_database(NULL, db)) {
         Emsg0(M_ERROR_TERM, 0, db_strerror(db));
      }
      Dmsg0(200, "Database opened\n");
      if (verbose) {
         Pmsg2(000, _("Using Database: %s, User: %s\n"), db_name, db_user);
      }

      bjcr->db = db;

      pthread_create(&thid, NULL, do_batch, bjcr);
   }

   while (nb > 0) {
      bmicrosleep(1,0);
   }

   return 0;
}