суббота, 29 марта 2014 г.

How to Check your Hard Disk for Bad Blocks in Ubuntu

Взято отсюда, спасибо автору.


If your system regularly does disk checks on boot up and if it often finds errors during the check, its highly possible that you have bad sectors on your hard disk.  In such cases its highly recommended to do a disk check to detect if you have bad sectors on the disk.

What is a bad sector? A bad sector is a sector on a computer’s disk drive or flash memory that cannot be used due to permanent damage (or an OS inability to successfully access it), such as physical damage to the disk surface (or sometimes sectors being stuck in a magnetic or digital state that cannot be reversed) or failed flash memory transistors.
The simplest way to do a check on a disk is to use the badblocks command from the command line in Linux. To check a disk partition(in this case /dev/sdc1) use the following command:
 sudo badblocks -v /dev/sdc1
 The output will be in the following format:
sudo badblocks -v /dev/sdc1
Checking blocks 0 to 130954239
Checking for bad blocks (read-only test): 5621828 done, 3:37 elapsed
5621860 done, 8:43 elapsed
5621861 done, 13:25 elapsed
5621862 done, 17:57 elapsed
done
Pass completed, 4 bad blocks found.
If you find bad sectors it usually means its time to change your disk. The situation will most probably get worse over time, but there is a tiny possibility that these are false positives(mostly coz of problems elsewhere in the system). The alternative option is to mark these blocks as badblocks and tell your system to not write any data there. This will surely buy you some more life of the disk.
Note: The second option is cheaper(takes a bit of time though) and effective way of finding over time if your disk really had errors but if your data is very important to you, please back it up elsewhere or you risk losing it.
First we have to write the location of the bad sectors into a file.
 sudo badblocks /dev/sdc > /home/hacks/bad-blocks
After that, we need to feed the file into the FSCK command to mark these bad sectors as ‘unusable’ sectors.
 sudo fsck -l bad-blocks /dev/sdc

среда, 19 марта 2014 г.

Ovirt и его странности.

Ovirt и его странности.

1)Backup/Restore

1.1 До 3.6
Бэкап базы - скриптом engine-backup --mode=backup

1.2 В версии 3.6 пример:

engine-backup --mode=backup --scope=all --archive-compressor=gzip --files-compressor=None --db-compressor=None --file=<filename>.tgz --log=<filename>.txt

На выходе будет tgz архив, внутри которого БД в формате custom и свернутые tar каталоги с конфигами, сертификатами и прочим.


1.3 Полная процедура восстановления:
- поставить ovirt-engine
- сделать engine-setup, ответы на вопросы давать такие же, как и при начальной установке
- остановить engine
- drop database engine / create database engine owner <your db owner>
- engine-backup --mode=restore --scope=all --file=<your archive file> --log=<log file> --change-db-credentials --db-host=<your host> --db-user=<your db user> --db-name=<your db name> --db-password='<you can watch it in /etc/ovirt-engine/engine.conf.d/10-setup-database.conf>' --restore-permissions
- внести изменения в  /etc/ovirt-engine/aaa/internal.properties
- запустить engine


2) Upgrade 3.4 to 3.5

2.1) Small bug when upgrading existing data centers from oVirt 3.4 to 3.5.

There is a bug filed on this that will likely be resolved in the next minor version upgrade. As a work-around, navigate to the Storage tab, click your VM’s storage domain, in the sub-tab at the bottom click Storage Profile, and add a default storage profile for your VM’s storage.
You will now be able to add disks to VMs again.

3) Инсталляция сервера - хоста.

  3.1) Перед запуском инсталляции присоединить репозиторий ovirt
yum localinstall  http://resources.ovirt.org/pub/yum-repo/ovirt-release41.rpm
  3.2) Если устанавливаем на сервер, загружающийся с usb flash, то необходимо провести следующие манипуляции:
     3.2.1) /var/log монтируем как tmpfs
     3.2.2) Настроить rsyslog на отправку сообщений на сервер централизованного сбора журналов работы
     3.2.3) при каждой загрузке сервера необходимо создавать структуру каталогов в /var/log, для этого:

cat /usr/local/bin/create-log-dirs.sh
#!/bin/bash
        /usr/bin/mkdir -p /var/log/zabbix
        /usr/bin/chown zabbix:zabbix /var/log/zabbix


/usr/bin/mkdir -p /var/log/vdsm                                                                                                                                                                                                               
/usr/bin/mkdir -p /var/log/libvirt                                                                                                                                                                                                            
/usr/bin/mkdir -p /var/log/glusterfs
/usr/bin/touch /var/log/vdsm/upgrade.log                                                                                                                                                                                                      
/usr/bin/chown -R vdsm:kvm /var/log/vdsm

