MySQL ERROR 2002 Can't connect to local MySQL server through socket '/tmp/mysql.sock'

# 概要
MySQLに接続できない。

# 結論
`$ sudo chown -R root /usr/local`を以前実行していたので、`sudo chown -R username /usr/local`として、所有者をrootから自分へ戻す

# 所見
`mysql`コマンドが使用できない。また、PlayFrameworkからも利用できない。

こうしてPostgreSQLやMySQLの設定が崩壊してしまった原因はおそらく、Macのユーザーを新しく作成したことだったと考えられる。それを機に新しいユーザーだけでなく、旧ユーザーの設定も壊れてしまったのである。合掌。今後は、その程度で崩壊するのだということを肝に銘じて、できるだけユーザーに依存しないように設定しなければならないなあ。

### `mysql`コマンド

```
$ mysql
ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2)
```

### PlayFramework
at Browser

```
Configuration error
Cannot connect to database [default]
```
at Console

```
[error] c.j.b.h.AbstractConnectionHook - Failed to obtain initial connection Sleeping for 0ms and trying again. Attempts left: 0. Exception: java.net.ConnectException: Connection refused
[error] application -

! @6i4dfen98 - Internal server error, for (GET) [/] ->

play.api.Configuration$$anon$1: Configuration error[Cannot connect to database [default]]
at play.api.Configuration$.play$api$Configuration$$configError(Configuration.scala:81) ~[play_2.10-2.1.4.jar:2.1.4]
at play.api.Configuration.reportError(Configuration.scala:559) ~[play_2.10-2.1.4.jar:2.1.4]
at play.api.db.BoneCPPlugin$$anonfun$onStart$1.apply(DB.scala:251) ~[play-jdbc_2.10-2.1.4.jar:2.1.4]
at play.api.db.BoneCPPlugin$$anonfun$onStart$1.apply(DB.scala:242) ~[play-jdbc_2.10-2.1.4.jar:2.1.4]
at scala.collection.TraversableLike$$anonfun$map$1.apply(TraversableLike.scala:244) ~[scala-library.jar:na]
at scala.collection.TraversableLike$$anonfun$map$1.apply(TraversableLike.scala:244) ~[scala-library.jar:na]
Caused by: com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure

The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) ~[na:1.6.0_43]
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39) ~[na:1.6.0_43]
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27) ~[na:1.6.0_43]
at java.lang.reflect.Constructor.newInstance(Constructor.java:513) ~[na:1.6.0_43]
at com.mysql.jdbc.Util.handleNewInstance(Util.java:411) ~[mysql-connector-java-5.1.24.jar:na]
at com.mysql.jdbc.SQLError.createCommunicationsException(SQLError.java:1121) ~[mysql-connector-java-5.1.24.jar:na]
Caused by: java.net.ConnectException: Connection refused
at java.net.PlainSocketImpl.socketConnect(Native Method) ~[na:1.6.0_43]
at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:351) ~[na:1.6.0_43]
at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:213) ~[na:1.6.0_43]
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:200) ~[na:1.6.0_43]
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:432) ~[na:1.6.0_43]
at java.net.Socket.connect(Socket.java:529) ~[na:1.6.0_43]
[debug] application - total: 1398932208461ms
```

# 処置と経過
ImageMagickを利用したプログラムを開発していたので、備忘録http://unix-like.dyndns-web.com/「[[Mac]HomebrewでCowardly refusing to `sudo brew’が出る](http://unix-like.dyndns-web.com/?p=56)」を参考に`$ sudo chown -R root /usr/local`を実行していました。

しかしながら、これ以降PostgreSQLやMySQLとの接続が全くうまく行かなくなりました。開発も終了した今、もはやそのままにしておく理由もないので、`sudo chown -R username /usr/local`として、所有者をrootから自分へ戻すことにしました。

おかげさまでその後は快調。

これに至るまで超絶周りくどい試みをいろいろやりました。再インストールまでも。

やはり何が起こるかよく理解しておかないとなあ。

### つみきWeb[(当該記事)](#link)にしたがって
以下の様な理由が考えられるとのこと。上から消化していきます。

* MySQLサーバーが起動していない
* MySQLサーバーで使っているUNIXソケットとクライアントソフトで使っているUNIXソケットのパスが違う
* なんらかの理由でソケットファイルが削除されている

##### MySQLサーバーが起動していない

```
$ ps ax | grep mysqld
548 s001 S+ 0:00.00 grep mysqld
```
なるほど。

