<commit_before>#!/usr/bin/python

import json
import sys
import os

from datetime import date, datetime

sys.path += [os.path.abspath(os.path.split(__file__)[0])[:-len("migration")] + "apps/"]

from meps.models import Deleguation, Committe, Country, Group, Opinion, MEP, Email, CV, Party, WebSite, DeleguationRole, CommitteRole, OpinionMEP

MEPS = "meps.xml.json"
MPS = "mps.xml.json"
VOTES = "votes.xml.json"

def clean_meps():
    print "Clean database:"
    print " * remove DeleguationRole"
    DeleguationRole.objects.all().delete()
    print " * remove CommitteRole"
    CommitteRole.objects.all().delete()
    print " * remove MEP"
    MEP.objects.all().delete()
    print " * remove Email"
    Email.objects.all().delete()
    print " * remove CV"
    CV.objects.all().delete()
    print " * remove Deleguation"
    WebSite.objects.all().delete()
    print " * remove WebSite"
    Deleguation.objects.all().delete()
    print " * remove Committe"
    Committe.objects.all().delete()
    print " * remove Country"
    Country.objects.all().delete()
    print " * remove Group"
    Group.objects.all().delete()
    print " * remove Party"
    Party.objects.all().delete()
    print " * remove Opinion"
    Opinion.objects.all().delete()

def _create_meps_functions(functions):
    for function in functions:
        if function.get("abbreviation") and not Committe.objects.filter(name=function["label"], abbreviation=function["abbreviation"]):
            print "   new committe:", function["abbreviation"], "-", function["label"]
            Committe.objects.create(abbreviation=function["abbreviation"],
                                    name=function["label"])
        elif type(function["label"]) is unicode and not Deleguation.objects.filter(name=function["label"]):
            print "   new deleguation:", function["label"]
            Deleguation.objects.create(name=function["label"])
        elif type(function["label"]) is not unicode and not Deleguation.objects.filter(name=function["label"]["text"]):
            print "   new deleguation:", function["label"]["text"]
            Deleguation.objects.create(name=function["label"]["text"])
        else:
            pass

def _create_countries(country):
    if not Country.objects.filter(code=country["code"]):
        print "   new country: %s (%s)" % (country["name"], country["code"])
        Country.objects.create(code=country["code"], name=country["name"])

def _create_groups_and_party(group):
    if not Group.objects.filter(abbreviation=group["abbreviation"]):
        print "   new group: %s (%s)" % (group["name"], group["abbreviation"])
        Group.objects.create(abbreviation=group["abbreviation"], name=group["name"])

    if not Party.objects.filter(name=group["party"]):
        print "   new party:", group["party"]
        Party.objects.create(name=group["party"])

def _create_opinions(opinions, _mep):
    for opinion in opinions:
        if not Opinion.objects.filter(title=opinion["title"]):
            print "    new opinion:", opinion["title"]
            Opinion.objects.create(title=opinion["title"], content=opinion["content"], url=opinion["url"])

        _date = datetime.strptime(opinion["date"], "%d/%m/%Y").date()
        print "   new link to opinion:", _mep.full_name, _date
        OpinionMEP.objects.create(mep=_mep, opinion=Opinion.objects.get(title=opinion["title"]), date=_date)

def _create_mep(mep):
    name = mep["infos"]["name"]
    birth_date = mep["infos"]["birth"]["date"]
    _mep = MEP.objects.create(active=mep["active"],
                       key_name=name["wiki"],
                       first_name=name["first"],
                       last_name=name["last"],
                       full_name=name["full"],
                       gender=mep["infos"]["gender"],
                       picture=mep["infos"]["picture"],
                       birth_place=mep["infos"]["birth"]["place"]["city"],
                       birth_date=date(int(birth_date["year"]), int(birth_date["month"]), int(birth_date["day"])),
                       ep_id=mep["extid"],
                       ep_opinions=mep["activities"]["opinions"],
                       ep_debates=mep["activities"]["debates"],
                       ep_questions=mep["activities"]["questions"],
                       ep_declarations=mep["activities"]["declarations"],
                       ep_reports=mep["activities"]["reports"],
                       ep_motions=mep["activities"]["motions"],
                       ep_webpage=mep["contact"]["web"][0]["text"],
                       bxl_building_name=mep["contact"]["address"]["Bruxelles"]["building"]["name"],
                       bxl_building_abbreviation=mep["contact"]["address"]["Bruxelles"]["building"]["abbreviation"],
                       bxl_office=mep["contact"]["address"]["Bruxelles"]["office"],
                       bxl_fax=mep["contact"]["address"]["Bruxelles"]["fax"],
                       bxl_phone1=mep["contact"]["address"]["Bruxelles"]["phone"][0],
                       bxl_phone2=mep["contact"]["address"]["Bruxelles"]["phone"][1],
                       bxl_street=mep["contact"]["address"]["Bruxelles"]["street"],
                       bxl_postcode=mep["contact"]["address"]["Bruxelles"]["postcode"],
                       stg_building_name=mep["contact"]["address"]["Strasbourg"]["building"]["name"],
                       stg_building_abbreviation=mep["contact"]["address"]["Strasbourg"]["building"]["abbreviation"],
                       stg_office=mep["contact"]["address"]["Strasbourg"]["office"],
                       stg_fax=mep["contact"]["address"]["Strasbourg"]["fax"],
                       stg_phone1=mep["contact"]["address"]["Strasbourg"]["phone"][0],
                       stg_phone2=mep["contact"]["address"]["Strasbourg"]["phone"][1],
                       stg_street=mep["contact"]["address"]["Strasbourg"]["street"],
                       stg_postcode=mep["contact"]["address"]["Strasbourg"]["postcode"],
                       party=Party.objects.get(name=mep["infos"]["group"]["party"]),
                       group_role=mep["infos"]["group"]["role"],
                       group=Group.objects.get(abbreviation=mep["infos"]["group"]["abbreviation"]),
                       country=Country.objects.get(code=mep["infos"]["constituency"]["country"]["code"]))

    if type(mep["contact"]["email"]) is list:
        for email in mep["contact"]["email"]:
            print "   new email", email
            Email.objects.create(email=email, mep=_mep)
    else:
        print "   new email", mep["contact"]["email"]["text"]
        Email.objects.create(email=mep["contact"]["email"]["text"], mep=_mep)

    if mep["contact"]["web"][1:]:
        for i in mep["contact"]["web"][1:]:
            print "   create website:", i["text"]
            WebSite.objects.create(url=i["text"], mep=_mep)

    return _mep

def _create_role(functions, _mep):
    for f in functions:
        if not f.get("abbreviation"):
            name = f["label"] if type(f["label"]) is unicode else f["label"]["text"]
            if not f.get("begin_term"):
                print "   new role in deleguation:", f["role"], "in", name
                DeleguationRole.objects.create(mep=_mep, role=f["role"], deleguation=Deleguation.objects.get(name=name))
            else:
                b = f["begin_term"]
                _begin = date(int(b["year"]), int(b["month"]), int(b["day"]))
                e = f["end_term"]
                _end = date(int(e["year"]), int(e["month"]), int(e["day"]))
                DeleguationRole.objects.create(mep=_mep, role=f["role"], deleguation=Deleguation.objects.get(name=name), begin=_begin, end=_end)
        else:
            if not f.get("begin_term"):
                print "   new role in committe:", f["role"], "in", f["abbreviation"]
                CommitteRole.objects.create(mep=_mep, role=f["role"], committe=Committe.objects.get(abbreviation=f["abbreviation"]))
            else:
                b = f["begin_term"]
                _begin = date(int(b["year"]), int(b["month"]), int(b["day"]))
                e = f["end_term"]
                _end = date(int(e["year"]), int(e["month"]), int(e["day"]))
                CommitteRole.objects.create(mep=_mep, role=f["role"], deleguation=Deleguation.objects.get(name=f["label"]), begin=_begin, end=_end)

def _create_cv(cv, _mep):
    if type(cv) is list:
        for c in cv:
            print "   new cv:", c
            CV.objects.create(title=c, mep=_mep)
    else:
        CV.objects.create(title=cv, mep=_mep)

def manage_meps(path):
    clean_meps()
    print
    print "Load meps json."
    meps = json.loads(open(os.path.join(path, MEPS), "r").read())
    print
    a = 0
    for mep in meps:
        if mep["_id"] in ["LucasHartong", "InnocenzoLeontini"]:
            #rubish data
            continue
        a += 1
        print " *", a, "-", mep["infos"]["name"]["full"], "-", mep["_id"]
        _create_meps_functions(mep["functions"])
        _create_countries(mep["infos"]["constituency"]["country"])
        _create_groups_and_party(mep["infos"]["group"])
        _mep = _create_mep(mep)
        _create_opinions(mep["opinions"], _mep)
        _create_role(mep["functions"], _mep)
        if mep["cv"]:
            _create_cv(mep["cv"]["position"], _mep)

if __name__ == "__main__":
    path = sys.argv[1]
    manage_meps(path)

<commit_msg>[mod] propare part-04 for migrating french mps<commit_after>#!/usr/bin/python

import json
import sys
import os

from datetime import date, datetime

sys.path += [os.path.abspath(os.path.split(__file__)[0])[:-len("migration")] + "apps/"]

from meps.models import Deleguation, Committe, Country, Group, Opinion, MEP, Email, CV, Party, WebSite, DeleguationRole, CommitteRole, OpinionMEP

MEPS = "meps.xml.json"
MPS = "mps.xml.json"
VOTES = "votes.xml.json"

def clean_meps():
    print "Clean database:"
    print " * remove DeleguationRole"
    DeleguationRole.objects.all().delete()
    print " * remove CommitteRole"
    CommitteRole.objects.all().delete()
    print " * remove MEP"
    MEP.objects.all().delete()
    print " * remove Email"
    Email.objects.all().delete()
    print " * remove CV"
    CV.objects.all().delete()
    print " * remove Deleguation"
    WebSite.objects.all().delete()
    print " * remove WebSite"
    Deleguation.objects.all().delete()
    print " * remove Committe"
    Committe.objects.all().delete()
    print " * remove Country"
    Country.objects.all().delete()
    print " * remove Group"
    Group.objects.all().delete()
    print " * remove Party"
    Party.objects.all().delete()
    print " * remove Opinion"
    Opinion.objects.all().delete()