cat /etc/systemd/system/create-log-dirs.service
[Unit]
After=local-fs.target

[Service]
ExecStart=/usr/local/bin/create-log-dirs.sh

[Install]
WantedBy=default.target

  systemctl daemon-reload
 

4)  USB устройства хоста внутри VM

На сегодня все должно работать из GUI ovirt-engine, немного про глюки: http://lists.ovirt.org/pipermail/users/2015-December/036808.html

На всякий случай то, что было до 3.6: 

Теория:

http://www.ovirt.org/VDSM-Hooks/hostusb

Практика (взято отсюда):
First you have to install hostusb hook on the host machine. Then you have to run this command  
on engine to define 'hostusb' as a custom 
property:

sudo engine-config -s UserDefinedVMProperties='hostusb=[\w:&]+'

You can check out using:

sudo engine-config -g UserDefinedVMProperties. 
 Then editing your virtual machine, go to the 'Custom Properties' tab. There, select 
'hostusb' and in the right textbox, put the id. Example: 0x1234:0xbeef.

You can define several ids, putting '&' between them: 
0x1234:0xbeef&0x2222:0xabaa.
5) Memory page sharing management on hosts.
KSM From RH RHEV documentation




6) Утечка памяти в VDSMD у Ovirt 3.5

На данный момент не решена проблема (обновился до 3.5.2) с утечкой памяти в vdsmd, что в общем-то признано разработчиками, есть многостраничный "плач ярославны" на багтрекере ovirt, но воз и ныне там.
Поэтому обходимся пока рестартом vdsmd по cron 2 раза в неделю.

7)Привязка сетевого интерфейса ovirt к fake network, например tun interface.

Источник
I suspect the problem is that VDSM isn't told by default to pass dummy
NICs on to the engine. Have a look at the following file (exact path
might vary):

/usr/lib64/python2.7/site-packages/vdsm/config.py

Search for a variable called "fake_nics", it should exist for 3.2. By
default it is empty, but you may define a pattern for fake NIC names to
be passed to the engine (in your case probably "dummy*"). Restart the
vdsm daemon and everything should be fine. Maybe you'll have to move the
host to maintenance and then reactivate just to refresh the UI.

8) reset/change admin password.

ovirt-aaa-jdbc-tool user password-reset admin –password-valid-to=’yyyy-MM-dd hh:mm:ssZ’

9) Remove DWH


 
remove related rpms
 
# su - postgres
psql
drop database ovirt_engine_history;
drop database ovirt_engine_reports;
 
remove the folders /var/lib/ovirt-engine-reports,
/var/lib/ovirt-engine-dwh, /etc/ovirt-engine-reports and
/etc/ovirt-engine-dwh manually. Then engine-backup works again.
Otherwise nothing has struck me. 


10) Create a windows template

11) Ошибки и способы их исправления.


11.1 "Host (hostname) is installed with VDSM version (4.14) and cannot join cluster (clustername) which is compatible with VDSM versions [4.13, 4.9, > 4.11, 4.12, 4.10]."
yum clean all, yum update ovirt-release, yum update
(выполнить на ovirt-engine)

11.2 "Could not retrieve mirrorlist http://www.jpackage.org/mirrorlist.php?dist=generic&type=free&release=6.0 error was
14: PYCURL ERROR 22 - "The requested URL returned error: 504 Gateway Time-out"
Error: Cannot find a valid baseurl for repo: ovirt-jpackage-6.0-generic"
[root@colove01 yum.repos.d]# cat /tmp/jp.txt
# No local mirror detected - defaulting to adding them all
http://sunsite.informatik.rwth-aachen.de/ftp/pub/Linux/jpackage/6.0/generic/free

redirect /etc/yum.conf.d files to /tmp/jp.txt:
...
#mirrorlist=http://www.jpackage.org/mirrorlist.php?dist=generic&type=free&release=6.0
mirrorlist=file:///tmp/jp.txt
источник: http://www.mail-archive.com/users@ovirt.org/msg18008.html


11) Debian ovirt-guest-agent.

apt-get install ovirt-guest-agent
chmod +x /usr/share/ovirt-guest-agent/ovirt-guest-agent.py
systemctl restart ovirt-guest-agent 
проверить права на каталог /var/log/ovirt-guest-agent

четверг, 13 февраля 2014 г.

