Exemplo n.º 1
0
class RasActionSyslogForm(RasActionBaseForm):

    PROTOCOL = ['udp', 'tcp', 'unix']
    FACILITY = SyslogConf.FACILITY
    PRIORITY = SyslogConf.PRIORITY

    address = StringField(label=u'アドレス(:ポート)',
                          validators=[validators.DataRequired()])
    protocol = SelectField(
        label=u'プロトコル',
        choices=[(i, i) for i in PROTOCOL],
    )
    facility = SelectField(
        label=u'ファシリティ',
        choices=[(i, i) for i in FACILITY],
        default='user',
    )
    priority = SelectField(
        label=u'プライオリティ',
        choices=[(i, i) for i in PRIORITY],
        default='info',
    )
    message = TextAreaField(
        label=u'メッセージ',
        default='{default}',
    )

    def _get_type(self):
        return 'syslog'
Exemplo n.º 2
0
class AdminConfLogForm(AdminConfBaseForm):

    level = IntegerField(
        label=u'ログレベル',
        validators=[validators.DataRequired()],
        default=SyslogConf.DEFAULT['level'],
    )

    address = StringField(
        label=u'Syslogサーバ',
        validators=[validators.DataRequired()],
        default=SyslogConf.DEFAULT['address'],
    )

    facility = SelectField(
        label=u'ファシリティ',
        choices=[(i, i) for i in SyslogConf.FACILITY],
        default=SyslogConf.DEFAULT['facility'],
    )
    priority = SelectField(
        label=u'プライオリティ',
        choices=[(i, i) for i in SyslogConf.PRIORITY],
        default=SyslogConf.DEFAULT['priority'],
    )

    def conf_type(self):
        return SyslogConf.NAME
Exemplo n.º 3
0
class MaintenanceForm(FlaskForm):
    name = StringField('Name', validators=[validators.DataRequired()])
    description = StringField('Description')
    asset = SelectField('Asset')
    schedule_multiplier = StringField('Schedule count')
    schedule = SelectField('Schedule')
    enabled = BooleanField('Enabled')
    submit = SubmitField()
Exemplo n.º 4
0
class BudgetForm(Form):
    budgetcategory = SelectField(u'Budget Category', coerce=int, choices=[], validators=[
        InputRequired(message=(u'Please enter a valid Category'))
    ])
    budgetsubcategory = SelectField(u'Budget SubCategory', coerce=int, choices=[(0,0)], validators=[
        Optional()
    ])
    budgetamount = DecimalField(u'Budget Amount', places=2, validators=[
        InputRequired(message=(u'Please enter a budget amount'))
    ])
class FlatPrice(FlaskForm):
    
    df_flat = pd.read_csv("https://raw.githubusercontent.com/shravankumargottala/Hyderabad_House_Price_Prediction/master/Hyd_Flat_Apartment_House_Price.csv")
    
    Flat_Furn_Uniq = df_flat['Furnished_status'].unique()
    for j in range(len(Flat_Furn_Uniq)):
        flat_furn_stat_dict[Flat_Furn_Uniq[j]] = j

    Flat_Fac_Uniq = df_flat['Facing'].unique()
    
    for k in range(len(Flat_Fac_Uniq)):
        flat_fac_dict[Flat_Fac_Uniq[k]] = k  

    flat_addr_Uniq = df_flat['Address'].unique()
    for l in range(len(flat_addr_Uniq)):
        flat_addr_dict[flat_addr_Uniq[l]] = l

    furn_main_list = []
    for i in range(len(Flat_Furn_Uniq)):
        furn_sub_list = []
        for j in range(2):
            furn_sub_list.append(Flat_Furn_Uniq[i])
        furn_main_list.append(tuple(furn_sub_list))

    fac_main_list = []
    for i in range(len(Flat_Fac_Uniq)):
        fac_sub_list = []
        for j in range(2):
            fac_sub_list.append(Flat_Fac_Uniq[i])
        fac_main_list.append(tuple(fac_sub_list))

    addr_main_list = []
    for i in range(len(flat_addr_Uniq)):
        addr_sub_list = []
        for j in range(2):
            addr_sub_list.append(flat_addr_Uniq[i])
        addr_main_list.append(tuple(addr_sub_list))
        
    

    df_flat['Furnished_status'] = df_flat['Furnished_status'].map(house_furn_stat_dict)
    df_flat['Facing'] = df_flat['Facing'].map(house_fac_dict)
    df_flat['Address'] = df_flat['Address'].map(house_addr_dict)
    No_of_Bedrooms = IntegerField('No of Bedrooms:',validators=[InputRequired()],render_kw={"placeholder": "i.e. 1,2"})
    No_of_Bathrooms = IntegerField('No of Bathrooms:', validators=[InputRequired()],render_kw={"placeholder": "i.e. 0,1"})
    No_of_Balconies = IntegerField('No of Balconies:', validators=[InputRequired()],render_kw={"placeholder": "i.e. 0,1"})
    No_of_Poojarooms = IntegerField('No of Poojarooms:', validators=[InputRequired()],render_kw={"placeholder": "i.e. 0,1"})
    Supr_Area = IntegerField('Super Area:', validators=[InputRequired()],render_kw={"placeholder": "i.e. 800,900 ( in sqft )"})
    Carp_Area = IntegerField('Carpet Area:', validators=[InputRequired()],render_kw={"placeholder": "i.e. 800,900 ( in sqft )"})
    Floor_No = IntegerField('Floor No:', validators=[InputRequired()],render_kw={"placeholder": "i.e. 1,2"})
    Total_Floors = IntegerField('Total Floors:', validators=[InputRequired()],render_kw={"placeholder": "i.e. 1,2"})
    Furn_status = SelectField('Furnishing Status:', choices=tuple(furn_main_list))
    Fac_status = SelectField('Facing:', choices=tuple(fac_main_list))
    Addrss = SelectField('Address:', choices=tuple(addr_main_list))
    submit = SubmitField('Predict', render_kw={"onclick": "checkform()"})