def clean_mps():
    pass

def _create_meps_functions(functions):
    for function in functions:
        if function.get("abbreviation") and not Committe.objects.filter(name=function["label"], abbreviation=function["abbreviation"]):
            print "   new committe:", function["abbreviation"], "-", function["label"]
            Committe.objects.create(abbreviation=function["abbreviation"],
                                    name=function["label"])
        elif type(function["label"]) is unicode and not Deleguation.objects.filter(name=function["label"]):
            print "   new deleguation:", function["label"]
            Deleguation.objects.create(name=function["label"])
        elif type(function["label"]) is not unicode and not Deleguation.objects.filter(name=function["label"]["text"]):
            print "   new deleguation:", function["label"]["text"]
            Deleguation.objects.create(name=function["label"]["text"])
        else:
            pass

def _create_countries(country):
    if not Country.objects.filter(code=country["code"]):
        print "   new country: %s (%s)" % (country["name"], country["code"])
        Country.objects.create(code=country["code"], name=country["name"])

def _create_groups_and_party(group):
    if not Group.objects.filter(abbreviation=group["abbreviation"]):
        print "   new group: %s (%s)" % (group["name"], group["abbreviation"])
        Group.objects.create(abbreviation=group["abbreviation"], name=group["name"])

    if not Party.objects.filter(name=group["party"]):
        print "   new party:", group["party"]
        Party.objects.create(name=group["party"])

def _create_opinions(opinions, _mep):
    for opinion in opinions:
        if not Opinion.objects.filter(title=opinion["title"]):
            print "    new opinion:", opinion["title"]
            Opinion.objects.create(title=opinion["title"], content=opinion["content"], url=opinion["url"])

        _date = datetime.strptime(opinion["date"], "%d/%m/%Y").date()
        print "   new link to opinion:", _mep.full_name, _date
        OpinionMEP.objects.create(mep=_mep, opinion=Opinion.objects.get(title=opinion["title"]), date=_date)

def _create_mep(mep):
    name = mep["infos"]["name"]
    birth_date = mep["infos"]["birth"]["date"]
    _mep = MEP.objects.create(active=mep["active"],
                       key_name=name["wiki"],
                       first_name=name["first"],
                       last_name=name["last"],
                       full_name=name["full"],
                       gender=mep["infos"]["gender"],
                       picture=mep["infos"]["picture"],
                       birth_place=mep["infos"]["birth"]["place"]["city"],
                       birth_date=date(int(birth_date["year"]), int(birth_date["month"]), int(birth_date["day"])),
                       ep_id=mep["extid"],
                       ep_opinions=mep["activities"]["opinions"],
                       ep_debates=mep["activities"]["debates"],
                       ep_questions=mep["activities"]["questions"],
                       ep_declarations=mep["activities"]["declarations"],
                       ep_reports=mep["activities"]["reports"],
                       ep_motions=mep["activities"]["motions"],
                       ep_webpage=mep["contact"]["web"][0]["text"],
                       bxl_building_name=mep["contact"]["address"]["Bruxelles"]["building"]["name"],
                       bxl_building_abbreviation=mep["contact"]["address"]["Bruxelles"]["building"]["abbreviation"],
                       bxl_office=mep["contact"]["address"]["Bruxelles"]["office"],
                       bxl_fax=mep["contact"]["address"]["Bruxelles"]["fax"],
                       bxl_phone1=mep["contact"]["address"]["Bruxelles"]["phone"][0],
                       bxl_phone2=mep["contact"]["address"]["Bruxelles"]["phone"][1],
                       bxl_street=mep["contact"]["address"]["Bruxelles"]["street"],
                       bxl_postcode=mep["contact"]["address"]["Bruxelles"]["postcode"],
                       stg_building_name=mep["contact"]["address"]["Strasbourg"]["building"]["name"],
                       stg_building_abbreviation=mep["contact"]["address"]["Strasbourg"]["building"]["abbreviation"],
                       stg_office=mep["contact"]["address"]["Strasbourg"]["office"],
                       stg_fax=mep["contact"]["address"]["Strasbourg"]["fax"],
                       stg_phone1=mep["contact"]["address"]["Strasbourg"]["phone"][0],
                       stg_phone2=mep["contact"]["address"]["Strasbourg"]["phone"][1],
                       stg_street=mep["contact"]["address"]["Strasbourg"]["street"],
                       stg_postcode=mep["contact"]["address"]["Strasbourg"]["postcode"],
                       party=Party.objects.get(name=mep["infos"]["group"]["party"]),
                       group_role=mep["infos"]["group"]["role"],
                       group=Group.objects.get(abbreviation=mep["infos"]["group"]["abbreviation"]),
                       country=Country.objects.get(code=mep["infos"]["constituency"]["country"]["code"]))

    if type(mep["contact"]["email"]) is list:
        for email in mep["contact"]["email"]:
            print "   new email", email
            Email.objects.create(email=email, mep=_mep)
    else:
        print "   new email", mep["contact"]["email"]["text"]
        Email.objects.create(email=mep["contact"]["email"]["text"], mep=_mep)

    if mep["contact"]["web"][1:]:
        for i in mep["contact"]["web"][1:]:
            print "   create website:", i["text"]
            WebSite.objects.create(url=i["text"], mep=_mep)

    return _mep

def _create_role(functions, _mep):
    for f in functions:
        if not f.get("abbreviation"):
            name = f["label"] if type(f["label"]) is unicode else f["label"]["text"]
            if not f.get("begin_term"):
                print "   new role in deleguation:", f["role"], "in", name
                DeleguationRole.objects.create(mep=_mep, role=f["role"], deleguation=Deleguation.objects.get(name=name))
            else:
                b = f["begin_term"]
                _begin = date(int(b["year"]), int(b["month"]), int(b["day"]))
                e = f["end_term"]
                _end = date(int(e["year"]), int(e["month"]), int(e["day"]))
                DeleguationRole.objects.create(mep=_mep, role=f["role"], deleguation=Deleguation.objects.get(name=name), begin=_begin, end=_end)
        else:
            if not f.get("begin_term"):
                print "   new role in committe:", f["role"], "in", f["abbreviation"]
                CommitteRole.objects.create(mep=_mep, role=f["role"], committe=Committe.objects.get(abbreviation=f["abbreviation"]))
            else:
                b = f["begin_term"]
                _begin = date(int(b["year"]), int(b["month"]), int(b["day"]))
                e = f["end_term"]
                _end = date(int(e["year"]), int(e["month"]), int(e["day"]))
                CommitteRole.objects.create(mep=_mep, role=f["role"], deleguation=Deleguation.objects.get(name=f["label"]), begin=_begin, end=_end)

def _create_cv(cv, _mep):
    if type(cv) is list:
        for c in cv:
            print "   new cv:", c
            CV.objects.create(title=c, mep=_mep)
    else:
        CV.objects.create(title=cv, mep=_mep)

def manage_meps(path):
    clean_meps()
    print
    print "Load meps json."
    meps = json.loads(open(os.path.join(path, MEPS), "r").read())
    print
    a = 0
    for mep in meps:
        if mep["_id"] in ["LucasHartong", "InnocenzoLeontini"]:
            #rubish data
            continue
        a += 1
        print " *", a, "-", mep["infos"]["name"]["full"], "-", mep["_id"]
        _create_meps_functions(mep["functions"])
        _create_countries(mep["infos"]["constituency"]["country"])
        _create_groups_and_party(mep["infos"]["group"])
        _mep = _create_mep(mep)
        _create_opinions(mep["opinions"], _mep)
        _create_role(mep["functions"], _mep)
        if mep["cv"]:
            _create_cv(mep["cv"]["position"], _mep)

def manage_mps(path):
    clean_mps()
    print
    print "Load mps json."
    mps = json.loads(open(os.path.join(path, MPS), "r").read())
    print
    a = 0
    for mp in mps:
        pass

if __name__ == "__main__":
    path = sys.argv[1]
    manage_meps(path)
    manage_mps(path)

<|endoftext|>


<commit_before># vim: tabstop=4 shiftwidth=4 softtabstop=4

# Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
#
#    Licensed under the Apache License, Version 2.0 (the "License"); you may
#    not use this file except in compliance with the License. You may obtain
#    a copy of the License at
#
#         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.
"""
Nova User API client library.
"""

import base64
import boto
import httplib
from boto.ec2.regioninfo import RegionInfo

DEFAULT_CLC_URL = 'http://127.0.0.1:8773'
DEFAULT_REGION = 'nova'
DEFAULT_ACCESS_KEY = 'admin'
DEFAULT_SECRET_KEY = 'admin'

class UserInfo(object):
    """
    Information about a Nova user, as parsed through SAX.

    **Fields Include**

    * username
    * accesskey
    * secretkey
    * file (optional) containing zip of X509 cert & rc file

    """

    def __init__(self, connection=None, username=None, endpoint=None):
        self.connection = connection
        self.username = username
        self.endpoint = endpoint

    def __repr__(self):
        return 'UserInfo:%s' % self.username

    def startElement(self, name, attrs, connection):
        return None

    def endElement(self, name, value, connection):
        if name == 'username':
            self.username = str(value)
        elif name == 'file':
            self.file = base64.b64decode(str(value))
        elif name == 'accesskey':
            self.accesskey = str(value)
        elif name == 'secretkey':
            self.secretkey = str(value)

class UserRole(object):
    """
    Information about a Nova user's role, as parsed through SAX.

    **Fields include**

    * role

    """

    def __init__(self, connection=None):
        self.connection = connection
        self.role = None

    def __repr__(self):
        return 'UserRole:%s' % self.role

    def startElement(self, name, attrs, connection):
        return None

    def endElement(self, name, value, connection):
        if name == 'role':
            self.role = value
        else:
            setattr(self, name, str(value))

