mongodb_connection.c 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. /*
  2. * Copyright (C) 2014 Daniel-Constantin Mierla (asipto.com)
  3. *
  4. * This file is part of Kamailio, a free SIP server.
  5. *
  6. * Kamailio is free software; you can redistribute it and/or modify
  7. * it under the terms of the GNU General Public License as published by
  8. * the Free Software Foundation; either version 2 of the License, or
  9. * (at your option) any later version
  10. *
  11. * Kamailio is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. * GNU General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU General Public License
  17. * along with this program; if not, write to the Free Software
  18. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  19. */
  20. #include "../../mem/mem.h"
  21. #include "../../dprint.h"
  22. #include "../../ut.h"
  23. #include "mongodb_connection.h"
  24. /*! \brief
  25. * Create a new connection structure,
  26. * open the mongodb connection and set reference count to 1
  27. */
  28. km_mongodb_con_t* db_mongodb_new_connection(const struct db_id* id)
  29. {
  30. km_mongodb_con_t *ptr;
  31. if (!id) {
  32. LM_ERR("invalid parameter value\n");
  33. return 0;
  34. }
  35. ptr = (km_mongodb_con_t*)pkg_malloc(sizeof(km_mongodb_con_t));
  36. if (!ptr) {
  37. LM_ERR("no private memory left\n");
  38. return 0;
  39. }
  40. memset(ptr, 0, sizeof(km_mongodb_con_t));
  41. ptr->ref = 1;
  42. mongoc_init();
  43. ptr->con = mongoc_client_new (id->url.s);
  44. if (!ptr->con) {
  45. LM_ERR("cannot open connection: %.*s\n", id->url.len, id->url.s);
  46. goto err;
  47. }
  48. LM_DBG("connection open to: %.*s\n", id->url.len, id->url.s);
  49. ptr->id = (struct db_id*)id;
  50. return ptr;
  51. err:
  52. if (ptr) pkg_free(ptr);
  53. return 0;
  54. }
  55. /*! \brief
  56. * Close the connection and release memory
  57. */
  58. void db_mongodb_free_connection(struct pool_con* con)
  59. {
  60. km_mongodb_con_t * _c;
  61. if (!con) return;
  62. _c = (km_mongodb_con_t*) con;
  63. if (_c->id) free_db_id(_c->id);
  64. if (_c->con) {
  65. mongoc_client_destroy(_c->con);
  66. }
  67. pkg_free(_c);
  68. }