Exemplo n.º 6
0
class CreateHourlyForm(Form):
    bare_metal = HiddenField(default='1')
    location = SelectField('Data Center', default='FIRST_AVAILABLE')
    hostname = StringField('Hostname', validators=[Required()])
    domain = StringField('Domain', validators=[Required()])
    server = SelectField('Server', validators=[Required()])
    os = SelectField('Operating System', validators=[Required()])
    port_speed = SelectField('Network Speed', validators=[Required()])
    # TODO - This could be turned into a regular SelectField
    disks = FieldList(SelectField('Disks', validators=[Required()]),
                      min_entries=1,
                      max_entries=4)
Exemplo n.º 7
0
class CreateVMForm(Form):
    datacenter = SelectField('Data Center')
    hostname = StringField('Hostname', validators=[Required()])
    domain = StringField('Domain', validators=[Required()])
    os = SelectField('Operating System', validators=[Required()])
    cpus = SelectField('CPUs', validators=[Required()])
    memory = SelectField('Memory (GB)', validators=[Required()])
    network = RadioField(choices=[('10',
                                   '10Mbps'), ('100',
                                               '100Mbps'), ('1000',
                                                            '1000 Mbps')])
    tags = StringField('Tags',
                       validators=[
                           Regexp(
                               r'^[A-Za-z0-9_\.\-,\ ]*$',
                               message="Tags must be alphanumeric, _ . or -")
                       ])
class PlotPrice(FlaskForm):
    df = pd.read_csv("https://raw.githubusercontent.com/shravankumargottala/Hyderabad_House_Price_Prediction/master/Hyd_Plot_Price.csv")
        
    Plot_Project_Unq = df.Project_Name.unique()
    for i in range(len(Plot_Project_Unq)):
        Plot_Project_Dict[Plot_Project_Unq[i]] = i
        
    soci_main_list = []
    for i in range(len(Plot_Project_Unq)):
        soci_sub_list = []
        for j in range(2):
            soci_sub_list.append(Plot_Project_Unq[i])
        soci_main_list.append(tuple(soci_sub_list))

    Plot_Transaction_Unq = df.Transaction_Type.unique()
    for i in range(len(Plot_Transaction_Unq)):
        Plot_Transaction_Dict[Plot_Transaction_Unq[i]] = i
    
    trans_main_list = []
    for i in range(len(Plot_Transaction_Unq)):
        trans_sub_list = []
        for j in range(2):
            trans_sub_list.append(Plot_Transaction_Unq[i])
        trans_main_list.append(tuple(trans_sub_list))


    Plot_Address_Unq = df.Address.unique()
    for i in range(len(Plot_Address_Unq)):
        Plt_Addr_Dict[Plot_Address_Unq[i]] = i
        
    addr_main_list = []
    for i in range(len(Plot_Address_Unq)):
        addr_sub_list = []
        for j in range(2):
            addr_sub_list.append(Plot_Address_Unq[i])
        addr_main_list.append(tuple(addr_sub_list))
        
    Soci_Name =  SelectField('Society Name:', choices=tuple(soci_main_list)) 
    Plt_Area = IntegerField('Plot Area:', validators=[InputRequired()],render_kw={"placeholder": "i.e. 200,300 ( in sqyrds )"})
    Trans_Type = SelectField('Transaction Type:', choices=tuple(trans_main_list))
    Addrss = SelectField('Address:', choices=tuple(addr_main_list))
    submit = SubmitField('Predict')   
        
        
        
        