class ProjectInfo(object):
    """
    Information about a Nova project, as parsed through SAX.

    **Fields include**

    * projectname
    * description
    * projectManagerId
    * memberIds

    """

    def __init__(self, connection=None):
        self.connection = connection
        self.projectname = None
        self.description = None
        self.projectManagerId = None
        self.memberIds = []

    def __repr__(self):
        return 'ProjectInfo:%s' % self.projectname

    def startElement(self, name, attrs, connection):
        return None

    def endElement(self, name, value, connection):
        if name == 'projectname':
            self.projectname = value
        elif name == 'description':
            self.description = value
        elif name == 'projectManagerId':
            self.projectManagerId = value
        elif name == 'memberId':
            self.memberIds.append(value)
        else:
            setattr(self, name, str(value))

class ProjectMember(object):
    """
    Information about a Nova project member, as parsed through SAX.

    **Fields include**

    * memberId

    """

    def __init__(self, connection=None):
        self.connection = connection
        self.memberId = None

    def __repr__(self):
        return 'ProjectMember:%s' % self.memberId

    def startElement(self, name, attrs, connection):
        return None

    def endElement(self, name, value, connection):
        if name == 'member':
            self.memberId = value
        else:
            setattr(self, name, str(value))

class HostInfo(object):
    """
    Information about a Nova Host, as parsed through SAX.

    **Fields Include**

    * Disk stats
    * Running Instances
    * Memory stats
    * CPU stats
    * Network address info
    * Firewall info
    * Bridge and devices

    """

    def __init__(self, connection=None):
        self.connection = connection
        self.hostname = None

    def __repr__(self):
        return 'Host:%s' % self.hostname

    # this is needed by the sax parser, so ignore the ugly name
    def startElement(self, name, attrs, connection):
        return None

    # this is needed by the sax parser, so ignore the ugly name
    def endElement(self, name, value, connection):
        setattr(self, name, value)

class NovaAdminClient(object):
    def __init__(self, clc_url=DEFAULT_CLC_URL, region=DEFAULT_REGION,
                 access_key=DEFAULT_ACCESS_KEY, secret_key=DEFAULT_SECRET_KEY,
                 **kwargs):
        parts = self.split_clc_url(clc_url)

        self.clc_url = clc_url
        self.region = region
        self.access = access_key
        self.secret = secret_key
        self.apiconn = boto.connect_ec2(aws_access_key_id=access_key,
                                        aws_secret_access_key=secret_key,
                                        is_secure=parts['is_secure'],
                                        region=RegionInfo(None,
                                                          region,
                                                          parts['ip']),
                                        port=parts['port'],
                                        path='/services/Admin',
                                        **kwargs)
        self.apiconn.APIVersion = 'nova'

    def connection_for(self, username, project, clc_url=None, region=None,
                       **kwargs):
        """Returns a boto ec2 connection for the given username."""
        if not clc_url:
            clc_url = self.clc_url
        if not region:
            region = self.region
        parts = self.split_clc_url(clc_url)
        user = self.get_user(username)
        access_key = '%s:%s' % (user.accesskey, project)
        return boto.connect_ec2(aws_access_key_id=access_key,
                                aws_secret_access_key=user.secretkey,
                                is_secure=parts['is_secure'],
                                region=RegionInfo(None,
                                                  self.region,
                                                  parts['ip']),
                                port=parts['port'],
                                path='/services/Cloud',
                                **kwargs)

    def split_clc_url(self, clc_url):
        """Splits a cloud controller endpoint url."""
        parts = httplib.urlsplit(clc_url)
        is_secure = parts.scheme == 'https'
        ip, port = parts.netloc.split(':')
        return {'ip': ip, 'port': int(port), 'is_secure': is_secure}

    def get_users(self):
        """Grabs the list of all users."""
        return self.apiconn.get_list('DescribeUsers', {}, [('item', UserInfo)])

    def get_user(self, name):
        """Grab a single user by name."""
        user = self.apiconn.get_object('DescribeUser', {'Name': name},
                                       UserInfo)
        if user.username != None:
            return user

    def has_user(self, username):
        """Determine if user exists."""
        return self.get_user(username) != None

    def create_user(self, username):
        """Creates a new user, returning the userinfo object with
        access/secret."""
        return self.apiconn.get_object('RegisterUser', {'Name': username},
                                       UserInfo)

    def delete_user(self, username):
        """Deletes a user."""
        return self.apiconn.get_object('DeregisterUser', {'Name': username},
                                       UserInfo)

    def get_roles(self, project_roles=True):
        """Returns a list of available roles."""
        return self.apiconn.get_list('DescribeRoles',
                                     {'ProjectRoles': project_roles},
                                     [('item', UserRole)])

    def get_user_roles(self, user, project=None):
        """Returns a list of roles for the given user.

        Omitting project will return any global roles that the user has.
        Specifying project will return only project specific roles.

        """
        params = {'User': user}
        if project:
            params['Project'] = project
        return self.apiconn.get_list('DescribeUserRoles',
                                     params,
                                     [('item', UserRole)])

    def add_user_role(self, user, role, project=None):
        """Add a role to a user either globally or for a specific project."""
        return self.modify_user_role(user, role, project=project,
                                     operation='add')

    def remove_user_role(self, user, role, project=None):
        """Remove a role from a user either globally or for a specific
        project."""
        return self.modify_user_role(user, role, project=project,
                                     operation='remove')

    def modify_user_role(self, user, role, project=None, operation='add',
                         **kwargs):
        """Add or remove a role for a user and project."""
        params = {'User': user,
                  'Role': role,
                  'Project': project,
                  'Operation': operation}
        return self.apiconn.get_status('ModifyUserRole', params)

    def get_projects(self, user=None):
        """Returns a list of all projects."""
        if user:
            params = {'User': user}
        else:
            params = {}
        return self.apiconn.get_list('DescribeProjects',
                                     params,
                                     [('item', ProjectInfo)])

    def get_project(self, name):
        """Returns a single project with the specified name."""
        project = self.apiconn.get_object('DescribeProject',
                                          {'Name': name},
                                          ProjectInfo)

        if project.projectname != None:
            return project

    def create_project(self, projectname, manager_user, description=None,
                       member_users=None):
        """Creates a new project."""
        params = {'Name': projectname,
                  'ManagerUser': manager_user,
                  'Description': description,
                  'MemberUsers': member_users}
        return self.apiconn.get_object('RegisterProject', params, ProjectInfo)

    def delete_project(self, projectname):
        """Permanently deletes the specified project."""
        return self.apiconn.get_object('DeregisterProject',
                                       {'Name': projectname},
                                       ProjectInfo)

    def get_project_members(self, name):
        """Returns a list of members of a project."""
        return self.apiconn.get_list('DescribeProjectMembers',
                                     {'Name': name},
                                     [('item', ProjectMember)])

    def add_project_member(self, user, project):
        """Adds a user to a project."""
        return self.modify_project_member(user, project, operation='add')

    def remove_project_member(self, user, project):
        """Removes a user from a project."""
        return self.modify_project_member(user, project, operation='remove')

    def modify_project_member(self, user, project, operation='add'):
        """Adds or removes a user from a project."""
        params = {'User': user,
                  'Project': project,
                  'Operation': operation}
        return self.apiconn.get_status('ModifyProjectMember', params)

    def get_zip(self, user, project):
        """Returns the content of a zip file containing novarc and access
        credentials."""
        params = {'Name': user, 'Project': project}
        zip = self.apiconn.get_object('GenerateX509ForUser', params, UserInfo)
        return zip.file

    def get_hosts(self):
        return self.apiconn.get_list('DescribeHosts', {}, [('item', HostInfo)])
<commit_msg>pep8 whitespace and line length fixes<commit_after># vim: tabstop=4 shiftwidth=4 softtabstop=4

# Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
#
#    Licensed under the Apache License, Version 2.0 (the "License"); you may
#    not use this file except in compliance with the License. You may obtain
#    a copy of the License at
#
#         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.
"""
Nova User API client library.
"""

import base64
import boto
import httplib
from boto.ec2.regioninfo import RegionInfo

DEFAULT_CLC_URL = 'http://127.0.0.1:8773'
DEFAULT_REGION = 'nova'
DEFAULT_ACCESS_KEY = 'admin'
DEFAULT_SECRET_KEY = 'admin'

class UserInfo(object):
    """
    Information about a Nova user, as parsed through SAX.

    **Fields Include**

    * username
    * accesskey
    * secretkey
    * file (optional) containing zip of X509 cert & rc file

    """

    def __init__(self, connection=None, username=None, endpoint=None):
        self.connection = connection
        self.username = username
        self.endpoint = endpoint

    def __repr__(self):
        return 'UserInfo:%s' % self.username

    def startElement(self, name, attrs, connection):
        return None

    def endElement(self, name, value, connection):
        if name == 'username':
            self.username = str(value)
        elif name == 'file':
            self.file = base64.b64decode(str(value))
        elif name == 'accesskey':
            self.accesskey = str(value)
        elif name == 'secretkey':
            self.secretkey = str(value)

class UserRole(object):
    """
    Information about a Nova user's role, as parsed through SAX.

    **Fields include**

    * role

    """

    def __init__(self, connection=None):
        self.connection = connection
        self.role = None

    def __repr__(self):
        return 'UserRole:%s' % self.role

    def startElement(self, name, attrs, connection):
        return None

    def endElement(self, name, value, connection):
        if name == 'role':
            self.role = value
        else:
            setattr(self, name, str(value))

class ProjectInfo(object):
    """
    Information about a Nova project, as parsed through SAX.

    **Fields include**

    * projectname
    * description
    * projectManagerId
    * memberIds

    """

    def __init__(self, connection=None):
        self.connection = connection
        self.projectname = None
        self.description = None
        self.projectManagerId = None
        self.memberIds = []

    def __repr__(self):
        return 'ProjectInfo:%s' % self.projectname

    def startElement(self, name, attrs, connection):
        return None

    def endElement(self, name, value, connection):
        if name == 'projectname':
            self.projectname = value
        elif name == 'description':
            self.description = value
        elif name == 'projectManagerId':
            self.projectManagerId = value
        elif name == 'memberId':
            self.memberIds.append(value)
        else:
            setattr(self, name, str(value))

class ProjectMember(object):
    """
    Information about a Nova project member, as parsed through SAX.

    **Fields include**

    * memberId

    """

    def __init__(self, connection=None):
        self.connection = connection
        self.memberId = None

    def __repr__(self):
        return 'ProjectMember:%s' % self.memberId

    def startElement(self, name, attrs, connection):
        return None

    def endElement(self, name, value, connection):
        if name == 'member':
            self.memberId = value
        else:
            setattr(self, name, str(value))

