Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adding unique constraint on the service name #92

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 8 additions & 1 deletion orchestration/api/instances.py
Original file line number Diff line number Diff line change
Expand Up @@ -145,7 +145,14 @@ def instance_ops(tenant_id=''):
service_map['user_id'] = user_id
service_map['tenant_id'] = tenant_id
service_map['status'] = status_map[ret_json['status']]
service_obj = create_service(None, service_map)
try:
service_obj = create_service(None, service_map)
except Exception as ex:
err_msg = str(ex)
logger.error("received exception in creating service: %s", err_msg)
err_ret = {}
err_ret['message'] = err_msg
return jsonify(err_ret), Apiconstants.HTTP_ERR_BAD_REQUEST

# Now that service is created append appropriate values
service_map['service_id'] = sd_id
Expand Down
17 changes: 13 additions & 4 deletions orchestration/db/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
from orchestration.db import Session
from orchestration.db import models
from sqlalchemy.exc import SQLAlchemyError
from sqlalchemy.exc import IntegrityError
from sqlalchemy.sql.expression import and_
from orchestration.utils.config import logger

Expand Down Expand Up @@ -135,10 +136,18 @@ def create_service(context, values):
for key, value in values.items():
if hasattr(service, key):
setattr(service, key, value)

with session_scope() as session:
session.add(service)
return get_service(None, values['id'])
try:
with session_scope() as session:
session.add(service)
return get_service(None, values['id'])
except IntegrityError as ie:
session.rollback()
err_msg = str(ie)
if err_msg.find('services.name'):
err_msg = "Instance Name should be unique"
raise ValueError(err_msg)
except SQLAlchemyError as sqe:
raise ValueError(str(sqe))


def get_service(context, id):
Expand Down
3 changes: 2 additions & 1 deletion orchestration/db/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
import datetime
import uuid

from sqlalchemy import ForeignKey
from sqlalchemy import ForeignKey, UniqueConstraint
from sqlalchemy import Column, String, Text, DateTime
from sqlalchemy.orm import relationship
from sqlalchemy.inspection import inspect
Expand Down Expand Up @@ -103,6 +103,7 @@ class Service(ModelBase):
primaryjoin='Service. \
service_definition_id == \
ServiceDefinition.id')
__table_args__ = (UniqueConstraint('name'),)


class Workflow(ModelBase):
Expand Down
14 changes: 12 additions & 2 deletions tests/unit/api/test_instances.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@

import json
import uuid
import random
from datetime import datetime
from mock import patch, Mock
from orchestration.connectionmanager.st2 import St2

Expand All @@ -22,10 +24,16 @@ def test_post_instance(client):
type_mime = 'application/json'
header = {'Content-Type': type_mime, 'Accept': type_mime,
'X-Auth-Token': 'abcde'}
# Using random number to generate random string.
# Name should be unique and with py27 run, the DB has already a name
# column inserted. Now with py3.x run it, will fail as DB has already
# the values for name column.
random.seed(datetime.now())
name = "test" + str(random.randint(1, 101))
data = {
"service_id": "26ab0773-fc5a-4211-a8e9-8e61ff16fa42",
"action": "opensds.migration-bucket",
"name": "foo",
"name": name,
"parameters": {
"ip_addr": "1.2.3.4",
"port": "8089",
Expand Down Expand Up @@ -83,9 +91,11 @@ def test_post_instance_valid(client):
header = {'Content-Type': type_mime, 'Accept': type_mime,
'X-Auth-Token': 'abcde'}
data = {}
random.seed(datetime.now())
name = "test" + str(random.randint(101, 201))
data["service_id"] = "26ab0773-fc5a-4211-a8e9-8e61ff16fa42"
data["action"] = "opensds.migration-bucket"
data["name"] = "foo"
data["name"] = name
data["parameters"] = {}
data["description"] = "Hello"
data["user_id"] = "abc"
Expand Down