```
$ sudo mysqld stop
2014-05-01 17:30:29 552 [Note] mysqld: Shutdown complete
$ ps ax | grep mysqld
554 s001 S+ 0:00.00 grep mysqld
```
あれっ?もしや動いてない?

```
$ mysqld start
...
...
...
2014-05-01 17:31:04 590 [Note] mysqld: Shutdown complete
```
Oh... 今まで動いてなかったということか。ということで以下エラーメッセージを読みます。読んだ結果、どうやら次のような症状だとわかりました。

1. ./mysql/plugin.frmを読み込めていない
2. アクセス権がない
2. mysql.plugin tableを開くことができない
3. エラー番号13、mysqldが当該ディレクトリに対するアクセス権を保持していないとのこと。


```
2014-05-01 17:38:41 0 [Warning] TIMESTAMP with implicit DEFAULT value is deprecated. Please use --explicit_defaults_for_timestamp server option (see documentation for more details).
2014-05-01 17:38:41 646 [Warning] Can't create test file /usr/local/var/mysql/computername.lower-test
2014-05-01 17:38:41 646 [Warning] Can't create test file /usr/local/var/mysql/computername.lower-test
2014-05-01 17:38:41 646 [Note] Plugin 'FEDERATED' is disabled.
mysqld: Can't find file: './mysql/plugin.frm' (errno: 13 - Permission denied)
2014-05-01 17:38:41 646 [ERROR] Can't open the mysql.plugin table. Please run mysql_upgrade to create it.
2014-05-01 17:38:41 646 [Note] InnoDB: The InnoDB memory heap is disabled
2014-05-01 17:38:41 646 [Note] InnoDB: Mutexes and rw_locks use GCC atomic builtins
2014-05-01 17:38:41 646 [Note] InnoDB: Compressed tables use zlib 1.2.3
2014-05-01 17:38:41 646 [Note] InnoDB: CPU does not support crc32 instructions
2014-05-01 17:38:41 646 [Note] InnoDB: Initializing buffer pool, size = 128.0M
2014-05-01 17:38:41 646 [Note] InnoDB: Completed initialization of buffer pool
2014-05-01 17:38:41 646 [Note] InnoDB: Highest supported file format is Barracuda.
2014-05-01 17:38:41 7fff7ade3310 InnoDB: Operating system error number 13 in a file operation.
InnoDB: The error means mysqld does not have the access rights to
InnoDB: the directory.
2014-05-01 17:38:41 646 [ERROR] InnoDB: Could not find a valid tablespace file for 'mysql/innodb_index_stats'. See http://dev.mysql.com/doc/refman/5.6/en/innodb-troubleshooting-datadict.html for how to resolve the issue.
2014-05-01 17:38:41 646 [ERROR] InnoDB: Tablespace open failed for '"mysql"."innodb_index_stats"', ignored.
2014-05-01 17:38:41 7fff7ade3310 InnoDB: Operating system error number 13 in a file operation.
InnoDB: The error means mysqld does not have the access rights to
InnoDB: the directory.
...(以下同様のエラー7件)...
2014-05-01 17:38:41 646 [Note] InnoDB: 1.2.10 started; log sequence number 76086831
mysqld: Too many arguments (first extra is 'start').
Use --verbose --help to get a list of available options
2014-05-01 17:38:41 646 [ERROR] Aborting
2014-05-01 17:38:41 646 [Note] Binlog end
2014-05-01 17:38:43 646 [Note] mysqld: Shutdown complete
```
どうしろと...