class HostInfo(object):
    """
    Information about a Nova Host, as parsed through SAX.

    **Fields Include**

    * Disk stats
    * Running Instances
    * Memory stats
    * CPU stats
    * Network address info
    * Firewall info
    * Bridge and devices

    """

    def __init__(self, connection=None):
        self.connection = connection
        self.hostname = None

    def __repr__(self):
        return 'Host:%s' % self.hostname

    # this is needed by the sax parser, so ignore the ugly name
    def startElement(self, name, attrs, connection):
        return None

    # this is needed by the sax parser, so ignore the ugly name
    def endElement(self, name, value, connection):
        setattr(self, name, value)

class NovaAdminClient(object):
    def __init__(self, clc_url=DEFAULT_CLC_URL, region=DEFAULT_REGION,
                 access_key=DEFAULT_ACCESS_KEY, secret_key=DEFAULT_SECRET_KEY,
                 **kwargs):
        parts = self.split_clc_url(clc_url)

        self.clc_url = clc_url
        self.region = region
        self.access = access_key
        self.secret = secret_key
        self.apiconn = boto.connect_ec2(aws_access_key_id=access_key,
                                        aws_secret_access_key=secret_key,
                                        is_secure=parts['is_secure'],
                                        region=RegionInfo(None,
                                                          region,
                                                          parts['ip']),
                                        port=parts['port'],
                                        path='/services/Admin',
                                        **kwargs)
        self.apiconn.APIVersion = 'nova'

    def connection_for(self, username, project, clc_url=None, region=None,
                       **kwargs):
        """Returns a boto ec2 connection for the given username."""
        if not clc_url:
            clc_url = self.clc_url
        if not region:
            region = self.region
        parts = self.split_clc_url(clc_url)
        user = self.get_user(username)
        access_key = '%s:%s' % (user.accesskey, project)
        return boto.connect_ec2(aws_access_key_id=access_key,
                                aws_secret_access_key=user.secretkey,
                                is_secure=parts['is_secure'],
                                region=RegionInfo(None,
                                                  self.region,
                                                  parts['ip']),
                                port=parts['port'],
                                path='/services/Cloud',
                                **kwargs)

    def split_clc_url(self, clc_url):
        """Splits a cloud controller endpoint url."""
        parts = httplib.urlsplit(clc_url)
        is_secure = parts.scheme == 'https'
        ip, port = parts.netloc.split(':')
        return {'ip': ip, 'port': int(port), 'is_secure': is_secure}

    def get_users(self):
        """Grabs the list of all users."""
        return self.apiconn.get_list('DescribeUsers', {}, [('item', UserInfo)])

    def get_user(self, name):
        """Grab a single user by name."""
        user = self.apiconn.get_object('DescribeUser', {'Name': name},
                                       UserInfo)
        if user.username != None:
            return user

    def has_user(self, username):
        """Determine if user exists."""
        return self.get_user(username) != None

    def create_user(self, username):
        """Creates a new user, returning the userinfo object with
        access/secret."""
        return self.apiconn.get_object('RegisterUser', {'Name': username},
                                       UserInfo)

    def delete_user(self, username):
        """Deletes a user."""
        return self.apiconn.get_object('DeregisterUser', {'Name': username},
                                       UserInfo)

    def get_roles(self, project_roles=True):
        """Returns a list of available roles."""
        return self.apiconn.get_list('DescribeRoles',
                                     {'ProjectRoles': project_roles},
                                     [('item', UserRole)])

    def get_user_roles(self, user, project=None):
        """Returns a list of roles for the given user.

        Omitting project will return any global roles that the user has.
        Specifying project will return only project specific roles.

        """
        params = {'User': user}
        if project:
            params['Project'] = project
        return self.apiconn.get_list('DescribeUserRoles',
                                     params,
                                     [('item', UserRole)])

    def add_user_role(self, user, role, project=None):
        """Add a role to a user either globally or for a specific project."""
        return self.modify_user_role(user, role, project=project,
                                     operation='add')

    def remove_user_role(self, user, role, project=None):
        """Remove a role from a user either globally or for a specific
        project."""
        return self.modify_user_role(user, role, project=project,
                                     operation='remove')

    def modify_user_role(self, user, role, project=None, operation='add',
                         **kwargs):
        """Add or remove a role for a user and project."""
        params = {'User': user,
                  'Role': role,
                  'Project': project,
                  'Operation': operation}
        return self.apiconn.get_status('ModifyUserRole', params)

    def get_projects(self, user=None):
        """Returns a list of all projects."""
        if user:
            params = {'User': user}
        else:
            params = {}
        return self.apiconn.get_list('DescribeProjects',
                                     params,
                                     [('item', ProjectInfo)])

    def get_project(self, name):
        """Returns a single project with the specified name."""
        project = self.apiconn.get_object('DescribeProject',
                                          {'Name': name},
                                          ProjectInfo)

        if project.projectname != None:
            return project

    def create_project(self, projectname, manager_user, description=None,
                       member_users=None):
        """Creates a new project."""
        params = {'Name': projectname,
                  'ManagerUser': manager_user,
                  'Description': description,
                  'MemberUsers': member_users}
        return self.apiconn.get_object('RegisterProject', params, ProjectInfo)

    def delete_project(self, projectname):
        """Permanently deletes the specified project."""
        return self.apiconn.get_object('DeregisterProject',
                                       {'Name': projectname},
                                       ProjectInfo)

    def get_project_members(self, name):
        """Returns a list of members of a project."""
        return self.apiconn.get_list('DescribeProjectMembers',
                                     {'Name': name},
                                     [('item', ProjectMember)])

    def add_project_member(self, user, project):
        """Adds a user to a project."""
        return self.modify_project_member(user, project, operation='add')

    def remove_project_member(self, user, project):
        """Removes a user from a project."""
        return self.modify_project_member(user, project, operation='remove')

    def modify_project_member(self, user, project, operation='add'):
        """Adds or removes a user from a project."""
        params = {'User': user,
                  'Project': project,
                  'Operation': operation}
        return self.apiconn.get_status('ModifyProjectMember', params)

    def get_zip(self, user, project):
        """Returns the content of a zip file containing novarc and access
        credentials."""
        params = {'Name': user, 'Project': project}
        zip = self.apiconn.get_object('GenerateX509ForUser', params, UserInfo)
        return zip.file

    def get_hosts(self):
        return self.apiconn.get_list('DescribeHosts', {}, [('item', HostInfo)])
<|endoftext|>


<commit_before># -*- encoding: utf-8 -*-
##############################################################################
#
#    res_partner
#    Copyright (c) 2013 Codeback Software S.L. (http://codeback.es)
#    @author: Miguel García <miguel@codeback.es>
#    @author: Javier Fuentes <javier@codeback.es>
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU Affero General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU Affero General Public License for more details.
#
#    You should have received a copy of the GNU Affero General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################

from osv import fields, osv
from datetime import datetime, timedelta
from openerp.tools.translate import _

import pytz

class mrp_production(osv.osv):
    _name = 'mrp.production'
    _inherit = "mrp.production"

    def create (self, cr, uid, data, context=None):
        args = []
        last_productions_id = self.search(cr, uid, args, order='date_planned desc', limit=1)[0]
        last_productions = self.browse(cr, uid, last_productions_id)

        date_planned = datetime.strptime(last_productions.date_planned, '%Y-%m-%d %H:%M:%S') + timedelta(hours=last_productions.hour_total)
        data["date_planned"] = date_planned.strftime('%Y-%m-%d %H:%M:%S')

        return super(mrp_production, self).create(cr, uid, data, context=context)

    def action_confirm(self, cr, uid, ids, context=None):

        shipment_id = super(mrp_production, self).action_confirm(cr, uid, ids, context=context)

        self.reorder_productions(cr, uid)

        return shipment_id

    def reorder_productions(self, cr, uid, date_start_from=datetime.now(), date_start_to=datetime.now(), context=None):

        work_sched_model = self.pool.get('resource.calendar')
        work_sched_ids = work_sched_model.search(cr, uid, [("name", "=", "Fábrica")])

        if len(work_sched_ids) > 0:
            work_sched = work_sched_model.browse(cr, uid, work_sched_ids)[0]

            str_date_start_from = datetime.strftime(date_start_from, '%Y-%m-%d %H:%M:%S')

            args = [('date_planned', '>=', str_date_start_from),
                ('state', '!=', "in_production"),
                ('state', '!=', "done")
            ]

            productions_ids = self.search(cr, uid, args, order='date_planned asc')
            productions = self.browse(cr, uid, productions_ids)

            for i, production in enumerate(productions):

                # Calcular fecha de inicio del trabajo
                if i < 1:
                    date_planned = date_start_to #datetime.strptime(production.date_planned, '%Y-%m-%d %H:%M:%S')
                    week_day = date_planned.isocalendar()[2]
                    if week_day > 5:
                        offset_hours = (week_day-5) * 24
                        week_day = 1
                        start_hour = work_sched.attendance_ids[week_day-1].hour_from
                        date_planned = self._date_conversion(date_planned.replace(hour=0, minute=0, second=0, microsecond=0), offset_hours+start_hour)

                else:
                    date_planned = date_planned + timedelta(hours=productions[i-1].hour_total)

                # Calcular fecha de fin del trabajo
                end_hour = work_sched.attendance_ids[week_day-1].hour_to
                end_last_work = self._date_conversion(date_planned, production.hour_total, localize=False)
                end_date = self._date_conversion(date_planned.replace(hour=0, minute=0, second=0, microsecond=0), end_hour)

                # Si el trabajo termina más tarde que la jornada laboral
                # se pasa al siguiente día
                if end_last_work > end_date:
                    week_day = week_day + 1

                    if week_day > 5:
                        # Hoy es viernes
                        offset_hours = 3 * 24
                        week_day = 1
                    else:
                        offset_hours = 24

                    start_hour = work_sched.attendance_ids[week_day-1].hour_from
                    date_planned = self._date_conversion(date_planned.replace(hour=0, minute=0, second=0, microsecond=0), offset_hours+start_hour)

                # Actualizar fecha de inicio del trabajo
                self.write(cr, uid, production.id, {'date_planned': date_planned.strftime('%Y-%m-%d %H:%M:%S')})

    def _date_conversion(self, date, hours, localize=True):

        local = pytz.timezone ("Europe/Madrid")
        utc = pytz.UTC
        local = local if localize else utc

        date = date.replace(tzinfo=None)
        end_date = date + timedelta(hours=hours)
        local_dt = local.localize(end_date, is_dst=None)

        return local_dt.astimezone (pytz.utc)