Exemplo n.º 9
0
class CreateSubnetForm(Form):
    vlan_id = HiddenField()
    subnet_type = RadioField(choices=[('public', 'Public'),
                                      ('private', 'Private')],
                             validators=[Required()])
    quantity = SelectField('Quantity', validators=[Required()],
                           choices=[('4', '4'), ('8', '8'), ('16', '16'),
                                    ('32', '32')])
Exemplo n.º 10
0
    def add_disk(cls, required=True):
        validators = []
        if required:
            validators.append(Required())

        new_field = SelectField('Disk', validators=validators)

        cls.disks.append_entry(new_field)
Exemplo n.º 11
0
class ParsleyTestForm(Form):
    email = StringField(
        'E-Mail Address',
        [validators.Email('Sorrry, not a valid email address.')],
        default='*****@*****.**')
    first_value = StringField('Some Value', default='Some value')
    second_value = StringField('Should be identical', [
        validators.EqualTo(message='Sorry, values do not match.',
                           fieldname='first_value')
    ],
                               default='Some value')
    ip_address = StringField(
        'IP4 Address',
        [validators.IPAddress(message='Sorry, not a valid IP4 Address.')],
        default='127.0.0.1')
    string_length = StringField('Length of String (5 to 10)', [
        validators.Length(
            message='Length should be between 5 and 10 characters.',
            min=5,
            max=10)
    ],
                                default='Hello!')
    number_range = IntegerField('Number Range (5 to 10)', [
        validators.NumberRange(
            message='Range should be between 5 and 10.', min=5, max=10)
    ],
                                default=7)

    required_text = StringField(
        'Required Field',
        [validators.DataRequired(message='Sorry, this is a required field.')],
        default='Mandatory text')
    required_select = SelectField(
        'Required Select',
        [validators.DataRequired(message='Sorry, you have to make a choice.')],
        choices=[('', 'Please select an option'), ('cpp', 'C++'),
                 ('py', 'Python'), ('text', 'Plain Text')],
        default='py')
    required_checkbox = BooleanField(
        'Required Checkbox',
        [validators.DataRequired(message='Sorry, you need to accept this.')],
        default=True)
    regexp = StringField('Regex-Matched Hex Color-Code', [
        validators.Regexp(message='Not a proper color code, sorry.',
                          regex=r'^#[A-Fa-f0-9]{6}$')
    ],
                         default='#7D384F')
    url = StringField(
        'URL Field',
        [validators.URL(message='Sorry, this is not a valid URL,')],
        default='http://example.com/parsley')
    anyof = StringField('Car, Bike or Plane?', [
        validators.AnyOf(
            message='Sorry, you can only choose from car, bike and plane',
            values=['car', 'bike', 'plane'])
    ],
                        default='car')
Exemplo n.º 12
0
class ZoneRecordForm(Form):
    zone_id = HiddenField()
    host = StringField('Host', validators=[Required()])
    type = SelectField('Type', choices=[('A', 'A'), ('AAAA', 'AAAA'),
                                        ('CNAME', 'CNAME'), ('TXT', 'TXT'),
                                        ('NS', 'NS'), ('SOA', 'SOA'),
                                        ('MX', 'MX'), ('PTR', 'PTR'),
                                        ('SRV', 'SRV')],
                       validators=[Required()])
    data = StringField('Data', validators=[Required()])
    ttl = IntegerField('TTL', validators=[Required(), NumberRange(min=0)])
Exemplo n.º 13
0
class RasActionHttpForm(RasActionBaseForm):

    METHODS = ['GET', 'POST', 'PUT', 'PATCH', 'DELETE']

    method = SelectField(label=u'メソッド', choices=[(i, i) for i in METHODS])
    url = StringField(label=u'URL',
                      validators=[validators.DataRequired(),
                                  validators.URL()])
    params = TextAreaField(label=u'パラメータ', )
    header = TextAreaField(label=u'ヘッダ', )

    def _get_type(self):
        return 'http'