エラーメッセージで検索したところ「[BmathLog mysql: BITNAMI の mysql が起動しない 2011年5月16日](http://bmath.org/wordpress/?p=1090)」を発見。

###### # my.cnfに我がユーザー名を追加してみる。
一時的に我がアカウントにもmy.cnfの書き込み権限を追加して、

```
$ vi my.cnf
[mysqld]
user=username
```
すると以下の様な結果に。

```
$ mysqld start
...
...
...
2014-05-01 17:38:43 646 [Note] mysqld: Shutdown complete
```
えっ...(^ν^)

### WordPress.orgのフォーラム[(当該記事)](#link)にて
相変わらず「書き込み権限がない」とのこと。`./mysql/plugin.frm`ってどのディレクトリだろう?ということで[ログファイルを捜索した結果](#logsearch)、`/usr/local/var/mysql/computername.local.err`なるものを発見。

```
2014-04-27 10:18:59 3325 [Note] Plugin 'FEDERATED' is disabled.
/usr/local/Cellar/mysql/5.6.10/bin/mysqld: Can't find file: './mysql/plugin.frm' (errno: 13 - Permission denied)
2014-04-27 10:18:59 3325 [ERROR] Can't open the mysql.plugin table. Please run mysql_upgrade to create it.
2014-04-27 10:18:59 3325 [ERROR] InnoDB: read can't be opened in ./ibdata1 mode
2014-04-27 10:18:59 3325 [ERROR] InnoDB: The system tablespace must be writable!
2014-04-27 10:18:59 3325 [ERROR] Plugin 'InnoDB' init function returned error.
2014-04-27 10:18:59 3325 [ERROR] Plugin 'InnoDB' registration as a STORAGE ENGINE failed.
2014-04-27 10:18:59 3325 [ERROR] Unknown/unsupported storage engine: InnoDB
2014-04-27 10:18:59 3325 [ERROR] Aborting
```

ということで`/usr/local/Cellar/mysql/5.6.10/bin/mysqld`に書き込み権限を付与してみようと。`$sudo chmod 775 /usr/local/Cellar/mysql/5.6.10/bin/mysqld`と入力しましたが、状況は変わりません。


`$sudo chmod 775 /usr/local/var/mysql`のおかげで`[Warning] Can't create test file /usr/local/var/mysql/Noriaki-MBA.lower-test`は消えました。

ところが、`$mysql mysql_upgrade`を行っても、相変わらず`[Note] Plugin 'FEDERATED' is disabled. /usr/local/Cellar/mysql/5.6.10/bin/mysqld: Can't find file: './mysql/plugin.frm' (errno: 13 - Permission denied)`と、`[ERROR] Can't open the mysql.plugin table. Please run mysql_upgrade to create it.`は残っています。

ふたたび`$vi /usr/local/var/mysql/Noriaki-MBA.local.err`を実行。

```
140427 10:18:59 mysqld_safe Starting mysqld daemon with databases from /usr/local/var/mysql
2014-04-27 10:18:59 0 [Warning] TIMESTAMP with implicit DEFAULT value is deprecated. Please use --explicit_defaults_for_timestamp server option (see documentation for more details).
2014-04-27 10:18:59 3325 [Warning] Setting lower_case_table_names=2 because file system for /usr/local/var/mysql/ is case insensitive
2014-04-27 10:18:59 3325 [Note] Plugin 'FEDERATED' is disabled.
^G/usr/local/Cellar/mysql/5.6.10/bin/mysqld: Can't find file: './mysql/plugin.frm' (errno: 13 - Permission denied)
2014-04-27 10:18:59 3325 [ERROR] Can't open the mysql.plugin table. Please run mysql_upgrade to create it.
2014-04-27 10:18:59 3325 [ERROR] InnoDB: read can't be opened in ./ibdata1 mode
2014-04-27 10:18:59 3325 [ERROR] InnoDB: The system tablespace must be writable!
2014-04-27 10:18:59 3325 [ERROR] Plugin 'InnoDB' init function returned error.
2014-04-27 10:18:59 3325 [ERROR] Plugin 'InnoDB' registration as a STORAGE ENGINE failed.
2014-04-27 10:18:59 3325 [ERROR] Unknown/unsupported storage engine: InnoDB
2014-04-27 10:18:59 3325 [ERROR] Aborting
```

えっ...(^ν^)?何も変わってないじゃないの...

あーもうわけわかんない。DBバックアップして再インストールや!!!

→[DBバックアップして再インストール編]

# 脇道
### 「そもそもmy.cnfってどこにあるんだっけ」というくだり
```
$find / -name my.cnf
/usr/local/Cellar/mysql/5.6.10/my.cnf
```

### 「my.cnfのアクセス権ってどうなってたっけ」というくだり
```
$ls -al /usr/local/Cellar/mysql/5.6.10/
-rw-r--r-- 1 root admin 943 May 1 17:38 my.cnf
```

### 書き込み権限を追加したり削除したり
###### #書き込み権限の追加
```
sudo chmod a+w /usr/local/Cellar/mysql/5.6.10/my.cnf
```

###### #書き込み権限の削除
```
sudo chmod g-w /usr/local/Cellar/mysql/5.6.10/my.cnf
sudo chmod o-w /usr/local/Cellar/mysql/5.6.10/my.cnf
```

### 「そもそもログファイルってどこにあるんだっけ」というくだり
`ls /usr/local/var/mysql`にて発見。ファイル名は`computername.local.pid`



# 参考
1. [つみきWeb「Can't connect to local MySQL server through socket」エラーについて](http://www.hi-ho.ne.jp/tsumiki/book_sup2.html)
2. [WordPress.org 日本語[解決済み] データベース接続確立エラー→mysqlが起動しない (8 件の投稿)1 year前の投稿](http://ja.forums.wordpress.org/topic/13746)
3. 今回は関係なかった話
1. [ウマい話、ちょいくれや。mysqlソケットエラー解決法 2009年03月30日](http://d.hatena.ne.jp/TamaC/20090330/1238418696)
1. [かにぱん冒険記 2011-03-08 MySQLが起動できなくなった件(MacOSX10.6)](http://d.hatena.ne.jp/mtxx/20110308/1299575899)


# 概要
前回の続き。MySQLのデータディレクトリをバックアップして再インストール。
# 所見
### スペック
OSX 10.9 Marvericks
### MySQLデータディレクトリのバックアップ

### MySQLの再インストール

# 結論


# 処置と経過
### MySQLデータディレクトリのバックアップ
```
$ls /usr/local/var/mysql
```
これを適当なフォルダにコピー

### MySQLの再インストール
このMySQLは確かHomebrewでインストールしたはず。
```
$ sudo brew uninstall mysql
```

```
$ sudo find / -name mysql
$ sudo find / -name my.cnf
```
関係するファイルも削除するためにリストアップ。

PCを再起動して、

```
$ sudo brew install mysql
Already downloaded: /Library/Caches/Homebrew/mysql-5.6.15.mavericks.bottle.tar.gz
==> Pouring mysql-5.6.15.mavericks.bottle.tar.gz
==> Caveats
A "/etc/my.cnf" from another install may interfere with a Homebrew-built
server starting up correctly.
To connect:
mysql -uroot
To have launchd start mysql at login:
ln -sfv /usr/local/opt/mysql/*.plist ~/Library/LaunchAgents
Then to load mysql now:
launchctl load ~/Library/LaunchAgents/homebrew.mxcl.mysql.plist
Or, if you don't want/need launchctl, you can just run:
mysql.server start
==> Summary
🍺 /usr/local/Cellar/mysql/5.6.15: 9409 files, 349M
```
以上。

```
$ sudo find / -name my.cnf
/usr/local/Cellar/mysql/5.6.15/my.cnf
```


```
$ mysql.server start
Starting MySQL
ERROR! The server quit without updating PID file (/usr/local/var/mysql/Noriaki-MBA.local.pid).
```







# 脇道
### 「そもそもログファイルってどこにあるんだっけ」というくだり
`ls /usr/local/var/mysql`にて発見。ファイル名は`computername.local.pid`


### [brew info mysql](#link)

```
$ brew info mysql
mysql: stable 5.6.15 (bottled)
Conflicts with: mariadb, mysql-cluster, mysql-connector-c, percona-server
/usr/local/Cellar/mysql/5.6.15 (9409 files, 349M) *
Poured from bottle
==> Dependencies
Build: cmake ✘
==> Options
--enable-debug
Build with debug support
--enable-local-infile
Build with local infile loading support
--enable-memcached
Enable innodb-memcached support
--universal
Build a universal binary
--with-archive-storage-engine
Compile with the ARCHIVE storage engine enabled
--with-blackhole-storage-engine
Compile with the BLACKHOLE storage engine enabled
--with-embedded
Build the embedded server
--with-tests
Build with unit tests
==> Caveats
A "/etc/my.cnf" from another install may interfere with a Homebrew-built
server starting up correctly.
To connect:
mysql -uroot
To reload mysql after an upgrade:
launchctl unload ~/Library/LaunchAgents/homebrew.mxcl.mysql.plist
launchctl load ~/Library/LaunchAgents/homebrew.mxcl.mysql.plist
```

# 参考
1. Macとかの雑記帳「[HomebrewでMySQLをインストールする時に知っておきたいこと](http://tukaikta.blog135.fc2.com/blog-entry-197.html)」2012年01月11日
2. INO HANGING AROUND 「[[MySQL]5.6でのmy.cnf](http://memo.choimemo.net/?p=634)」2013年4月3日
3. (・∀・) ozamasa「[MacのMySQLを5.5から5.6にバージョンアップしたときのメモ。](http://ozamasa.naganoblog.jp/e1194854.html)」2013年2月7日
3. karakaram-blog「[HomebrewでMySQL 5.6をインストール。開発用my.cnfもさらす](http://www.karakaram.com/install-mysql56-homebrew)」2013年3月9日