class mrp_production_scheduler(osv.osv_memory):
    _name = "mrp.production.scheduler"
    _columns = {
        'start_from': fields.datetime('Start Date from', required=True),
        'start_to': fields.datetime('Start Date To', required=True)
    }

    _defaults = {
        'start_from' : datetime.strftime(datetime.now(), '%Y-%m-%d %H:%M:%S'),
        'start_to': datetime.strftime(datetime.now(), '%Y-%m-%d %H:%M:%S'),
    }

    def reorder_production_queue(self, cr, uid, ids, context=None):
        """ reorder production queue from wizard"""

        obj = self.pool.get('mrp.production')
        data = self.browse(cr, uid, ids, context=context)[0]

        start_from = datetime.strptime(data.start_from, '%Y-%m-%d %H:%M:%S')
        start_to = datetime.strptime(data.start_to, '%Y-%m-%d %H:%M:%S')

        obj.reorder_productions(cr, uid, date_start_from=start_from, date_start_to=start_to, context=context)

        menu_mod = self.pool.get('ir.ui.menu')
        args = [('name', '=', 'Order Planning')]
        menu_ids = menu_mod.search(cr, uid, args)

        return {
            'name': 'Order Planning',
            'type': 'ir.actions.client',
            'tag': 'reload',
            'params': {'menu_id': menu_ids[0]},
        }
<commit_msg>Cambios menores<commit_after># -*- encoding: utf-8 -*-
##############################################################################
#
#    res_partner
#    Copyright (c) 2013 Codeback Software S.L. (http://codeback.es)
#    @author: Miguel García <miguel@codeback.es>
#    @author: Javier Fuentes <javier@codeback.es>
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU Affero General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU Affero General Public License for more details.
#
#    You should have received a copy of the GNU Affero General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################

from osv import fields, osv
from datetime import datetime, timedelta
from openerp.tools.translate import _

import pytz

class mrp_production(osv.osv):
    _name = 'mrp.production'
    _inherit = "mrp.production"

    def create (self, cr, uid, data, context=None):
        args = []
        last_productions_id = self.search(cr, uid, args, order='date_planned desc', limit=1)[0]
        last_productions = self.browse(cr, uid, last_productions_id)

        date_planned = datetime.strptime(last_productions.date_planned, '%Y-%m-%d %H:%M:%S') + timedelta(hours=last_productions.hour_total)
        data["date_planned"] = date_planned.strftime('%Y-%m-%d %H:%M:%S')

        mrp_prod = super(mrp_production, self).create(cr, uid, data, context=context)
        self.reorder_productions(cr, uid, date_start_from=date_planned, date_start_to=date_planned, context=context)
        return mrp_prod

    # def action_confirm(self, cr, uid, ids, context=None):
    #
    #     shipment_id = super(mrp_production, self).action_confirm(cr, uid, ids, context=context)

    #     self.reorder_productions(cr, uid)

    #     return shipment_id

    def reorder_productions(self, cr, uid, date_start_from=datetime.now(), date_start_to=datetime.now(), context=None):

        work_sched_model = self.pool.get('resource.calendar')
        work_sched_ids = work_sched_model.search(cr, uid, [("name", "=", "Fábrica")])

        if len(work_sched_ids) > 0:
            work_sched = work_sched_model.browse(cr, uid, work_sched_ids)[0]

            str_date_start_from = datetime.strftime(date_start_from, '%Y-%m-%d %H:%M:%S')

            args = [('date_planned', '>=', str_date_start_from),
                ('state', '!=', "in_production"),
                ('state', '!=', "done")
            ]

            productions_ids = self.search(cr, uid, args, order='date_planned asc')
            productions = self.browse(cr, uid, productions_ids)

            for i, production in enumerate(productions):

                # Calcular fecha de inicio del trabajo
                if i < 1:
                    date_planned = date_start_to #datetime.strptime(production.date_planned, '%Y-%m-%d %H:%M:%S')
                    week_day = date_planned.isocalendar()[2]
                    if week_day > 5:
                        offset_hours = (week_day-5) * 24
                        week_day = 1
                        start_hour = work_sched.attendance_ids[week_day-1].hour_from
                        date_planned = self._date_conversion(date_planned.replace(hour=0, minute=0, second=0, microsecond=0), offset_hours+start_hour)

                else:
                    date_planned = date_planned + timedelta(hours=productions[i-1].hour_total)

                # Calcular fecha de fin del trabajo
                end_hour = work_sched.attendance_ids[week_day-1].hour_to
                end_last_work = self._date_conversion(date_planned, production.hour_total, localize=False)
                end_date = self._date_conversion(date_planned.replace(hour=0, minute=0, second=0, microsecond=0), end_hour)

                # Si el trabajo termina más tarde que la jornada laboral
                # se pasa al siguiente día
                if end_last_work > end_date:
                    week_day = week_day + 1

                    if week_day > 5:
                        # Hoy es viernes
                        offset_hours = 3 * 24
                        week_day = 1
                    else:
                        offset_hours = 24

                    start_hour = work_sched.attendance_ids[week_day-1].hour_from
                    date_planned = self._date_conversion(date_planned.replace(hour=0, minute=0, second=0, microsecond=0), offset_hours+start_hour)

                # Actualizar fecha de inicio del trabajo
                self.write(cr, uid, production.id, {'date_planned': date_planned.strftime('%Y-%m-%d %H:%M:%S')})

    def _date_conversion(self, date, hours, localize=True):

        local = pytz.timezone ("Europe/Madrid")
        utc = pytz.UTC
        local = local if localize else utc

        date = date.replace(tzinfo=None)
        end_date = date + timedelta(hours=hours)
        local_dt = local.localize(end_date, is_dst=None)

        return local_dt.astimezone (pytz.utc)

class mrp_production_scheduler(osv.osv_memory):
    _name = "mrp.production.scheduler"
    _columns = {
        'start_from': fields.datetime('Start Date from', required=True),
        'start_to': fields.datetime('Start Date To', required=True)
    }

    _defaults = {
        'start_from' : datetime.strftime(datetime.now(), '%Y-%m-%d %H:%M:%S'),
        'start_to': datetime.strftime(datetime.now(), '%Y-%m-%d %H:%M:%S'),
    }

    def reorder_production_queue(self, cr, uid, ids, context=None):
        """ reorder production queue from wizard"""

        obj = self.pool.get('mrp.production')
        data = self.browse(cr, uid, ids, context=context)[0]

        start_from = datetime.strptime(data.start_from, '%Y-%m-%d %H:%M:%S')
        start_to = datetime.strptime(data.start_to, '%Y-%m-%d %H:%M:%S')

        obj.reorder_productions(cr, uid, date_start_from=start_from, date_start_to=start_to, context=context)

        menu_mod = self.pool.get('ir.ui.menu')
        args = [('name', '=', 'Order Planning')]
        menu_ids = menu_mod.search(cr, uid, args)

        return {
            'name': 'Order Planning',
            'type': 'ir.actions.client',
            'tag': 'reload',
            'params': {'menu_id': menu_ids[0]},
        }
<|endoftext|>


<commit_before># vim: tabstop=4 shiftwidth=4 softtabstop=4

# Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
#
#    Licensed under the Apache License, Version 2.0 (the "License"); you may
#    not use this file except in compliance with the License. You may obtain
#    a copy of the License at
#
#         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.
"""
Nova User API client library.
"""

import base64
import boto
import httplib

from boto.ec2.regioninfo import RegionInfo

DEFAULT_CLC_URL = 'http://127.0.0.1:8773'
DEFAULT_REGION = 'nova'

class UserInfo(object):
    """
    Information about a Nova user, as parsed through SAX.

    **Fields Include**

    * username
    * accesskey
    * secretkey
    * file (optional) containing zip of X509 cert & rc file

    """

    def __init__(self, connection=None, username=None, endpoint=None):
        self.connection = connection
        self.username = username
        self.endpoint = endpoint

    def __repr__(self):
        return 'UserInfo:%s' % self.username

    def startElement(self, name, attrs, connection):
        return None

    def endElement(self, name, value, connection):
        if name == 'username':
            self.username = str(value)
        elif name == 'file':
            self.file = base64.b64decode(str(value))
        elif name == 'accesskey':
            self.accesskey = str(value)
        elif name == 'secretkey':
            self.secretkey = str(value)

class UserRole(object):
    """
    Information about a Nova user's role, as parsed through SAX.

    **Fields include**

    * role

    """

    def __init__(self, connection=None):
        self.connection = connection
        self.role = None

    def __repr__(self):
        return 'UserRole:%s' % self.role

    def startElement(self, name, attrs, connection):
        return None

    def endElement(self, name, value, connection):
        if name == 'role':
            self.role = value
        else:
            setattr(self, name, str(value))

class ProjectInfo(object):
    """
    Information about a Nova project, as parsed through SAX.

    **Fields include**

    * projectname
    * description
    * projectManagerId
    * memberIds

    """

    def __init__(self, connection=None):
        self.connection = connection
        self.projectname = None
        self.description = None
        self.projectManagerId = None
        self.memberIds = []

    def __repr__(self):
        return 'ProjectInfo:%s' % self.projectname

    def startElement(self, name, attrs, connection):
        return None

    def endElement(self, name, value, connection):
        if name == 'projectname':
            self.projectname = value
        elif name == 'description':
            self.description = value
        elif name == 'projectManagerId':
            self.projectManagerId = value
        elif name == 'memberId':
            self.memberIds.append(value)
        else:
            setattr(self, name, str(value))