Exemplo n.º 14
0
class RasTargetCellForm(RasTargetForm):

    cell = SelectField(
        label=u'セル名',
        coerce=int,
        choices=[],
    )
    comment = TextAreaField(
        label=u'コメント',
        default=u'',
    )

    @classmethod
    def obj2dict(cls, obj):
        cell = Cell.select().where(Cell.name == obj.name).first()
        logger.debug("CELL ID: {}".format(cell.id))
        return {
            'type': 'cell',
            'cell': cell.id,
            'comment': obj.comment,
        }

    def get_cell_name(self, id):
        cell = Cell.get(Cell.id == id)
        return cell.name

    def _update_selectfield(self):
        registerd = RasTarget.select(
            RasTarget.name).where(RasTarget.type == 'cell')
        self.cell.choices = [
            (c.id, c.name)
            for c in Cell.select().where(Cell.name.not_in(registerd))
        ]

    def _get_type(self):
        return 'cell'

    def create(self, grpid):
        logger.debug("CREATE: {}".format(grpid))
        tgt = RasTarget()
        cell = Cell.get(Cell.id == self.cell.data)
        tgt.name = cell.name
        tgt.group = grpid
        tgt.type = 'cell'
        tgt.path = '{app}/{cell}'.format(app=cell.get_appname(),
                                         cell=cell.name)
        tgt.comment = self.comment.data
        tgt.save()
Exemplo n.º 15
0
class RasTargetRasForm(RasTargetForm):

    group = SelectField(
        label=u'監視クラスタ名',
        coerce=int,
        choices=[],
    )
    comment = TextAreaField(
        label=u'コメント',
        default=u'',
    )

    @classmethod
    def obj2dict(cls, obj):
        grp = RasGroup.select().where(RasGroup.name == obj.name).first()
        logger.debug("RasGroup ID: {}".format(grp.id))
        return {
            'type': 'ras',
            'group': grp.id,
            'comment': obj.comment,
        }

    def _update_selectfield(self):
        registerd = RasTarget.select(
            RasTarget.name).where(RasTarget.type == 'ras')
        self.group.choices = [
            (g.id, g.name)
            for g in RasGroup.select().where(RasGroup.name.not_in(registerd))
        ]

    def _get_type(self):
        return 'ras'

    def get_group_name(self, id):
        grp = RasGroup.get(RasGroup.id == id)
        return grp.name

    def create(self, grpid):
        tgt = RasTarget()
        group = RasGroup.get(RasGroup.id == self.group.data)
        tgt.name = group.name
        tgt.group = grpid
        tgt.type = 'ras'
        tgt.path = '{app}/{grp}'.format(app='RasEye', grp=group.name)
        tgt.comment = self.comment.data
        tgt.save()
Exemplo n.º 16
0
class CellNodeForm(BaseForm):
    node = SelectField(
        label=u'サーバ',
        coerce=int,
        choices=[],
    )
    udp_addr = StringField(
        label=u'ホストアドレス(UDP)',
        validators=[validators.DataRequired(),
                    validators.IPAddress()],
    )
    udp_port = IntegerField(
        label=u'UDPポート番号',
        validators=[
            validators.DataRequired(),
            validators.NumberRange(
                min=0,
                max=65535,
            )
        ],
        default=14000,
    )
    tcp_addr = StringField(
        label=u'ホストアドレス(TCP)',
        validators=[validators.DataRequired(),
                    validators.IPAddress()],
    )
    tcp_port = IntegerField(
        label=u'TCPポート番号',
        validators=[
            validators.DataRequired(),
            validators.NumberRange(
                min=0,
                max=65535,
            )
        ],
        default=14000,
    )
    node_id = HiddenField()
Exemplo n.º 17
0
class CreateMonthlyForm(Form):
    package_id = HiddenField(validators=[Required()])
    location = SelectField('Data Center', default='FIRST_AVAILABLE')
    hostname = StringField('Hostname', validators=[Required()])
    domain = StringField('Domain', validators=[Required()])
    server = SelectField('CPU', validators=[Required()])
    ram = SelectField('Memory', validators=[Required()])
    os = SelectField('Operating System', validators=[Required()])
    port_speed = SelectField('Network Speed', validators=[Required()])
    disks = FieldList(SelectField('Disks', validators=[Required()]),
                      min_entries=1)
    disk_controller = SelectField('Disk Controller', validators=[Required()])

    @classmethod
    def add_disk(cls, required=True):
        validators = []
        if required:
            validators.append(Required())

        new_field = SelectField('Disk', validators=validators)

        cls.disks.append_entry(new_field)