VPLS и AToM, участвуют Cisco ASR9001 и ASR1002


   Итак задача: организовать L2 туннель между сабинтерфейсами указанных устройств (начиная с версии IOS XE 3.10 на ASR 1000 разрешили-таки service-instance на Port-Channel интерфейсах и тогда я бы рекомендовал делать нормальный VPLS, в 3.13.2 даже пофиксили странное поведение service instants в определенных условиях).

   Очевидно, что L3 connectivity между устройствами (и loopback интерфейсами) должно присутствовать.

1. AToM.

 Конфигурация ASR9001

interface Bundle-Ether1
 description *** Uplink ***
 mtu 9000
interface Bundle-Ether1.2903
 description *** to ASR1002 ***
 ipv4 address 192.168.1.1 255.255.255.254
 encapsulation dot1q 2903
 !
 interface Bundle-Ether1.396 l2transport
  description *** test subinterface for AToM ***
  encapsulation dot1q 396
  rewrite ingress tag pop 1 symmetric <------ обратите внимание!!
  mtu 1564
 !
 mpls ldp
  router-id 192.168.10.1
  discovery targeted-hello accept
  log
  neighbor
  !
  interface Bundle-Ether1.2903
 !
 l2vpn
   logging
   pseudowire
  !
  pw-class test-atom
   encapsulation mpls
    protocol ldp
    control-word
  !
  xconnect group Test-Atom_group
   p2p asr1002
    interface Bundle-Ether1.396
    neighbor ipv4 192.168.10.2 pw-id 396
    pw-class test-atom
    !
   !
  !
   Конфигурация ASR1002
mpls label protocol ldp
mpls ldp discovery targeted-hello accept
mpls ldp router-id Loopback0 force
!
pseudowire-class test-atom
  encapsulation mpls
  control-word
!
interface Port-channel1
  description *** Uplink ***
  mtu 1546
  no ip address
    no negotiation auto
!
interface Port-channel1.2903
  description *** to ASR9001 ***
  encapsulation dot1Q 2903
  ip address 192.168.1.2 255.255.255.254
  no ip unreachables
  ip flow ingress
  ip ospf network point-to-point
  ip ospf mtu-ignore
  ip ospf cost 2
  mpls ip
  mpls label protocol ldp
  mpls mtu 1536
!
interface Port-channel1.396
  description *** test subinterface for AToM ***
  encapsulation dot1Q 396
  xconnect 192.168.10.1 396 encapsulation mpls pw-class test-atom
!

   Проверка работоспособности:
ASR1000: show mpls l2transport vc detail
ASR9001: show l2vpn xconnect detail

2. VPLS. 

Настройки интерфейсов подключения устройств и базовые настройки MPLS те же.
Вообще, VPLS в данной связке "взлетает" согласно официальным мануалам, один нюанс: после конфигурации первого VPLS на ASR1000 с ПО версии 3.10.2 устройство необходимо перезагрузить, иначе появляются фантомные глюки из серии "только что трафик ходил и вдруг перестал на некоторое время", при этом никаких ошибок сигнализации VPLS нигде не видно


Конфигурация ASR9001
interface Bundle-Ether1.51 l2transport
  encapsulation dot1q 325

!
l2vpn
  logging
  pseudowire
 !
 pw-class core-vpls
  encapsulation mpls
  protocol ldp
  !
 bridge group test-group
  bridge-domain 51
   interface Bundle-Ether1.51
   !
   vfi Inet_corp1
    neighbor 192.168.10.2 pw-id 51
    pw-class core-vpls
Конфигурация ASR1002
l2vpn vfi context Inet_corp1
  vpn id 51
  member 192.168.10.1 encapsulation mpls
!
bridge-domain 51
 member Port-channel1 service-instance 51
 member vfi Inet_corp1
!
interface Port-channel2
  description *** test ***
  mtu 1546
  no ip address
  no negotiation auto
  service instance 51 ethernet
   encapsulation dot1q 325
 !

Проверка работоспособности:
ASR1000: show mpls l2transport vc detail
ASR9001: show l2vpn bridge-domain bd-name 51 detail

суббота, 23 ноября 2013 г.

Cisco catalyst 4900M, обновление IOS.

Cisco catalyst 4900M, обновление IOS.


В отличие от большинства устройств с Cisco IOS на борту, данный коммутатор имеет редкую особенность:
когда вы загрузите на flash новую версию ПО и пропишете в конфиге например:
boot system flash bootflash:cat4500e-entservices-mz.122-54.SG1.bin
затем перезагрузите коммутатор, то удивленно увидите устройство, загрузившееся с  ПО все той же старой версии. А дело в том, что на этом коммутаторе config register необходимо переписывать при каждом обновлении ПО. Т.е. кроме команды boot system.... необходимо сказать коммутатору
config-register 0x2102
после чего, сохранив конфигурацию, проверьте правильность загрузочной записи командой
 show bootvar