class ProjectMember(object):
    """
    Information about a Nova project member, as parsed through SAX.

    **Fields include**

    * memberId

    """

    def __init__(self, connection=None):
        self.connection = connection
        self.memberId = None

    def __repr__(self):
        return 'ProjectMember:%s' % self.memberId

    def startElement(self, name, attrs, connection):
        return None

    def endElement(self, name, value, connection):
        if name == 'member':
            self.memberId = value
        else:
            setattr(self, name, str(value))

class HostInfo(object):
    """
    Information about a Nova Host, as parsed through SAX.

    **Fields Include**

    * Disk stats
    * Running Instances
    * Memory stats
    * CPU stats
    * Network address info
    * Firewall info
    * Bridge and devices

    """

    def __init__(self, connection=None):
        self.connection = connection
        self.hostname = None

    def __repr__(self):
        return 'Host:%s' % self.hostname

    # this is needed by the sax parser, so ignore the ugly name
    def startElement(self, name, attrs, connection):
        return None

    # this is needed by the sax parser, so ignore the ugly name
    def endElement(self, name, value, connection):
        setattr(self, name, value)

class SimpleResponse(object):
    def __init__(self, connection=None):
        self.connection = connection
        self.status = None
        self.message = ''

    def __repr__(self):
        return 'Status:%s' % self.status

    def startElement(self, name, attrs, connection):
        return None

    def endElement(self, name, value, connection):
        setattr(self, name.lower(), str(value))

class NovaAdminClient(object):

    def __init__(
            self,
            clc_url=DEFAULT_CLC_URL,
            region=DEFAULT_REGION,
            access_key=None,
            secret_key=None,
            **kwargs):
        parts = self.split_clc_url(clc_url)

        self.clc_url = clc_url
        self.region = region
        self.access = access_key
        self.secret = secret_key
        self.apiconn = boto.connect_ec2(aws_access_key_id=access_key,
                                        aws_secret_access_key=secret_key,
                                        is_secure=parts['is_secure'],
                                        region=RegionInfo(None,
                                                          region,
                                                          parts['ip']),
                                        port=parts['port'],
                                        path='/services/Admin',
                                        **kwargs)
        self.apiconn.APIVersion = 'nova'

    def connection_for(self, username, project, clc_url=None, region=None,
                       **kwargs):
        """Returns a boto ec2 connection for the given username."""
        if not clc_url:
            clc_url = self.clc_url
        if not region:
            region = self.region
        parts = self.split_clc_url(clc_url)
        user = self.get_user(username)
        access_key = '%s:%s' % (user.accesskey, project)
        return boto.connect_ec2(aws_access_key_id=access_key,
                                aws_secret_access_key=user.secretkey,
                                is_secure=parts['is_secure'],
                                region=RegionInfo(None,
                                                  self.region,
                                                  parts['ip']),
                                port=parts['port'],
                                path='/services/Cloud',
                                **kwargs)

    def split_clc_url(self, clc_url):
        """Splits a cloud controller endpoint url."""
        parts = httplib.urlsplit(clc_url)
        is_secure = parts.scheme == 'https'
        ip, port = parts.netloc.split(':')
        return {'ip': ip, 'port': int(port), 'is_secure': is_secure}

    def get_users(self):
        """Grabs the list of all users."""
        return self.apiconn.get_list('DescribeUsers', {}, [('item', UserInfo)])

    def get_user(self, name):
        """Grab a single user by name."""
        user = self.apiconn.get_object('DescribeUser', {'Name': name},
                                       UserInfo)
        if user.username != None:
            return user

    def has_user(self, username):
        """Determine if user exists."""
        return self.get_user(username) != None

    def create_user(self, username):
        """Creates a new user, returning the userinfo object with
        access/secret."""
        return self.apiconn.get_object('RegisterUser', {'Name': username},
                                       UserInfo)

    def delete_user(self, username):
        """Deletes a user."""
        return self.apiconn.get_object('DeregisterUser', {'Name': username},
                                       UserInfo)

    def get_roles(self, project_roles=True):
        """Returns a list of available roles."""
        return self.apiconn.get_list('DescribeRoles',
                                     {'ProjectRoles': project_roles},
                                     [('item', UserRole)])

    def get_user_roles(self, user, project=None):
        """Returns a list of roles for the given user.

        Omitting project will return any global roles that the user has.
        Specifying project will return only project specific roles.

        """
        params = {'User': user}
        if project:
            params['Project'] = project
        return self.apiconn.get_list('DescribeUserRoles',
                                     params,
                                     [('item', UserRole)])

    def add_user_role(self, user, role, project=None):
        """Add a role to a user either globally or for a specific project."""
        return self.modify_user_role(user, role, project=project,
                                     operation='add')

    def remove_user_role(self, user, role, project=None):
        """Remove a role from a user either globally or for a specific
        project."""
        return self.modify_user_role(user, role, project=project,
                                     operation='remove')

    def modify_user_role(self, user, role, project=None, operation='add',
                         **kwargs):
        """Add or remove a role for a user and project."""
        params = {'User': user,
                  'Role': role,
                  'Project': project,
                  'Operation': operation}
        return self.apiconn.get_status('ModifyUserRole', params)

    def get_projects(self, user=None):
        """Returns a list of all projects."""
        if user:
            params = {'User': user}
        else:
            params = {}
        return self.apiconn.get_list('DescribeProjects',
                                     params,
                                     [('item', ProjectInfo)])

    def get_project(self, name):
        """Returns a single project with the specified name."""
        project = self.apiconn.get_object('DescribeProject',
                                          {'Name': name},
                                          ProjectInfo)

        if project.projectname != None:
            return project

    def create_project(self, projectname, manager_user, description=None,
                       member_users=None):
        """Creates a new project."""
        params = {'Name': projectname,
                  'ManagerUser': manager_user,
                  'Description': description,
                  'MemberUsers': member_users}
        return self.apiconn.get_object('RegisterProject', params, ProjectInfo)

    def delete_project(self, projectname):
        """Permanently deletes the specified project."""
        return self.apiconn.get_object('DeregisterProject',
                                       {'Name': projectname},
                                       ProjectInfo)

    def get_project_members(self, name):
        """Returns a list of members of a project."""
        return self.apiconn.get_list('DescribeProjectMembers',
                                     {'Name': name},
                                     [('item', ProjectMember)])

    def add_project_member(self, user, project):
        """Adds a user to a project."""
        return self.modify_project_member(user, project, operation='add')

    def remove_project_member(self, user, project):
        """Removes a user from a project."""
        return self.modify_project_member(user, project, operation='remove')

    def modify_project_member(self, user, project, operation='add'):
        """Adds or removes a user from a project."""
        params = {'User': user,
                  'Project': project,
                  'Operation': operation}
        return self.apiconn.get_status('ModifyProjectMember', params)

    def get_zip(self, user, project):
        """Returns the content of a zip file containing novarc and access
        credentials."""
        params = {'Name': user, 'Project': project}
        zip = self.apiconn.get_object('GenerateX509ForUser', params, UserInfo)
        return zip.file

    def get_hosts(self):
        return self.apiconn.get_list('DescribeHosts', {}, [('item', HostInfo)])

    def block_ips(self, cidr):
        """Block incoming traffic from specified hosts."""
        return self.apiconn.get_object('BlockExternalAddresses',
                                       {'Cidr': cidr}, SimpleResponse)
<commit_msg>Whitespace (pep8) cleanups.<commit_after># vim: tabstop=4 shiftwidth=4 softtabstop=4

# Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
#
#    Licensed under the Apache License, Version 2.0 (the "License"); you may
#    not use this file except in compliance with the License. You may obtain
#    a copy of the License at
#
#         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.
"""
Nova User API client library.
"""

import base64
import boto
import httplib

from boto.ec2.regioninfo import RegionInfo

DEFAULT_CLC_URL = 'http://127.0.0.1:8773'
DEFAULT_REGION = 'nova'

class UserInfo(object):
    """
    Information about a Nova user, as parsed through SAX.

    **Fields Include**

    * username
    * accesskey
    * secretkey
    * file (optional) containing zip of X509 cert & rc file

    """

    def __init__(self, connection=None, username=None, endpoint=None):
        self.connection = connection
        self.username = username
        self.endpoint = endpoint

    def __repr__(self):
        return 'UserInfo:%s' % self.username

    def startElement(self, name, attrs, connection):
        return None

    def endElement(self, name, value, connection):
        if name == 'username':
            self.username = str(value)
        elif name == 'file':
            self.file = base64.b64decode(str(value))
        elif name == 'accesskey':
            self.accesskey = str(value)
        elif name == 'secretkey':
            self.secretkey = str(value)

class UserRole(object):
    """
    Information about a Nova user's role, as parsed through SAX.

    **Fields include**

    * role

    """

    def __init__(self, connection=None):
        self.connection = connection
        self.role = None

    def __repr__(self):
        return 'UserRole:%s' % self.role

    def startElement(self, name, attrs, connection):
        return None

    def endElement(self, name, value, connection):
        if name == 'role':
            self.role = value
        else:
            setattr(self, name, str(value))

class ProjectInfo(object):
    """
    Information about a Nova project, as parsed through SAX.

    **Fields include**

    * projectname
    * description
    * projectManagerId
    * memberIds

    """

    def __init__(self, connection=None):
        self.connection = connection
        self.projectname = None
        self.description = None
        self.projectManagerId = None
        self.memberIds = []

    def __repr__(self):
        return 'ProjectInfo:%s' % self.projectname

    def startElement(self, name, attrs, connection):
        return None

    def endElement(self, name, value, connection):
        if name == 'projectname':
            self.projectname = value
        elif name == 'description':
            self.description = value
        elif name == 'projectManagerId':
            self.projectManagerId = value
        elif name == 'memberId':
            self.memberIds.append(value)
        else:
            setattr(self, name, str(value))

class ProjectMember(object):
    """
    Information about a Nova project member, as parsed through SAX.

    **Fields include**

    * memberId

    """

    def __init__(self, connection=None):
        self.connection = connection
        self.memberId = None

    def __repr__(self):
        return 'ProjectMember:%s' % self.memberId

    def startElement(self, name, attrs, connection):
        return None

    def endElement(self, name, value, connection):
        if name == 'member':
            self.memberId = value
        else:
            setattr(self, name, str(value))