Exemplo n.º 18
0
class SecurityQuestionForm(Form):
    question_id = SelectField('Question', 'question_id')
    answer = StringField('Answer', validators=[Required()])
Exemplo n.º 19
0
class UserSurvey1(Form):
    age = [("u10", "Under 10"), ("11-20", "11-20"), ("21-40", "21-40"),
           ("41-60", "41-60"), ("61-80", "61-80"), ("81+", "Over 81")]
    allDifficulties = [("AMD", "Age Related Macular Degeneration"),
                       ("BI", "Brain Injury"), ("D", "Dyslexia"),
                       ("VI", "Vision Issues"), ("O", "Other"), ("N", "None")]
    nativelang = [("yes", "Yes"), ("no", "No")]
    device = [("desktop", "Desktop"), ("laptop", "Laptop"),
              ("tablet", "Tablet"), ("mobile", "Smartphone")]

    cc = {}
    t = list(pycountry.countries)
    for country in t:
        cc[country.name] = country.name
    cc = [(v, v) for v, v in cc.iteritems()]
    cc.sort()
    cc.insert(0, (None, ""))
    age.insert(0, (None, ""))
    country = SelectField(
        'Country',
        [validators.DataRequired(message='Sorry, this is a required field.')],
        choices=cc)
    agerange = SelectField(
        'Age Range',
        [validators.DataRequired(message='Sorry, this is a required field.')],
        choices=age)
    difficulties = SelectMultipleField(
        'Reading Difficulties (select all that apply)',
        [validators.DataRequired(message='Sorry, this is a required field.')],
        choices=allDifficulties,
        coerce=unicode,
        option_widget=widgets.CheckboxInput(),
        widget=widgets.ListWidget(prefix_label=False))
    nativelang = RadioField(
        'Is English your native language?',
        [validators.DataRequired(message='Sorry, this is a required field.')],
        choices=nativelang)
    deviceused = RadioField(
        'What device are you using?',
        [validators.DataRequired(message='Sorry, this is a required field.')],
        choices=device)

    aq1_label = "How tall was the Iron Man?"
    aq2_label = "His eyes were like?"
    aq3_label = "What flew over and landed?"
    aq4_label = "What did they have on the cliff?"
    aq5_label = "What did the seagull pick up first?"
    aq1_answers = [("a", "very tall"), ("b", "short"),
                   ("c", "taller than a house"),
                   ("d", "taller than a boulder")]
    aq2_answers = [("a", "headlamps"), ("b", "rocks"), ("c", "cats"),
                   ("d", "flames")]
    aq3_answers = [("a", "a hummingbird"), ("b", "a bat"),
                   ("c", "two seagulls"), ("d", "a plane")]
    aq4_answers = [("a", "a houseboat"), ("b", "two chicks in a nest"),
                   ("c", "a nest"), ("d", "a drum of oil")]
    aq5_answers = [("a", "nothing"), ("b", "a finger"), ("c", "a knife blade"),
                   ("d", "one of the Iron Man's eyes")]
    aq1 = RadioField(aq1_label, choices=aq1_answers)
    aq2 = RadioField(aq2_label, choices=aq2_answers)
    aq3 = RadioField(aq3_label, choices=aq3_answers)
    aq4 = RadioField(aq4_label, choices=aq4_answers)
    aq5 = RadioField(aq5_label, choices=aq5_answers)

    bq1_label = "What did the second seagull pickup?"
    bq2_label = "What color did the eye glow?"
    bq3_label = "What did the Iron Man try to pick up, stuck between the rocks?"
    bq4_label = "What was the eye doing when they found it?"
    bq5_label = "How did the legs move?"
    bq1_answers = [("a", "a clam"), ("b", "the right hand"), ("c", "a house"),
                   ("d", "bridseed")]
    bq2_answers = [("a", "blue"), ("b", "purple"), ("c", "white"),
                   ("d", "pink")]
    bq3_answers = [("a", "a hummingbird"), ("b", "the left arm"),
                   ("c", "two seagulls"), ("d", "a plane")]
    bq4_answers = [("a", "waving"), ("b", "blinking at them"),
                   ("c", "sleeping"), ("d", "nothing")]
    bq5_answers = [("a", "running"), ("b", "skip"), ("c", "with a limp"),
                   ("d", "Hop, hop, hop, hop")]
    bq1 = RadioField(bq1_label, choices=bq1_answers)
    bq2 = RadioField(bq2_label, choices=bq2_answers)
    bq3 = RadioField(bq3_label, choices=bq3_answers)
    bq4 = RadioField(bq4_label, choices=bq4_answers)
    bq5 = RadioField(bq5_label, choices=bq5_answers)