после перезагрузки не забудьте удостовериться в правильности версии ПО командой
sh version

понедельник, 18 ноября 2013 г.

ОС CentOS, список персональных граблей.


1) После установки "чистой" ОС и обновления пакетов до актуального состояния нам могут понадобиться пакеты из сторонних репозиториев, пример: htop, его в стандартных репо просто нет.
Ниже буду писать список репозиториев, принесших пользу лично мне.

Fedoraproject Epel x86_64
для версии 6, для 7 версии.
для подключения к своей системе устанавливаем RPM epel-release.

(В случае возникновения Error: Cannot retrieve metalink for repository: epel. Please verify its path and try again)

Фикс простой:
vim /etc/yum.repos.d/epel.repo
И на строке mirrorlist=https заменяем на http. 

RepoForge (ex. RPMForge)


RPMfusion.org

2) Смена timezone на работающем сервере:
 cp /usr/share/zoneinfo/Europe/moscow /etc/localtime

3)  dot1q vlan на сетевых интерфейсах (from redhat customer portal)

modprobe 8021q 
 Configure your physical interface in /etc/sysconfig/network-scripts/ifcfg-ethX, where X is a unique number corresponding to a specific interface, as follows:

DEVICE=ethX
TYPE=Ethernet
BOOTPROTO=none
ONBOOT=yes
 Configure the VLAN interface configuration in /etc/sysconfig/network-scripts. The configuration filename should be the physical interface plus a . character plus the VLAN ID number. For example, if the VLAN ID is 192, and the physical interface is eth0, then the configuration filename should be ifcfg-eth0.192:

DEVICE=ethX.192
BOOTPROTO=none
ONBOOT=yes
IPADDR=192.168.1.1
NETMASK=255.255.255.0
USERCTL=no
NETWORK=192.168.1.0
VLAN=yes
If there is a need to configure a second VLAN, with for example, VLAN ID 193, on the same interface, eth0 , add a new file with the name eth0.193 with the VLAN configuration details.
 Restart the networking service, in order for the changes to take effect, as follows:

service network restart
5) Использование Http proxy  в yum и консоли (from centos docs):

To enable all yum operations to use a proxy server, specify the proxy server details in /etc/yum.conf. The proxy setting must specify the proxy server as a complete URL, including the TCP port number. If your proxy server requires a username and password, specify these by adding proxy_username and proxy_password settings.
The settings below enable yum to use the proxy server mycache.mydomain.com, connecting to port 3128, with the username yum-user and the password qwerty.
# The proxy server - proxy server:port number
proxy=http://mycache.mydomain.com:3128
# The account details for yum connections
proxy_username=yum-user
proxy_password=qwerty
 To enable proxy access for a specific user, add the lines in the example box below to the user's shell profile. For the default bash shell, the profile is the file ~/.bash_profile. The settings below enable yum to use the proxy server mycache.mydomain.com, connecting to port 3128.
# The Web proxy server used by this account
http_proxy="http://mycache.mydomain.com:3128"
export http_proxy

6) How to install dig on CentOS
yum install bind-utils

четверг, 3 октября 2013 г.

Авторизация абонентов по ip адресу, ISG, Cisco BRAS

Итак, задача: обеспечение возможности авторизации абонентов по ip адресу на устройстве Cisco.
В наличии стенд в виде Cisco 7301, билинг с сервером, умеющим протокол radius для общения с BRASами и ноутбук, изображающий из себя простого абонента.

Реализация.
1) Настройки серверов radius на bras опустим (описаны в предыдущем посте).
2) Настройки политик ISG:

class-map type control match-all ISG-IP-UNAUTH
 match timer UNAUTH-TIMER
 match authen-status unauthenticated
!
!
policy-map type service OPENGV
 ip access-group OPENGV-IN in
 ip access-group OPENGV-OUT out
!
policy-map type control IP_SUBS
 class type control ISG-IP-UNAUTH event timed-policy-expiry
  1 service disconnect
 !
 class type control always event session-start
  19 authorize identifier source-ip-address
  20 set-timer UNAUTH-TIMER 1
  99 service-policy type service name OPENGV
 !
 class type control always event service-start
  35 service-policy type service identifier service-name
 !
 class type control always event service-stop
  1 service-policy type service unapply identifier service-name
 !
 class type control always event session-restart
  19 authorize identifier source-ip-address
  20 set-timer UNAUTH-TIMER 1
  99 service-policy type service name OPENGV
 !