class HostInfo(object):
    """
    Information about a Nova Host, as parsed through SAX.

    **Fields Include**

    * Disk stats
    * Running Instances
    * Memory stats
    * CPU stats
    * Network address info
    * Firewall info
    * Bridge and devices

    """

    def __init__(self, connection=None):
        self.connection = connection
        self.hostname = None

    def __repr__(self):
        return 'Host:%s' % self.hostname

    # this is needed by the sax parser, so ignore the ugly name
    def startElement(self, name, attrs, connection):
        return None

    # this is needed by the sax parser, so ignore the ugly name
    def endElement(self, name, value, connection):
        setattr(self, name, value)

class SimpleResponse(object):
    def __init__(self, connection=None):
        self.connection = connection
        self.status = None
        self.message = ''

    def __repr__(self):
        return 'Status:%s' % self.status

    def startElement(self, name, attrs, connection):
        return None

    def endElement(self, name, value, connection):
        setattr(self, name.lower(), str(value))

class NovaAdminClient(object):

    def __init__(
            self,
            clc_url=DEFAULT_CLC_URL,
            region=DEFAULT_REGION,
            access_key=None,
            secret_key=None,
            **kwargs):
        parts = self.split_clc_url(clc_url)

        self.clc_url = clc_url
        self.region = region
        self.access = access_key
        self.secret = secret_key
        self.apiconn = boto.connect_ec2(aws_access_key_id=access_key,
                                        aws_secret_access_key=secret_key,
                                        is_secure=parts['is_secure'],
                                        region=RegionInfo(None, region,
                                                          parts['ip']),
                                        port=parts['port'],
                                        path='/services/Admin',
                                        **kwargs)
        self.apiconn.APIVersion = 'nova'

    def connection_for(self, username, project, clc_url=None, region=None,
                       **kwargs):
        """Returns a boto ec2 connection for the given username."""
        if not clc_url:
            clc_url = self.clc_url
        if not region:
            region = self.region
        parts = self.split_clc_url(clc_url)
        user = self.get_user(username)
        access_key = '%s:%s' % (user.accesskey, project)
        return boto.connect_ec2(aws_access_key_id=access_key,
                                aws_secret_access_key=user.secretkey,
                                is_secure=parts['is_secure'],
                                region=RegionInfo(None,
                                                  self.region,
                                                  parts['ip']),
                                port=parts['port'],
                                path='/services/Cloud',
                                **kwargs)

    def split_clc_url(self, clc_url):
        """Splits a cloud controller endpoint url."""
        parts = httplib.urlsplit(clc_url)
        is_secure = parts.scheme == 'https'
        ip, port = parts.netloc.split(':')
        return {'ip': ip, 'port': int(port), 'is_secure': is_secure}

    def get_users(self):
        """Grabs the list of all users."""
        return self.apiconn.get_list('DescribeUsers', {}, [('item', UserInfo)])

    def get_user(self, name):
        """Grab a single user by name."""
        user = self.apiconn.get_object('DescribeUser', {'Name': name},
                                       UserInfo)
        if user.username != None:
            return user

    def has_user(self, username):
        """Determine if user exists."""
        return self.get_user(username) != None

    def create_user(self, username):
        """Creates a new user, returning the userinfo object with
        access/secret."""
        return self.apiconn.get_object('RegisterUser', {'Name': username},
                                       UserInfo)

    def delete_user(self, username):
        """Deletes a user."""
        return self.apiconn.get_object('DeregisterUser', {'Name': username},
                                       UserInfo)

    def get_roles(self, project_roles=True):
        """Returns a list of available roles."""
        return self.apiconn.get_list('DescribeRoles',
                                     {'ProjectRoles': project_roles},
                                     [('item', UserRole)])

    def get_user_roles(self, user, project=None):
        """Returns a list of roles for the given user.

        Omitting project will return any global roles that the user has.
        Specifying project will return only project specific roles.

        """
        params = {'User': user}
        if project:
            params['Project'] = project
        return self.apiconn.get_list('DescribeUserRoles',
                                     params,
                                     [('item', UserRole)])

    def add_user_role(self, user, role, project=None):
        """Add a role to a user either globally or for a specific project."""
        return self.modify_user_role(user, role, project=project,
                                     operation='add')

    def remove_user_role(self, user, role, project=None):
        """Remove a role from a user either globally or for a specific
        project."""
        return self.modify_user_role(user, role, project=project,
                                     operation='remove')

    def modify_user_role(self, user, role, project=None, operation='add',
                         **kwargs):
        """Add or remove a role for a user and project."""
        params = {'User': user,
                  'Role': role,
                  'Project': project,
                  'Operation': operation}
        return self.apiconn.get_status('ModifyUserRole', params)

    def get_projects(self, user=None):
        """Returns a list of all projects."""
        if user:
            params = {'User': user}
        else:
            params = {}
        return self.apiconn.get_list('DescribeProjects',
                                     params,
                                     [('item', ProjectInfo)])

    def get_project(self, name):
        """Returns a single project with the specified name."""
        project = self.apiconn.get_object('DescribeProject',
                                          {'Name': name},
                                          ProjectInfo)

        if project.projectname != None:
            return project

    def create_project(self, projectname, manager_user, description=None,
                       member_users=None):
        """Creates a new project."""
        params = {'Name': projectname,
                  'ManagerUser': manager_user,
                  'Description': description,
                  'MemberUsers': member_users}
        return self.apiconn.get_object('RegisterProject', params, ProjectInfo)

    def delete_project(self, projectname):
        """Permanently deletes the specified project."""
        return self.apiconn.get_object('DeregisterProject',
                                       {'Name': projectname},
                                       ProjectInfo)

    def get_project_members(self, name):
        """Returns a list of members of a project."""
        return self.apiconn.get_list('DescribeProjectMembers',
                                     {'Name': name},
                                     [('item', ProjectMember)])

    def add_project_member(self, user, project):
        """Adds a user to a project."""
        return self.modify_project_member(user, project, operation='add')

    def remove_project_member(self, user, project):
        """Removes a user from a project."""
        return self.modify_project_member(user, project, operation='remove')

    def modify_project_member(self, user, project, operation='add'):
        """Adds or removes a user from a project."""
        params = {'User': user,
                  'Project': project,
                  'Operation': operation}
        return self.apiconn.get_status('ModifyProjectMember', params)

    def get_zip(self, user, project):
        """Returns the content of a zip file containing novarc and access
        credentials."""
        params = {'Name': user, 'Project': project}
        zip = self.apiconn.get_object('GenerateX509ForUser', params, UserInfo)
        return zip.file

    def get_hosts(self):
        return self.apiconn.get_list('DescribeHosts', {}, [('item', HostInfo)])

    def block_ips(self, cidr):
        """Block incoming traffic from specified hosts."""
        return self.apiconn.get_object('BlockExternalAddresses',
                                       {'Cidr': cidr}, SimpleResponse)
<|endoftext|>


<commit_before># Copyright (c) 2016 TUBITAK BILGEM
# All Rights Reserved.
#
#    Licensed under the Apache License, Version 2.0 (the "License"); you may
#    not use this file except in compliance with the License. You may obtain
#    a copy of the License at
#
#         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.

from oslo_config import cfg

hyperv_opt_group = cfg.OptGroup("hyperv",
                title="The Hyper-V feature",
                help="""
The hyperv feature allows you to configure the Hyper-V hypervisor
driver to be used within an OpenStack deployment.
""")

dynamic_memory_ratio_opt = cfg.FloatOpt('dynamic_memory_ratio',
                default=1.0,
                help="""
Dynamic memory ratio

Enables dynamic memory allocation (ballooning) when set to a value
greater than 1. The value expresses the ratio between the total RAM
assigned to an instance and its startup RAM amount. For example a
ratio of 2.0 for an instance with 1024MB of RAM implies 512MB of
RAM allocated at startup.

Possible values:

* 1.0: Disables dynamic memory allocation (Default).
* Float values greater than 1.0: Enables allocation of total implied
  RAM divided by this value for startup.

Services which consume this:

* nova-compute

Related options:

* None
""")

enable_instance_metrics_collection_opt = cfg.BoolOpt(
                'enable_instance_metrics_collection',
                default=False,
                help="""
Enable instance metrics collection

Enables metrics collections for an instance by using Hyper-V's
metric APIs. Collected data can by retrieved by other apps and
services, e.g.: Ceilometer.

Possible values:

* True: Enables metrics collection.
* False: Disables metric collection (Default).

Services which consume this:

* nova-compute

Related options:

* None
""")

instances_path_share_opt = cfg.StrOpt('instances_path_share',
                default="",
                help="""
Instances path share

The name of a Windows share mapped to the "instances_path" dir
and used by the resize feature to copy files to the target host.
If left blank, an administrative share (hidden network share) will
be used, looking for the same "instances_path" used locally.

Possible values:

* "": An administrative share will be used (Default).
* Name of a Windows share.

Services which consume this:

* nova-compute

Related options:

* "instances_path": The directory which will be used if this option
  here is left blank.
""")

limit_cpu_features_opt = cfg.BoolOpt('limit_cpu_features',
                default=False,
                help="""
Limit CPU features

This flag is needed to support live migration to hosts with
different CPU features and checked during instance creation
in order to limit the CPU features used by the instance.

Possible values:

* True: Limit processor-specific features.
* False: Do not limit processor-specific features (Default).

Services which consume this:

* nova-compute

Related options:

* None
""")

mounted_disk_query_retry_count_opt = cfg.IntOpt(
                'mounted_disk_query_retry_count',
                default=10,
                help="""
The number of times to retry checking for a disk mounted via iSCSI.
""")

mounted_disk_query_retry_interval_opt = cfg.IntOpt(
                'mounted_disk_query_retry_interval',
                default=5,
                help="""
Interval between checks for a mounted iSCSI disk, in seconds.
""")

power_state_check_timeframe_opt = cfg.IntOpt('power_state_check_timeframe',
                default=60,
                help="""
The timeframe to be checked for instance power state changes.
""")

power_state_event_polling_interval_opt = cfg.IntOpt(
                'power_state_event_polling_interval',
                default=2,
                help="""
Instance power state change event polling frequency.
""")

qemu_img_cmd_opt = cfg.StrOpt('qemu_img_cmd',
                default="qemu-img.exe",
                help="""
Path of qemu-img command which is used to convert
between different image types
""")

