import pyramid.httpexceptions\r
import re\r
import time\r
+import sqlalchemy.sql.expression as expr\r
from pyramid.response import Response\r
from sqlalchemy import Sequence\r
from sqlalchemy.orm.exc import MultipleResultsFound, NoResultFound\r
session.flush()\r
\r
\r
-def get_or_create_server(session=None, name=None, hashkey=None, ip_addr=None,\r
- revision=None):\r
+def get_or_create_server(session, name, hashkey, ip_addr, revision):\r
"""\r
Find a server by name or create one if not found. Parameters:\r
\r
name - server name of the server to be found or created\r
hashkey - server hashkey\r
"""\r
- try:\r
- # find one by that name, if it exists\r
- server = session.query(Server).filter_by(name=name).one()\r
-\r
- # store new hashkey\r
- if server.hashkey != hashkey:\r
- server.hashkey = hashkey\r
- session.add(server)\r
-\r
- # store new IP address\r
- if server.ip_addr != ip_addr:\r
- server.ip_addr = ip_addr\r
- session.add(server)\r
-\r
- # store new revision\r
- if server.revision != revision:\r
- server.revision = revision\r
- session.add(server)\r
-\r
- log.debug("Found existing server {0}".format(server.server_id))\r
+ server = None\r
+\r
+ # finding by hashkey is preferred, but if not we will fall\r
+ # back to using name only, which can result in dupes\r
+ if hashkey is not None:\r
+ servers = session.query(Server).\\r
+ filter_by(hashkey=hashkey).\\r
+ order_by(expr.desc(Server.create_dt)).limit(1).all()\r
+\r
+ if len(servers) > 0:\r
+ server = servers[0]\r
+ log.debug("Found existing server {0} by hashkey ({1})".format(\r
+ server.server_id, server.hashkey))\r
+ else:\r
+ servers = session.query(Server).\\r
+ filter_by(name=name).\\r
+ order_by(expr.desc(Server.create_dt)).limit(1).all()\r
\r
- except MultipleResultsFound, e:\r
- # multiple found, so also filter by hashkey\r
- server = session.query(Server).filter_by(name=name).\\r
- filter_by(hashkey=hashkey).one()\r
- log.debug("Found existing server {0}".format(server.server_id))\r
+ if len(servers) > 0:\r
+ server = servers[0]\r
+ log.debug("Found existing server {0} by name".format(server.server_id))\r
\r
- except NoResultFound, e:\r
- # not found, create one\r
+ # still haven't found a server by hashkey or name, so we need to create one\r
+ if server is None:\r
server = Server(name=name, hashkey=hashkey)\r
session.add(server)\r
session.flush()\r
log.debug("Created server {0} with hashkey {1}".format(\r
server.server_id, server.hashkey))\r
\r
+ # detect changed fields\r
+ if server.name != name:\r
+ server.name = name\r
+ session.add(server)\r
+\r
+ if server.hashkey != hashkey:\r
+ server.hashkey = hashkey\r
+ session.add(server)\r
+\r
+ if server.ip_addr != ip_addr:\r
+ server.ip_addr = ip_addr\r
+ session.add(server)\r
+\r
+ if server.revision != revision:\r
+ server.revision = revision\r
+ session.add(server)\r
+\r
return server\r
\r
\r