!
ip access-list extended OPENGV-IN
 permit ip any host <личный кабинет>
 permit udp any host <DNS Server 1> eq domain
 permit udp any host <DNS Server 2> eq domain
ip access-list extended OPENGV-OUT
 permit ip host <личный кабинет> any
 permit udp host <DNS Server 1> eq domain any
 permit udp host <DNS Server 2> eq domain any
3) пример настройки интерфейса для подключения абонента:
interface GigabitEthernet0/1
 ip address <адрес шлюза для абонента> ! возможно сделать просто ip unnumbered как вариант
 ip verify unicast source reachable-via rx allow-default allow-self-ping
 ip helper-address <адрес сервера DHCP>
 no ip redirects
 no ip unreachables
 no ip proxy-arp
 ip flow ingress
 media-type rj45
 speed auto
 duplex auto
 no negotiation auto
 service-policy type control IP_SUBS
 ip subscriber routed
  initiator unclassified ip-address
4) ну и немного косметики для реализации функционала IPoE subscribers:
 ip dhcp relay information trust-all

среда, 25 сентября 2013 г.

L2TP авторизация на BRASе Cisco

В качестве стенда Cisco 7301, задача - настроить авторизацию абонентов по протоколу L2TP для одного из сегментов сети.

Поскольку инфраструктура используется с полноценной поддержкой Cisco ISG нам понадобится соответствующий IOS для 7301-й.
На просторах необъятной сети был найден 122-31.SB18 в версии enterprise (sic! в версии service provider нам не хватит функционала, внезапно там нет vpdn, вообще.) В принципе все новомодные SRC, SRD, SRE и т.д. релизы также должны подойти для решения задачи, просто исторически в нашей конторе SBшные IOSы как-то особенно хорошо прижились для задач авторизации и аккаунтинга абонентов.

Итак собственно кусочки конфига:

aaa group server radius CAR
 server 192.168.1.1 auth-port 1812 acct-port 1813
 load-balance method least-outstanding ignore-preferred-server
!
aaa authentication login default local group CAR
aaa authentication ppp default group CAR
aaa authorization exec default local group CAR
aaa authorization network default group CAR
aaa authorization auth-proxy default group CAR
aaa authorization subscriber-service default local group CAR
aaa accounting delay-start all
aaa accounting suppress null-username
aaa accounting update periodic 10
aaa accounting network default start-stop group CAR
aaa accounting network ACCNT_LIST1 start-stop group CAR
это что касалось настроек порядка авторизации и аккаутинга 
продолжим:
aaa server radius dynamic-author
 client 192.168.1.1 server-key <password>
 server-key <password>
 port 1912
это для возможности получить CoA от сервера с целью например прибития сессии абонента или изменения её параметров на лету

subscriber authorization enable
vpdn enable
 !
vpdn-group VPDN-L2TP
! Default L2TP VPDN group
 accept-dialin
  protocol l2tp
  virtual-template 2
 no l2tp tunnel authentication
!
interface Loopback0
 ip address 192.168.1.2 255.255.255.255
 no ip unreachables
!
interface Virtual-Template2
 description *** L2TP subscribers ***
 mtu 1492
 ip unnumbered Loopback0
 ip verify unicast source reachable-via rx allow-default allow-self-ping
 no ip redirects
 no ip unreachables
 no ip proxy-arp
 ip mtu 1492
 ip flow ingress
 ip tcp adjust-mss 1452
 no logging event link-status
 ppp authentication chap
 ppp ipcp dns 192.168.1.3 192.168.1.4
 service-policy type control L2TP
 service-policy type control нам необходимо предварительно настроить, это тема отдельной записи, т.к. там полно тонких материй работы с ISG
!
radius-server attribute 44 include-in-access-req vrf default
radius-server attribute 6 on-for-login-auth
radius-server attribute 8 include-in-access-req
radius-server attribute 32 include-in-access-req
radius-server attribute 55 access-request include
radius-server attribute 25 access-request include
radius-server attribute nas-port format d
radius-server host 192.168.1.1 auth-port 1812 acct-port 1813 test username cisco key <passwotrd>
radius-server timeout 10
radius-server unique-ident 20
radius-server key <passwotrd>
radius-server vsa send cisco-nas-port
radius-server vsa send accounting
radius-server vsa send authentication
radius-server load-balance method least-outstanding ignore-preferred-server
косметика для правильной работы с radius серверами