vswitch_name_opt = cfg.StrOpt('vswitch_name',
                help="""
External virtual switch Name, if not provided,
the first external virtual switch is used
""")

wait_soft_reboot_seconds_opt = cfg.IntOpt('wait_soft_reboot_seconds',
                default=60,
                help="""
Number of seconds to wait for instance to shut down after
soft reboot request is made. We fall back to hard reboot
if instance does not shutdown within this window.
""")

config_drive_cdrom_opt = cfg.BoolOpt('config_drive_cdrom',
                default=False,
                help="""
Attaches the Config Drive image as a cdrom drive
instead of a disk drive
""")

config_drive_inject_password_opt = cfg.BoolOpt('config_drive_inject_password',
                default=False,
                help="""
Sets the admin password in the config drive image
""")

volume_attach_retry_count_opt = cfg.IntOpt('volume_attach_retry_count',
                default=10,
                help="""
The number of times to retry to attach a volume
""")

volume_attach_retry_interval_opt = cfg.IntOpt('volume_attach_retry_interval',
                default=5,
                help="""
Interval between volume attachment attempts, in seconds
""")

ALL_OPTS = [dynamic_memory_ratio_opt,
            enable_instance_metrics_collection_opt,
            instances_path_share_opt,
            limit_cpu_features_opt,
            mounted_disk_query_retry_count_opt,
            mounted_disk_query_retry_interval_opt,
            power_state_check_timeframe_opt,
            power_state_event_polling_interval_opt,
            qemu_img_cmd_opt,
            vswitch_name_opt,
            wait_soft_reboot_seconds_opt,
            config_drive_cdrom_opt,
            config_drive_inject_password_opt,
            volume_attach_retry_count_opt,
            volume_attach_retry_interval_opt]

def register_opts(conf):
    conf.register_opts(ALL_OPTS, group=hyperv_opt_group)

def list_opts():
    return {hyperv_opt_group: ALL_OPTS}
<commit_msg>Improve the help text for hyperv options (2)<commit_after># Copyright (c) 2016 TUBITAK BILGEM
# All Rights Reserved.
#
#    Licensed under the Apache License, Version 2.0 (the "License"); you may
#    not use this file except in compliance with the License. You may obtain
#    a copy of the License at
#
#         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.

from oslo_config import cfg

hyperv_opt_group = cfg.OptGroup("hyperv",
                title="The Hyper-V feature",
                help="""
The hyperv feature allows you to configure the Hyper-V hypervisor
driver to be used within an OpenStack deployment.
""")

dynamic_memory_ratio_opt = cfg.FloatOpt('dynamic_memory_ratio',
                default=1.0,
                help="""
Dynamic memory ratio

Enables dynamic memory allocation (ballooning) when set to a value
greater than 1. The value expresses the ratio between the total RAM
assigned to an instance and its startup RAM amount. For example a
ratio of 2.0 for an instance with 1024MB of RAM implies 512MB of
RAM allocated at startup.

Possible values:

* 1.0: Disables dynamic memory allocation (Default).
* Float values greater than 1.0: Enables allocation of total implied
  RAM divided by this value for startup.

Services which consume this:

* nova-compute

Related options:

* None
""")

enable_instance_metrics_collection_opt = cfg.BoolOpt(
                'enable_instance_metrics_collection',
                default=False,
                help="""
Enable instance metrics collection

Enables metrics collections for an instance by using Hyper-V's
metric APIs. Collected data can by retrieved by other apps and
services, e.g.: Ceilometer.

Possible values:

* True: Enables metrics collection.
* False: Disables metric collection (Default).

Services which consume this:

* nova-compute

Related options:

* None
""")

instances_path_share_opt = cfg.StrOpt('instances_path_share',
                default="",
                help="""
Instances path share

The name of a Windows share mapped to the "instances_path" dir
and used by the resize feature to copy files to the target host.
If left blank, an administrative share (hidden network share) will
be used, looking for the same "instances_path" used locally.

Possible values:

* "": An administrative share will be used (Default).
* Name of a Windows share.

Services which consume this:

* nova-compute

Related options:

* "instances_path": The directory which will be used if this option
  here is left blank.
""")

limit_cpu_features_opt = cfg.BoolOpt('limit_cpu_features',
                default=False,
                help="""
Limit CPU features

This flag is needed to support live migration to hosts with
different CPU features and checked during instance creation
in order to limit the CPU features used by the instance.

Possible values:

* True: Limit processor-specific features.
* False: Do not limit processor-specific features (Default).

Services which consume this:

* nova-compute

Related options:

* None
""")

mounted_disk_query_retry_count_opt = cfg.IntOpt(
                'mounted_disk_query_retry_count',
                default=10,
                help="""
Mounted disk query retry count

The number of times to retry checking for a disk mounted via iSCSI.
During long stress runs the WMI query that is looking for the iSCSI
device number can incorrectly return no data. If the query is
retried the appropriate data can then be obtained. The query runs
until the device can be found or the retry count is reached.

Possible values:

* Positive integer values. Values greater than 1 is recommended
  (Default: 10).

Services which consume this:

* nova-compute

Related options:

* Time interval between disk mount retries is declared with
  "mounted_disk_query_retry_interval" option.
""")

mounted_disk_query_retry_interval_opt = cfg.IntOpt(
                'mounted_disk_query_retry_interval',
                default=5,
                help="""
Mounted disk query retry interval

Interval between checks for a mounted iSCSI disk, in seconds.

Possible values:

* Time in seconds (Default: 5).

Services which consume this:

* nova-compute

Related options:

* This option is meaningful when the mounted_disk_query_retry_count
  is greater than 1.
* The retry loop runs with mounted_disk_query_retry_count and
  mounted_disk_query_retry_interval configuration options.
""")

power_state_check_timeframe_opt = cfg.IntOpt('power_state_check_timeframe',
                default=60,
                help="""
Power state check timeframe

The timeframe to be checked for instance power state changes.
This option is used to fetch the state of the instance from Hyper-V
through the WMI interface, within the specified timeframe.

Possible values:

* Timeframe in seconds (Default: 60).

Services which consume this:

* nova-compute

Related options:

* None
""")

power_state_event_polling_interval_opt = cfg.IntOpt(
                'power_state_event_polling_interval',
                default=2,
                help="""
Power state event polling interval

Instance power state change event polling frequency. Sets the
listener interval for power state events to the given value.
This option enhances the internal lifecycle notifications of
instances that reboot themselves. It is unlikely that an operator
has to change this value.

Possible values:

* Time in seconds (Default: 2).

Services which consume this:

* nova-compute

Related options:

* None
""")

qemu_img_cmd_opt = cfg.StrOpt('qemu_img_cmd',
                default="qemu-img.exe",
                help="""
qemu-img command

qemu-img is required for some of the image related operations
like converting between different image types. You can get it
from here: (http://qemu.weilnetz.de/) or you can install the
Cloudbase OpenStack Hyper-V Compute Driver
(https://cloudbase.it/openstack-hyperv-driver/) which automatically
sets the proper path for this config option. You can either give the
full path of qemu-img.exe or set its path in the PATH environment
variable and leave this option to the default value.

Possible values:

* Name of the qemu-img executable, in case it is in the same
  directory as the nova-compute service or its path is in the
  PATH environment variable (Default).
* Path of qemu-img command (DRIVELETTER:\PATH\TO\QEMU-IMG\COMMAND).

Services which consume this:

* nova-compute

Related options:

* If the config_drive_cdrom option is False, qemu-img will be used to
  convert the ISO to a VHD, otherwise the configuration drive will
  remain an ISO. To use configuration drive with Hyper-V, you must
  set the mkisofs_cmd value to the full path to an mkisofs.exe
  installation.
""")

vswitch_name_opt = cfg.StrOpt('vswitch_name',
                help="""
External virtual switch name

The Hyper-V Virtual Switch is a software-based layer-2 Ethernet
network switch that is available with the installation of the
Hyper-V server role. The switch includes programmatically managed
and extensible capabilities to connect virtual machines to both
virtual networks and the physical network. In addition, Hyper-V
Virtual Switch provides policy enforcement for security, isolation,
and service levels. The vSwitch represented by this config option
must be an external one (not internal or private).

Possible values:

* If not provided, the first of a list of available vswitches
  is used. This list is queried using WQL.
* Virtual switch name.

Services which consume this:

* nova-compute

Related options:

* None
""")

wait_soft_reboot_seconds_opt = cfg.IntOpt('wait_soft_reboot_seconds',
                default=60,
                help="""
Number of seconds to wait for instance to shut down after
soft reboot request is made. We fall back to hard reboot
if instance does not shutdown within this window.
""")

config_drive_cdrom_opt = cfg.BoolOpt('config_drive_cdrom',
                default=False,
                help="""
Attaches the Config Drive image as a cdrom drive
instead of a disk drive
""")

config_drive_inject_password_opt = cfg.BoolOpt('config_drive_inject_password',
                default=False,
                help="""
Sets the admin password in the config drive image
""")

volume_attach_retry_count_opt = cfg.IntOpt('volume_attach_retry_count',
                default=10,
                help="""
The number of times to retry to attach a volume
""")

volume_attach_retry_interval_opt = cfg.IntOpt('volume_attach_retry_interval',
                default=5,
                help="""
Interval between volume attachment attempts, in seconds
""")

ALL_OPTS = [dynamic_memory_ratio_opt,
            enable_instance_metrics_collection_opt,
            instances_path_share_opt,
            limit_cpu_features_opt,
            mounted_disk_query_retry_count_opt,
            mounted_disk_query_retry_interval_opt,
            power_state_check_timeframe_opt,
            power_state_event_polling_interval_opt,
            qemu_img_cmd_opt,
            vswitch_name_opt,
            wait_soft_reboot_seconds_opt,
            config_drive_cdrom_opt,
            config_drive_inject_password_opt,
            volume_attach_retry_count_opt,
            volume_attach_retry_interval_opt]

def register_opts(conf):
    conf.register_opts(ALL_OPTS, group=hyperv_opt_group)

def list_opts():
    return {hyperv_opt_group: ALL_OPTS}
<|endoftext|>


<commit_before><commit_msg>Added laser class with functions for powerstate<commit_after><|endoftext|>