Django02_01 CMDB (attached source)

Source: Internet
Author: User
Tags table definition

I. Overview of the CMDB development process

The CMDB is divided into three parts according to the process: server, central control machine, background management. Through the central control machine and the server interaction, collect the required hardware, service-side related information. and passes the data to the background database, which is rendered by the daemon.


1. Backstage Management

Use the Django framework to install databases and create Web applications;

Create API for the communication of the central control machine, and data operation;

Storage in the computer mobile phone to the data, and to the central control machine through the assets entered into the host list;

2, central control machine

The main remote operation of the server, and data collection;

3. Server

Data acquisition client, according to the authentication method of the central control machine to complete the certification, such as saving the private key, such as the control machine;

Capture command for install response

--Dmidecode for collecting memory information
--MEGACLI for capturing hard disk information

Ii. Environmental Preparedness and planning

1. Backstage Management (Application django1.8.2)


1.1 Database Design

1.1) User-related tables

    • Define a user type table, categorized with user rights:

Class Usertype (models. Model):
Caption = models. Charfield (max_length=32, Db_index=true, Unique=true)
Code = models. Charfield (max_length=32, Db_index=true, Unique=true)

def __unicode__ (self):
Return self.caption

Class Meta:
verbose_name_plural = "User Type"
    • Defining a user-hosted table

Class UserProfile (models. Model): User_type = models. ForeignKey (' usertype ') #用户创建时需选择响应类型, and the Usertype table is a many-to-one relationship name = models. Charfield (U ' name ', max_length=32) email = models. Emailfield (U ' mailbox ') phone = models. Charfield (U ' landline ', max_length=50) mobile = models. Charfield (U ' mobile phone ', max_length=32) memo = models. TextField (U ' Memo ', blank=true) Create_at = models. Datetimefield (Blank=true, auto_now_add=true) Update_at = models. Datetimefield (Blank=true, auto_now=true) class Meta:verbose_name = ' user information ' verbose_name_plural = ' user Information ' Def __unicode_ _ (Self): return self.name
    • Define Adininfo/usergroup table to store user name password, user group

1.2) host information related table definition

According to the actual situation, define the host machine mainframe computer application and operation log and other related tables;

1.2 Application Authoring

    • API URL Interface Program

WEB_API Host list generation function

Def get_untreated_servers ():     response = baseresponse ()      try:        current_date = datetime.date.today ()          values =  (' Server__hostname ',)          condition = q ()         con_date  = q ()         con_date.connector =  ' OR '          con_date.children.append (("Latest_date__lt",  current_date))         con_date.children.append (("Latest_date",  None))          con_status = q ()          #  Online Status Server (1000: shelves; 1001: Online)         con_ Status.children.append (' Device_status__code ', ' 1001 ')         condition.add (con_date,  ' and ')          condition.add (con_status,  ' and ')          result = dal_asset.get_q (condition, *values)          result = list (Result)         response.status =  True        response.data = result     except exception, e:        response.message =  str (e)     return response        #  #############  server-related information  ############ #class  serverhelper (object):     #   Get server Objects      @staticmethod     def get_server_obj (SN):       &nBsp; response = baseresponse ()         try:             RESULT = DAL_SERVER.GET_OBJ_BY_SN (SN)             if not result:                 raise exception (' not  found server obj ')              response.data = result             response.status = true        except exception,e:             response.message = e.message         return response
    • WEB_API receives from the central control and the information, carries on the data processing, this process contains the massive data contrast, the resource update deletes the addition and so on the massive operation procedure.

operate basic operations and log logs to update relevant hardware information. Create the DAL package to manipulate the NIC as an example, as follows:

# #############  Operation network card information  ##############  operation network card, and record operation log #  add Nic #  remove NIC #  update NIC information class  handlenic (object):     @staticmethod     def process (Server_ Obj,client_nic,user_obj):         response = baseresponse ()         try:             status = client_nic[' status ']             if status == 0:                 raise exception (' Nic plugin is error ')              client_nic_dict = client_nic[' data ']            nic_objs = dal_nic.get_ Objs_by_server (server_obj)              nic_names = map (Lambda x:x, ( ITEM.NAME FOR ITEM IN NIC_OBJS))              update_list = agorithm.get_intersection (Set (Client_nic_dict.keys ()), set (Nic_names) )             add_list = agorithm.get_ Exclude (Client_nic_dict.keys (), update_list)              del_list = agorithm.get_exclude (nic_names,update_list)              handlenic._add_nic (Add_list, client_nic_dict, server_obj,user_ obj)             handlenic._update_nic (update_list,  nic_objs, client_nic_dict, server_obj, user_obj)               handlenic._del_nic (Del_list, nic_objs, server_obj, user_obj)              response.status = True         except Exception,e:             response.message = e.message              #write  error log            print  e.message        return response
    • Create a DAL package, which is used to store data manipulation programs, specifically for interacting with the database. such as user authentication:

From web_models import modelsdef get_count (**kwargs): Count = models. AdminInfo.objects.filter (**kwargs). Count () return countdef Get_single (**kwargs): obj = models. AdminInfo.objects.get (**kwargs) return obj

1.3 Background Management App

Ideas on the API application, the difference is that the need to add a front-end interaction with the forms module, etc.;

1.4 Front-end programs

Create application directory in templates, distinguish store application foreground file;



+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

2, central control machine

2.1 Central Control Machine Program

The control machine for Python program can be based on saltstack/ansible and other programs to the server batch data collection.

          Accept host information from the API

    •     Plugin authoring, plugins module for server data acquisition, such as:

#!/usr/bin/env python# -*- coding:utf-8 -*-#内存数据采集import  osimport  subprocessimport commandsimport basepluginfrom lib.commons import convertfrom  Lib.commons import logclass memoryplugin (baseplugin.baseplugin):     def  linux (self):         result = {' status ': 0, ' data ': {}}         try:              #shell_command  =  "/usr/bin/sudo dmidecode -q -t 17 2>/ Dev/null "            shell_command = " Sudo dmidecode  -q -t 17 2>/dev/null "             output = self.exec_shell_cmd (Shell_command)              result[' data '] = self.parse (output)              result[' status '] = 1        except  exception,e:            print e             result[' ERROR '] = e         return result    def parse (self,content):          "         Parse shell command return result         :p aram content: shell  Command Results          :return: Parsed results          '          ram_dict = {}        key _map = {             ' Size ': ' Capacity ',              ' Locator ': ' Slot ',              ' Type ': ' Model ',              ' speed ': ' Speed ',             ' manufacturer ': ' Manufactory ',             ' Serial Number ': ' SN ' ,         }        devices  = content.split (' Memory device ')         for item  in devices:            item =  item.strip ()             if not  Item:                continue             if item.startswith (' # '):                 continue             segment = {}             lines = item.split (' \n\t ')              for line in lines:                 if len (Line.split (': ')) >1:                     key,value =  Line.split (': ')                  else:                    key =  Line.split (': ') [0]                     value =  ""                  if key_map.has_key (Key):                     if key ==  ' Size ':                          segment[key_map[' Size ']] = CONVERT.CONVERT_MB_TO_GB (value,0)                      else:                    &nbsP;    segment[key_map[key.strip ()]] = value.strip ()              ram_dict[segment[' Slots ']] = segment         return ram_dict


3. Server

Get through the interaction with the central control machine

    • Save the public key to server A, Server B ...

    • Installed on the server
      --Dmidecode used to capture memory information
      --MEGACLI for capturing hard disk information

Other:

To generate a background verification code installation pillow, and related application package

Http://www.reader8.cn/jiaocheng/20120906/2009724.html


Django02_01 CMDB (attached source)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.