Exemplo n.º 20
0
class RasGroupForm(Form):
    name = StringField(
        label=u'クラスタ名',
        validators=[
            validators.DataRequired(),
            validators.Length(max=256),
            validators.Regexp('^\w+$')
        ],
    )
    comment = TextAreaField(
        label=u'コメント',
        default=u'',
    )
    cell = SelectField(
        label=u'RASセル',
        coerce=int,
        choices=[],
    )

    @classmethod
    def delete(cls, id):
        grp = RasGroup.get(RasGroup.id == id)
        with database.database.atomic():
            RasTargetForm.delete_nonexists_target('ras', grp.name)
            for tgt in grp.targets:
                RasTargetForm.delete(tgt.id)
            for srv in grp.servers:
                RasServerForm.delete(srv.id)
            grp.delete_instance()

    @classmethod
    def obj2dict(cls, obj):
        return {
            'name': obj.name,
            'comment': obj.comment,
            'cell': obj.cell.id,
        }

    def get_cell_name(self, id):
        cell = Cell.get(Cell.id == id)
        return cell.name

    def __init__(self,
                 formdata=None,
                 obj=None,
                 prefix='',
                 data=None,
                 meta=None,
                 **kwargs):
        super(RasGroupForm, self).__init__(formdata, obj, prefix, data, meta,
                                           **kwargs)
        self._update_select()

    def _update_select(self):
        cells = Cell.select().where(Cell.type == 'RAS')
        self.cell.choices = [(c.id, c.name) for c in cells]

    def create(self, url):
        group = RasGroup()
        self.populate_obj(group)
        group.id = None
        group.save(url=url)
        return group
Exemplo n.º 21
0
class RasServerForm(Form):

    node = SelectField(
        label=u'サーバ',
        coerce=int,
        choices=[],
    )

    def __init__(self,
                 formdata=None,
                 obj=None,
                 prefix='',
                 data=None,
                 meta=None,
                 group=None,
                 **kwargs):
        super(RasServerForm, self).__init__(formdata, obj, prefix, data, meta,
                                            **kwargs)
        self._update_select(group)
        try:
            self.node.data = obj.node.id
        except AttributeError:
            pass

    def _update_select(self, grpid):
        nodes0 = RasServer.select(
            RasServer.node).where(RasServer.group == grpid)
        nodes = Node.select().where(Node.id.not_in(nodes0))
        self.node.choices = [(n.id, n.hostname) for n in nodes]

    def create(self, grpid):
        srv = RasServer()
        self.populate_obj(srv)
        srv.id = None
        last_no = RasServer.select(fn.Max(
            RasServer.no)).where(RasServer.group == grpid).scalar()
        srv.no = last_no + 1 if last_no is not None else 0
        srv.group = grpid
        if len(srv.group.servers) == 0:
            grp = RasGroup.get(RasGroup.id == grpid)
            srv.save(callback=lambda: self.regist_auto_target(grp))
        else:
            srv.save()

    def exist_restart_action(self, cell):
        tgts = RasTarget.select().where((RasTarget.name == cell.name)
                                        & (RasTarget.type == 'cell'))
        for tgt in tgts:
            acts = RasAction.select().where((RasAction.target == tgt.id) & (
                RasAction.type == 'restart')).first()
            if acts is not None:
                return True
        return False

    def regist_ras_cell(self, group):
        cell = group.cell
        if self.exist_restart_action(cell):
            return
        logger.debug("REGIST CELL: {}".format(cell))
        tgt = RasTargetCellForm(data={'type': 'cell', 'cell': cell.id})
        tgt.create(group.id)
        tobj = RasTarget.select().where((RasTarget.name == cell.name) & (
            RasTarget.type == 'cell') & (RasTarget.group == group.id)).first()
        act = RasActionRestartForm(data={'type': 'restart', 'name': 'restart'})
        act.create(tobj.id)

    def regist_ras_eye(self, group):
        logger.debug("REGIST RAS: {}".format(group))
        tgt = RasTargetRasForm(data={'type': 'ras', 'group': group.id})
        tgt.create(group.id)
        tobj = RasTarget.select().where((RasTarget.name == group.name) & (
            RasTarget.type == 'ras') & (RasTarget.group == group.id)).first()
        act = RasActionRestartForm(data={'type': 'restart', 'name': 'restart'})
        act.create(tobj.id)

    def regist_auto_target(self, group):
        logger.debug("REGIST AUTO TARGET: {}".format(group))
        self.regist_ras_cell(group)
        self.regist_ras_eye(group)

    def get_hostname(self, nid):
        for c in self.node.choices:
            if c[0] == nid:
                return c[1]
        return None

    @classmethod
    def delete(cls, id):
        srv = RasServer.get(RasServer.id == id)
        with database.database.atomic():
            srv.stop()
            srv.delete_instance()
Exemplo n.º 22
0
def create_monthly(package_id=None):
    """ This presents a form for ordering a monthly dedicated server. """

    # If we don't have a package ID yet, show the chassis selection page.
    if not package_id:
        payload = {}
        payload['title'] = 'Order Monthly Server - Select Chassis'
        payload['options'] = manager.get_available_monthly_server_packages()

        return render_template("server_monthly_add_package.html", **payload)

    payload = {}
    form = forms.CreateMonthlyForm(package_id=package_id)

    all_options = manager.get_monthly_create_options('', package_id)

    dc_options = []
    for dc in all_options['locations']:
        dc_options.append((dc['keyname'], dc['long_name']))
    form.location.choices = dc_options

    form.server.choices = _process_category_items(all_options, 'server')
    form.ram.choices = _process_category_items(all_options, 'ram')
    form.os.choices = _process_category_items(all_options, 'os')
    form.port_speed.choices = _process_category_items(all_options,
                                                      'port_speed')
    form.disk_controller.choices = _process_category_items(all_options,
                                                           'disk_controller')

    # Setup disk choices
    form.disks.entries[0].choices = _process_category_items(all_options,
                                                            'disk0')

    for category, data in all_options['categories'].items():
        if category.startswith('disk') and category not in ['disk0',
                                                            'disk_controller']:
            if data['is_required']:
                disk_num = category.replace('disk', '')
                field = SelectField('Disks', validators=[Required()])
                form.disks.append_entry(field)
                choices = _process_category_items(all_options,
                                                  'disk' + disk_num)
                form.disks.entries[int(disk_num)].choices = choices

    payload['form'] = form
    payload['title'] = 'Order Monthly Server - Details'
    payload['options'] = all_options
#    payload['domains'] = all_zones(current_username())

    # I want to display these in a different order than the API suggests, so
    # I'm going to exclude them from their normal sections.
    payload['excluded_options'] = ['os', 'ram', 'server', 'disk_controller']

    if form.validate_on_submit():
        fields = _extract_fields_from_form(form)

        (success, message) = manager.place_order(**fields)
        if success:
            flash(message, 'success')

            # TODO - This is not implemented yet
            if request.form.get('save_template'):
                template_name = request.form.get('template_title')

                fields['title'] = template_name
                _save_template(fields)

                flash('Configuration saved for future use.', 'success')

            return redirect(url_for(".index"))
        else:
            flash(message, 'error')

    if form.errors:
        flash('There are validation errors with your submission.', 'error')

    return render_template('server_monthly_add.html', **payload)
Exemplo n.º 23
0
class CellForm(BaseForm):

    CNODE_MIN = 3
    name = StringField(
        label=u'セル名',
        validators=[
            validators.DataRequired(),
            validators.Length(max=256),
            validators.Regexp('^\w+$')
        ],
    )
    type = SelectField(
        label=u'セル種別',
        choices=[(tp, tp) for tp in Cell.CELL_TYPE],
    )
    comment = TextAreaField(label=u'コメント', )
    nodes = FieldList(
        FormField(CellNodeForm),
        label=u'サーバ',
        min_entries=CNODE_MIN,
    )

    def __init__(self,
                 formdata=None,
                 obj=None,
                 prefix='',
                 data=None,
                 meta=None,
                 **kwargs):
        super(CellForm, self).__init__(formdata, obj, prefix, data, meta,
                                       **kwargs)
        self.update_nodes()

    def update_nodes(self):
        nodes = Node.select()
        for cnode in self.nodes:
            cnode['node'].choices = [(n.id, n.hostname) for n in nodes]

    def populate_obj(self, obj):
        for name, field in iteritems(self._fields):
            if not isinstance(field, FieldList):
                field.populate_obj(obj, name)

    def populate_cellnodes(self, nodes):
        while len(self.nodes) > 0:
            self.nodes.pop_entry()
        for n in nodes:
            ent = self.nodes.append_entry(n)
            ent['node'].data = n.node.id
            ent['node_id'].data = n.id
        self.update_nodes()

    def exists_cnode(self, cnode):
        for ent in self.nodes:
            if ent['node_id'].data.isnumeric() and\
               int(ent['node_id'].data) == cnode.id:
                return True
        return False

    def get_hostname(self, host_id):
        if len(self.nodes) == 0:
            return None
        choices = self.nodes[0]['node'].choices
        for ch in choices:
            if ch[0] == host_id:
                return ch[1]
        return None

    def _save_cell(self, cell):
        self.populate_obj(cell)
        try:
            cell.save()
            return True
        except IntegrityError as e:
            logger.error(str(e))
            self.name.errors.append(e.message)

    def _save_cnode(self, nform, nid, idx, cell):
        cnode = CellNode()
        nform.form.populate_obj(cnode)
        cnode.id = nid
        cnode.no = idx
        cnode.cell = cell
        try:
            cnode.save()
            return True
        except IntegrityError as e:
            logger.error(str(e))
            if string.find(e.message, 'tcp') >= 0:
                nform.form.tcp_port.errors.append(e.message)
            elif string.find(e.message, 'udp') >= 0:
                nform.form.udp_port.errors.append(e.message)
            else:
                self.name.errors.append(e.message)

    def create(self):
        with database.database.atomic() as txn:
            cell = Cell()
            if not self._save_cell(cell):
                txn.rollback()
                return False
            for idx, nform in enumerate(self.nodes):
                if not self._save_cnode(nform, None, idx, cell):
                    txn.rollback()
                    return False
        try:
            cell.deploy_conf()
        except Exception as e:
            logger.exceptions(e)
        return True

    def update(self, id):
        with database.database.atomic() as txn:
            cell = Cell().get(Cell.id == id)
            if not self._save_cell(cell):
                txn.rollback()
                return False
            for cnode in cell.nodes:
                if not self.exists_cnode(cnode):
                    cnode.delete().where(CellNode.id == cnode.id).execute()
            for idx, nform in enumerate(self.nodes):
                node_id = nform.form['node_id'].data
                nid = (int(node_id) if node_id is not None
                       and node_id.isnumeric() else None)
                if not self._save_cnode(nform, nid, idx, cell):
                    txn.rollback()
                    return False
        try:
            cell.deploy_conf()
        except Exception as e:
            logger.exceptions(e)
        return True

    def _pop_cnode(self, num):
        cnode_list = []
        for i in range(num):
            cnode = CellNode()
            nform = self.nodes.pop_entry()
            nform.form.populate_obj(cnode)
            cnode_list.insert(0, cnode)
        return cnode_list

    def _push_cnode(self, cnode_list):
        node_list = Node.select()
        for cnode in cnode_list:
            nform = self.nodes.append_entry(cnode)
            nform['node'].choices = [(n.id, n.hostname) for n in node_list]
            if cnode._data.get('node') is not None:
                nform['node'].data = cnode.node.id

    def delete_cnode_by_no(self, no):
        if len(self.nodes) <= CellForm.CNODE_MIN:
            return
        cnode_list = self._pop_cnode(len(self.nodes) - no - 1)
        self.nodes.pop_entry()
        self._push_cnode(cnode_list)

    def insert_cnode_by_no(self, no):
        cnode_list = self._pop_cnode(len(self.nodes) - no)
        cnode_list.insert(0, CellNode())
        self._push_cnode(cnode_list)

    @classmethod
    def delete(cls, id):
        with database.database.atomic():
            cell = Cell.get(Cell.id == id)
            try:
                from .ras.forms import RasTargetForm
                RasTargetForm.delete_nonexists_target('cell', cell.name)
            except Exception as e:
                logger.exception(e)
            cell.delete_instance()
            CellNode.delete().where(CellNode.cell == id).execute()